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

cli.ts

1,157 lines39.3 KB

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