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 // Only the first read carries pull request previews; later pages omit them.
463 thread = Object.assign({}, thread, page.thread);
464 // A window can hold the whole --messages count, too many to spread as arguments.
465 messages = window.concat(messages);
466 before = start;
467 span *= 2;
468 } while (messages.length < count && start > 0);
469 return { thread, messages: messages.slice(Math.max(0, messages.length - count)) };
470});
471
472/** Item text past the read's per-item cap. */
473const readFullText = Effect.fn("cli.thread.readFullText")(function* (
474 tools: ThreadTools,
475 threadId: ThreadId,
476 item: OrchestratorMcpThreadTimelineItem,
477) {
478 let text = item.text ?? "";
479 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
480 while (nextTextOffset !== null) {
481 const page = yield* tools.call(
482 "t3_thread_read",
483 {
484 threadId,
485 itemId: item.itemId,
486 textOffset: nextTextOffset,
487 runLimit: 1,
488 maxCharsPerItem: READ_ITEM_MAX_CHARS,
489 },
490 OrchestratorMcpThreadReadResult,
491 );
492 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
493 if (chunk === undefined) break;
494 text += chunk.text ?? "";
495 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
496 }
497 return text;
498});
499
500/** The run's last assistant message, or its last error when it did not complete. */
501const runResultText = Effect.fn("cli.thread.runResultText")(function* (
502 tools: ThreadTools,
503 threadId: ThreadId,
504 runId: RunId,
505 type: "assistant_message" | "error",
506) {
507 const { items } = yield* readTimeline(
508 tools,
509 threadId,
510 type === "assistant_message" ? "messages" : "activity",
511 );
512 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
513 return item === undefined ? null : yield* readFullText(tools, threadId, item);
514});
515
516/** The latest run's last error once it ended without completing, else null. */
517export const latestRunError = Effect.fn("cli.thread.latestRunError")(function* (
518 tools: ThreadTools,
519 thread: Pick<OrchestratorMcpThreadDetail, "threadId" | "status" | "latestRunId">,
520) {
521 const { status, latestRunId } = thread;
522 if (latestRunId === null || status === "idle" || status === "completed") return null;
523 if (!TERMINAL_RUN_STATUSES.has(status)) return null;
524 return yield* runResultText(tools, thread.threadId, latestRunId, "error");
525});
526
527type WaitOutcome =
528 | {
529 readonly type: "ended";
530 readonly runId: RunId | null;
531 readonly status: OrchestratorMcpThreadStatus;
532 readonly output?: Schema.Json;
533 }
534 | { readonly type: "needs_input" };
535
536/**
537 * Whether the thread has nothing left to do: no active run and no delegated
538 * or background work. Only then is the work a later wait settles on this
539 * send's own.
540 */
541const threadIsIdle = Effect.fn("cli.thread.threadIsIdle")(function* (
542 tools: ThreadTools,
543 threadId: ThreadId,
544) {
545 const waited = yield* tools.call(
546 "t3_thread_wait",
547 { threadId, timeoutMs: 1, untilDelegatedWorkSettled: true },
548 OrchestratorMcpThreadWaitResult,
549 );
550 return !waited.timedOut;
551});
552
553/**
554 * The runs after `runId`, and whether one holds a message someone sent.
555 * Background work wakes a run with a notification, never a user message, so
556 * such a run is another request and its reply is not this one's.
557 */
558const runsAfter = Effect.fn("cli.thread.runsAfter")(function* (
559 tools: ThreadTools,
560 threadId: ThreadId,
561 runId: RunId,
562) {
563 const { recentRuns } = yield* tools.call(
564 "t3_thread_read",
565 { threadId, limit: 1, runLimit: 50 },
566 OrchestratorMcpThreadReadResult,
567 );
568 const own = recentRuns.find((run) => run.runId === runId);
569 if (own === undefined) return { later: [], sent: true };
570 const later = recentRuns.filter((run) => run.ordinal > own.ordinal);
571 if (later.length === 0) return { later, sent: false };
572 const { items } = yield* readTimeline(tools, threadId, "messages");
573 const sent = items.some(
574 (item) => item.type === "user_message" && later.some((run) => run.runId === item.runId),
575 );
576 return { later, sent };
577});
578
579/**
580 * Waits for this exact run, following a restart to its continuation, so a
581 * message another client sends meanwhile cannot stand in for its result.
582 * With `followWakes`, a completed run is followed further to the runs its
583 * background work wakes, as long as no one else sends to the thread.
584 */
585export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
586 tools: ThreadTools,
587 threadId: ThreadId,
588 runId: RunId,
589 followWakes = false,
590) {
591 const waitSlice = (timeoutMs: number, untilDelegatedWorkSettled?: true) =>
592 tools.call(
593 "t3_thread_wait",
594 {
595 threadId,
596 runId,
597 timeoutMs,
598 ...(untilDelegatedWorkSettled ? { untilDelegatedWorkSettled } : {}),
599 },
600 OrchestratorMcpThreadWaitResult,
601 );
602 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
603 ({
604 type: "ended",
605 runId: waited.runId,
606 status: waited.status,
607 ...(waited.output === undefined ? {} : { output: waited.output }),
608 }) satisfies WaitOutcome;
609 const ownRun = Effect.gen(function* () {
610 while (true) {
611 const waited = yield* waitSlice(WAIT_SLICE_MS);
612 if (!waited.timedOut) return ended(waited);
613 // A pending request on this run, or on an earlier run this one is queued
614 // behind, blocks it until someone answers.
615 const { thread } = yield* tools.call(
616 "t3_thread_read",
617 { threadId, limit: 1, runLimit: 1 },
618 OrchestratorMcpThreadReadResult,
619 );
620 if (thread.pendingRequestCount > 0) {
621 // The count is thread-wide: if this run ended since the slice, the
622 // request belongs to a later run.
623 const recheck = yield* waitSlice(1);
624 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
625 }
626 }
627 });
628 const outcome = yield* ownRun;
629 if (!followWakes || outcome.type !== "ended" || outcome.status !== "completed") return outcome;
630 const finalRunId = outcome.runId ?? runId;
631 // A provider records the run that background work wakes only after that
632 // work has ended, so the thread briefly looks settled in between.
633 const wakeRunRecorded = Effect.gen(function* () {
634 for (let waited = 0; waited < WAKE_GRACE_MS; waited += WAKE_POLL_MS) {
635 yield* Effect.sleep(WAKE_POLL_MS);
636 const after = yield* runsAfter(tools, threadId, finalRunId);
637 if (after.sent) return false;
638 if (after.later.length > 0) return true;
639 }
640 return false;
641 });
642 let workOutlivedRun = false;
643 while (true) {
644 const waited = yield* waitSlice(WAIT_SLICE_MS, true);
645 // `resultRun` is the thread's latest finished run, whoever sent it.
646 const result = waited.timedOut ? undefined : waited.resultRun;
647 // A later run can submit the result the asked run owes, so read it again.
648 const settled = waited.output === undefined ? outcome : { ...outcome, output: waited.output };
649 const after = yield* runsAfter(tools, threadId, finalRunId);
650 if (after.sent) return settled;
651 if (!waited.timedOut) {
652 if (result !== undefined && after.later.some((run) => run.runId === result.runId)) {
653 // A run that work woke was not asked for the result; the run before it holds it.
654 return {
655 type: "ended",
656 runId: result.runId,
657 status: result.status,
658 ...(settled.output === undefined ? {} : { output: settled.output }),
659 } satisfies WaitOutcome;
660 }
661 if (!workOutlivedRun) return settled;
662 if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue;
663 if (after.later.length === 0 && (yield* wakeRunRecorded)) continue;
664 return settled;
665 }
666 workOutlivedRun = true;
667 const { thread } = yield* tools.call(
668 "t3_thread_read",
669 { threadId, limit: 1, runLimit: 1 },
670 OrchestratorMcpThreadReadResult,
671 );
672 // Earlier runs have ended, so the request is on a run this one's work woke.
673 if (thread.pendingRequestCount > 0) return { type: "needs_input" } satisfies WaitOutcome;
674 }
675});
676
677/**
678 * With --json the result always reaches stdout, so a script keeps the thread
679 * id even when the run fails.
680 */
681const finishRun = Effect.fn("cli.thread.finishRun")(function* (
682 tools: ThreadTools,
683 input: {
684 readonly threadId: ThreadId;
685 readonly runId: RunId;
686 readonly json: boolean;
687 readonly followWakes: boolean;
688 },
689) {
690 const outcome = yield* waitForRun(tools, input.threadId, input.runId, input.followWakes);
691 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
692 const status = outcome.type === "ended" ? outcome.status : "waiting";
693 const reply =
694 status === "completed"
695 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
696 : null;
697 const error =
698 status === "completed" || status === "waiting"
699 ? null
700 : yield* runResultText(tools, input.threadId, runId, "error");
701 if (input.json) {
702 const output = outcome.type === "ended" ? outcome.output : undefined;
703 yield* printJson({
704 threadId: input.threadId,
705 runId,
706 status,
707 reply,
708 error,
709 ...(output === undefined ? {} : { output }),
710 });
711 } else if (reply !== null) {
712 yield* Console.log(reply);
713 }
714 if (outcome.type === "needs_input") {
715 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
716 }
717 if (status !== "completed") {
718 return yield* new ThreadRunEndedError({
719 threadId: input.threadId,
720 status,
721 ...(error === null ? {} : { error }),
722 });
723 }
724});
725
726export const titleFromMessage = (message: string) => {
727 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
728 if (firstLine.length <= TITLE_MAX_CHARS) return firstLine;
729 let end = TITLE_MAX_CHARS - 1;
730 const previous = firstLine.charCodeAt(end - 1);
731 const next = firstLine.charCodeAt(end);
732 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
733 end -= 1;
734 }
735 return `${firstLine.slice(0, end).trimEnd()}…`;
736};
737
738const launchWorkspaceStrategy = (input: {
739 readonly worktree: Option.Option<string>;
740 readonly branch: Option.Option<string>;
741}) =>
742 Option.match(input.worktree, {
743 onNone: () =>
744 Option.isSome(input.branch)
745 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
746 : Effect.void,
747 onSome: (baseRef) =>
748 Effect.succeed({
749 type: "worktree" as const,
750 baseRef,
751 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
752 }),
753 });
754
755/**
756 * Options are model specific, so they need an explicit model. `true` and
757 * `false` become booleans because boolean options such as fastMode only match
758 * a boolean.
759 */
760export const launchModelSelection = Effect.fn("cli.thread.launchModelSelection")(function* (input: {
761 readonly provider: Option.Option<string>;
762 readonly model: Option.Option<string>;
763 readonly option: ReadonlyArray<string>;
764}) {
765 if (Option.isSome(input.provider) !== Option.isSome(input.model)) {
766 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
767 }
768 if (Option.isNone(input.provider) || Option.isNone(input.model)) {
769 if (input.option.length > 0) {
770 return yield* new ThreadUsageError({ detail: "--option needs --provider and --model." });
771 }
772 return undefined;
773 }
774 const options: Array<{ readonly id: string; readonly value: string | boolean }> = [];
775 for (const entry of input.option) {
776 const separator = entry.indexOf("=");
777 const id = separator < 0 ? "" : entry.slice(0, separator).trim();
778 const value = separator < 0 ? "" : entry.slice(separator + 1).trim();
779 if (id.length === 0 || value.length === 0) {
780 return yield* new ThreadUsageError({ detail: `--option '${entry}' is not id=value.` });
781 }
782 if (options.some((option) => option.id === id)) {
783 return yield* new ThreadUsageError({ detail: `--option ${id} is given more than once.` });
784 }
785 options.push({ id, value: value === "true" ? true : value === "false" ? false : value });
786 }
787 return {
788 instanceId: input.provider.value,
789 model: input.model.value,
790 ...(options.length === 0 ? {} : { options }),
791 };
792});
793
794const jsonFlag = Flag.Boolean("json").pipe(
795 Flag.withDescription("Print JSON instead of text."),
796 Flag.withDefault(false),
797);
798const waitFlag = Flag.Boolean("wait").pipe(
799 Flag.withDescription(
800 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
801 ),
802 Flag.withDefault(false),
803);
804const outputSchemaFlag = Flag.String("output-schema").pipe(
805 Flag.withDescription(
806 "File holding a JSON Schema. The agent must return data matching it; --wait --json prints it as `output`.",
807 ),
808 Flag.optional,
809);
810const decodeOutputSchema = Schema.decodeUnknownEffect(
811 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)),
812);
813const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* (
814 path: Option.Option<string>,
815) {
816 if (Option.isNone(path)) return {};
817 const fileSystem = yield* FileSystem.FileSystem;
818 const usage = () =>
819 new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` });
820 const text = yield* fileSystem.readFileString(path.value).pipe(Effect.mapError(usage));
821 return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) };
822});
823const messageArgument = Argument.String("message").pipe(
824 Argument.withDescription("Message for the agent, or - to read it from stdin."),
825);
826const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
827
828const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
829const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
830const decodeThreadId = (value: string) =>
831 decodeThreadIdValue(value.trim()).pipe(
832 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
833 );
834
835const threadListCommand = Command.make("list", {
836 ...projectLocationFlags,
837 project: Flag.String("project").pipe(
838 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
839 Flag.withDefault("."),
840 ),
841 json: jsonFlag,
842}).pipe(
843 Command.withDescription("List a project's threads, newest first."),
844 Command.withHandler((flags) =>
845 withThreadTools(
846 flags,
847 Effect.fn("cli.thread.list")(function* (tools) {
848 const project = yield* resolveProject(tools, flags.project);
849 const threads: Array<OrchestratorMcpThreadListItem> = [];
850 let cursor: number | null = 0;
851 while (cursor !== null) {
852 const page: OrchestratorMcpThreadListResult = yield* tools.call(
853 "t3_thread_list",
854 { projectId: project.id, includeSubagents: true, limit: 100, cursor },
855 OrchestratorMcpThreadListResult,
856 );
857 threads.push(
858 ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"),
859 );
860 cursor = page.nextCursor;
861 }
862 if (flags.json) {
863 return yield* printJson(threads);
864 }
865 for (const thread of threads) {
866 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
867 }
868 }),
869 ).pipe(reportThreadErrors),
870 ),
871);
872
873const threadStartCommand = Command.make("start", {
874 ...projectLocationFlags,
875 project: Argument.String("project").pipe(
876 Argument.withDescription("Project id or a path inside the project, such as ."),
877 ),
878 message: messageArgument,
879 title: Flag.String("title").pipe(
880 Flag.withDescription("Thread title. Defaults to the message's first line."),
881 Flag.optional,
882 ),
883 generateTitle: Flag.Boolean("generate-title").pipe(
884 Flag.withDescription(
885 "Generate the thread's title from the message. Until it's ready, the thread shows --title or the first line.",
886 ),
887 Flag.withDefault(false),
888 ),
889 provider: Flag.String("provider").pipe(
890 Flag.withDescription("Provider instance id. Pass with --model."),
891 Flag.optional,
892 ),
893 model: Flag.String("model").pipe(
894 Flag.withDescription("Model slug. Defaults to the project's default model."),
895 Flag.optional,
896 ),
897 option: Flag.String("option").pipe(
898 Flag.withDescription(
899 "Model option as id=value, such as effort=high. Repeat for more. Needs --provider and --model.",
900 ),
901 Flag.atLeast(0),
902 ),
903 worktree: Flag.String("worktree").pipe(
904 Flag.withDescription(
905 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
906 ),
907 Flag.optional,
908 ),
909 branch: Flag.String("branch").pipe(
910 Flag.withDescription("Branch name for the new worktree."),
911 Flag.optional,
912 ),
913 outputSchema: outputSchemaFlag,
914 wait: waitFlag,
915 json: jsonFlag,
916}).pipe(
917 Command.withDescription("Start a thread in a project and print its id."),
918 Command.withHandler((flags) =>
919 Effect.gen(function* () {
920 const message = yield* readMessageArgument(flags.message);
921 const output = yield* readOutputSchema(flags.outputSchema);
922 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
923 const modelSelection = yield* launchModelSelection(flags);
924 const title = yield* decodeTitle(
925 Option.getOrElse(flags.title, () => titleFromMessage(message)),
926 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
927 yield* withThreadTools(
928 flags,
929 Effect.fn("cli.thread.start")(function* (tools) {
930 const project = yield* resolveProject(tools, flags.project);
931 const launched = yield* tools.call(
932 "t3_thread_launch",
933 {
934 projectId: project.id,
935 title,
936 ...(flags.generateTitle ? { generateTitle: true } : {}),
937 message,
938 ...output,
939 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
940 ...(modelSelection === undefined ? {} : { modelSelection }),
941 },
942 ThreadLaunchResult,
943 );
944 if (flags.wait && launched.runId !== null) {
945 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
946 return yield* finishRun(tools, {
947 threadId: launched.threadId,
948 runId: launched.runId,
949 json: flags.json,
950 followWakes: true,
951 });
952 }
953 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
954 }),
955 );
956 }).pipe(reportThreadErrors),
957 ),
958);
959
960const threadSendCommand = Command.make("send", {
961 ...projectLocationFlags,
962 thread: threadArgument,
963 message: messageArgument,
964 outputSchema: outputSchemaFlag,
965 wait: waitFlag,
966 json: jsonFlag,
967}).pipe(
968 Command.withDescription(
969 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
970 ),
971 Command.withHandler((flags) =>
972 Effect.gen(function* () {
973 const threadId = yield* decodeThreadId(flags.thread);
974 const message = yield* readMessageArgument(flags.message);
975 const output = yield* readOutputSchema(flags.outputSchema);
976 yield* withThreadTools(
977 flags,
978 Effect.fn("cli.thread.send")(function* (tools) {
979 // Work already running when this is sent is not this message's to wait for.
980 const followWakes = flags.wait ? yield* threadIsIdle(tools, threadId) : false;
981 const sent = yield* tools.call(
982 "t3_thread_send",
983 { threadId, message, mode: "queue", ...output },
984 OrchestratorMcpThreadSendResult,
985 );
986 if (flags.wait) {
987 return yield* finishRun(tools, {
988 threadId,
989 runId: sent.runId,
990 json: flags.json,
991 followWakes,
992 });
993 }
994 yield* flags.json
995 ? printJson(sent)
996 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
997 }),
998 );
999 }).pipe(reportThreadErrors),
1000 ),
1001);
1002
1003const threadShowCommand = Command.make("show", {
1004 ...projectLocationFlags,
1005 thread: threadArgument,
1006 messages: Flag.Int("messages").pipe(
1007 Flag.withDescription("How many of the latest messages to print."),
1008 Flag.withDefault(10),
1009 ),
1010 json: jsonFlag,
1011}).pipe(
1012 Command.withDescription("Show a thread's state and its latest messages."),
1013 Command.withHandler((flags) =>
1014 Effect.gen(function* () {
1015 const threadId = yield* decodeThreadId(flags.thread);
1016 yield* withThreadTools(
1017 flags,
1018 Effect.fn("cli.thread.show")(function* (tools) {
1019 const { thread, messages: latest } = yield* readLatestMessages(
1020 tools,
1021 threadId,
1022 flags.messages,
1023 );
1024 const messages = yield* Effect.forEach(latest, (item) =>
1025 readFullText(tools, threadId, item).pipe(
1026 Effect.map((text) => ({
1027 role:
1028 item.type === "assistant_message"
1029 ? "assistant"
1030 : item.createdBy === "system"
1031 ? "system"
1032 : "user",
1033 runId: item.runId,
1034 text,
1035 })),
1036 ),
1037 );
1038 const error = yield* latestRunError(tools, thread);
1039 if (flags.json) {
1040 return yield* printJson({ thread, messages, error });
1041 }
1042 yield* Console.log(thread.title);
1043 yield* Console.log(
1044 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
1045 " ",
1046 ),
1047 );
1048 if (thread.worktreePath !== null) {
1049 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
1050 }
1051 if (thread.pendingRequestCount > 0) {
1052 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
1053 }
1054 if (error !== null) {
1055 yield* Console.log(`Error: ${error}`);
1056 }
1057 for (const entry of messages) {
1058 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
1059 }
1060 }),
1061 );
1062 }).pipe(reportThreadErrors),
1063 ),
1064);
1065
1066export const threadCommand = Command.make("thread").pipe(
1067 Command.withDescription("Start, message, and read threads on the running server."),
1068 Command.withSubcommands([
1069 threadListCommand,
1070 threadStartCommand,
1071 threadSendCommand,
1072 threadShowCommand,
1073 ]),
1074);