Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

thread.ts

1,188 lines43.5 KB

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