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