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