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