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