@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 1,057 lines 38.2 KB
Raw
1 import {
2 OrchestratorMcpFailure,
3 OrchestratorMcpThreadListResult,
4 OrchestratorMcpThreadReadResult,
5 OrchestratorMcpThreadSendResult,
6 OrchestratorMcpThreadWaitResult,
7 ProjectId,
8 RunId,
9 ThreadId,
10 TrimmedNonEmptyString,
11 type OrchestratorMcpThreadDetail,
12 type OrchestratorMcpThreadListItem,
13 type OrchestratorMcpThreadRun,
14 type OrchestratorMcpThreadStatus,
15 type OrchestratorMcpThreadTimelineItem,
16 } from "@t3tools/contracts";
17 import * as HostProcess from "@t3tools/shared/HostProcess";
18 import * as Console from "effect/Console";
19 import * as Effect from "effect/Effect";
20 import * as FileSystem from "effect/FileSystem";
21 import * as Layer from "effect/Layer";
22 import * as Option from "effect/Option";
23 import * as Path from "effect/Path";
24 import * as References from "effect/References";
25 import * as Runtime from "effect/Runtime";
26 import * as Schema from "effect/Schema";
27 import * as Stdio from "effect/Stdio";
28 import * as Stream from "effect/Stream";
29 import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
30
31 import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
32 import * as ServerConfig from "../config.ts";
33 import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
34 import { expandHomePath } from "../os-jank.ts";
35 import * as ProcessRunner from "../processRunner.ts";
36 import { readLiveServerRuntimeState } from "../serverRuntimeState.ts";
37 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
38
39 /**
40 * Short enough that a run which stops to ask the user something is noticed
41 * soon, since `t3_thread_wait` only returns on a terminal run.
42 */
43 const WAIT_SLICE_MS = 15_000;
44 const WAKE_GRACE_MS = 10_000;
45 const WAKE_POLL_MS = 500;
46 const TERMINAL_RUN_STATUSES = new Set<OrchestratorMcpThreadRun["status"]>([
47 "completed",
48 "failed",
49 "cancelled",
50 "interrupted",
51 "rolled_back",
52 ]);
53 const READ_PAGE_LIMIT = 100;
54 const READ_ITEM_MAX_CHARS = 20_000;
55 const TITLE_MAX_CHARS = 80;
56
57 export class ThreadServerNotRunningError extends Schema.TaggedError<ThreadServerNotRunningError>()(
58 "ThreadServerNotRunningError",
59 { baseDir: Schema.String },
60 ) {
61 override readonly [Runtime.errorReported] = false;
62 override get message(): string {
63 return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`;
64 }
65 }
66
67 export class ThreadServerUnreachableError extends Schema.TaggedError<ThreadServerUnreachableError>()(
68 "ThreadServerUnreachableError",
69 { origin: Schema.String, cause: Schema.Defect() },
70 ) {
71 override readonly [Runtime.errorReported] = false;
72 override get message(): string {
73 const reason = this.cause instanceof Error ? ` ${this.cause.message}` : "";
74 return `Could not reach the T3 Code server at ${this.origin}.${reason}`;
75 }
76 }
77
78 export class ThreadToolFailedError extends Schema.TaggedError<ThreadToolFailedError>()(
79 "ThreadToolFailedError",
80 { tool: Schema.String, detail: Schema.String },
81 ) {
82 override readonly [Runtime.errorReported] = false;
83 override get message(): string {
84 return this.detail;
85 }
86 }
87
88 export class ThreadUsageError extends Schema.TaggedError<ThreadUsageError>()("ThreadUsageError", {
89 detail: Schema.String,
90 }) {
91 override readonly [Runtime.errorReported] = false;
92 override get message(): string {
93 return this.detail;
94 }
95 }
96
97 export class ThreadProjectNotFoundError extends Schema.TaggedError<ThreadProjectNotFoundError>()(
98 "ThreadProjectNotFoundError",
99 { identifier: Schema.String },
100 ) {
101 override readonly [Runtime.errorReported] = false;
102 override get message(): string {
103 return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`;
104 }
105 }
106
107 /** Exit code 2 lets a script tell "needs a human" apart from a failed run. */
108 export class ThreadNeedsInputError extends Schema.TaggedError<ThreadNeedsInputError>()(
109 "ThreadNeedsInputError",
110 { threadId: ThreadId },
111 ) {
112 override readonly [Runtime.errorReported] = false;
113 override readonly [Runtime.errorExitCode] = 2;
114
115 override get message(): string {
116 return `Thread ${this.threadId} is waiting for an answer. Open it in T3 Code to respond.`;
117 }
118 }
119
120 export class ThreadRunEndedError extends Schema.TaggedError<ThreadRunEndedError>()(
121 "ThreadRunEndedError",
122 { threadId: ThreadId, status: Schema.String, error: Schema.optional(Schema.String) },
123 ) {
124 override readonly [Runtime.errorReported] = false;
125 override get message(): string {
126 const reason = this.error === undefined ? "." : `: ${this.error}`;
127 return `Thread ${this.threadId} stopped with status ${this.status}${reason}`;
128 }
129 }
130
131 const ThreadCliError = Schema.Union([
132 ThreadServerNotRunningError,
133 ThreadServerUnreachableError,
134 ThreadToolFailedError,
135 ThreadUsageError,
136 ThreadProjectNotFoundError,
137 ThreadNeedsInputError,
138 ThreadRunEndedError,
139 ]);
140 const isThreadCliError = Schema.is(ThreadCliError);
141
142 /**
143 * These errors are expected outcomes for a script, so they print as one line
144 * on stderr instead of the runtime's logged stack trace.
145 */
146 const reportThreadErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
147 effect.pipe(
148 Effect.tapError((error) =>
149 isThreadCliError(error) ? Console.error(error.message) : Effect.void,
150 ),
151 );
152
153 const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure));
154 const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
155 const printJson = (value: unknown) => Console.log(encodeJson(value));
156
157 const ToolResult = Schema.Struct({
158 isError: Schema.optional(Schema.Boolean),
159 structuredContent: Schema.optional(Schema.Unknown),
160 content: Schema.optional(
161 Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })),
162 ),
163 });
164
165 const decodeToolResult = Schema.decodeUnknownEffect(ToolResult);
166
167 const ProjectListResult = Schema.Struct({
168 projects: Schema.Array(
169 Schema.Struct({ id: ProjectId, title: Schema.String, workspaceRoot: Schema.String }),
170 ),
171 nextCursor: Schema.NullOr(Schema.Int),
172 });
173
174 const ThreadLaunchResult = Schema.Struct({
175 threadId: ThreadId,
176 projectId: ProjectId,
177 runId: Schema.NullOr(RunId),
178 });
179
180 const toolFailureDetail = (result: typeof ToolResult.Type) => {
181 const text = result.content?.find((part) => part.text !== undefined)?.text ?? "";
182 return Option.match(decodeFailureText(text), {
183 onNone: () => text || "The tool call failed.",
184 onSome: (failure) => failure.message,
185 });
186 };
187
188 const makeThreadTools = (session: McpToolSession, origin: string) => {
189 const unexpected = (tool: string) =>
190 new ThreadToolFailedError({
191 tool,
192 detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`,
193 });
194 return {
195 call: Effect.fn("cli.thread.callTool")(function* <S extends Schema.Decoder<unknown>>(
196 tool: string,
197 args: Readonly<Record<string, unknown>>,
198 schema: S,
199 ): Effect.fn.Return<S["Type"], ThreadServerUnreachableError | ThreadToolFailedError> {
200 const raw = yield* session
201 .call(tool, args)
202 .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
203 const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool)));
204 if (result.isError === true) {
205 return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) });
206 }
207 return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe(
208 Effect.mapError(() => unexpected(tool)),
209 );
210 }),
211 };
212 };
213 export type ThreadTools = ReturnType<typeof makeThreadTools>;
214
215 /**
216 * Signs in as a short-lived MCP client of the running server, the same way an
217 * outside agent does, and revokes that session when the command ends.
218 */
219 const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E, R>(
220 flags: { readonly baseDir: Option.Option<string>; readonly json: boolean },
221 run: (tools: ThreadTools) => Effect.Effect<A, E, R>,
222 ) {
223 const logLevel = yield* GlobalFlag.LogLevel;
224 const config = yield* resolveCliAuthConfig(flags, logLevel, { quietLogs: flags.json });
225 const minimumLogLevel = flags.json ? "Error" : config.logLevel;
226 return yield* Effect.gen(function* () {
227 const runtimeState = yield* readLiveServerRuntimeState(config.serverRuntimeStatePath);
228 if (Option.isNone(runtimeState)) {
229 return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
230 }
231 const origin = runtimeState.value.origin;
232 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
233 const issued = yield* Effect.acquireRelease(
234 environmentAuth.issueMcpClientSession({
235 label: "t3 thread cli",
236 // The CLI runs as the machine's owner. New threads still start at
237 // the project's default mode, never at this ceiling by default.
238 access: "full-access",
239 peerLink: false,
240 client: { deviceType: "bot" },
241 }),
242 (session) =>
243 environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })),
244 );
245 const session = yield* mcpToolSession({
246 endpoint: new URL("/mcp", origin).href,
247 authorization: `Bearer ${issued.token}`,
248 clientName: "t3-thread-cli",
249 }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
250 return yield* run(makeThreadTools(session, origin));
251 }).pipe(
252 Effect.scoped,
253 Effect.provideService(References.MinimumLogLevel, minimumLogLevel),
254 Effect.provide(
255 EnvironmentAuth.layerRuntime.pipe(
256 Layer.provide(ServerConfig.layer(config)),
257 Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
258 ),
259 ),
260 );
261 });
262
263 const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) {
264 const text =
265 argument === "-"
266 ? yield* Stdio.Stdio.pipe(
267 Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
268 )
269 : argument;
270 if (text.trim().length === 0) {
271 return yield* new ThreadUsageError({ detail: "The message is empty." });
272 }
273 return text;
274 });
275
276 const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) {
277 const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = [];
278 let cursor: number | null = 0;
279 while (cursor !== null) {
280 const page: typeof ProjectListResult.Type = yield* tools.call(
281 "t3_project_list",
282 { cursor, limit: 100 },
283 ProjectListResult,
284 );
285 projects.push(...page.projects);
286 cursor = page.nextCursor;
287 }
288 return projects;
289 });
290
291 /** The checkouts of the git repository at `directory`, or none outside a repository. */
292 const listGitCheckouts = Effect.fn("cli.thread.listGitCheckouts")(function* (directory: string) {
293 const processRunner = yield* ProcessRunner.ProcessRunner;
294 const list = (args: ReadonlyArray<string>) =>
295 processRunner
296 .run({ command: "git", args: ["worktree", "list", "--porcelain", ...args], cwd: directory })
297 .pipe(
298 Effect.option,
299 Effect.map((result) =>
300 Option.isSome(result) && result.value.code === 0 ? result.value.stdout : undefined,
301 ),
302 );
303 // Pre-2.36 Git rejects worktree list -z; normalize its line output to NUL records.
304 const stdout = (yield* list(["-z"])) ?? (yield* list([]))?.replaceAll("\n", "\0") ?? "";
305 return stdout.split("\0\0").flatMap((record) => {
306 const [first = "", ...attributes] = record.split("\0");
307 return first.startsWith("worktree ") && !attributes.includes("bare")
308 ? [first.slice("worktree ".length)]
309 : [];
310 });
311 });
312
313 /**
314 * A project id, or a path inside a project's folder (deepest project wins).
315 * A path inside a git worktree resolves as the same path in the repository's
316 * other checkouts.
317 */
318 export const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
319 tools: ThreadTools,
320 identifier: string,
321 ) {
322 const projects = yield* listAllProjects(tools);
323 const byId = projects.find((project) => project.id === identifier);
324 if (byId !== undefined) return byId;
325
326 const path = yield* Path.Path;
327 const fileSystem = yield* FileSystem.FileSystem;
328 // Stored roots keep the path the project was added with, which may pass
329 // through a symlink (macOS /tmp), so both sides compare as real paths.
330 const realPath = (value: string) =>
331 fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
332 const target = yield* realPath(
333 path.resolve(yield* HostProcess.WorkingDirectory, yield* expandHomePath(identifier)),
334 );
335 const roots = yield* Effect.forEach(projects, (project) =>
336 Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
337 );
338 const contains = (root: string, candidate: string) => {
339 const relative = path.relative(root, candidate);
340 return (
341 relative === "" ||
342 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
343 );
344 };
345 const deepestContaining = (candidate: string) =>
346 roots
347 .filter(({ root }) => contains(root, candidate))
348 .toSorted((left, right) => right.root.length - left.root.length)[0]?.project;
349
350 const containing = deepestContaining(target);
351 if (containing !== undefined) return containing;
352 const targetInfo = yield* fileSystem.stat(target).pipe(Effect.option);
353 const gitDirectory =
354 Option.isSome(targetInfo) && targetInfo.value.type === "File" ? path.dirname(target) : target;
355 const listed = yield* listGitCheckouts(gitDirectory).pipe(
356 Effect.flatMap((paths) => Effect.forEach(paths, realPath)),
357 Effect.provide(ProcessRunner.layer),
358 );
359 const ownCheckout = listed
360 .filter((checkout) => contains(checkout, target))
361 .toSorted((left, right) => right.length - left.length)[0];
362 if (ownCheckout === undefined) {
363 return yield* new ThreadProjectNotFoundError({ identifier });
364 }
365 const relative = path.relative(ownCheckout, target);
366 const matches = new Map<ProjectId, (typeof projects)[number]>();
367 for (const checkout of listed) {
368 if (checkout === ownCheckout) continue;
369 const project = deepestContaining(path.join(checkout, relative));
370 if (project !== undefined) matches.set(project.id, project);
371 }
372 const [match, ...others] = matches.values();
373 if (match === undefined) {
374 return yield* new ThreadProjectNotFoundError({ identifier });
375 }
376 if (others.length > 0) {
377 const names = [match, ...others].map((project) => `${project.title} (${project.id})`);
378 return yield* new ThreadUsageError({
379 detail: `'${identifier}' is in a git worktree shared by several projects: ${names.join(", ")}. Pass a project id instead.`,
380 });
381 }
382 return match;
383 });
384
385 /** Every item on a timeline view, oldest first. */
386 const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
387 tools: ThreadTools,
388 threadId: ThreadId,
389 view: "messages" | "activity",
390 ) {
391 const items: Array<OrchestratorMcpThreadTimelineItem> = [];
392 let afterPosition: number | undefined;
393 let page: OrchestratorMcpThreadReadResult;
394 do {
395 page = yield* tools.call(
396 "t3_thread_read",
397 {
398 threadId,
399 view,
400 limit: READ_PAGE_LIMIT,
401 maxCharsPerItem: READ_ITEM_MAX_CHARS,
402 runLimit: 1,
403 ...(afterPosition === undefined ? {} : { afterPosition }),
404 },
405 OrchestratorMcpThreadReadResult,
406 );
407 items.push(...page.items);
408 afterPosition = page.nextPosition ?? undefined;
409 } while (page.hasMore && afterPosition !== undefined);
410 return { thread: page.thread, items };
411 });
412
413 /**
414 * The latest `count` user and assistant messages, oldest first. Positions
415 * count every timeline item, so the read starts near the end and widens
416 * backward only while tool and plan items leave too few messages.
417 */
418 export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(function* (
419 tools: ThreadTools,
420 threadId: ThreadId,
421 count: number,
422 ) {
423 let { thread } = yield* tools.call(
424 "t3_thread_read",
425 { threadId, limit: 1, runLimit: 1 },
426 OrchestratorMcpThreadReadResult,
427 );
428 let messages: Array<OrchestratorMcpThreadTimelineItem> = [];
429 // The newest window has no upper bound, so items added since the first
430 // read are still shown.
431 let before: number | undefined;
432 let start = thread.itemCount;
433 let span = Math.max(count, READ_PAGE_LIMIT);
434 do {
435 const end = before;
436 start = Math.max(0, start - span);
437 const window: Array<OrchestratorMcpThreadTimelineItem> = [];
438 let afterPosition = start - 1;
439 let page: OrchestratorMcpThreadReadResult;
440 do {
441 page = yield* tools.call(
442 "t3_thread_read",
443 {
444 threadId,
445 view: "messages",
446 limit: READ_PAGE_LIMIT,
447 maxCharsPerItem: READ_ITEM_MAX_CHARS,
448 runLimit: 1,
449 ...(afterPosition < 0 ? {} : { afterPosition }),
450 },
451 OrchestratorMcpThreadReadResult,
452 );
453 window.push(
454 ...page.items.filter(
455 (item) =>
456 (item.type === "user_message" || item.type === "assistant_message") &&
457 (end === undefined || item.position < end),
458 ),
459 );
460 afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY;
461 } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1);
462 thread = page.thread;
463 // A window can hold the whole --messages count, too many to spread as arguments.
464 messages = window.concat(messages);
465 before = start;
466 span *= 2;
467 } while (messages.length < count && start > 0);
468 return { thread, messages: messages.slice(Math.max(0, messages.length - count)) };
469 });
470
471 /** Item text past the read's per-item cap. */
472 const readFullText = Effect.fn("cli.thread.readFullText")(function* (
473 tools: ThreadTools,
474 threadId: ThreadId,
475 item: OrchestratorMcpThreadTimelineItem,
476 ) {
477 let text = item.text ?? "";
478 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
479 while (nextTextOffset !== null) {
480 const page = yield* tools.call(
481 "t3_thread_read",
482 {
483 threadId,
484 itemId: item.itemId,
485 textOffset: nextTextOffset,
486 runLimit: 1,
487 maxCharsPerItem: READ_ITEM_MAX_CHARS,
488 },
489 OrchestratorMcpThreadReadResult,
490 );
491 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
492 if (chunk === undefined) break;
493 text += chunk.text ?? "";
494 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
495 }
496 return text;
497 });
498
499 /** The run's last assistant message, or its last error when it did not complete. */
500 const runResultText = Effect.fn("cli.thread.runResultText")(function* (
501 tools: ThreadTools,
502 threadId: ThreadId,
503 runId: RunId,
504 type: "assistant_message" | "error",
505 ) {
506 const { items } = yield* readTimeline(
507 tools,
508 threadId,
509 type === "assistant_message" ? "messages" : "activity",
510 );
511 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
512 return item === undefined ? null : yield* readFullText(tools, threadId, item);
513 });
514
515 /** The latest run's last error once it ended without completing, else null. */
516 export const latestRunError = Effect.fn("cli.thread.latestRunError")(function* (
517 tools: ThreadTools,
518 thread: Pick<OrchestratorMcpThreadDetail, "threadId" | "status" | "latestRunId">,
519 ) {
520 const { status, latestRunId } = thread;
521 if (latestRunId === null || status === "idle" || status === "completed") return null;
522 if (!TERMINAL_RUN_STATUSES.has(status)) return null;
523 return yield* runResultText(tools, thread.threadId, latestRunId, "error");
524 });
525
526 type WaitOutcome =
527 | {
528 readonly type: "ended";
529 readonly runId: RunId | null;
530 readonly status: OrchestratorMcpThreadStatus;
531 readonly output?: Schema.Json;
532 }
533 | { readonly type: "needs_input" };
534
535 /**
536 * Whether the thread has nothing left to do: no active run and no delegated
537 * or background work. Only then is the work a later wait settles on this
538 * send's own.
539 */
540 const threadIsIdle = Effect.fn("cli.thread.threadIsIdle")(function* (
541 tools: ThreadTools,
542 threadId: ThreadId,
543 ) {
544 const waited = yield* tools.call(
545 "t3_thread_wait",
546 { threadId, timeoutMs: 1, untilDelegatedWorkSettled: true },
547 OrchestratorMcpThreadWaitResult,
548 );
549 return !waited.timedOut;
550 });
551
552 /**
553 * The runs after `runId`, and whether one holds a message someone sent.
554 * Background work wakes a run with a notification, never a user message, so
555 * such a run is another request and its reply is not this one's.
556 */
557 const runsAfter = Effect.fn("cli.thread.runsAfter")(function* (
558 tools: ThreadTools,
559 threadId: ThreadId,
560 runId: RunId,
561 ) {
562 const { recentRuns } = yield* tools.call(
563 "t3_thread_read",
564 { threadId, limit: 1, runLimit: 50 },
565 OrchestratorMcpThreadReadResult,
566 );
567 const own = recentRuns.find((run) => run.runId === runId);
568 if (own === undefined) return { later: [], sent: true };
569 const later = recentRuns.filter((run) => run.ordinal > own.ordinal);
570 if (later.length === 0) return { later, sent: false };
571 const { items } = yield* readTimeline(tools, threadId, "messages");
572 const sent = items.some(
573 (item) => item.type === "user_message" && later.some((run) => run.runId === item.runId),
574 );
575 return { later, sent };
576 });
577
578 /**
579 * Waits for this exact run, following a restart to its continuation, so a
580 * message another client sends meanwhile cannot stand in for its result.
581 * With `followWakes`, a completed run is followed further to the runs its
582 * background work wakes, as long as no one else sends to the thread.
583 */
584 export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
585 tools: ThreadTools,
586 threadId: ThreadId,
587 runId: RunId,
588 followWakes = false,
589 ) {
590 const waitSlice = (timeoutMs: number, untilDelegatedWorkSettled?: true) =>
591 tools.call(
592 "t3_thread_wait",
593 {
594 threadId,
595 runId,
596 timeoutMs,
597 ...(untilDelegatedWorkSettled ? { untilDelegatedWorkSettled } : {}),
598 },
599 OrchestratorMcpThreadWaitResult,
600 );
601 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
602 ({
603 type: "ended",
604 runId: waited.runId,
605 status: waited.status,
606 ...(waited.output === undefined ? {} : { output: waited.output }),
607 }) satisfies WaitOutcome;
608 const ownRun = Effect.gen(function* () {
609 while (true) {
610 const waited = yield* waitSlice(WAIT_SLICE_MS);
611 if (!waited.timedOut) return ended(waited);
612 // A pending request on this run, or on an earlier run this one is queued
613 // behind, blocks it until someone answers.
614 const { thread } = yield* tools.call(
615 "t3_thread_read",
616 { threadId, limit: 1, runLimit: 1 },
617 OrchestratorMcpThreadReadResult,
618 );
619 if (thread.pendingRequestCount > 0) {
620 // The count is thread-wide: if this run ended since the slice, the
621 // request belongs to a later run.
622 const recheck = yield* waitSlice(1);
623 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
624 }
625 }
626 });
627 const outcome = yield* ownRun;
628 if (!followWakes || outcome.type !== "ended" || outcome.status !== "completed") return outcome;
629 const finalRunId = outcome.runId ?? runId;
630 // A provider records the run that background work wakes only after that
631 // work has ended, so the thread briefly looks settled in between.
632 const wakeRunRecorded = Effect.gen(function* () {
633 for (let waited = 0; waited < WAKE_GRACE_MS; waited += WAKE_POLL_MS) {
634 yield* Effect.sleep(WAKE_POLL_MS);
635 const after = yield* runsAfter(tools, threadId, finalRunId);
636 if (after.sent) return false;
637 if (after.later.length > 0) return true;
638 }
639 return false;
640 });
641 let workOutlivedRun = false;
642 while (true) {
643 const waited = yield* waitSlice(WAIT_SLICE_MS, true);
644 // `resultRun` is the thread's latest finished run, whoever sent it.
645 const result = waited.timedOut ? undefined : waited.resultRun;
646 const after = yield* runsAfter(tools, threadId, finalRunId);
647 if (after.sent) return outcome;
648 if (!waited.timedOut) {
649 if (result !== undefined && after.later.some((run) => run.runId === result.runId)) {
650 // A run that work woke was not asked for the result; the run before it holds it.
651 return {
652 type: "ended",
653 runId: result.runId,
654 status: result.status,
655 ...(outcome.output === undefined ? {} : { output: outcome.output }),
656 } satisfies WaitOutcome;
657 }
658 if (!workOutlivedRun) return outcome;
659 if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue;
660 if (after.later.length === 0 && (yield* wakeRunRecorded)) continue;
661 return outcome;
662 }
663 workOutlivedRun = true;
664 const { thread } = yield* tools.call(
665 "t3_thread_read",
666 { threadId, limit: 1, runLimit: 1 },
667 OrchestratorMcpThreadReadResult,
668 );
669 // Earlier runs have ended, so the request is on a run this one's work woke.
670 if (thread.pendingRequestCount > 0) return { type: "needs_input" } satisfies WaitOutcome;
671 }
672 });
673
674 /**
675 * With --json the result always reaches stdout, so a script keeps the thread
676 * id even when the run fails.
677 */
678 const finishRun = Effect.fn("cli.thread.finishRun")(function* (
679 tools: ThreadTools,
680 input: {
681 readonly threadId: ThreadId;
682 readonly runId: RunId;
683 readonly json: boolean;
684 readonly followWakes: boolean;
685 },
686 ) {
687 const outcome = yield* waitForRun(tools, input.threadId, input.runId, input.followWakes);
688 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
689 const status = outcome.type === "ended" ? outcome.status : "waiting";
690 const reply =
691 status === "completed"
692 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
693 : null;
694 const error =
695 status === "completed" || status === "waiting"
696 ? null
697 : yield* runResultText(tools, input.threadId, runId, "error");
698 if (input.json) {
699 const output = outcome.type === "ended" ? outcome.output : undefined;
700 yield* printJson({
701 threadId: input.threadId,
702 runId,
703 status,
704 reply,
705 error,
706 ...(output === undefined ? {} : { output }),
707 });
708 } else if (reply !== null) {
709 yield* Console.log(reply);
710 }
711 if (outcome.type === "needs_input") {
712 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
713 }
714 if (status !== "completed") {
715 return yield* new ThreadRunEndedError({
716 threadId: input.threadId,
717 status,
718 ...(error === null ? {} : { error }),
719 });
720 }
721 });
722
723 export const titleFromMessage = (message: string) => {
724 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
725 if (firstLine.length <= TITLE_MAX_CHARS) return firstLine;
726 let end = TITLE_MAX_CHARS - 1;
727 const previous = firstLine.charCodeAt(end - 1);
728 const next = firstLine.charCodeAt(end);
729 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
730 end -= 1;
731 }
732 return `${firstLine.slice(0, end).trimEnd()}…`;
733 };
734
735 const launchWorkspaceStrategy = (input: {
736 readonly worktree: Option.Option<string>;
737 readonly branch: Option.Option<string>;
738 }) =>
739 Option.match(input.worktree, {
740 onNone: () =>
741 Option.isSome(input.branch)
742 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
743 : Effect.void,
744 onSome: (baseRef) =>
745 Effect.succeed({
746 type: "worktree" as const,
747 baseRef,
748 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
749 }),
750 });
751
752 /**
753 * Options are model specific, so they need an explicit model. `true` and
754 * `false` become booleans because boolean options such as fastMode only match
755 * a boolean.
756 */
757 export const launchModelSelection = Effect.fn("cli.thread.launchModelSelection")(function* (input: {
758 readonly provider: Option.Option<string>;
759 readonly model: Option.Option<string>;
760 readonly option: ReadonlyArray<string>;
761 }) {
762 if (Option.isSome(input.provider) !== Option.isSome(input.model)) {
763 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
764 }
765 if (Option.isNone(input.provider) || Option.isNone(input.model)) {
766 if (input.option.length > 0) {
767 return yield* new ThreadUsageError({ detail: "--option needs --provider and --model." });
768 }
769 return undefined;
770 }
771 const options: Array<{ readonly id: string; readonly value: string | boolean }> = [];
772 for (const entry of input.option) {
773 const separator = entry.indexOf("=");
774 const id = separator < 0 ? "" : entry.slice(0, separator).trim();
775 const value = separator < 0 ? "" : entry.slice(separator + 1).trim();
776 if (id.length === 0 || value.length === 0) {
777 return yield* new ThreadUsageError({ detail: `--option '${entry}' is not id=value.` });
778 }
779 if (options.some((option) => option.id === id)) {
780 return yield* new ThreadUsageError({ detail: `--option ${id} is given more than once.` });
781 }
782 options.push({ id, value: value === "true" ? true : value === "false" ? false : value });
783 }
784 return {
785 instanceId: input.provider.value,
786 model: input.model.value,
787 ...(options.length === 0 ? {} : { options }),
788 };
789 });
790
791 const jsonFlag = Flag.Boolean("json").pipe(
792 Flag.withDescription("Print JSON instead of text."),
793 Flag.withDefault(false),
794 );
795 const waitFlag = Flag.Boolean("wait").pipe(
796 Flag.withDescription(
797 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
798 ),
799 Flag.withDefault(false),
800 );
801 const outputSchemaFlag = Flag.String("output-schema").pipe(
802 Flag.withDescription(
803 "File holding a JSON Schema. The agent must return data matching it; --wait --json prints it as `output`.",
804 ),
805 Flag.optional,
806 );
807 const decodeOutputSchema = Schema.decodeUnknownEffect(
808 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)),
809 );
810 const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* (
811 path: Option.Option<string>,
812 ) {
813 if (Option.isNone(path)) return {};
814 const fileSystem = yield* FileSystem.FileSystem;
815 const usage = () =>
816 new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` });
817 const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage));
818 return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) };
819 });
820 const messageArgument = Argument.String("message").pipe(
821 Argument.withDescription("Message for the agent, or - to read it from stdin."),
822 );
823 const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
824
825 const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
826 const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
827 const decodeThreadId = (value: string) =>
828 decodeThreadIdValue(value.trim()).pipe(
829 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
830 );
831
832 const threadListCommand = Command.make("list", {
833 ...projectLocationFlags,
834 project: Flag.String("project").pipe(
835 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
836 Flag.withDefault("."),
837 ),
838 json: jsonFlag,
839 }).pipe(
840 Command.withDescription("List a project's threads, newest first."),
841 Command.withHandler((flags) =>
842 withThreadTools(
843 flags,
844 Effect.fn("cli.thread.list")(function* (tools) {
845 const project = yield* resolveProject(tools, flags.project);
846 const threads: Array<OrchestratorMcpThreadListItem> = [];
847 let cursor: number | null = 0;
848 while (cursor !== null) {
849 const page: OrchestratorMcpThreadListResult = yield* tools.call(
850 "t3_thread_list",
851 { projectId: project.id, includeSubagents: false, limit: 100, cursor },
852 OrchestratorMcpThreadListResult,
853 );
854 threads.push(...page.threads);
855 cursor = page.nextCursor;
856 }
857 if (flags.json) {
858 return yield* printJson(threads);
859 }
860 for (const thread of threads) {
861 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
862 }
863 }),
864 ).pipe(reportThreadErrors),
865 ),
866 );
867
868 const threadStartCommand = Command.make("start", {
869 ...projectLocationFlags,
870 project: Argument.String("project").pipe(
871 Argument.withDescription("Project id or a path inside the project, such as ."),
872 ),
873 message: messageArgument,
874 title: Flag.String("title").pipe(
875 Flag.withDescription("Thread title. Defaults to the message's first line."),
876 Flag.optional,
877 ),
878 provider: Flag.String("provider").pipe(
879 Flag.withDescription("Provider instance id. Pass with --model."),
880 Flag.optional,
881 ),
882 model: Flag.String("model").pipe(
883 Flag.withDescription("Model slug. Defaults to the project's default model."),
884 Flag.optional,
885 ),
886 option: Flag.String("option").pipe(
887 Flag.withDescription(
888 "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.",
889 ),
890 Flag.atLeast(0),
891 ),
892 worktree: Flag.String("worktree").pipe(
893 Flag.withDescription(
894 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
895 ),
896 Flag.optional,
897 ),
898 branch: Flag.String("branch").pipe(
899 Flag.withDescription("Branch name for the new worktree."),
900 Flag.optional,
901 ),
902 outputSchema: outputSchemaFlag,
903 wait: waitFlag,
904 json: jsonFlag,
905 }).pipe(
906 Command.withDescription("Start a thread in a project and print its id."),
907 Command.withHandler((flags) =>
908 Effect.gen(function* () {
909 const message = yield* readMessageArgument(flags.message);
910 const output = yield* readOutputSchema(flags.outputSchema);
911 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
912 const modelSelection = yield* launchModelSelection(flags);
913 const title = yield* decodeTitle(
914 Option.getOrElse(flags.title, () => titleFromMessage(message)),
915 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
916 yield* withThreadTools(
917 flags,
918 Effect.fn("cli.thread.start")(function* (tools) {
919 const project = yield* resolveProject(tools, flags.project);
920 const launched = yield* tools.call(
921 "t3_thread_launch",
922 {
923 projectId: project.id,
924 title,
925 message,
926 ...output,
927 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
928 ...(modelSelection === undefined ? {} : { modelSelection }),
929 },
930 ThreadLaunchResult,
931 );
932 if (flags.wait && launched.runId !== null) {
933 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
934 return yield* finishRun(tools, {
935 threadId: launched.threadId,
936 runId: launched.runId,
937 json: flags.json,
938 followWakes: true,
939 });
940 }
941 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
942 }),
943 );
944 }).pipe(reportThreadErrors),
945 ),
946 );
947
948 const threadSendCommand = Command.make("send", {
949 ...projectLocationFlags,
950 thread: threadArgument,
951 message: messageArgument,
952 outputSchema: outputSchemaFlag,
953 wait: waitFlag,
954 json: jsonFlag,
955 }).pipe(
956 Command.withDescription(
957 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
958 ),
959 Command.withHandler((flags) =>
960 Effect.gen(function* () {
961 const threadId = yield* decodeThreadId(flags.thread);
962 const message = yield* readMessageArgument(flags.message);
963 const output = yield* readOutputSchema(flags.outputSchema);
964 yield* withThreadTools(
965 flags,
966 Effect.fn("cli.thread.send")(function* (tools) {
967 // Work already running when this is sent is not this message's to wait for.
968 const followWakes = flags.wait ? yield* threadIsIdle(tools, threadId) : false;
969 const sent = yield* tools.call(
970 "t3_thread_send",
971 { threadId, message, mode: "queue", ...output },
972 OrchestratorMcpThreadSendResult,
973 );
974 if (flags.wait) {
975 return yield* finishRun(tools, {
976 threadId,
977 runId: sent.runId,
978 json: flags.json,
979 followWakes,
980 });
981 }
982 yield* flags.json
983 ? printJson(sent)
984 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
985 }),
986 );
987 }).pipe(reportThreadErrors),
988 ),
989 );
990
991 const threadShowCommand = Command.make("show", {
992 ...projectLocationFlags,
993 thread: threadArgument,
994 messages: Flag.Int("messages").pipe(
995 Flag.withDescription("How many of the latest messages to print."),
996 Flag.withDefault(10),
997 ),
998 json: jsonFlag,
999 }).pipe(
1000 Command.withDescription("Show a thread's state and its latest messages."),
1001 Command.withHandler((flags) =>
1002 Effect.gen(function* () {
1003 const threadId = yield* decodeThreadId(flags.thread);
1004 yield* withThreadTools(
1005 flags,
1006 Effect.fn("cli.thread.show")(function* (tools) {
1007 const { thread, messages: latest } = yield* readLatestMessages(
1008 tools,
1009 threadId,
1010 flags.messages,
1011 );
1012 const messages = yield* Effect.forEach(latest, (item) =>
1013 readFullText(tools, threadId, item).pipe(
1014 Effect.map((text) => ({
1015 role: item.type === "user_message" ? "user" : "assistant",
1016 runId: item.runId,
1017 text,
1018 })),
1019 ),
1020 );
1021 const error = yield* latestRunError(tools, thread);
1022 if (flags.json) {
1023 return yield* printJson({ thread, messages, error });
1024 }
1025 yield* Console.log(thread.title);
1026 yield* Console.log(
1027 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
1028 " ",
1029 ),
1030 );
1031 if (thread.worktreePath !== null) {
1032 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
1033 }
1034 if (thread.pendingRequestCount > 0) {
1035 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
1036 }
1037 if (error !== null) {
1038 yield* Console.log(`Error: ${error}`);
1039 }
1040 for (const entry of messages) {
1041 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
1042 }
1043 }),
1044 );
1045 }).pipe(reportThreadErrors),
1046 ),
1047 );
1048
1049 export const threadCommand = Command.make("thread").pipe(
1050 Command.withDescription("Start, message, and read threads on the running server."),
1051 Command.withSubcommands([
1052 threadListCommand,
1053 threadStartCommand,
1054 threadSendCommand,
1055 threadShowCommand,
1056 ]),
1057 );