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