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

thread.ts

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