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

cli.ts

1,132 lines37.8 KB

1import { NetService } from "@t3tools/shared/Net";
2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import {
4 AuthSessionId,
5 CommandId,
6 OrchestrationReadModel,
7 ProjectId,
8 type ClientOrchestrationCommand,
9} from "@t3tools/contracts";
10import {
11 Config,
12 Console,
13 Duration,
14 Effect,
15 Exit,
16 FileSystem,
17 Layer,
18 LogLevel,
19 Option,
20 Path,
21 References,
22 Schema,
23 SchemaIssue,
24 SchemaTransformation,
25} from "effect";
26import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
27import {
28 FetchHttpClient,
29 HttpClient,
30 HttpClientRequest,
31 HttpClientResponse,
32} from "effect/unstable/http";
33​
34import {
35 DEFAULT_PORT,
36 deriveServerPaths,
37 ensureServerDirectories,
38 resolveStaticDir,
39 ServerConfig,
40 RuntimeMode,
41 type ServerConfigShape,
42 type StartupPresentation,
43} from "./config";
44import { readBootstrapEnvelope } from "./bootstrap";
45import { expandHomePath, resolveBaseDir } from "./os-jank";
46import { runServer } from "./server";
47import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
48import {
49 formatIssuedPairingCredential,
50 formatIssuedSession,
51 formatPairingCredentialList,
52 formatSessionList,
53} from "./cliAuthFormat";
54import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
55import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
56import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
57import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
58import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
59import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
60import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
61import {
62 clearPersistedServerRuntimeState,
63 readPersistedServerRuntimeState,
64} from "./serverRuntimeState";
65import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
66import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
67​
68const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
69​
70const BootstrapEnvelopeSchema = Schema.Struct({
71 mode: Schema.optional(RuntimeMode),
72 port: Schema.optional(PortSchema),
73 host: Schema.optional(Schema.String),
74 t3Home: Schema.optional(Schema.String),
75 devUrl: Schema.optional(Schema.URLFromString),
76 noBrowser: Schema.optional(Schema.Boolean),
77 desktopBootstrapToken: Schema.optional(Schema.String),
78 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
79 logWebSocketEvents: Schema.optional(Schema.Boolean),
80 otlpTracesUrl: Schema.optional(Schema.String),
81 otlpMetricsUrl: Schema.optional(Schema.String),
82});
83​
84const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
85 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
86 Flag.optional,
87);
88const portFlag = Flag.integer("port").pipe(
89 Flag.withSchema(PortSchema),
90 Flag.withDescription("Port for the HTTP/WebSocket server."),
91 Flag.optional,
92);
93const hostFlag = Flag.string("host").pipe(
94 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
95 Flag.optional,
96);
97const baseDirFlag = Flag.string("base-dir").pipe(
98 Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
99 Flag.optional,
100);
101const devUrlFlag = Flag.string("dev-url").pipe(
102 Flag.withSchema(Schema.URLFromString),
103 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
104 Flag.optional,
105);
106const noBrowserFlag = Flag.boolean("no-browser").pipe(
107 Flag.withDescription("Disable automatic browser opening."),
108 Flag.optional,
109);
110const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
111 Flag.withSchema(Schema.Int),
112 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
113 Flag.optional,
114);
115const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
116 Flag.withDescription(
117 "Create a project for the current working directory on startup when missing.",
118 ),
119 Flag.optional,
120);
121const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
122 Flag.withDescription(
123 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
124 ),
125 Flag.withAlias("log-ws-events"),
126 Flag.optional,
127);
128​
129const EnvServerConfig = Config.all({
130 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
131 traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
132 traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
133 traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
134 Config.option,
135 Config.map(Option.getOrUndefined),
136 ),
137 traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
138 traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
139 traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
140 otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
141 Config.option,
142 Config.map(Option.getOrUndefined),
143 ),
144 otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
145 Config.option,
146 Config.map(Option.getOrUndefined),
147 ),
148 otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
149 Config.withDefault(10_000),
150 ),
151 otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
152 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
153 Config.option,
154 Config.map(Option.getOrUndefined),
155 ),
156 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
157 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
158 t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
159 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
160 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
161 Config.option,
162 Config.map(Option.getOrUndefined),
163 ),
164 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
165 Config.option,
166 Config.map(Option.getOrUndefined),
167 ),
168 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
169 Config.option,
170 Config.map(Option.getOrUndefined),
171 ),
172 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
173 Config.option,
174 Config.map(Option.getOrUndefined),
175 ),
176});
177​
178interface CliServerFlags {
179 readonly mode: Option.Option<RuntimeMode>;
180 readonly port: Option.Option<number>;
181 readonly host: Option.Option<string>;
182 readonly baseDir: Option.Option<string>;
183 readonly cwd: Option.Option<string>;
184 readonly devUrl: Option.Option<URL>;
185 readonly noBrowser: Option.Option<boolean>;
186 readonly bootstrapFd: Option.Option<number>;
187 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
188 readonly logWebSocketEvents: Option.Option<boolean>;
190​
191interface CliAuthLocationFlags {
192 readonly baseDir: Option.Option<string>;
193 readonly devUrl?: Option.Option<URL>;
195​
196const resolveOptionPrecedence = <Value>(
197 ...values: ReadonlyArray<Option.Option<Value>>
198): Option.Option<Value> => Option.firstSomeOf(values);
199​
200const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
201 const fs = yield* FileSystem.FileSystem;
202 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
203 if (!exists) {
204 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
205 }
206​
207 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
208 return parsePersistedServerObservabilitySettings(raw);
209});
210​
211export const resolveServerConfig = (
212 flags: CliServerFlags,
213 cliLogLevel: Option.Option<LogLevel.LogLevel>,
214 options?: {
215 readonly startupPresentation?: StartupPresentation;
216 readonly forceAutoBootstrapProjectFromCwd?: boolean;
217 },
218) =>
219 Effect.gen(function* () {
220 const { findAvailablePort } = yield* NetService;
221 const path = yield* Path.Path;
222 const fs = yield* FileSystem.FileSystem;
223 const env = yield* EnvServerConfig;
224 const normalizedFlags = {
225 mode: flags.mode ?? Option.none(),
226 port: flags.port ?? Option.none(),
227 host: flags.host ?? Option.none(),
228 baseDir: flags.baseDir ?? Option.none(),
229 cwd: flags.cwd ?? Option.none(),
230 devUrl: flags.devUrl ?? Option.none(),
231 noBrowser: flags.noBrowser ?? Option.none(),
232 bootstrapFd: flags.bootstrapFd ?? Option.none(),
233 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
234 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
235 } satisfies CliServerFlags;
236 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
237 const bootstrapEnvelope =
238 bootstrapFd !== undefined
239 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
240 : Option.none();
241 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
242​
243 const mode: RuntimeMode = Option.getOrElse(
244 resolveOptionPrecedence(
245 normalizedFlags.mode,
246 Option.fromUndefinedOr(env.mode),
247 Option.fromUndefinedOr(bootstrap?.mode),
248 ),
249 () => "web",
250 );
251​
252 const port = yield* Option.match(
253 resolveOptionPrecedence(
254 normalizedFlags.port,
255 Option.fromUndefinedOr(env.port),
256 Option.fromUndefinedOr(bootstrap?.port),
257 ),
258 {
259 onSome: (value) => Effect.succeed(value),
260 onNone: () => {
261 if (mode === "desktop") {
262 return Effect.succeed(DEFAULT_PORT);
263 }
264 return findAvailablePort(DEFAULT_PORT);
265 },
266 },
267 );
268 const devUrl = Option.getOrElse(
269 resolveOptionPrecedence(
270 normalizedFlags.devUrl,
271 Option.fromUndefinedOr(env.devUrl),
272 Option.fromUndefinedOr(bootstrap?.devUrl),
273 ),
274 () => undefined,
275 );
276 const baseDir = yield* resolveBaseDir(
277 Option.getOrUndefined(
278 resolveOptionPrecedence(
279 normalizedFlags.baseDir,
280 Option.fromUndefinedOr(env.t3Home),
281 Option.fromUndefinedOr(bootstrap?.t3Home),
282 ),
283 ),
284 );
285 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
286 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
287 yield* fs.makeDirectory(cwd, { recursive: true });
288 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
289 yield* ensureServerDirectories(derivedPaths);
290 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
291 derivedPaths.settingsPath,
292 );
293 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
294 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
295 const startupPresentation = options?.startupPresentation ?? "browser";
296 const isHeadlessStartup = startupPresentation === "headless";
297 const noBrowser = Option.getOrElse(
298 resolveOptionPrecedence(
299 isHeadlessStartup ? Option.some(true) : Option.none(),
300 normalizedFlags.noBrowser,
301 Option.fromUndefinedOr(env.noBrowser),
302 Option.fromUndefinedOr(bootstrap?.noBrowser),
303 ),
304 () => mode === "desktop",
305 );
306 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
307 const autoBootstrapProjectFromCwd = Option.getOrElse(
308 resolveOptionPrecedence(
309 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
310 isHeadlessStartup ? Option.some(false) : Option.none(),
311 normalizedFlags.autoBootstrapProjectFromCwd,
312 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
313 Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
314 ),
315 () => mode === "web",
316 );
317 const logWebSocketEvents = Option.getOrElse(
318 resolveOptionPrecedence(
319 normalizedFlags.logWebSocketEvents,
320 Option.fromUndefinedOr(env.logWebSocketEvents),
321 Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
322 ),
323 () => Boolean(devUrl),
324 );
325 const staticDir = devUrl ? undefined : yield* resolveStaticDir();
326 const host = Option.getOrElse(
327 resolveOptionPrecedence(
328 normalizedFlags.host,
329 Option.fromUndefinedOr(env.host),
330 Option.fromUndefinedOr(bootstrap?.host),
331 ),
332 () => (mode === "desktop" ? "127.0.0.1" : undefined),
333 );
334 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
335​
336 const config: ServerConfigShape = {
337 logLevel,
338 traceMinLevel: env.traceMinLevel,
339 traceTimingEnabled: env.traceTimingEnabled,
340 traceBatchWindowMs: env.traceBatchWindowMs,
341 traceMaxBytes: env.traceMaxBytes,
342 traceMaxFiles: env.traceMaxFiles,
343 otlpTracesUrl:
344 env.otlpTracesUrl ??
345 bootstrap?.otlpTracesUrl ??
346 persistedObservabilitySettings.otlpTracesUrl,
347 otlpMetricsUrl:
348 env.otlpMetricsUrl ??
349 bootstrap?.otlpMetricsUrl ??
350 persistedObservabilitySettings.otlpMetricsUrl,
351 otlpExportIntervalMs: env.otlpExportIntervalMs,
352 otlpServiceName: env.otlpServiceName,
353 mode,
354 port,
355 cwd,
356 baseDir,
357 ...derivedPaths,
358 serverTracePath,
359 host,
360 staticDir,
361 devUrl,
362 noBrowser,
363 startupPresentation,
364 desktopBootstrapToken,
365 autoBootstrapProjectFromCwd,
366 logWebSocketEvents,
367 };
368​
369 return config;
370 });
371​
372const resolveCliAuthConfig = (
373 flags: CliAuthLocationFlags,
374 cliLogLevel: Option.Option<LogLevel.LogLevel>,
375) =>
376 resolveServerConfig(
377 {
378 mode: Option.none(),
379 port: Option.none(),
380 host: Option.none(),
381 baseDir: flags.baseDir,
382 cwd: Option.none(),
383 devUrl: flags.devUrl ?? Option.none(),
384 noBrowser: Option.none(),
385 bootstrapFd: Option.none(),
386 autoBootstrapProjectFromCwd: Option.none(),
387 logWebSocketEvents: Option.none(),
388 },
389 cliLogLevel,
390 );
391​
392const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
393​
394const parseDurationInput = (value: string): Duration.Duration | null => {
395 const trimmed = value.trim();
396 if (trimmed.length === 0) return null;
397​
398 const shorthand = DurationShorthandPattern.exec(trimmed);
399 const normalizedInput = shorthand?.groups
400 ? (() => {
401 const amountText = shorthand.groups.value;
402 const unitText = shorthand.groups.unit;
403 if (typeof amountText !== "string" || typeof unitText !== "string") {
404 return null;
405 }
406​
407 const amount = Number.parseInt(amountText, 10);
408 if (!Number.isFinite(amount)) return null;
409​
410 switch (unitText.toLowerCase()) {
411 case "ms":
412 return `${amount} millis`;
413 case "s":
414 return `${amount} seconds`;
415 case "m":
416 return `${amount} minutes`;
417 case "h":
418 return `${amount} hours`;
419 case "d":
420 return `${amount} days`;
421 case "w":
422 return `${amount} weeks`;
423 default:
424 return null;
425 }
426 })()
427 : (trimmed as Duration.Input);
428​
429 if (normalizedInput === null) return null;
430​
431 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
432 return Option.isSome(decoded) ? decoded.value : null;
433};
434​
435const DurationFromString = Schema.String.pipe(
436 Schema.decodeTo(
437 Schema.Duration,
438 SchemaTransformation.transformOrFail({
439 decode: (value) => {
440 const duration = parseDurationInput(value);
441 if (duration !== null) {
442 return Effect.succeed(duration);
443 }
444 return Effect.fail(
445 new SchemaIssue.InvalidValue(Option.some(value), {
446 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
447 }),
448 );
449 },
450 encode: (duration) => Effect.succeed(Duration.format(duration)),
451 }),
452 ),
453);
454​
455const runWithAuthControlPlane = <A, E>(
456 flags: CliAuthLocationFlags,
457 run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
458 options?: {
459 readonly quietLogs?: boolean;
460 },
461) =>
462 Effect.gen(function* () {
463 const logLevel = yield* GlobalFlag.LogLevel;
464 const config = yield* resolveCliAuthConfig(flags, logLevel);
465 const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
466 return yield* Effect.gen(function* () {
467 const authControlPlane = yield* AuthControlPlane;
468 return yield* run(authControlPlane);
469 }).pipe(
470 Effect.provide(
471 Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
472 Layer.provide(Layer.succeed(ServerConfig, config)),
473 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
474 ),
475 ),
476 );
477 });
478​
479type ProjectMutationTarget = {
480 readonly id: ProjectId;
481 readonly title: string;
482 readonly workspaceRoot: string;
483};
484​
485type ProjectCommandExecutionMode = "live" | "offline";
486type ProjectCliDispatchCommand = Extract<
487 ClientOrchestrationCommand,
488 { type: "project.create" | "project.meta.update" | "project.delete" }
489>;
490​
491const ProjectCliRuntimeLive = Layer.mergeAll(
492 WorkspacePathsLive,
493 OrchestrationLayerLive.pipe(
494 Layer.provideMerge(RepositoryIdentityResolverLive),
495 Layer.provideMerge(SqlitePersistenceLayerLive),
496 ),
497);
498​
499const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
500const OrchestrationHttpErrorResponse = Schema.Struct({
501 error: Schema.String,
502});
503​
504const withProjectCliSessionToken = <A, E, R>(
505 authControlPlane: AuthControlPlaneShape,
506 run: (token: string) => Effect.Effect<A, E, R>,
507) =>
508 Effect.acquireUseRelease(
509 authControlPlane.issueSession({
510 role: "owner",
511 label: "t3 project cli",
512 }),
513 (issued) => run(issued.token),
514 (issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
515 );
516​
517const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
518 effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
519​
520const runLiveServerRequest = <A, E extends Error, R>(
521 request: HttpClientRequest.HttpClientRequest,
522 handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
523) =>
524 Effect.gen(function* () {
525 const httpClient = yield* HttpClient.HttpClient;
526 const response = yield* httpClient.execute(request);
527 return yield* handle(response);
528 }).pipe(withProjectCliLiveServerTimeout);
529​
530const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
531 HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
532​
533const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
534 HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
535 Effect.map((body) => body.error),
536 Effect.catch(() => Effect.succeed(null)),
537 Effect.map((body) => {
538 if (typeof body === "string" && body.trim().length > 0) {
539 return body;
540 }
541 return `Server request failed with status ${response.status}.`;
542 }),
543 );
544​
545const normalizeWorkspaceRootForProjectCommand = Effect.fn(
546 "normalizeWorkspaceRootForProjectCommand",
547)(function* (workspaceRoot: string) {
548 const workspacePaths = yield* WorkspacePaths;
549 return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
550});
551​
552const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
553 workspaceRoot: string,
554 explicitTitle?: string,
555) {
556 if (explicitTitle !== undefined) {
557 const trimmed = explicitTitle.trim();
558 if (trimmed.length > 0) {
559 return trimmed;
560 }
561 return yield* Effect.fail(new Error("Project title cannot be empty."));
562 }
563​
564 const path = yield* Path.Path;
565 const basename = path.basename(workspaceRoot).trim();
566 return basename.length > 0 ? basename : "project";
567});
568​
569const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
570 readonly snapshot: OrchestrationReadModel;
571 readonly identifier: string;
572}) {
573 const trimmedIdentifier = input.identifier.trim();
574 if (trimmedIdentifier.length === 0) {
575 return yield* Effect.fail(new Error("Project identifier cannot be empty."));
576 }
577​
578 const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
579 const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
580 if (exactIdMatch) {
581 return {
582 id: exactIdMatch.id,
583 title: exactIdMatch.title,
584 workspaceRoot: exactIdMatch.workspaceRoot,
585 } satisfies ProjectMutationTarget;
586 }
587​
588 const normalizedWorkspaceRootResult = yield* Effect.exit(
589 normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
590 );
591 const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
592 ? normalizedWorkspaceRootResult.value
593 : null;
594​
595 const exactWorkspaceMatch =
596 normalizedWorkspaceRoot === null
597 ? undefined
598 : activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
599​
600 const resolved = exactWorkspaceMatch;
601 if (!resolved) {
602 return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
603 }
604​
605 return {
606 id: resolved.id,
607 title: resolved.title,
608 workspaceRoot: resolved.workspaceRoot,
609 } satisfies ProjectMutationTarget;
610});
611​
612const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
613 runLiveServerRequest(
614 HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
615 HttpClientRequest.acceptJson,
616 HttpClientRequest.bearerToken(bearerToken),
617 ),
618 HttpClientResponse.matchStatus({
619 "2xx": decodeOrchestrationReadModelResponse,
620 orElse: (response) =>
621 readErrorMessageFromResponse(response).pipe(
622 Effect.flatMap((message) => Effect.fail(new Error(message))),
623 ),
624 }),
625 );
626​
627const dispatchLiveOrchestrationCommand = (
628 origin: string,
629 bearerToken: string,
630 command: ProjectCliDispatchCommand,
631) =>
632 HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
633 HttpClientRequest.acceptJson,
634 HttpClientRequest.bearerToken(bearerToken),
635 HttpClientRequest.bodyJson(command),
636 Effect.flatMap((request) =>
637 runLiveServerRequest(
638 request,
639 HttpClientResponse.matchStatus({
640 "2xx": () => Effect.void,
641 orElse: (response) =>
642 readErrorMessageFromResponse(response).pipe(
643 Effect.flatMap((message) => Effect.fail(new Error(message))),
644 ),
645 }),
646 ),
647 ),
648 );
649​
650const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
651 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
652 return yield* projectionSnapshotQuery.getSnapshot();
653});
654​
655const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
656 function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
657 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
658 if (Option.isNone(runtimeState)) {
659 return Option.none<{ readonly origin: string }>();
660 }
661​
662 const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
663 fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
664 Effect.as({
665 origin: runtimeState.value.origin,
666 }),
667 ),
668 );
669​
670 const attempted = yield* Effect.exit(attempt);
671 if (Exit.isSuccess(attempted)) {
672 return Option.some(attempted.value);
673 }
674​
675 yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
676 return Option.none<{ readonly origin: string }>();
677 },
678);
679​
680const runProjectMutation = Effect.fn("runProjectMutation")(function* (
681 flags: CliAuthLocationFlags,
682 run: (input: {
683 readonly snapshot: OrchestrationReadModel;
684 readonly dispatch: (
685 command: ProjectCliDispatchCommand,
686 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
687 readonly mode: ProjectCommandExecutionMode;
688 }) => Effect.Effect<
689 string,
690 Error,
691 FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
692 >,
693) {
694 const logLevel = yield* GlobalFlag.LogLevel;
695 const config = yield* resolveCliAuthConfig(flags, logLevel);
696 const minimumLogLevel = config.logLevel;
697​
698 return yield* Effect.gen(function* () {
699 const authControlPlane = yield* AuthControlPlane;
700 const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
701​
702 if (Option.isSome(liveMode)) {
703 return yield* withProjectCliSessionToken(authControlPlane, (token) =>
704 Effect.gen(function* () {
705 const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
706 const output = yield* run({
707 snapshot,
708 dispatch: (command) =>
709 dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
710 mode: "live",
711 });
712 yield* Console.log(output);
713 }),
714 );
715 }
716​
717 const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
718 Layer.provide(Layer.succeed(ServerConfig, config)),
719 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
720 );
721​
722 return yield* Effect.gen(function* () {
723 const snapshot = yield* getOfflineSnapshot();
724 const orchestrationEngine = yield* OrchestrationEngineService;
725 const output = yield* run({
726 snapshot,
727 dispatch: (command) => orchestrationEngine.dispatch(command),
728 mode: "offline",
729 });
730 yield* Console.log(output);
731 }).pipe(Effect.provide(offlineRuntimeLayer));
732 }).pipe(
733 Effect.provide(
734 Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
735 Layer.provideMerge(FetchHttpClient.layer),
736 Layer.provide(Layer.succeed(ServerConfig, config)),
737 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
738 ),
739 ),
740 );
741});
742​
743const sharedServerLocationFlags = {
744 baseDir: baseDirFlag,
745 devUrl: devUrlFlag,
746} as const;
747​
748const projectLocationFlags = {
749 baseDir: baseDirFlag,
750} as const;
751​
752const sharedServerCommandFlags = {
753 mode: modeFlag,
754 port: portFlag,
755 host: hostFlag,
756 baseDir: baseDirFlag,
757 cwd: Argument.string("cwd").pipe(
758 Argument.withDescription(
759 "Working directory for provider sessions (defaults to the current directory).",
760 ),
761 Argument.optional,
762 ),
763 devUrl: devUrlFlag,
764 noBrowser: noBrowserFlag,
765 bootstrapFd: bootstrapFdFlag,
766 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
767 logWebSocketEvents: logWebSocketEventsFlag,
768} as const;
769​
770const authLocationFlags = sharedServerLocationFlags;
771​
772const ttlFlag = Flag.string("ttl").pipe(
773 Flag.withSchema(DurationFromString),
774 Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
775 Flag.optional,
776);
777​
778const jsonFlag = Flag.boolean("json").pipe(
779 Flag.withDescription("Emit JSON instead of human-readable output."),
780 Flag.withDefault(false),
781);
782​
783const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
784 Flag.withDescription("Role for the issued bearer session."),
785 Flag.withDefault("owner"),
786);
787​
788const labelFlag = Flag.string("label").pipe(
789 Flag.withDescription("Optional human-readable label."),
790 Flag.optional,
791);
792​
793const subjectFlag = Flag.string("subject").pipe(
794 Flag.withDescription("Optional session subject."),
795 Flag.optional,
796);
797​
798const baseUrlFlag = Flag.string("base-url").pipe(
799 Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
800 Flag.optional,
801);
802​
803const tokenOnlyFlag = Flag.boolean("token-only").pipe(
804 Flag.withDescription("Print only the issued bearer token."),
805 Flag.withDefault(false),
806);
807​
808const pairingCreateCommand = Command.make("create", {
809 ...authLocationFlags,
810 ttl: ttlFlag,
811 label: labelFlag,
812 baseUrl: baseUrlFlag,
813 json: jsonFlag,
814}).pipe(
815 Command.withDescription("Issue a new client pairing token."),
816 Command.withHandler((flags) =>
817 runWithAuthControlPlane(
818 flags,
819 (authControlPlane) =>
820 Effect.gen(function* () {
821 const issued = yield* authControlPlane.createPairingLink({
822 role: "client",
823 subject: "one-time-token",
824 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
825 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
826 });
827 const output = formatIssuedPairingCredential(issued, {
828 json: flags.json,
829 ...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
830 });
831 yield* Console.log(output);
832 }),
833 {
834 quietLogs: flags.json,
835 },
836 ),
837 ),
838);
839​
840const pairingListCommand = Command.make("list", {
841 ...authLocationFlags,
842 json: jsonFlag,
843}).pipe(
844 Command.withDescription("List active client pairing tokens without revealing their secrets."),
845 Command.withHandler((flags) =>
846 runWithAuthControlPlane(
847 flags,
848 (authControlPlane) =>
849 Effect.gen(function* () {
850 const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
851 yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
852 }),
853 {
854 quietLogs: flags.json,
855 },
856 ),
857 ),
858);
859​
860const pairingRevokeCommand = Command.make("revoke", {
861 ...authLocationFlags,
862 id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
863}).pipe(
864 Command.withDescription("Revoke an active client pairing token."),
865 Command.withHandler((flags) =>
866 runWithAuthControlPlane(flags, (authControlPlane) =>
867 Effect.gen(function* () {
868 const revoked = yield* authControlPlane.revokePairingLink(flags.id);
869 yield* Console.log(
870 revoked
871 ? `Revoked pairing credential ${flags.id}.\n`
872 : `No active pairing credential found for ${flags.id}.\n`,
873 );
874 }),
875 ),
876 ),
877);
878​
879const pairingCommand = Command.make("pairing").pipe(
880 Command.withDescription("Manage one-time client pairing tokens."),
881 Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
882);
883​
884const sessionIssueCommand = Command.make("issue", {
885 ...authLocationFlags,
886 ttl: ttlFlag,
887 role: sessionRoleFlag,
888 label: labelFlag,
889 subject: subjectFlag,
890 tokenOnly: tokenOnlyFlag,
891 json: jsonFlag,
892}).pipe(
893 Command.withDescription("Issue a bearer session token for headless or remote clients."),
894 Command.withHandler((flags) =>
895 runWithAuthControlPlane(
896 flags,
897 (authControlPlane) =>
898 Effect.gen(function* () {
899 const issued = yield* authControlPlane.issueSession({
900 role: flags.role,
901 ...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
902 ...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
903 ...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
904 });
905 yield* Console.log(
906 formatIssuedSession(issued, {
907 json: flags.json,
908 tokenOnly: flags.tokenOnly,
909 }),
910 );
911 }),
912 {
913 quietLogs: flags.json || flags.tokenOnly,
914 },
915 ),
916 ),
917);
918​
919const sessionListCommand = Command.make("list", {
920 ...authLocationFlags,
921 json: jsonFlag,
922}).pipe(
923 Command.withDescription("List active sessions without revealing bearer tokens."),
924 Command.withHandler((flags) =>
925 runWithAuthControlPlane(
926 flags,
927 (authControlPlane) =>
928 Effect.gen(function* () {
929 const sessions = yield* authControlPlane.listSessions();
930 yield* Console.log(formatSessionList(sessions, { json: flags.json }));
931 }),
932 {
933 quietLogs: flags.json,
934 },
935 ),
936 ),
937);
938​
939const sessionRevokeCommand = Command.make("revoke", {
940 ...authLocationFlags,
941 sessionId: Argument.string("session-id").pipe(
942 Argument.withDescription("Session id to revoke."),
943 Argument.withSchema(AuthSessionId),
944 ),
945}).pipe(
946 Command.withDescription("Revoke an active session."),
947 Command.withHandler((flags) =>
948 runWithAuthControlPlane(flags, (authControlPlane) =>
949 Effect.gen(function* () {
950 const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
951 yield* Console.log(
952 revoked
953 ? `Revoked session ${flags.sessionId}.\n`
954 : `No active session found for ${flags.sessionId}.\n`,
955 );
956 }),
957 ),
958 ),
959);
960​
961const sessionCommand = Command.make("session").pipe(
962 Command.withDescription("Manage bearer sessions."),
963 Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
964);
965​
966const authCommand = Command.make("auth").pipe(
967 Command.withDescription("Manage the local auth control plane for headless deployments."),
968 Command.withSubcommands([pairingCommand, sessionCommand]),
969);
970​
971const projectAddCommand = Command.make("add", {
972 ...projectLocationFlags,
973 workspaceRoot: Argument.string("path").pipe(
974 Argument.withDescription("Workspace root to add as a project."),
975 ),
976 title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
977}).pipe(
978 Command.withDescription("Add a project."),
979 Command.withHandler((flags) =>
980 runProjectMutation(
981 flags,
982 Effect.fn("projectAddMutation")(function* ({
983 snapshot,
984 dispatch,
985 }: {
986 readonly snapshot: OrchestrationReadModel;
987 readonly dispatch: (
988 command: ProjectCliDispatchCommand,
989 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
990 }) {
991 const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
992 const existingProject = snapshot.projects.find(
993 (project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
994 );
995 if (existingProject) {
996 return yield* Effect.fail(
997 new Error(`An active project already exists for '${workspaceRoot}'.`),
998 );
999 }
1000​
1001 const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
1002 const projectId = ProjectId.make(crypto.randomUUID());
1003 yield* dispatch({
1004 type: "project.create",
1005 commandId: CommandId.make(crypto.randomUUID()),
1006 projectId,
1007 title,
1008 workspaceRoot,
1009 defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
1010 createdAt: new Date().toISOString(),
1011 });
1012 return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
1013 }),
1014 ),
1015 ),
1017​
1018const projectRemoveCommand = Command.make("remove", {
1019 ...projectLocationFlags,
1020 project: Argument.string("project").pipe(
1021 Argument.withDescription("Project id or workspace root to remove."),
1022 ),
1023}).pipe(
1024 Command.withDescription("Remove a project."),
1025 Command.withHandler((flags) =>
1026 runProjectMutation(
1027 flags,
1028 Effect.fn("projectRemoveMutation")(function* ({
1029 snapshot,
1030 dispatch,
1031 }: {
1032 readonly snapshot: OrchestrationReadModel;
1033 readonly dispatch: (
1034 command: ProjectCliDispatchCommand,
1035 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
1036 }) {
1037 const project = yield* findActiveProjectTarget({
1038 snapshot,
1039 identifier: flags.project,
1040 });
1041 yield* dispatch({
1042 type: "project.delete",
1043 commandId: CommandId.make(crypto.randomUUID()),
1044 projectId: project.id,
1045 });
1046 return `Removed project ${project.id} (${project.title}).`;
1047 }),
1048 ),
1049 ),
1051​
1052const projectRenameCommand = Command.make("rename", {
1053 ...projectLocationFlags,
1054 project: Argument.string("project").pipe(
1055 Argument.withDescription("Project id or workspace root to rename."),
1056 ),
1057 title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
1058}).pipe(
1059 Command.withDescription("Rename a project."),
1060 Command.withHandler((flags) =>
1061 runProjectMutation(
1062 flags,
1063 Effect.fn("projectRenameMutation")(function* ({
1064 snapshot,
1065 dispatch,
1066 }: {
1067 readonly snapshot: OrchestrationReadModel;
1068 readonly dispatch: (
1069 command: ProjectCliDispatchCommand,
1070 ) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
1071 }) {
1072 const project = yield* findActiveProjectTarget({
1073 snapshot,
1074 identifier: flags.project,
1075 });
1076 const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
1077 if (nextTitle === project.title) {
1078 return `Project ${project.id} is already named ${nextTitle}.`;
1080​
1081 yield* dispatch({
1082 type: "project.meta.update",
1083 commandId: CommandId.make(crypto.randomUUID()),
1084 projectId: project.id,
1085 title: nextTitle,
1086 });
1087 return `Renamed project ${project.id} to ${nextTitle}.`;
1088 }),
1089 ),
1090 ),
1092​
1093const projectCommand = Command.make("project").pipe(
1094 Command.withDescription("Manage projects."),
1095 Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
1097​
1098const runServerCommand = (
1099 flags: CliServerFlags,
1100 options?: {
1101 readonly startupPresentation?: StartupPresentation;
1102 readonly forceAutoBootstrapProjectFromCwd?: boolean;
1103 },
1104) =>
1105 Effect.gen(function* () {
1106 const logLevel = yield* GlobalFlag.LogLevel;
1107 const config = yield* resolveServerConfig(flags, logLevel, options);
1108 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
1109 });
1110​
1111const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
1112 Command.withDescription("Run the T3 Code server."),
1113 Command.withHandler((flags) => runServerCommand(flags)),
1115​
1116const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
1117 Command.withDescription(
1118 "Run the T3 Code server without opening a browser and print headless pairing details.",
1119 ),
1120 Command.withHandler((flags) =>
1121 runServerCommand(flags, {
1122 startupPresentation: "headless",
1123 forceAutoBootstrapProjectFromCwd: false,
1124 }),
1125 ),
1127​
1128export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
1129 Command.withDescription("Run the T3 Code server."),
1130 Command.withHandler((flags) => runServerCommand(flags)),
1131 Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),