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

thread.ts

1,180 lines43.1 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 resolvedTarget = yield* fileSystem.realPath(requestedPath).pipe(
382 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
383 Effect.orElseSucceed(() => requestedPath),
384 );
385 const target = resolvedTarget ?? requestedPath;
386 const roots = yield* Effect.forEach(projects, (project) =>
387 Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
388 );
389 const contains = (root: string, candidate: string) => {
390 const relative = path.relative(root, candidate);
391 return (
392 relative === "" ||
393 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
394 );
395 };
396 const containingRoots = (candidate: string, originalPath?: string) => {
397 // Projects can register the same directory through separate symlinks.
398 const matchingPathLength = (root: string) =>
399 originalPath !== undefined && contains(root, originalPath) ? root.length : 0;
400 return roots
401 .filter(({ root }) => contains(root, candidate))
402 .toSorted(
403 (left, right) =>
404 right.root.length - left.root.length ||
405 matchingPathLength(right.project.workspaceRoot) -
406 matchingPathLength(left.project.workspaceRoot),
407 );
408 };
409​
410 const containingMatch = containingRoots(target, requestedPath)[0];
411 const containing = containingMatch?.project;
412 if (resolvedTarget !== undefined && containing !== undefined) return containing;
413 const projectNotFound = () => new ThreadProjectNotFoundError({ identifier });
414 const statIfExists = (value: string) =>
415 fileSystem.stat(value).pipe(
416 Effect.catchReason("PlatformError", "NotFound", () => Effect.undefined),
417 Effect.mapError(projectNotFound),
418 );
419 // Git needs an existing cwd, so a path that doesn't exist yet resolves
420 // through its nearest existing ancestor.
421 let existing = target;
422 let info = yield* statIfExists(existing);
423 while (info === undefined) {
424 const parent = path.dirname(existing);
425 if (parent === existing) return yield* projectNotFound();
426 existing = parent;
427 info = yield* statIfExists(existing);
428 }
429 let gitDirectory = info.type === "File" ? path.dirname(target) : target;
430 let checkoutTarget = target;
431 if (existing !== target) {
432 if (info.type !== "Directory") return yield* projectNotFound();
433 gitDirectory = yield* realPath(existing);
434 checkoutTarget = path.join(gitDirectory, path.relative(existing, target));
435 const canonical = containingRoots(checkoutTarget, requestedPath)[0];
436 if (canonical !== undefined) {
437 // A registration whose own root is absent only matches by spelling; keep it unless the
438 // canonical match is closer.
439 const depth = (root: string, candidate: string) => {
440 const relative = path.relative(root, candidate);
441 return relative === "" ? 0 : relative.split(path.sep).length;
442 };
443 return containingMatch !== undefined &&
444 depth(containingMatch.root, target) <= depth(canonical.root, checkoutTarget)
445 ? containingMatch.project
446 : canonical.project;
447 }
448 }
449 if (containing !== undefined) return containing;
450 const listed = yield* listGitCheckouts(gitDirectory).pipe(
451 Effect.flatMap((paths) => Effect.forEach(paths, realPath)),
452 Effect.provide(ProcessRunner.layer),
453 );
454 const ownCheckout = listed
455 .filter((checkout) => contains(checkout, checkoutTarget))
456 .toSorted((left, right) => right.length - left.length)[0];
457 if (ownCheckout === undefined) {
458 return yield* projectNotFound();
459 }
460 const relative = path.relative(ownCheckout, checkoutTarget);
461 const matches = new Map<ProjectId, (typeof projects)[number]>();
462 for (const checkout of listed) {
463 if (checkout === ownCheckout) continue;
464 const checkoutMatches = containingRoots(path.join(checkout, relative));
465 const deepestLength = checkoutMatches[0]?.root.length;
466 for (const { project, root } of checkoutMatches) {
467 if (root.length !== deepestLength) break;
468 matches.set(project.id, project);
469 }
470 }
471 const [match, ...others] = matches.values();
472 if (match === undefined) {
473 return yield* projectNotFound();
474 }
475 if (others.length > 0) {
476 const names = [match, ...others].map((project) => `${project.title} (${project.id})`);
477 return yield* new ThreadUsageError({
478 detail: `'${identifier}' is in a git worktree shared by several projects: ${names.join(", ")}. Pass a project id instead.`,
479 });
480 }
481 return match;
482});
483​
484/** Every item on a timeline view, oldest first. */
485const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
486 tools: ThreadTools,
487 threadId: ThreadId,
488 view: "messages" | "activity",
489) {
490 const items: Array<OrchestratorMcpThreadTimelineItem> = [];
491 let afterPosition: number | null = -1;
492 let page: OrchestratorMcpThreadReadResult;
493 do {
494 page = yield* tools.call(
495 "t3_thread_read",
496 {
497 threadId,
498 view,
499 limit: READ_PAGE_LIMIT,
500 maxCharsPerItem: READ_ITEM_MAX_CHARS,
501 runLimit: 1,
502 afterPosition,
503 },
504 OrchestratorMcpThreadReadResult,
505 );
506 items.push(...page.items);
507 afterPosition = page.nextPosition;
508 } while (page.hasMore && afterPosition !== null);
509 return { thread: page.thread, items };
510});
511​
512/**
513 * The latest `count` user and assistant messages, oldest first. Positions
514 * count every timeline item, so the read starts near the end and widens
515 * backward only while tool and plan items leave too few messages.
516 */
517export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(function* (
518 tools: ThreadTools,
519 threadId: ThreadId,
520 count: number,
521) {
522 let { thread } = yield* tools.call(
523 "t3_thread_read",
524 { threadId, limit: 1, runLimit: 1 },
525 OrchestratorMcpThreadReadResult,
526 );
527 let messages: Array<OrchestratorMcpThreadTimelineItem> = [];
528 // The newest window has no upper bound, so items added since the first
529 // read are still shown.
530 let before: number | undefined;
531 let start = thread.itemCount;
532 let span = Math.max(count, READ_PAGE_LIMIT);
533 do {
534 const end = before;
535 start = Math.max(0, start - span);
536 const window: Array<OrchestratorMcpThreadTimelineItem> = [];
537 let afterPosition = start - 1;
538 let page: OrchestratorMcpThreadReadResult;
539 do {
540 page = yield* tools.call(
541 "t3_thread_read",
542 {
543 threadId,
544 view: "messages",
545 limit: READ_PAGE_LIMIT,
546 maxCharsPerItem: READ_ITEM_MAX_CHARS,
547 runLimit: 1,
548 afterPosition,
549 },
550 OrchestratorMcpThreadReadResult,
551 );
552 window.push(
553 ...page.items.filter(
554 (item) =>
555 (item.type === "user_message" || item.type === "assistant_message") &&
556 (end === undefined || item.position < end),
557 ),
558 );
559 afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY;
560 } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1);
561 // Only the first read carries pull request previews; later pages omit them.
562 thread = Object.assign({}, thread, page.thread);
563 // A window can hold the whole --messages count, too many to spread as arguments.
564 messages = window.concat(messages);
565 before = start;
566 span *= 2;
567 } while (messages.length < count && start > 0);
568 return { thread, messages: messages.slice(Math.max(0, messages.length - count)) };
569});
570​
571/** Item text past the read's per-item cap. */
572const readFullText = Effect.fn("cli.thread.readFullText")(function* (
573 tools: ThreadTools,
574 threadId: ThreadId,
575 item: OrchestratorMcpThreadTimelineItem,
576) {
577 let text = item.text ?? "";
578 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
579 while (nextTextOffset !== null) {
580 const page = yield* tools.call(
581 "t3_thread_read",
582 {
583 threadId,
584 itemId: item.itemId,
585 textOffset: nextTextOffset,
586 runLimit: 1,
587 maxCharsPerItem: READ_ITEM_MAX_CHARS,
588 },
589 OrchestratorMcpThreadReadResult,
590 );
591 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
592 if (chunk === undefined) break;
593 text += chunk.text ?? "";
594 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
595 }
596 return text;
597});
598​
599/** The run's last assistant message, or its last error when it did not complete. */
600const runResultText = Effect.fn("cli.thread.runResultText")(function* (
601 tools: ThreadTools,
602 threadId: ThreadId,
603 runId: RunId,
604 type: "assistant_message" | "error",
605) {
606 const { items } = yield* readTimeline(
607 tools,
608 threadId,
609 type === "assistant_message" ? "messages" : "activity",
610 );
611 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
612 return item === undefined ? null : yield* readFullText(tools, threadId, item);
613});
614​
615/** The latest run's last error once it ended without completing, else null. */
616export const latestRunError = Effect.fn("cli.thread.latestRunError")(function* (
617 tools: ThreadTools,
618 thread: Pick<OrchestratorMcpThreadDetail, "threadId" | "status" | "latestRunId">,
619) {
620 const { status, latestRunId } = thread;
621 if (latestRunId === null || status === "idle" || status === "completed") return null;
622 if (!TERMINAL_RUN_STATUSES.has(status)) return null;
623 return yield* runResultText(tools, thread.threadId, latestRunId, "error");
624});
625​
626type WaitOutcome =
627 | {
628 readonly type: "ended";
629 readonly runId: RunId | null;
630 readonly status: OrchestratorMcpThreadStatus;
631 readonly output?: Schema.Json;
632 }
633 | { readonly type: "needs_input" };
634​
635/**
636 * Whether the thread has nothing left to do: no active run and no delegated
637 * or background work. Only then is the work a later wait settles on this
638 * send's own.
639 */
640const threadIsIdle = Effect.fn("cli.thread.threadIsIdle")(function* (
641 tools: ThreadTools,
642 threadId: ThreadId,
643) {
644 const waited = yield* tools.call(
645 "t3_thread_wait",
646 { threadId, timeoutMs: 1, untilDelegatedWorkSettled: true },
647 OrchestratorMcpThreadWaitResult,
648 );
649 return !waited.timedOut;
650});
651​
652/**
653 * The runs after `runId`, and whether one holds a message someone sent.
654 * Background work wakes a run with a notification, never a user message, so
655 * such a run is another request and its reply is not this one's.
656 */
657const runsAfter = Effect.fn("cli.thread.runsAfter")(function* (
658 tools: ThreadTools,
659 threadId: ThreadId,
660 runId: RunId,
661) {
662 const { recentRuns } = yield* tools.call(
663 "t3_thread_read",
664 { threadId, limit: 1, runLimit: 50 },
665 OrchestratorMcpThreadReadResult,
666 );
667 const own = recentRuns.find((run) => run.runId === runId);
668 if (own === undefined) return { later: [], sent: true };
669 const later = recentRuns.filter((run) => run.ordinal > own.ordinal);
670 if (later.length === 0) return { later, sent: false };
671 const { items } = yield* readTimeline(tools, threadId, "messages");
672 const sent = items.some(
673 (item) => item.type === "user_message" && later.some((run) => run.runId === item.runId),
674 );
675 return { later, sent };
676});
677​
678/**
679 * Waits for this exact run, following a restart to its continuation, so a
680 * message another client sends meanwhile cannot stand in for its result.
681 * With `followWakes`, a completed run is followed further to the runs its
682 * background work wakes, as long as no one else sends to the thread.
683 */
684export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
685 tools: ThreadTools,
686 threadId: ThreadId,
687 runId: RunId,
688 followWakes = false,
689) {
690 const waitSlice = (timeoutMs: number, untilDelegatedWorkSettled?: true) =>
691 tools.call(
692 "t3_thread_wait",
693 {
694 threadId,
695 runId,
696 timeoutMs,
697 ...(untilDelegatedWorkSettled ? { untilDelegatedWorkSettled } : {}),
698 },
699 OrchestratorMcpThreadWaitResult,
700 );
701 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
702 ({
703 type: "ended",
704 runId: waited.runId,
705 status: waited.status,
706 ...(waited.output === undefined ? {} : { output: waited.output }),
707 }) satisfies WaitOutcome;
708 const ownRun = Effect.gen(function* () {
709 while (true) {
710 const waited = yield* waitSlice(WAIT_SLICE_MS);
711 if (!waited.timedOut) return ended(waited);
712 // A pending request on this run, or on an earlier run this one is queued
713 // behind, blocks it until someone answers.
714 const { thread } = yield* tools.call(
715 "t3_thread_read",
716 { threadId, limit: 1, runLimit: 1 },
717 OrchestratorMcpThreadReadResult,
718 );
719 if (thread.pendingRequestCount > 0) {
720 // The count is thread-wide: if this run ended since the slice, the
721 // request belongs to a later run.
722 const recheck = yield* waitSlice(1);
723 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
724 }
725 }
726 });
727 const outcome = yield* ownRun;
728 if (!followWakes || outcome.type !== "ended" || outcome.status !== "completed") return outcome;
729 const finalRunId = outcome.runId ?? runId;
730 // A provider records the run that background work wakes only after that
731 // work has ended, so the thread briefly looks settled in between.
732 const wakeRunRecorded = Effect.gen(function* () {
733 for (let waited = 0; waited < WAKE_GRACE_MS; waited += WAKE_POLL_MS) {
734 yield* Effect.sleep(WAKE_POLL_MS);
735 const after = yield* runsAfter(tools, threadId, finalRunId);
736 if (after.sent) return false;
737 if (after.later.length > 0) return true;
738 }
739 return false;
740 });
741 let workOutlivedRun = false;
742 while (true) {
743 const waited = yield* waitSlice(WAIT_SLICE_MS, true);
744 // `resultRun` is the thread's latest finished run, whoever sent it.
745 const result = waited.timedOut ? undefined : waited.resultRun;
746 // A later run can submit the result the asked run owes, so read it again.
747 const settled = waited.output === undefined ? outcome : { ...outcome, output: waited.output };
748 const after = yield* runsAfter(tools, threadId, finalRunId);
749 if (after.sent) return settled;
750 if (!waited.timedOut) {
751 if (result !== undefined && after.later.some((run) => run.runId === result.runId)) {
752 // A run that work woke was not asked for the result; the run before it holds it.
753 return {
754 type: "ended",
755 runId: result.runId,
756 status: result.status,
757 ...(settled.output === undefined ? {} : { output: settled.output }),
758 } satisfies WaitOutcome;
759 }
760 if (!workOutlivedRun) return settled;
761 if (after.later.some((run) => !TERMINAL_RUN_STATUSES.has(run.status))) continue;
762 if (after.later.length === 0 && (yield* wakeRunRecorded)) continue;
763 return settled;
764 }
765 workOutlivedRun = true;
766 const { thread } = yield* tools.call(
767 "t3_thread_read",
768 { threadId, limit: 1, runLimit: 1 },
769 OrchestratorMcpThreadReadResult,
770 );
771 // Earlier runs have ended, so the request is on a run this one's work woke.
772 if (thread.pendingRequestCount > 0) return { type: "needs_input" } satisfies WaitOutcome;
773 }
774});
775​
776/**
777 * With --json the result always reaches stdout, so a script keeps the thread
778 * id even when the run fails.
779 */
780const finishRun = Effect.fn("cli.thread.finishRun")(function* (
781 tools: ThreadTools,
782 input: {
783 readonly threadId: ThreadId;
784 readonly runId: RunId;
785 readonly json: boolean;
786 readonly followWakes: boolean;
787 },
788) {
789 const outcome = yield* waitForRun(tools, input.threadId, input.runId, input.followWakes);
790 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
791 const status = outcome.type === "ended" ? outcome.status : "waiting";
792 const reply =
793 status === "completed"
794 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
795 : null;
796 const error =
797 status === "completed" || status === "waiting"
798 ? null
799 : yield* runResultText(tools, input.threadId, runId, "error");
800 if (input.json) {
801 const output = outcome.type === "ended" ? outcome.output : undefined;
802 yield* printJson({
803 threadId: input.threadId,
804 runId,
805 status,
806 reply,
807 error,
808 ...(output === undefined ? {} : { output }),
809 });
810 } else if (reply !== null) {
811 yield* Console.log(reply);
812 }
813 if (outcome.type === "needs_input") {
814 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
815 }
816 if (status !== "completed") {
817 return yield* new ThreadRunEndedError({
818 threadId: input.threadId,
819 status,
820 ...(error === null ? {} : { error }),
821 });
822 }
823});
824​
825export const titleFromMessage = (message: string) => {
826 const firstLine =
827 message
828 .trim()
829 .split(/[\r\n\u2028\u2029]/, 1)[0]
830 ?.trim() ?? "";
831 if (firstLine.length <= TITLE_MAX_CHARS) return firstLine;
832 let end = TITLE_MAX_CHARS - 1;
833 const previous = firstLine.charCodeAt(end - 1);
834 const next = firstLine.charCodeAt(end);
835 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
836 end -= 1;
837 }
838 return `${firstLine.slice(0, end).trimEnd()}…`;
839};
840​
841const launchWorkspaceStrategy = (input: {
842 readonly worktree: Option.Option<string>;
843 readonly branch: Option.Option<string>;
844}) =>
845 Option.match(input.worktree, {
846 onNone: () =>
847 Option.isSome(input.branch)
848 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
849 : Effect.void,
850 onSome: (baseRef) =>
851 Effect.succeed({
852 type: "worktree" as const,
853 baseRef,
854 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
855 }),
856 });
857​
858/**
859 * Options are model specific, so they need an explicit model. `true` and
860 * `false` become booleans because boolean options such as fastMode only match
861 * a boolean.
862 */
863export const launchModelSelection = Effect.fn("cli.thread.launchModelSelection")(function* (input: {
864 readonly provider: Option.Option<string>;
865 readonly model: Option.Option<string>;
866 readonly option: ReadonlyArray<string>;
867}) {
868 if (Option.isSome(input.provider) !== Option.isSome(input.model)) {
869 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
870 }
871 if (Option.isNone(input.provider) || Option.isNone(input.model)) {
872 if (input.option.length > 0) {
873 return yield* new ThreadUsageError({ detail: "--option needs --provider and --model." });
874 }
875 return undefined;
876 }
877 const options: Array<{ readonly id: string; readonly value: string | boolean }> = [];
878 for (const entry of input.option) {
879 const separator = entry.indexOf("=");
880 const id = separator < 0 ? "" : entry.slice(0, separator).trim();
881 const value = separator < 0 ? "" : entry.slice(separator + 1).trim();
882 if (id.length === 0 || value.length === 0) {
883 return yield* new ThreadUsageError({ detail: `--option '${entry}' is not id=value.` });
884 }
885 if (options.some((option) => option.id === id)) {
886 return yield* new ThreadUsageError({ detail: `--option ${id} is given more than once.` });
887 }
888 options.push({ id, value: value === "true" ? true : value === "false" ? false : value });
889 }
890 return {
891 instanceId: input.provider.value,
892 model: input.model.value,
893 ...(options.length === 0 ? {} : { options }),
894 };
895});
896​
897export const jsonFlag = Flag.Boolean("json").pipe(
898 Flag.withDescription("Print JSON instead of text."),
899 Flag.withDefault(false),
900);
901const waitFlag = Flag.Boolean("wait").pipe(
902 Flag.withDescription(
903 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
904 ),
905 Flag.withDefault(false),
906);
907const outputSchemaFlag = Flag.String("output-schema").pipe(
908 Flag.withDescription(
909 "File holding a JSON Schema. The agent must return data matching it; --wait --json prints it as `output`.",
910 ),
911 Flag.optional,
912);
913const decodeOutputSchema = Schema.decodeUnknownEffect(
914 Schema.fromJsonString(Schema.Record(Schema.String, Schema.Json)),
915);
916export const readOutputSchema = Effect.fn("cli.thread.readOutputSchema")(function* (
917 path: Option.Option<string>,
918) {
919 if (Option.isNone(path)) return {};
920 const fileSystem = yield* FileSystem.FileSystem;
921 const usage = () =>
922 new ThreadUsageError({ detail: `${path.value} does not hold a JSON Schema object.` });
923 const text = yield* fileSystem
924 .readFileString(yield* expandHomePath(path.value))
925 .pipe(Effect.mapError(usage));
926 return { outputSchema: yield* decodeOutputSchema(text).pipe(Effect.mapError(usage)) };
927});
928const messageArgument = Argument.String("message").pipe(
929 Argument.withDescription("Message for the agent, or - to read it from stdin."),
930);
931const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
932​
933const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
934const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
935const decodeThreadId = (value: string) =>
936 decodeThreadIdValue(value.trim()).pipe(
937 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
938 );
939​
940const threadListCommand = Command.make("list", {
941 ...projectLocationFlags,
942 project: Flag.String("project").pipe(
943 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
944 Flag.withDefault("."),
945 ),
946 json: jsonFlag,
947}).pipe(
948 Command.withDescription("List a project's threads, newest first."),
949 Command.withHandler((flags) =>
950 withThreadTools(
951 flags,
952 Effect.fn("cli.thread.list")(function* (tools) {
953 const project = yield* resolveProject(tools, flags.project);
954 const threads: Array<OrchestratorMcpThreadListItem> = [];
955 let cursor: number | null = 0;
956 while (cursor !== null) {
957 const page: OrchestratorMcpThreadListResult = yield* tools.call(
958 "t3_thread_list",
959 { projectId: project.id, includeSubagents: true, limit: 100, cursor },
960 OrchestratorMcpThreadListResult,
961 );
962 threads.push(
963 ...page.threads.filter((thread) => thread.relationshipToParent !== "subagent"),
964 );
965 cursor = page.nextCursor;
966 }
967 if (flags.json) {
968 return yield* printJson(threads);
969 }
970 for (const thread of threads) {
971 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
972 }
973 }),
974 ).pipe(reportThreadErrors),
975 ),
976);
977​
978const threadStartCommand = Command.make("start", {
979 ...projectLocationFlags,
980 project: Argument.String("project").pipe(
981 Argument.withDescription("Project id or a path inside the project, such as ."),
982 ),
983 message: messageArgument,
984 title: Flag.String("title").pipe(
985 Flag.withDescription("Thread title. Defaults to the message's first line."),
986 Flag.optional,
987 ),
988 generateTitle: Flag.Boolean("generate-title").pipe(
989 Flag.withDescription(
990 "Generate the thread's title from the message. Until it's ready, the thread shows --title or the first line.",
991 ),
992 Flag.withDefault(false),
993 ),
994 provider: Flag.String("provider").pipe(
995 Flag.withDescription("Provider instance id. Pass with --model."),
996 Flag.optional,
997 ),
998 model: Flag.String("model").pipe(
999 Flag.withDescription("Model slug. Defaults to the project's default model."),
1000 Flag.optional,
1001 ),
1002 option: Flag.String("option").pipe(
1003 Flag.withDescription(
1004 "Model option as id=value (Codex: reasoningEffort=high; Claude: effort=high). Ids depend on the model. Repeat for more. Needs --provider and --model.",
1005 ),
1006 Flag.atLeast(0),
1007 ),
1008 worktree: Flag.String("worktree").pipe(
1009 Flag.withDescription(
1010 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
1011 ),
1012 Flag.optional,
1013 ),
1014 branch: Flag.String("branch").pipe(
1015 Flag.withDescription("Branch name for the new worktree."),
1016 Flag.optional,
1017 ),
1018 outputSchema: outputSchemaFlag,
1019 wait: waitFlag,
1020 json: jsonFlag,
1021}).pipe(
1022 Command.withDescription("Start a thread in a project and print its id."),
1023 Command.withHandler((flags) =>
1024 Effect.gen(function* () {
1025 const message = yield* readMessageArgument(flags.message);
1026 const output = yield* readOutputSchema(flags.outputSchema);
1027 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
1028 const modelSelection = yield* launchModelSelection(flags);
1029 const title = yield* decodeTitle(
1030 Option.getOrElse(flags.title, () => titleFromMessage(message)),
1031 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
1032 yield* withThreadTools(
1033 flags,
1034 Effect.fn("cli.thread.start")(function* (tools) {
1035 const project = yield* resolveProject(tools, flags.project);
1036 const launched = yield* tools.call(
1037 "t3_thread_launch",
1039 projectId: project.id,
1040 title,
1041 ...(flags.generateTitle ? { generateTitle: true } : {}),
1042 message,
1043 ...output,
1044 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
1045 ...(modelSelection === undefined ? {} : { modelSelection }),
1046 },
1047 ThreadLaunchResult,
1048 );
1049 if (flags.wait && launched.runId !== null) {
1050 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
1051 return yield* finishRun(tools, {
1052 threadId: launched.threadId,
1053 runId: launched.runId,
1054 json: flags.json,
1055 followWakes: true,
1056 });
1058 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
1059 }),
1060 );
1061 }).pipe(reportThreadErrors),
1062 ),
1064​
1065const threadSendCommand = Command.make("send", {
1066 ...projectLocationFlags,
1067 thread: threadArgument,
1068 message: messageArgument,
1069 outputSchema: outputSchemaFlag,
1070 wait: waitFlag,
1071 json: jsonFlag,
1072}).pipe(
1073 Command.withDescription(
1074 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
1075 ),
1076 Command.withHandler((flags) =>
1077 Effect.gen(function* () {
1078 const threadId = yield* decodeThreadId(flags.thread);
1079 const message = yield* readMessageArgument(flags.message);
1080 const output = yield* readOutputSchema(flags.outputSchema);
1081 yield* withThreadTools(
1082 flags,
1083 Effect.fn("cli.thread.send")(function* (tools) {
1084 // Work already running when this is sent is not this message's to wait for.
1085 const followWakes = flags.wait ? yield* threadIsIdle(tools, threadId) : false;
1086 const sent = yield* tools.call(
1087 "t3_thread_send",
1088 { threadId, message, mode: "queue", ...output },
1089 OrchestratorMcpThreadSendResult,
1090 );
1091 if (flags.wait) {
1092 return yield* finishRun(tools, {
1093 threadId,
1094 runId: sent.runId,
1095 json: flags.json,
1096 followWakes,
1097 });
1099 yield* flags.json
1100 ? printJson(sent)
1101 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
1102 }),
1103 );
1104 }).pipe(reportThreadErrors),
1105 ),
1107​
1108const threadShowCommand = Command.make("show", {
1109 ...projectLocationFlags,
1110 thread: threadArgument,
1111 messages: Flag.Int("messages").pipe(
1112 Flag.withSchema(NonNegativeInt),
1113 Flag.withDescription("How many of the latest messages to print."),
1114 Flag.withDefault(10),
1115 ),
1116 json: jsonFlag,
1117}).pipe(
1118 Command.withDescription("Show a thread's state and its latest messages."),
1119 Command.withHandler((flags) =>
1120 Effect.gen(function* () {
1121 const threadId = yield* decodeThreadId(flags.thread);
1122 yield* withThreadTools(
1123 flags,
1124 Effect.fn("cli.thread.show")(function* (tools) {
1125 const { thread, messages: latest } = yield* readLatestMessages(
1126 tools,
1127 threadId,
1128 flags.messages,
1129 );
1130 const messages = yield* Effect.forEach(latest, (item) =>
1131 readFullText(tools, threadId, item).pipe(
1132 Effect.map((text) => ({
1133 role:
1134 item.type === "assistant_message"
1135 ? "assistant"
1136 : item.createdBy === "system"
1137 ? "system"
1138 : "user",
1139 runId: item.runId,
1140 text,
1141 })),
1142 ),
1143 );
1144 const error = yield* latestRunError(tools, thread);
1145 if (flags.json) {
1146 return yield* printJson({ thread, messages, error });
1148 yield* Console.log(thread.title);
1149 yield* Console.log(
1150 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
1151 " ",
1152 ),
1153 );
1154 if (thread.worktreePath !== null) {
1155 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
1157 if (thread.pendingRequestCount > 0) {
1158 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
1160 if (error !== null) {
1161 yield* Console.log(`Error: ${error}`);
1163 for (const entry of messages) {
1164 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
1166 }),
1167 );
1168 }).pipe(reportThreadErrors),
1169 ),
1171​
1172export const threadCommand = Command.make("thread").pipe(
1173 Command.withDescription("Start, message, and read threads on the running server."),
1174 Command.withSubcommands([
1175 threadListCommand,
1176 threadStartCommand,
1177 threadSendCommand,
1178 threadShowCommand,
1179 ]),