Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cli.ts

698 lines22.9 KB

1import { NetService } from "@t3tools/shared/Net";
2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import { AuthSessionId } from "@t3tools/contracts";
4import {
5 Config,
6 Console,
7 Duration,
8 Effect,
9 FileSystem,
10 LogLevel,
11 Option,
12 Path,
13 References,
14 Schema,
15 SchemaIssue,
16 SchemaTransformation,
17} from "effect";
18import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
19​
20import {
21 DEFAULT_PORT,
22 deriveServerPaths,
23 ensureServerDirectories,
24 resolveStaticDir,
25 ServerConfig,
26 RuntimeMode,
27 type ServerConfigShape,
28} from "./config";
29import { readBootstrapEnvelope } from "./bootstrap";
30import { expandHomePath, resolveBaseDir } from "./os-jank";
31import { runServer } from "./server";
32import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
33import {
34 formatIssuedPairingCredential,
35 formatIssuedSession,
36 formatPairingCredentialList,
37 formatSessionList,
38} from "./cliAuthFormat";
39import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
40​
41const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
42​
43const BootstrapEnvelopeSchema = Schema.Struct({
44 mode: Schema.optional(RuntimeMode),
45 port: Schema.optional(PortSchema),
46 host: Schema.optional(Schema.String),
47 t3Home: Schema.optional(Schema.String),
48 devUrl: Schema.optional(Schema.URLFromString),
49 noBrowser: Schema.optional(Schema.Boolean),
50 desktopBootstrapToken: Schema.optional(Schema.String),
51 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
52 logWebSocketEvents: Schema.optional(Schema.Boolean),
53 otlpTracesUrl: Schema.optional(Schema.String),
54 otlpMetricsUrl: Schema.optional(Schema.String),
55});
56​
57const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
58 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
59 Flag.optional,
60);
61const portFlag = Flag.integer("port").pipe(
62 Flag.withSchema(PortSchema),
63 Flag.withDescription("Port for the HTTP/WebSocket server."),
64 Flag.optional,
65);
66const hostFlag = Flag.string("host").pipe(
67 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
68 Flag.optional,
69);
70const baseDirFlag = Flag.string("base-dir").pipe(
71 Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
72 Flag.optional,
73);
74const devUrlFlag = Flag.string("dev-url").pipe(
75 Flag.withSchema(Schema.URLFromString),
76 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
77 Flag.optional,
78);
79const noBrowserFlag = Flag.boolean("no-browser").pipe(
80 Flag.withDescription("Disable automatic browser opening."),
81 Flag.optional,
82);
83const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
84 Flag.withSchema(Schema.Int),
85 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
86 Flag.optional,
87);
88const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
89 Flag.withDescription(
90 "Create a project for the current working directory on startup when missing.",
91 ),
92 Flag.optional,
93);
94const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
95 Flag.withDescription(
96 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
97 ),
98 Flag.withAlias("log-ws-events"),
99 Flag.optional,
100);
101​
102const EnvServerConfig = Config.all({
103 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
104 traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
105 traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
106 traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
107 Config.option,
108 Config.map(Option.getOrUndefined),
109 ),
110 traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
111 traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
112 traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
113 otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
114 Config.option,
115 Config.map(Option.getOrUndefined),
116 ),
117 otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
118 Config.option,
119 Config.map(Option.getOrUndefined),
120 ),
121 otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
122 Config.withDefault(10_000),
123 ),
124 otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
125 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
126 Config.option,
127 Config.map(Option.getOrUndefined),
128 ),
129 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
130 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
131 t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
132 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
133 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
134 Config.option,
135 Config.map(Option.getOrUndefined),
136 ),
137 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
138 Config.option,
139 Config.map(Option.getOrUndefined),
140 ),
141 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
142 Config.option,
143 Config.map(Option.getOrUndefined),
144 ),
145 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
146 Config.option,
147 Config.map(Option.getOrUndefined),
148 ),
149});
150​
151interface CliServerFlags {
152 readonly mode: Option.Option<RuntimeMode>;
153 readonly port: Option.Option<number>;
154 readonly host: Option.Option<string>;
155 readonly baseDir: Option.Option<string>;
156 readonly cwd: Option.Option<string>;
157 readonly devUrl: Option.Option<URL>;
158 readonly noBrowser: Option.Option<boolean>;
159 readonly bootstrapFd: Option.Option<number>;
160 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
161 readonly logWebSocketEvents: Option.Option<boolean>;
163​
164interface CliAuthLocationFlags {
165 readonly baseDir: Option.Option<string>;
166 readonly devUrl: Option.Option<URL>;
168​
169const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
170 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
171​
172const resolveOptionPrecedence = <Value>(
173 ...values: ReadonlyArray<Option.Option<Value>>
174): Option.Option<Value> => Option.firstSomeOf(values);
175​
176const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
177 const fs = yield* FileSystem.FileSystem;
178 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
179 if (!exists) {
180 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
181 }
182​
183 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
184 return parsePersistedServerObservabilitySettings(raw);
185});
186​
187export const resolveServerConfig = (
188 flags: CliServerFlags,
189 cliLogLevel: Option.Option<LogLevel.LogLevel>,
190) =>
191 Effect.gen(function* () {
192 const { findAvailablePort } = yield* NetService;
193 const path = yield* Path.Path;
194 const fs = yield* FileSystem.FileSystem;
195 const env = yield* EnvServerConfig;
196 const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
197 const bootstrapEnvelope =
198 bootstrapFd !== undefined
199 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
200 : Option.none();
201​
202 const mode: RuntimeMode = Option.getOrElse(
203 resolveOptionPrecedence(
204 flags.mode,
205 Option.fromUndefinedOr(env.mode),
206 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
207 ),
208 () => "web",
209 );
210​
211 const port = yield* Option.match(
212 resolveOptionPrecedence(
213 flags.port,
214 Option.fromUndefinedOr(env.port),
215 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
216 ),
217 {
218 onSome: (value) => Effect.succeed(value),
219 onNone: () => {
220 if (mode === "desktop") {
221 return Effect.succeed(DEFAULT_PORT);
222 }
223 return findAvailablePort(DEFAULT_PORT);
224 },
225 },
226 );
227 const devUrl = Option.getOrElse(
228 resolveOptionPrecedence(
229 flags.devUrl,
230 Option.fromUndefinedOr(env.devUrl),
231 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
232 ),
233 () => undefined,
234 );
235 const baseDir = yield* resolveBaseDir(
236 Option.getOrUndefined(
237 resolveOptionPrecedence(
238 flags.baseDir,
239 Option.fromUndefinedOr(env.t3Home),
240 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
241 Option.fromUndefinedOr(bootstrap.t3Home),
242 ),
243 ),
244 ),
245 );
246 const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
247 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
248 yield* fs.makeDirectory(cwd, { recursive: true });
249 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
250 yield* ensureServerDirectories(derivedPaths);
251 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
252 derivedPaths.settingsPath,
253 );
254 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
255 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
256 const noBrowser = resolveBooleanFlag(
257 flags.noBrowser,
258 Option.getOrElse(
259 resolveOptionPrecedence(
260 Option.fromUndefinedOr(env.noBrowser),
261 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
262 Option.fromUndefinedOr(bootstrap.noBrowser),
263 ),
264 ),
265 () => mode === "desktop",
266 ),
267 );
268 const desktopBootstrapToken = Option.getOrUndefined(
269 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
270 Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
271 ),
272 );
273 const autoBootstrapProjectFromCwd = resolveBooleanFlag(
274 flags.autoBootstrapProjectFromCwd,
275 Option.getOrElse(
276 resolveOptionPrecedence(
277 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
278 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
279 Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
280 ),
281 ),
282 () => mode === "web",
283 ),
284 );
285 const logWebSocketEvents = resolveBooleanFlag(
286 flags.logWebSocketEvents,
287 Option.getOrElse(
288 resolveOptionPrecedence(
289 Option.fromUndefinedOr(env.logWebSocketEvents),
290 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
291 Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
292 ),
293 ),
294 () => Boolean(devUrl),
295 ),
296 );
297 const staticDir = devUrl ? undefined : yield* resolveStaticDir();
298 const host = Option.getOrElse(
299 resolveOptionPrecedence(
300 flags.host,
301 Option.fromUndefinedOr(env.host),
302 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
303 ),
304 () => (mode === "desktop" ? "127.0.0.1" : undefined),
305 );
306 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
307​
308 const config: ServerConfigShape = {
309 logLevel,
310 traceMinLevel: env.traceMinLevel,
311 traceTimingEnabled: env.traceTimingEnabled,
312 traceBatchWindowMs: env.traceBatchWindowMs,
313 traceMaxBytes: env.traceMaxBytes,
314 traceMaxFiles: env.traceMaxFiles,
315 otlpTracesUrl:
316 env.otlpTracesUrl ??
317 Option.getOrUndefined(
318 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
319 Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
320 ),
321 ) ??
322 persistedObservabilitySettings.otlpTracesUrl,
323 otlpMetricsUrl:
324 env.otlpMetricsUrl ??
325 Option.getOrUndefined(
326 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
327 Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
328 ),
329 ) ??
330 persistedObservabilitySettings.otlpMetricsUrl,
331 otlpExportIntervalMs: env.otlpExportIntervalMs,
332 otlpServiceName: env.otlpServiceName,
333 mode,
334 port,
335 cwd,
336 baseDir,
337 ...derivedPaths,
338 serverTracePath,
339 host,
340 staticDir,
341 devUrl,
342 noBrowser,
343 desktopBootstrapToken,
344 autoBootstrapProjectFromCwd,
345 logWebSocketEvents,
346 };
347​
348 return config;
349 });
350​
351const resolveCliAuthConfig = (
352 flags: CliAuthLocationFlags,
353 cliLogLevel: Option.Option<LogLevel.LogLevel>,
354) =>
355 resolveServerConfig(
356 {
357 mode: Option.none(),
358 port: Option.none(),
359 host: Option.none(),
360 baseDir: flags.baseDir,
361 cwd: Option.none(),
362 devUrl: flags.devUrl,
363 noBrowser: Option.none(),
364 bootstrapFd: Option.none(),
365 autoBootstrapProjectFromCwd: Option.none(),
366 logWebSocketEvents: Option.none(),
367 },
368 cliLogLevel,
369 );
370​
371const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
372​
373const parseDurationInput = (value: string): Duration.Duration | null => {
374 const trimmed = value.trim();
375 if (trimmed.length === 0) return null;
376​
377 const shorthand = DurationShorthandPattern.exec(trimmed);
378 const normalizedInput = shorthand?.groups
379 ? (() => {
380 const amountText = shorthand.groups.value;
381 const unitText = shorthand.groups.unit;
382 if (typeof amountText !== "string" || typeof unitText !== "string") {
383 return null;
384 }
385​
386 const amount = Number.parseInt(amountText, 10);
387 if (!Number.isFinite(amount)) return null;
388​
389 switch (unitText.toLowerCase()) {
390 case "ms":
391 return `${amount} millis`;
392 case "s":
393 return `${amount} seconds`;
394 case "m":
395 return `${amount} minutes`;
396 case "h":
397 return `${amount} hours`;
398 case "d":
399 return `${amount} days`;
400 case "w":
401 return `${amount} weeks`;
402 default:
403 return null;
404 }
405 })()
406 : (trimmed as Duration.Input);
407​
408 if (normalizedInput === null) return null;
409​
410 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
411 return Option.isSome(decoded) ? decoded.value : null;
412};
413​
414const DurationFromString = Schema.String.pipe(
415 Schema.decodeTo(
416 Schema.Duration,
417 SchemaTransformation.transformOrFail({
418 decode: (value) => {
419 const duration = parseDurationInput(value);
420 if (duration !== null) {
421 return Effect.succeed(duration);
422 }
423 return Effect.fail(
424 new SchemaIssue.InvalidValue(Option.some(value), {
425 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
426 }),
427 );
428 },
429 encode: (duration) => Effect.succeed(Duration.format(duration)),
430 }),
431 ),
432);
433​
434const runWithAuthControlPlane = <A, E>(
435 flags: CliAuthLocationFlags,
436 run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
437 options?: {
438 readonly quietLogs?: boolean;
439 },
440) =>
441 Effect.gen(function* () {
442 const logLevel = yield* GlobalFlag.LogLevel;
443 const config = yield* resolveCliAuthConfig(flags, logLevel);
444 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
445 return yield* Effect.gen(function* () {
446 const authControlPlane = yield* AuthControlPlane;
447 return yield* run(authControlPlane);
448 }).pipe(
449 Effect.provide(AuthControlPlaneRuntimeLive),
450 Effect.provideService(ServerConfig, config),
451 Effect.provideService(References.MinimumLogLevel, minimumLogLevel),
452 );
453 });
454​
455const commandFlags = {
456 mode: modeFlag,
457 port: portFlag,
458 host: hostFlag,
459 baseDir: baseDirFlag,
460 cwd: Argument.string("cwd").pipe(
461 Argument.withDescription(
462 "Working directory for provider sessions (defaults to the current directory).",
463 ),
464 Argument.optional,
465 ),
466 devUrl: devUrlFlag,
467 noBrowser: noBrowserFlag,
468 bootstrapFd: bootstrapFdFlag,
469 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
470 logWebSocketEvents: logWebSocketEventsFlag,
471} as const;
472​
473const authLocationFlags = {
474 baseDir: baseDirFlag,
475 devUrl: devUrlFlag,
476} as const;
477​
478const ttlFlag = Flag.string("ttl").pipe(
479 Flag.withSchema(DurationFromString),
480 Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
481 Flag.optional,
482);
483​
484const jsonFlag = Flag.boolean("json").pipe(
485 Flag.withDescription("Emit JSON instead of human-readable output."),
486 Flag.withDefault(false),
487);
488​
489const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
490 Flag.withDescription("Role for the issued bearer session."),
491 Flag.withDefault("owner"),
492);
493​
494const labelFlag = Flag.string("label").pipe(
495 Flag.withDescription("Optional human-readable label."),
496 Flag.optional,
497);
498​
499const subjectFlag = Flag.string("subject").pipe(
500 Flag.withDescription("Optional session subject."),
501 Flag.optional,
502);
503​
504const baseUrlFlag = Flag.string("base-url").pipe(
505 Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
506 Flag.optional,
507);
508​
509const tokenOnlyFlag = Flag.boolean("token-only").pipe(
510 Flag.withDescription("Print only the issued bearer token."),
511 Flag.withDefault(false),
512);
513​
514const pairingCreateCommand = Command.make("create", {
515 ...authLocationFlags,
516 ttl: ttlFlag,
517 label: labelFlag,
518 baseUrl: baseUrlFlag,
519 json: jsonFlag,
520}).pipe(
521 Command.withDescription("Issue a new client pairing token."),
522 Command.withHandler((flags) =>
523 runWithAuthControlPlane(
524 flags,
525 (authControlPlane) =>
526 Effect.gen(function* () {
527 const issued = yield* authControlPlane.createPairingLink({
528 role: "client",
529 subject: "one-time-token",
530 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
531 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
532 });
533 const output = formatIssuedPairingCredential(issued, {
534 json: flags.json,
535 ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
536 });
537 yield* Console.log(output);
538 }),
539 {
540 quietLogs: flags.json,
541 },
542 ),
543 ),
544);
545​
546const pairingListCommand = Command.make("list", {
547 ...authLocationFlags,
548 json: jsonFlag,
549}).pipe(
550 Command.withDescription("List active client pairing tokens without revealing their secrets."),
551 Command.withHandler((flags) =>
552 runWithAuthControlPlane(
553 flags,
554 (authControlPlane) =>
555 Effect.gen(function* () {
556 const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
557 yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
558 }),
559 {
560 quietLogs: flags.json,
561 },
562 ),
563 ),
564);
565​
566const pairingRevokeCommand = Command.make("revoke", {
567 ...authLocationFlags,
568 id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
569}).pipe(
570 Command.withDescription("Revoke an active client pairing token."),
571 Command.withHandler((flags) =>
572 runWithAuthControlPlane(flags, (authControlPlane) =>
573 Effect.gen(function* () {
574 const revoked = yield* authControlPlane.revokePairingLink(flags.id);
575 yield* Console.log(
576 revoked
577 ? `Revoked pairing credential ${flags.id}.\n`
578 : `No active pairing credential found for ${flags.id}.\n`,
579 );
580 }),
581 ),
582 ),
583);
584​
585const pairingCommand = Command.make("pairing").pipe(
586 Command.withDescription("Manage one-time client pairing tokens."),
587 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
588);
589​
590const sessionIssueCommand = Command.make("issue", {
591 ...authLocationFlags,
592 ttl: ttlFlag,
593 role: sessionRoleFlag,
594 label: labelFlag,
595 subject: subjectFlag,
596 tokenOnly: tokenOnlyFlag,
597 json: jsonFlag,
598}).pipe(
599 Command.withDescription("Issue a bearer session token for headless or remote clients."),
600 Command.withHandler((flags) =>
601 runWithAuthControlPlane(
602 flags,
603 (authControlPlane) =>
604 Effect.gen(function* () {
605 const issued = yield* authControlPlane.issueSession({
606 role: flags.role,
607 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
608 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
609 ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
610 });
611 yield* Console.log(
612 formatIssuedSession(issued, {
613 json: flags.json,
614 tokenOnly: flags.tokenOnly,
615 }),
616 );
617 }),
618 {
619 quietLogs: flags.json || flags.tokenOnly,
620 },
621 ),
622 ),
623);
624​
625const sessionListCommand = Command.make("list", {
626 ...authLocationFlags,
627 json: jsonFlag,
628}).pipe(
629 Command.withDescription("List active sessions without revealing bearer tokens."),
630 Command.withHandler((flags) =>
631 runWithAuthControlPlane(
632 flags,
633 (authControlPlane) =>
634 Effect.gen(function* () {
635 const sessions = yield* authControlPlane.listSessions();
636 yield* Console.log(formatSessionList(sessions, { json: flags.json }));
637 }),
638 {
639 quietLogs: flags.json,
640 },
641 ),
642 ),
643);
644​
645const sessionRevokeCommand = Command.make("revoke", {
646 ...authLocationFlags,
647 sessionId: Argument.string("session-id").pipe(
648 Argument.withDescription("Session id to revoke."),
649 Argument.withSchema(AuthSessionId),
650 ),
651}).pipe(
652 Command.withDescription("Revoke an active session."),
653 Command.withHandler((flags) =>
654 runWithAuthControlPlane(flags, (authControlPlane) =>
655 Effect.gen(function* () {
656 const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
657 yield* Console.log(
658 revoked
659 ? `Revoked session ${flags.sessionId}.\n`
660 : `No active session found for ${flags.sessionId}.\n`,
661 );
662 }),
663 ),
664 ),
665);
666​
667const sessionCommand = Command.make("session").pipe(
668 Command.withDescription("Manage bearer sessions."),
669 Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
670);
671​
672const authCommand = Command.make("auth").pipe(
673 Command.withDescription("Manage the local auth control plane for headless deployments."),
674 Command.withSubcommands([pairingCommand, sessionCommand]),
675);
676​
677const startCommand = Command.make("start", commandFlags).pipe(
678 Command.withDescription("Run the T3 Code server."),
679 Command.withHandler((flags) =>
680 Effect.gen(function* () {
681 const logLevel = yield* GlobalFlag.LogLevel;
682 const config = yield* resolveServerConfig(flags, logLevel);
683 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
684 }),
685 ),
686);
687​
688export const cli = Command.make("t3", commandFlags).pipe(
689 Command.withDescription("Run the T3 Code server."),
690 Command.withHandler((flags) =>
691 Effect.gen(function* () {
692 const logLevel = yield* GlobalFlag.LogLevel;
693 const config = yield* resolveServerConfig(flags, logLevel);
694 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
695 }),
696 ),
697 Command.withSubcommands([startCommand, authCommand]),
698);