Open History to see the last commit
1import * as HostProcess from "@t3tools/shared/HostProcess";
2import * as Config from "effect/Config";
3import * as ConfigProvider from "effect/ConfigProvider";
4import * as Console from "effect/Console";
5import * as Effect from "effect/Effect";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
9import * as CliError from "effect/cli/CliError";
10
11import packageJson from "../../package.json" with { type: "json" };
12import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
13import * as BootService from "../cloud/bootService.ts";
14import * as CliState from "../cloud/CliState.ts";
15import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/config.ts";
16import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
17import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
18import * as ServerConfig from "../config.ts";
19import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
20import {
21 connectSubcommands,
22 disconnectCloud,
23 headlessFlag,
24 linkEnvironmentForConnect,
25 runCloudCommand,
26 waitForReachability,
27} from "./connect.ts";
28import { resolveHostCliCommand } from "./invocation.ts";
29import * as CliService from "./service.ts";
30
31type Route = "connect" | "lan";
32type Routes = Readonly<Record<Route, boolean>>;
33
34/** How other devices reach this machine now. */
35interface Setup {
36 readonly service: BootService.BootServiceStatus;
37 /** Null in builds without T3 Connect. Off when T3 Connect revoked the link. */
38 readonly connect: boolean | null;
39 /** T3 Connect revoked the link; `t3 connect` links again. */
40 readonly connectRevoked: boolean;
41 readonly lan: boolean;
42 /** An installed service with no T3CODE_LAN keeps the old default: on. */
43 readonly lanFromOldDefault: boolean;
44 readonly host: string | undefined;
45}
46
47/**
48 * T3 Connect is on when this CLI asked for a managed link, or when the desktop or
49 * web app made one: that saves the tunnel config but no CLI marker. Revoked is off.
50 */
51export const connectEnabled = (link: {
52 readonly cliDesired: boolean;
53 readonly cliMode: CliState.CliDesiredLinkMode;
54 readonly managedTunnel: boolean;
55 readonly revoked: boolean;
56}) =>
57 // The server starts no tunnel for a CLI publish-only link, even with an old tunnel config.
58 !link.revoked && (link.cliDesired ? link.cliMode === "managed" : link.managedTunnel);
59
60const readSetup = Effect.fn("cli.up.read_setup")(function* () {
61 const { baseDir } = yield* ServerConfig.ServerConfig;
62 const service = yield* (yield* BootService.BootService).status;
63 const { entries } = yield* CliService.readServiceEnv(baseDir);
64 // Parsed as the server parses it.
65 const lan = yield* Config.Boolean("T3CODE_LAN")
66 .pipe(Config.option)
67 .parse(ConfigProvider.fromEnv({ env: entries }));
68 const secrets = yield* ServerSecretStore.ServerSecretStore;
69 const connectRevoked =
70 hasCloudPublicConfig && Option.isSome(yield* secrets.get(CLOUD_LINK_REVOKED));
71 const connect = hasCloudPublicConfig
72 ? connectEnabled({
73 cliDesired: yield* CliState.readCliDesiredCloudLink,
74 cliMode: yield* CliState.readCliDesiredLinkMode,
75 managedTunnel: Option.isSome(yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
76 revoked: connectRevoked,
77 })
78 : null;
79 return {
80 service,
81 connect,
82 connectRevoked,
83 lan: Option.getOrElse(lan, () => service.installed),
84 lanFromOldDefault: Option.isNone(lan) && service.installed,
85 host: entries.T3CODE_HOST,
86 } satisfies Setup;
87});
88
89/**
90 * The routes `t3 up` starts from. With no route flag it asks about every
91 * route, starting a machine with no service from T3 Connect. Any route flag
92 * means it asks nothing and keeps the routes not named as they are.
93 */
94export const planRoutes = (
95 setup: { readonly installed: boolean; readonly connect: boolean | null; readonly lan: boolean },
96 flags: { readonly connect: Option.Option<boolean>; readonly lan: Option.Option<boolean> },
97) => {
98 const ask = Option.isNone(flags.connect) && Option.isNone(flags.lan);
99 const start = {
100 connect: setup.connect === true || (ask && !setup.installed && setup.connect !== null),
101 lan: setup.lan,
102 };
103 return {
104 routes: {
105 connect: Option.getOrElse(flags.connect, () => start.connect),
106 lan: Option.getOrElse(flags.lan, () => start.lan),
107 } satisfies Routes,
108 ask: ask
109 ? (["connect", "lan"] as const).filter((r) => r !== "connect" || setup.connect !== null)
110 : [],
111 };
112};
113
114/** A running service reads T3CODE_LAN and its T3 Connect link only when it starts. */
115const needsRestart = (before: Routes, after: Routes) =>
116 after.lan !== before.lan || (after.connect && !before.connect);
117
118const CHOICES = {
119 connect: { title: "T3 Connect", description: "Creates a tunnel to control your PC." },
120 lan: { title: "Local network", description: "LAN and tailnet. Pairing code required." },
121} satisfies Record<Route, { readonly title: string; readonly description: string }>;
122
123const formatSetup = (setup: Setup) => {
124 const { service } = setup;
125 const rows: ReadonlyArray<readonly [string, string]> = [
126 [
127 "Service",
128 !service.supported
129 ? "unavailable"
130 : service.installed
131 ? `installed · t3@${service.installedVersion ?? packageJson.version}`
132 : "not installed",
133 ],
134 ...(setup.connect === null
135 ? []
136 : [
137 [
138 "T3 Connect",
139 setup.connect
140 ? "on · your T3 account"
141 : setup.connectRevoked
142 ? "off · link revoked. Run `t3 connect`."
143 : "off",
144 ] as const,
145 ]),
146 [
147 "Local network",
148 setup.host !== undefined
149 ? `overridden · T3CODE_HOST=${setup.host}`
150 : setup.lanFromOldDefault
151 ? "on · kept from an older install"
152 : setup.lan
153 ? "on · pairing code only"
154 : "off",
155 ],
156 ];
157 const notes = [
158 ...(setup.host === undefined && setup.lan
159 ? ["Anyone on your LAN or tailnet can reach the port. A pairing code is the only lock."]
160 : []),
161 ...(setup.lanFromOldDefault
162 ? ["Older installs keep LAN access on. Turn it off: `t3 up --no-lan`."]
163 : []),
164 ];
165 return [
166 ...rows.map(([label, value]) => ` ${label.padEnd(15)}${value}`),
167 ...(notes.length === 0 ? [] : ["", ...notes]),
168 ].join("\n");
169};
170
171const formatNextSteps = (routes: Routes, serviceInstalled: boolean) =>
172 [
173 ...(routes.connect
174 ? ["On your other device, sign in to T3 Connect with the same account."]
175 : []),
176 ...(routes.lan ? ["Run `t3 pair`. Use the code on your other device."] : []),
177 ...(routes.connect || routes.lan
178 ? []
179 : [
180 serviceInstalled
181 ? "Remote access is off. T3 Code still runs here in the background."
182 : "Remote access is off. Run `t3` to use T3 Code here.",
183 ]),
184 ].join("\n");
185
186const interactiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
187
188const setUp = Effect.fn("cli.up")(function* (flags: {
189 readonly baseDir: Option.Option<string>;
190 readonly connect: Option.Option<boolean>;
191 readonly lan: Option.Option<boolean>;
192 readonly yes: boolean;
193 readonly headless: boolean;
194}) {
195 const { baseDir } = yield* ServerConfig.ServerConfig;
196 const service = yield* BootService.BootService;
197 const before = yield* readSetup();
198 if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {
199 return yield* new CliError.UserError({
200 cause: "connect",
201 userMessage: "T3 Connect is unavailable in this build.",
202 });
203 }
204
205 const current = { connect: before.connect === true, lan: before.lan };
206 // A publish-only link is not "on", but a rollback must put it back.
207 const priorPublishOnly =
208 hasCloudPublicConfig &&
209 (yield* CliState.readCliDesiredCloudLink) &&
210 (yield* CliState.readCliDesiredLinkMode) === "publish_only";
211 const plan = planRoutes({ ...before, installed: before.service.installed }, flags);
212 const interactive = !flags.yes && interactiveTerminal();
213 let routes = plan.routes;
214 if (plan.ask.length > 0 && interactive) {
215 if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`);
216 const picked = yield* Prompt.run(
217 Prompt.MultiSelect({
218 message: "Allow connections through:",
219 selectAll: "Select all",
220 selectNone: "Clear all",
221 inverseSelection: "Invert selection",
222 choices: plan.ask.map((route) => ({
223 ...CHOICES[route],
224 value: route,
225 selected: plan.routes[route],
226 })),
227 }),
228 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(null) }));
229 if (picked === null) return yield* Console.log("Nothing changed.");
230 routes = { connect: picked.includes("connect"), lan: picked.includes("lan") };
231 } else if (plan.ask.length > 0 && !flags.yes && !before.service.installed) {
232 return yield* new CliError.UserError({
233 cause: "routes",
234 userMessage: `No terminal. Choose access with ${
235 before.connect === null ? "--lan" : "--connect or --lan"
236 }, or use --yes for the default. See \`t3 up --help\`.`,
237 });
238 }
239 // Nothing to run in the background, but a route left on still gets turned off.
240 if (!before.service.installed && !routes.connect && !routes.lan) {
241 if (current.connect || before.connectRevoked) {
242 yield* disconnectCloud({ clearAuthorization: false });
243 }
244 if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
245 return yield* Console.log(formatNextSteps(routes, false));
246 }
247 const { installedVersion } = before.service;
248 const newer =
249 installedVersion !== undefined &&
250 compareExactServiceVersions(installedVersion, packageJson.version) > 0;
251 // Asked before anything changes, so a declined restart leaves service.env
252 // matching what the running service read when it started.
253 // A stopped service of this version is not current, so reconcile starts it;
254 // a newer one is left alone and needs this restart to start.
255 const stopped = before.service.problems?.includes("service-stopped") === true;
256 const restart =
257 before.service.installed &&
258 (before.service.current || newer) &&
259 (needsRestart(current, routes) || stopped);
260 // An older or broken service is reinstalled, which restarts it too.
261 const update = before.service.installed && !before.service.current && !newer && !stopped;
262 if ((restart || update) && interactive && !stopped) {
263 const confirmed = yield* Prompt.run(
264 Prompt.Confirm({
265 message: update
266 ? "Update and restart T3 Code? Running agent turns will stop."
267 : "Apply changes and restart? Running agent turns will stop.",
268 initial: true,
269 }),
270 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
271 if (!confirmed) return yield* Console.log("Nothing changed.");
272 }
273
274 if (routes.connect && !current.connect) {
275 const linked = yield* linkEnvironmentForConnect({
276 headless: flags.headless,
277 installRelayClient: true,
278 });
279 if (linked === null) return;
280 yield* Console.log(
281 `✓ Signed in to T3 Connect${linked.identity ? ` as ${linked.identity}` : ""}`,
282 );
283 }
284 // A running server unlinks live; when that fails, only a restart stops its tunnel.
285 const unlinkFailed =
286 !routes.connect && (current.connect || before.connectRevoked)
287 ? (yield* disconnectCloud({ clearAuthorization: false })).status === "failed"
288 : false;
289 const previousLan = (yield* CliService.readServiceEnv(baseDir)).entries.T3CODE_LAN;
290 // Also with no service manager: the file records the choice that `t3 status` shows.
291 yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });
292 // When the service step fails, an installed service still runs with the old
293 // value, so the file goes back to match it.
294 // A new T3 Connect link is undone too, with any tunnel the failed start saved, so a
295 // rerun sees it as a change and restarts. The sign-in stays.
296 const restoreServiceEnv = before.service.installed
297 ? CliService.writeServiceEnv(baseDir, { T3CODE_LAN: previousLan }).pipe(
298 Effect.andThen(
299 !routes.connect || current.connect
300 ? Effect.void
301 : priorPublishOnly
302 ? CliState.setCliDesiredCloudLink(true, "publish_only")
303 : disconnectCloud({ clearAuthorization: false }).pipe(Effect.asVoid),
304 ),
305 )
306 : Effect.void;
307 // A failed update or restart may still have started the service with the new
308 // settings, so restart it once more on the old ones.
309 const rollBack = before.service.installed
310 ? restoreServiceEnv.pipe(Effect.andThen(service.restart.pipe(Effect.ignore)))
311 : Effect.void;
312 if (before.host !== undefined) {
313 yield* Console.warn(
314 `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,
315 );
316 }
317
318 const printServeCommand = Effect.fn(function* (reason: string) {
319 const { command } = yield* resolveHostCliCommand("serve", [
320 ...Option.match(flags.baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
321 // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.
322 routes.lan ? "--lan" : "--no-lan",
323 ]);
324 yield* Console.log(`${reason} Keep this command running:\n ${command}`);
325 // A host wins over --lan and --no-lan, as it does in service.env.
326 const shellHost = (yield* HostProcess.Environment).T3CODE_HOST;
327 if (shellHost !== undefined) {
328 yield* Console.warn(
329 `T3CODE_HOST=${shellHost} in this shell overrides that choice. Unset it before you run the command.`,
330 );
331 }
332 });
333 let started = false;
334 if (!before.service.supported) {
335 yield* printServeCommand("Background service unavailable.");
336 } else {
337 if (newer) {
338 yield* Console.log(`Keeping installed service version t3@${installedVersion}.`);
339 }
340 if (update && !interactive) {
341 yield* Console.log("Updating T3 Code. Running agent turns will stop.");
342 }
343 const result = newer
344 ? ({ changed: false } as const)
345 : yield* CliService.reconcileService().pipe(
346 Effect.catchTags({
347 BootServicePrerequisiteError: (error) => Effect.succeed({ failed: error.message }),
348 BootServiceUnsupportedError: (error) => Effect.succeed({ failed: error.message }),
349 }),
350 Effect.tapError(() => rollBack),
351 );
352 if ("failed" in result && before.service.installed) {
353 // The old service still runs, so a foreground server would clash with it.
354 yield* restoreServiceEnv;
355 yield* Console.log(
356 `Service setup failed: ${result.failed} Fix that, then run \`t3 up\` again.`,
357 );
358 } else if ("failed" in result) {
359 yield* printServeCommand(`Service setup failed: ${result.failed}`);
360 } else if (result.changed) {
361 yield* Console.log(CliService.formatServiceChange(result));
362 started = true;
363 } else if (restart || (unlinkFailed && before.service.installed)) {
364 const confirmed =
365 restart ||
366 !interactive ||
367 (yield* Prompt.run(
368 Prompt.Confirm({
369 message:
370 "The running service still has T3 Connect on. Restart it? Running agent turns will stop.",
371 initial: true,
372 }),
373 ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) })));
374 if (!confirmed) {
375 yield* Console.log("Run `t3 service restart` to turn T3 Connect off.");
376 } else {
377 if (!interactive && !stopped) {
378 yield* Console.log("Restarting T3 Code. Running agent turns will stop.");
379 }
380 const outcome = yield* service.restart.pipe(Effect.tapError(() => rollBack));
381 if (outcome === "queued") {
382 yield* Console.log("Restart queued. This session will disconnect.");
383 }
384 if (outcome === "skipped") {
385 yield* Console.log(
386 "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",
387 );
388 }
389 started = outcome === "restarted";
390 }
391 }
392 }
393 if (started && routes.connect && !current.connect) yield* waitForReachability();
394
395 const after = yield* readSetup();
396 yield* Console.log(
397 // From what took effect: a failed service step can undo a choice.
398 `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps(
399 { connect: after.connect === true, lan: after.lan },
400 after.service.installed,
401 )}`,
402 );
403});
404
405export const upCommand = Command.make("up", {
406 ...projectLocationFlags,
407 connect: Flag.Boolean("connect").pipe(
408 Flag.withDescription(
409 "Allow access through T3 Connect with your T3 account. Turn off with --no-connect.",
410 ),
411 Flag.optional,
412 ),
413 lan: Flag.Boolean("lan").pipe(
414 Flag.withDescription(
415 "Allow LAN and tailnet connections. Anyone there can reach the port; a pairing code is the only lock. Turn off with --no-lan.",
416 ),
417 Flag.optional,
418 ),
419 yes: Flag.Boolean("yes").pipe(
420 Flag.withDescription(
421 "Ask nothing. Keep the access settings; a new machine gets T3 Connect. A restart stops running agent turns.",
422 ),
423 Flag.withDefault(false),
424 ),
425 headless: headlessFlag,
426}).pipe(
427 Command.withShortDescription("Set up remote access and the T3 Code background service."),
428 Command.withDescription(
429 "Set up remote access and the T3 Code background service. Access flags skip the question, and routes not named keep their settings. Without a terminal, a needed restart runs without asking and stops running agent turns.",
430 ),
431 Command.withExamples([
432 { command: "t3 up", description: "Choose remote access." },
433 { command: "t3 up --connect", description: "Turn on T3 Connect. Keep other settings." },
434 { command: "t3 up --lan", description: "Allow LAN access with pairing codes." },
435 { command: "t3 up --no-lan", description: "Stop LAN access." },
436 { command: "t3 up --yes", description: "Take the defaults with no questions." },
437 { command: "t3 status --json", description: "Read the settings from a script." },
438 ]),
439 Command.withHandler((flags) => runCloudCommand(flags, setUp(flags), { quietLogs: true })),
440);
441
442export const connectCommand = Command.make("connect", {
443 ...projectLocationFlags,
444 headless: headlessFlag,
445}).pipe(
446 Command.withDescription("Set up T3 Connect for this machine. Same as `t3 up --connect`."),
447 Command.withHandler((flags) =>
448 runCloudCommand(
449 flags,
450 setUp({ ...flags, connect: Option.some(true), lan: Option.none(), yes: false }),
451 { quietLogs: true },
452 ),
453 ),
454 Command.withSubcommands(connectSubcommands),
455);
456
457/** `t3 status --json`, for scripts and agents. */
458const setupJson = (setup: Setup) =>
459 JSON.stringify(
460 {
461 service: {
462 supported: setup.service.supported,
463 installed: setup.service.installed,
464 installedVersion: setup.service.installedVersion ?? null,
465 },
466 connect:
467 setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },
468 lan: {
469 enabled: setup.lan,
470 inheritedDefault: setup.lanFromOldDefault,
471 hostOverride: setup.host ?? null,
472 },
473 },
474 null,
475 2,
476 );
477
478export const statusCommand = Command.make("status", {
479 ...projectLocationFlags,
480 json: Flag.Boolean("json").pipe(
481 Flag.withDescription("Print the settings as JSON. Does not test connections."),
482 Flag.withDefault(false),
483 ),
484}).pipe(
485 Command.withDescription("Show service setup and remote access settings."),
486 Command.withExamples([
487 { command: "t3 status", description: "Show the settings." },
488 { command: "t3 status --json", description: "Print them for scripts and agents." },
489 ]),
490 Command.withHandler(
491 Effect.fn("cli.status")(function* (flags) {
492 const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel, {
493 quietLogs: flags.json,
494 });
495 // Only what readSetup reads: no database, unlike the T3 Connect commands.
496 const setup = yield* readSetup().pipe(
497 Effect.provide(
498 Layer.merge(CliService.layer(config), ServerSecretStore.layer).pipe(
499 Layer.provideMerge(ServerConfig.layer(config)),
500 ),
501 ),
502 );
503 yield* Console.log(
504 flags.json
505 ? setupJson(setup)
506 : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,
507 );
508 }),
509 ),
510);