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

thread.ts

711 lines25.2 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 OrchestratorMcpThreadStatus,
13 type OrchestratorMcpThreadTimelineItem,
14} from "@t3tools/contracts";
15import * as HostProcess from "@t3tools/shared/HostProcess";
16import * as Console from "effect/Console";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Layer from "effect/Layer";
20import * as Option from "effect/Option";
21import * as Path from "effect/Path";
22import * as References from "effect/References";
23import * as Runtime from "effect/Runtime";
24import * as Schema from "effect/Schema";
25import * as Stdio from "effect/Stdio";
26import * as Stream from "effect/Stream";
27import { Argument, Command, Flag, GlobalFlag } from "effect/cli";
28​
29import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
30import * as ServerConfig from "../config.ts";
31import { mcpToolSession, type McpToolSession } from "../mcp/AcpMcpStdioBridge.ts";
32import { readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
33import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
34​
35/**
36 * Short enough that a run which stops to ask the user something is noticed
37 * soon, since `t3_thread_wait` only returns on a terminal run.
38 */
39const WAIT_SLICE_MS = 15_000;
40const READ_PAGE_LIMIT = 100;
41const TITLE_MAX_CHARS = 80;
42​
43export class ThreadServerNotRunningError extends Schema.TaggedError<ThreadServerNotRunningError>()(
44 "ThreadServerNotRunningError",
45 { baseDir: Schema.String },
46) {
47 override readonly [Runtime.errorReported] = false;
48 override get message(): string {
49 return `No running T3 Code server uses ${this.baseDir}. Start T3 Code, then retry.`;
50 }
52​
53export class ThreadServerUnreachableError extends Schema.TaggedError<ThreadServerUnreachableError>()(
54 "ThreadServerUnreachableError",
55 { origin: Schema.String, cause: Schema.Defect() },
56) {
57 override readonly [Runtime.errorReported] = false;
58 override get message(): string {
59 const reason = this.cause instanceof Error ? ` ${this.cause.message}` : "";
60 return `Could not reach the T3 Code server at ${this.origin}.${reason}`;
61 }
63​
64export class ThreadToolFailedError extends Schema.TaggedError<ThreadToolFailedError>()(
65 "ThreadToolFailedError",
66 { tool: Schema.String, detail: Schema.String },
67) {
68 override readonly [Runtime.errorReported] = false;
69 override get message(): string {
70 return this.detail;
71 }
73​
74export class ThreadUsageError extends Schema.TaggedError<ThreadUsageError>()("ThreadUsageError", {
75 detail: Schema.String,
76}) {
77 override readonly [Runtime.errorReported] = false;
78 override get message(): string {
79 return this.detail;
80 }
82​
83export class ThreadProjectNotFoundError extends Schema.TaggedError<ThreadProjectNotFoundError>()(
84 "ThreadProjectNotFoundError",
85 { identifier: Schema.String },
86) {
87 override readonly [Runtime.errorReported] = false;
88 override get message(): string {
89 return `No T3 Code project matches '${this.identifier}'. Pass a project id or a path inside a project.`;
90 }
92​
93/** Exit code 2 lets a script tell "needs a human" apart from a failed run. */
94export class ThreadNeedsInputError extends Schema.TaggedError<ThreadNeedsInputError>()(
95 "ThreadNeedsInputError",
96 { threadId: ThreadId },
97) {
98 override readonly [Runtime.errorReported] = false;
99 override readonly [Runtime.errorExitCode] = 2;
100​
101 override get message(): string {
102 return `Thread ${this.threadId} is waiting for an answer. Open it in T3 Code to respond.`;
103 }
105​
106export class ThreadRunEndedError extends Schema.TaggedError<ThreadRunEndedError>()(
107 "ThreadRunEndedError",
108 { threadId: ThreadId, status: Schema.String, error: Schema.optional(Schema.String) },
109) {
110 override readonly [Runtime.errorReported] = false;
111 override get message(): string {
112 const reason = this.error === undefined ? "." : `: ${this.error}`;
113 return `Thread ${this.threadId} stopped with status ${this.status}${reason}`;
114 }
116​
117const ThreadCliError = Schema.Union([
118 ThreadServerNotRunningError,
119 ThreadServerUnreachableError,
120 ThreadToolFailedError,
121 ThreadUsageError,
122 ThreadProjectNotFoundError,
123 ThreadNeedsInputError,
124 ThreadRunEndedError,
125]);
126const isThreadCliError = Schema.is(ThreadCliError);
127​
128/**
129 * These errors are expected outcomes for a script, so they print as one line
130 * on stderr instead of the runtime's logged stack trace.
131 */
132const reportThreadErrors = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
133 effect.pipe(
134 Effect.tapError((error) =>
135 isThreadCliError(error) ? Console.error(error.message) : Effect.void,
136 ),
137 );
138​
139const decodeFailureText = Schema.decodeUnknownOption(Schema.fromJsonString(OrchestratorMcpFailure));
140const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
141const printJson = (value: unknown) => Console.log(encodeJson(value));
142​
143const ToolResult = Schema.Struct({
144 isError: Schema.optional(Schema.Boolean),
145 structuredContent: Schema.optional(Schema.Unknown),
146 content: Schema.optional(
147 Schema.Array(Schema.Struct({ type: Schema.String, text: Schema.optional(Schema.String) })),
148 ),
149});
150​
151const decodeToolResult = Schema.decodeUnknownEffect(ToolResult);
152​
153const ProjectListResult = Schema.Struct({
154 projects: Schema.Array(
155 Schema.Struct({ id: ProjectId, title: Schema.String, workspaceRoot: Schema.String }),
156 ),
157 nextCursor: Schema.NullOr(Schema.Int),
158});
159​
160const ThreadLaunchResult = Schema.Struct({
161 threadId: ThreadId,
162 projectId: ProjectId,
163 runId: Schema.NullOr(RunId),
164});
165​
166const toolFailureDetail = (result: typeof ToolResult.Type) => {
167 const text = result.content?.find((part) => part.text !== undefined)?.text ?? "";
168 return Option.match(decodeFailureText(text), {
169 onNone: () => text || "The tool call failed.",
170 onSome: (failure) => failure.message,
171 });
172};
173​
174const makeThreadTools = (session: McpToolSession, origin: string) => {
175 const unexpected = (tool: string) =>
176 new ThreadToolFailedError({
177 tool,
178 detail: `The server sent an unexpected ${tool} result. Update the t3 CLI to match the server.`,
179 });
180 return {
181 call: Effect.fn("cli.thread.callTool")(function* <S extends Schema.Decoder<unknown>>(
182 tool: string,
183 args: Readonly<Record<string, unknown>>,
184 schema: S,
185 ): Effect.fn.Return<S["Type"], ThreadServerUnreachableError | ThreadToolFailedError> {
186 const raw = yield* session
187 .call(tool, args)
188 .pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
189 const result = yield* decodeToolResult(raw).pipe(Effect.mapError(() => unexpected(tool)));
190 if (result.isError === true) {
191 return yield* new ThreadToolFailedError({ tool, detail: toolFailureDetail(result) });
192 }
193 return yield* Schema.decodeUnknownEffect(schema)(result.structuredContent).pipe(
194 Effect.mapError(() => unexpected(tool)),
195 );
196 }),
197 };
198};
199export type ThreadTools = ReturnType<typeof makeThreadTools>;
200​
201/**
202 * Signs in as a short-lived MCP client of the running server, the same way an
203 * outside agent does, and revokes that session when the command ends.
204 */
205const withThreadTools = Effect.fn("cli.thread.withThreadTools")(function* <A, E, R>(
206 flags: { readonly baseDir: Option.Option<string> },
207 run: (tools: ThreadTools) => Effect.Effect<A, E, R>,
208) {
209 const logLevel = yield* GlobalFlag.LogLevel;
210 const config = yield* resolveCliAuthConfig(flags, logLevel);
211 return yield* Effect.gen(function* () {
212 const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
213 if (Option.isNone(runtimeState)) {
214 return yield* new ThreadServerNotRunningError({ baseDir: config.baseDir });
215 }
216 const origin = runtimeState.value.origin;
217 const environmentAuth = yield* EnvironmentAuth.EnvironmentAuth;
218 const issued = yield* Effect.acquireRelease(
219 environmentAuth.issueMcpClientSession({
220 label: "t3 thread cli",
221 // The CLI runs as the machine's owner. New threads still start at
222 // the project's default mode, never at this ceiling by default.
223 access: "full-access",
224 peerLink: false,
225 client: { deviceType: "bot" },
226 }),
227 (session) =>
228 environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })),
229 );
230 const session = yield* mcpToolSession({
231 endpoint: new URL("/mcp", origin).href,
232 authorization: `Bearer ${issued.token}`,
233 clientName: "t3-thread-cli",
234 }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
235 return yield* run(makeThreadTools(session, origin));
236 }).pipe(
237 Effect.scoped,
238 Effect.provide(
239 EnvironmentAuth.layerRuntime.pipe(
240 Layer.provide(ServerConfig.layer(config)),
241 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
242 ),
243 ),
244 );
245});
246​
247const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) {
248 const text =
249 argument === "-"
250 ? yield* Stdio.Stdio.pipe(
251 Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
252 )
253 : argument;
254 if (text.trim().length === 0) {
255 return yield* new ThreadUsageError({ detail: "The message is empty." });
256 }
257 return text;
258});
259​
260const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) {
261 const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = [];
262 let cursor: number | null = 0;
263 while (cursor !== null) {
264 const page: typeof ProjectListResult.Type = yield* tools.call(
265 "t3_project_list",
266 { cursor, limit: 100 },
267 ProjectListResult,
268 );
269 projects.push(...page.projects);
270 cursor = page.nextCursor;
271 }
272 return projects;
273});
274​
275/** A project id, or a path inside a project's folder (deepest project wins). */
276const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
277 tools: ThreadTools,
278 identifier: string,
279) {
280 const projects = yield* listAllProjects(tools);
281 const byId = projects.find((project) => project.id === identifier);
282 if (byId !== undefined) return byId;
283​
284 const path = yield* Path.Path;
285 const fileSystem = yield* FileSystem.FileSystem;
286 // Stored roots keep the path the project was added with, which may pass
287 // through a symlink (macOS /tmp), so both sides compare as real paths.
288 const realPath = (value: string) =>
289 fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
290 const target = yield* realPath(path.resolve(yield* HostProcess.WorkingDirectory, identifier));
291 const roots = yield* Effect.forEach(projects, (project) =>
292 Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
293 );
294 const containing = roots
295 .filter(({ root }) => {
296 const relative = path.relative(root, target);
297 return (
298 relative === "" ||
299 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
300 );
301 })
302 .toSorted((left, right) => right.root.length - left.root.length)[0];
303 if (containing === undefined) {
304 return yield* new ThreadProjectNotFoundError({ identifier });
305 }
306 return containing.project;
307});
308​
309/** Every item on a timeline view, oldest first. */
310const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
311 tools: ThreadTools,
312 threadId: ThreadId,
313 view: "messages" | "activity",
314) {
315 const items: Array<OrchestratorMcpThreadTimelineItem> = [];
316 let afterPosition: number | undefined;
317 let page: OrchestratorMcpThreadReadResult;
318 do {
319 page = yield* tools.call(
320 "t3_thread_read",
321 {
322 threadId,
323 view,
324 limit: READ_PAGE_LIMIT,
325 runLimit: 1,
326 ...(afterPosition === undefined ? {} : { afterPosition }),
327 },
328 OrchestratorMcpThreadReadResult,
329 );
330 items.push(...page.items);
331 afterPosition = page.nextPosition ?? undefined;
332 } while (page.hasMore && afterPosition !== undefined);
333 return { thread: page.thread, items };
334});
335​
336/** Item text past the read's per-item cap. */
337const readFullText = Effect.fn("cli.thread.readFullText")(function* (
338 tools: ThreadTools,
339 threadId: ThreadId,
340 item: OrchestratorMcpThreadTimelineItem,
341) {
342 let text = item.text ?? "";
343 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
344 while (nextTextOffset !== null) {
345 const page = yield* tools.call(
346 "t3_thread_read",
347 { threadId, itemId: item.itemId, textOffset: nextTextOffset, runLimit: 1 },
348 OrchestratorMcpThreadReadResult,
349 );
350 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
351 if (chunk === undefined) break;
352 text += chunk.text ?? "";
353 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
354 }
355 return text;
356});
357​
358/** The run's last assistant message, or its last error when it did not complete. */
359const runResultText = Effect.fn("cli.thread.runResultText")(function* (
360 tools: ThreadTools,
361 threadId: ThreadId,
362 runId: RunId,
363 type: "assistant_message" | "error",
364) {
365 const { items } = yield* readTimeline(
366 tools,
367 threadId,
368 type === "assistant_message" ? "messages" : "activity",
369 );
370 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
371 return item === undefined ? null : yield* readFullText(tools, threadId, item);
372});
373​
374type WaitOutcome =
375 | {
376 readonly type: "ended";
377 readonly runId: RunId | null;
378 readonly status: OrchestratorMcpThreadStatus;
379 }
380 | { readonly type: "needs_input" };
381​
382/**
383 * Waits for this exact run, following a restart to its continuation, so a
384 * message another client sends meanwhile cannot stand in for its result.
385 */
386export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
387 tools: ThreadTools,
388 threadId: ThreadId,
389 runId: RunId,
390) {
391 const waitSlice = (timeoutMs: number) =>
392 tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
393 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
394 ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
395 while (true) {
396 const waited = yield* waitSlice(WAIT_SLICE_MS);
397 if (!waited.timedOut) return ended(waited);
398 // A pending request on this run, or on an earlier run this one is queued
399 // behind, blocks it until someone answers.
400 const { thread } = yield* tools.call(
401 "t3_thread_read",
402 { threadId, limit: 1, runLimit: 1 },
403 OrchestratorMcpThreadReadResult,
404 );
405 if (thread.pendingRequestCount > 0) {
406 // The count is thread-wide: if this run ended since the slice, the
407 // request belongs to a later run.
408 const recheck = yield* waitSlice(1);
409 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
410 }
411 }
412});
413​
414/**
415 * With --json the result always reaches stdout, so a script keeps the thread
416 * id even when the run fails.
417 */
418const finishRun = Effect.fn("cli.thread.finishRun")(function* (
419 tools: ThreadTools,
420 input: {
421 readonly threadId: ThreadId;
422 readonly runId: RunId;
423 readonly json: boolean;
424 },
425) {
426 const outcome = yield* waitForRun(tools, input.threadId, input.runId);
427 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
428 const status = outcome.type === "ended" ? outcome.status : "waiting";
429 const reply =
430 status === "completed"
431 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
432 : null;
433 const error =
434 status === "completed" || status === "waiting"
435 ? null
436 : yield* runResultText(tools, input.threadId, runId, "error");
437 if (input.json) {
438 yield* printJson({ threadId: input.threadId, runId, status, reply, error });
439 } else if (reply !== null) {
440 yield* Console.log(reply);
441 }
442 if (outcome.type === "needs_input") {
443 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
444 }
445 if (status !== "completed") {
446 return yield* new ThreadRunEndedError({
447 threadId: input.threadId,
448 status,
449 ...(error === null ? {} : { error }),
450 });
451 }
452});
453​
454const titleFromMessage = (message: string) => {
455 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
456 return firstLine.length > TITLE_MAX_CHARS
457 ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`
458 : firstLine;
459};
460​
461const launchWorkspaceStrategy = (input: {
462 readonly worktree: Option.Option<string>;
463 readonly branch: Option.Option<string>;
464}) =>
465 Option.match(input.worktree, {
466 onNone: () =>
467 Option.isSome(input.branch)
468 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
469 : Effect.void,
470 onSome: (baseRef) =>
471 Effect.succeed({
472 type: "worktree" as const,
473 baseRef,
474 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
475 }),
476 });
477​
478const jsonFlag = Flag.Boolean("json").pipe(
479 Flag.withDescription("Print JSON instead of text."),
480 Flag.withDefault(false),
481);
482const waitFlag = Flag.Boolean("wait").pipe(
483 Flag.withDescription(
484 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
485 ),
486 Flag.withDefault(false),
487);
488const messageArgument = Argument.String("message").pipe(
489 Argument.withDescription("Message for the agent, or - to read it from stdin."),
490);
491const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
492​
493const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
494const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
495const decodeThreadId = (value: string) =>
496 decodeThreadIdValue(value.trim()).pipe(
497 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
498 );
499​
500const threadListCommand = Command.make("list", {
501 ...projectLocationFlags,
502 project: Flag.String("project").pipe(
503 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
504 Flag.withDefault("."),
505 ),
506 json: jsonFlag,
507}).pipe(
508 Command.withDescription("List a project's threads, newest first."),
509 Command.withHandler((flags) =>
510 withThreadTools(
511 flags,
512 Effect.fn("cli.thread.list")(function* (tools) {
513 const project = yield* resolveProject(tools, flags.project);
514 const threads: Array<OrchestratorMcpThreadListItem> = [];
515 let cursor: number | null = 0;
516 while (cursor !== null) {
517 const page: OrchestratorMcpThreadListResult = yield* tools.call(
518 "t3_thread_list",
519 { projectId: project.id, includeSubagents: false, limit: 100, cursor },
520 OrchestratorMcpThreadListResult,
521 );
522 threads.push(...page.threads);
523 cursor = page.nextCursor;
524 }
525 if (flags.json) {
526 return yield* printJson(threads);
527 }
528 for (const thread of threads) {
529 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
530 }
531 }),
532 ).pipe(reportThreadErrors),
533 ),
534);
535​
536const threadStartCommand = Command.make("start", {
537 ...projectLocationFlags,
538 project: Argument.String("project").pipe(
539 Argument.withDescription("Project id or a path inside the project, such as ."),
540 ),
541 message: messageArgument,
542 title: Flag.String("title").pipe(
543 Flag.withDescription("Thread title. Defaults to the message's first line."),
544 Flag.optional,
545 ),
546 provider: Flag.String("provider").pipe(
547 Flag.withDescription("Provider instance id. Pass with --model."),
548 Flag.optional,
549 ),
550 model: Flag.String("model").pipe(
551 Flag.withDescription("Model slug. Defaults to the project's default model."),
552 Flag.optional,
553 ),
554 worktree: Flag.String("worktree").pipe(
555 Flag.withDescription(
556 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
557 ),
558 Flag.optional,
559 ),
560 branch: Flag.String("branch").pipe(
561 Flag.withDescription("Branch name for the new worktree."),
562 Flag.optional,
563 ),
564 wait: waitFlag,
565 json: jsonFlag,
566}).pipe(
567 Command.withDescription("Start a thread in a project and print its id."),
568 Command.withHandler((flags) =>
569 Effect.gen(function* () {
570 const message = yield* readMessageArgument(flags.message);
571 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
572 if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
573 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
574 }
575 const title = yield* decodeTitle(
576 Option.getOrElse(flags.title, () => titleFromMessage(message)),
577 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
578 yield* withThreadTools(
579 flags,
580 Effect.fn("cli.thread.start")(function* (tools) {
581 const project = yield* resolveProject(tools, flags.project);
582 const launched = yield* tools.call(
583 "t3_thread_launch",
584 {
585 projectId: project.id,
586 title,
587 message,
588 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
589 ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
590 ? {
591 modelSelection: {
592 instanceId: flags.provider.value,
593 model: flags.model.value,
594 },
595 }
596 : {}),
597 },
598 ThreadLaunchResult,
599 );
600 if (flags.wait && launched.runId !== null) {
601 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
602 return yield* finishRun(tools, {
603 threadId: launched.threadId,
604 runId: launched.runId,
605 json: flags.json,
606 });
607 }
608 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
609 }),
610 );
611 }).pipe(reportThreadErrors),
612 ),
613);
614​
615const threadSendCommand = Command.make("send", {
616 ...projectLocationFlags,
617 thread: threadArgument,
618 message: messageArgument,
619 wait: waitFlag,
620 json: jsonFlag,
621}).pipe(
622 Command.withDescription(
623 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
624 ),
625 Command.withHandler((flags) =>
626 Effect.gen(function* () {
627 const threadId = yield* decodeThreadId(flags.thread);
628 const message = yield* readMessageArgument(flags.message);
629 yield* withThreadTools(
630 flags,
631 Effect.fn("cli.thread.send")(function* (tools) {
632 const sent = yield* tools.call(
633 "t3_thread_send",
634 { threadId, message, mode: "queue" },
635 OrchestratorMcpThreadSendResult,
636 );
637 if (flags.wait) {
638 return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
639 }
640 yield* flags.json
641 ? printJson(sent)
642 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
643 }),
644 );
645 }).pipe(reportThreadErrors),
646 ),
647);
648​
649const threadShowCommand = Command.make("show", {
650 ...projectLocationFlags,
651 thread: threadArgument,
652 messages: Flag.Int("messages").pipe(
653 Flag.withDescription("How many of the latest messages to print."),
654 Flag.withDefault(10),
655 ),
656 json: jsonFlag,
657}).pipe(
658 Command.withDescription("Show a thread's state and its latest messages."),
659 Command.withHandler((flags) =>
660 Effect.gen(function* () {
661 const threadId = yield* decodeThreadId(flags.thread);
662 yield* withThreadTools(
663 flags,
664 Effect.fn("cli.thread.show")(function* (tools) {
665 const { thread, items } = yield* readTimeline(tools, threadId, "messages");
666 const conversation = items.filter(
667 (item) => item.type === "user_message" || item.type === "assistant_message",
668 );
669 const latest = conversation.slice(Math.max(0, conversation.length - flags.messages));
670 const messages = yield* Effect.forEach(latest, (item) =>
671 readFullText(tools, threadId, item).pipe(
672 Effect.map((text) => ({
673 role: item.type === "user_message" ? "user" : "assistant",
674 runId: item.runId,
675 text,
676 })),
677 ),
678 );
679 if (flags.json) {
680 return yield* printJson({ thread, messages });
681 }
682 yield* Console.log(thread.title);
683 yield* Console.log(
684 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
685 " ",
686 ),
687 );
688 if (thread.worktreePath !== null) {
689 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
690 }
691 if (thread.pendingRequestCount > 0) {
692 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
693 }
694 for (const entry of messages) {
695 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
696 }
697 }),
698 );
699 }).pipe(reportThreadErrors),
700 ),
701);
702​
703export const threadCommand = Command.make("thread").pipe(
704 Command.withDescription("Start, message, and read threads on the running server."),
705 Command.withSubcommands([
706 threadListCommand,
707 threadStartCommand,
708 threadSendCommand,
709 threadShowCommand,
710 ]),
711);