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

thread.ts

950 lines34.1 KB

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