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

thread.ts

710 lines25.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 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 client: { deviceType: "bot" },
225 }),
226 (session) =>
227 environmentAuth.revokeSession(session.sessionId).pipe(Effect.ignore({ log: true })),
228 );
229 const session = yield* mcpToolSession({
230 endpoint: new URL("/mcp", origin).href,
231 authorization: `Bearer ${issued.token}`,
232 clientName: "t3-thread-cli",
233 }).pipe(Effect.mapError((cause) => new ThreadServerUnreachableError({ origin, cause })));
234 return yield* run(makeThreadTools(session, origin));
235 }).pipe(
236 Effect.scoped,
237 Effect.provide(
238 EnvironmentAuth.layerRuntime.pipe(
239 Layer.provide(ServerConfig.layer(config)),
240 Layer.provide(Layer.succeed(References.MinimumLogLevel, config.logLevel)),
241 ),
242 ),
243 );
244});
245​
246const readMessageArgument = Effect.fn("cli.thread.readMessage")(function* (argument: string) {
247 const text =
248 argument === "-"
249 ? yield* Stdio.Stdio.pipe(
250 Effect.flatMap((stdio) => stdio.stdin.pipe(Stream.decodeText(), Stream.mkString)),
251 )
252 : argument;
253 if (text.trim().length === 0) {
254 return yield* new ThreadUsageError({ detail: "The message is empty." });
255 }
256 return text;
257});
258​
259const listAllProjects = Effect.fn("cli.thread.listAllProjects")(function* (tools: ThreadTools) {
260 const projects: Array<(typeof ProjectListResult.Type)["projects"][number]> = [];
261 let cursor: number | null = 0;
262 while (cursor !== null) {
263 const page: typeof ProjectListResult.Type = yield* tools.call(
264 "t3_project_list",
265 { cursor, limit: 100 },
266 ProjectListResult,
267 );
268 projects.push(...page.projects);
269 cursor = page.nextCursor;
270 }
271 return projects;
272});
273​
274/** A project id, or a path inside a project's folder (deepest project wins). */
275const resolveProject = Effect.fn("cli.thread.resolveProject")(function* (
276 tools: ThreadTools,
277 identifier: string,
278) {
279 const projects = yield* listAllProjects(tools);
280 const byId = projects.find((project) => project.id === identifier);
281 if (byId !== undefined) return byId;
282​
283 const path = yield* Path.Path;
284 const fileSystem = yield* FileSystem.FileSystem;
285 // Stored roots keep the path the project was added with, which may pass
286 // through a symlink (macOS /tmp), so both sides compare as real paths.
287 const realPath = (value: string) =>
288 fileSystem.realPath(value).pipe(Effect.orElseSucceed(() => value));
289 const target = yield* realPath(path.resolve(yield* HostProcess.WorkingDirectory, identifier));
290 const roots = yield* Effect.forEach(projects, (project) =>
291 Effect.map(realPath(project.workspaceRoot), (root) => ({ project, root })),
292 );
293 const containing = roots
294 .filter(({ root }) => {
295 const relative = path.relative(root, target);
296 return (
297 relative === "" ||
298 (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
299 );
300 })
301 .toSorted((left, right) => right.root.length - left.root.length)[0];
302 if (containing === undefined) {
303 return yield* new ThreadProjectNotFoundError({ identifier });
304 }
305 return containing.project;
306});
307​
308/** Every item on a timeline view, oldest first. */
309const readTimeline = Effect.fn("cli.thread.readTimeline")(function* (
310 tools: ThreadTools,
311 threadId: ThreadId,
312 view: "messages" | "activity",
313) {
314 const items: Array<OrchestratorMcpThreadTimelineItem> = [];
315 let afterPosition: number | undefined;
316 let page: OrchestratorMcpThreadReadResult;
317 do {
318 page = yield* tools.call(
319 "t3_thread_read",
320 {
321 threadId,
322 view,
323 limit: READ_PAGE_LIMIT,
324 runLimit: 1,
325 ...(afterPosition === undefined ? {} : { afterPosition }),
326 },
327 OrchestratorMcpThreadReadResult,
328 );
329 items.push(...page.items);
330 afterPosition = page.nextPosition ?? undefined;
331 } while (page.hasMore && afterPosition !== undefined);
332 return { thread: page.thread, items };
333});
334​
335/** Item text past the read's per-item cap. */
336const readFullText = Effect.fn("cli.thread.readFullText")(function* (
337 tools: ThreadTools,
338 threadId: ThreadId,
339 item: OrchestratorMcpThreadTimelineItem,
340) {
341 let text = item.text ?? "";
342 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
343 while (nextTextOffset !== null) {
344 const page = yield* tools.call(
345 "t3_thread_read",
346 { threadId, itemId: item.itemId, textOffset: nextTextOffset, runLimit: 1 },
347 OrchestratorMcpThreadReadResult,
348 );
349 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
350 if (chunk === undefined) break;
351 text += chunk.text ?? "";
352 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
353 }
354 return text;
355});
356​
357/** The run's last assistant message, or its last error when it did not complete. */
358const runResultText = Effect.fn("cli.thread.runResultText")(function* (
359 tools: ThreadTools,
360 threadId: ThreadId,
361 runId: RunId,
362 type: "assistant_message" | "error",
363) {
364 const { items } = yield* readTimeline(
365 tools,
366 threadId,
367 type === "assistant_message" ? "messages" : "activity",
368 );
369 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
370 return item === undefined ? null : yield* readFullText(tools, threadId, item);
371});
372​
373type WaitOutcome =
374 | {
375 readonly type: "ended";
376 readonly runId: RunId | null;
377 readonly status: OrchestratorMcpThreadStatus;
378 }
379 | { readonly type: "needs_input" };
380​
381/**
382 * Waits for this exact run, following a restart to its continuation, so a
383 * message another client sends meanwhile cannot stand in for its result.
384 */
385export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
386 tools: ThreadTools,
387 threadId: ThreadId,
388 runId: RunId,
389) {
390 const waitSlice = (timeoutMs: number) =>
391 tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
392 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
393 ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
394 while (true) {
395 const waited = yield* waitSlice(WAIT_SLICE_MS);
396 if (!waited.timedOut) return ended(waited);
397 // A pending request on this run, or on an earlier run this one is queued
398 // behind, blocks it until someone answers.
399 const { thread } = yield* tools.call(
400 "t3_thread_read",
401 { threadId, limit: 1, runLimit: 1 },
402 OrchestratorMcpThreadReadResult,
403 );
404 if (thread.pendingRequestCount > 0) {
405 // The count is thread-wide: if this run ended since the slice, the
406 // request belongs to a later run.
407 const recheck = yield* waitSlice(1);
408 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
409 }
410 }
411});
412​
413/**
414 * With --json the result always reaches stdout, so a script keeps the thread
415 * id even when the run fails.
416 */
417const finishRun = Effect.fn("cli.thread.finishRun")(function* (
418 tools: ThreadTools,
419 input: {
420 readonly threadId: ThreadId;
421 readonly runId: RunId;
422 readonly json: boolean;
423 },
424) {
425 const outcome = yield* waitForRun(tools, input.threadId, input.runId);
426 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
427 const status = outcome.type === "ended" ? outcome.status : "waiting";
428 const reply =
429 status === "completed"
430 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
431 : null;
432 const error =
433 status === "completed" || status === "waiting"
434 ? null
435 : yield* runResultText(tools, input.threadId, runId, "error");
436 if (input.json) {
437 yield* printJson({ threadId: input.threadId, runId, status, reply, error });
438 } else if (reply !== null) {
439 yield* Console.log(reply);
440 }
441 if (outcome.type === "needs_input") {
442 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
443 }
444 if (status !== "completed") {
445 return yield* new ThreadRunEndedError({
446 threadId: input.threadId,
447 status,
448 ...(error === null ? {} : { error }),
449 });
450 }
451});
452​
453const titleFromMessage = (message: string) => {
454 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
455 return firstLine.length > TITLE_MAX_CHARS
456 ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`
457 : firstLine;
458};
459​
460const launchWorkspaceStrategy = (input: {
461 readonly worktree: Option.Option<string>;
462 readonly branch: Option.Option<string>;
463}) =>
464 Option.match(input.worktree, {
465 onNone: () =>
466 Option.isSome(input.branch)
467 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
468 : Effect.void,
469 onSome: (baseRef) =>
470 Effect.succeed({
471 type: "worktree" as const,
472 baseRef,
473 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
474 }),
475 });
476​
477const jsonFlag = Flag.Boolean("json").pipe(
478 Flag.withDescription("Print JSON instead of text."),
479 Flag.withDefault(false),
480);
481const waitFlag = Flag.Boolean("wait").pipe(
482 Flag.withDescription(
483 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
484 ),
485 Flag.withDefault(false),
486);
487const messageArgument = Argument.String("message").pipe(
488 Argument.withDescription("Message for the agent, or - to read it from stdin."),
489);
490const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
491​
492const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
493const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
494const decodeThreadId = (value: string) =>
495 decodeThreadIdValue(value.trim()).pipe(
496 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
497 );
498​
499const threadListCommand = Command.make("list", {
500 ...projectLocationFlags,
501 project: Flag.String("project").pipe(
502 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
503 Flag.withDefault("."),
504 ),
505 json: jsonFlag,
506}).pipe(
507 Command.withDescription("List a project's threads, newest first."),
508 Command.withHandler((flags) =>
509 withThreadTools(
510 flags,
511 Effect.fn("cli.thread.list")(function* (tools) {
512 const project = yield* resolveProject(tools, flags.project);
513 const threads: Array<OrchestratorMcpThreadListItem> = [];
514 let cursor: number | null = 0;
515 while (cursor !== null) {
516 const page: OrchestratorMcpThreadListResult = yield* tools.call(
517 "t3_thread_list",
518 { projectId: project.id, includeSubagents: false, limit: 100, cursor },
519 OrchestratorMcpThreadListResult,
520 );
521 threads.push(...page.threads);
522 cursor = page.nextCursor;
523 }
524 if (flags.json) {
525 return yield* printJson(threads);
526 }
527 for (const thread of threads) {
528 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
529 }
530 }),
531 ).pipe(reportThreadErrors),
532 ),
533);
534​
535const threadStartCommand = Command.make("start", {
536 ...projectLocationFlags,
537 project: Argument.String("project").pipe(
538 Argument.withDescription("Project id or a path inside the project, such as ."),
539 ),
540 message: messageArgument,
541 title: Flag.String("title").pipe(
542 Flag.withDescription("Thread title. Defaults to the message's first line."),
543 Flag.optional,
544 ),
545 provider: Flag.String("provider").pipe(
546 Flag.withDescription("Provider instance id. Pass with --model."),
547 Flag.optional,
548 ),
549 model: Flag.String("model").pipe(
550 Flag.withDescription("Model slug. Defaults to the project's default model."),
551 Flag.optional,
552 ),
553 worktree: Flag.String("worktree").pipe(
554 Flag.withDescription(
555 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
556 ),
557 Flag.optional,
558 ),
559 branch: Flag.String("branch").pipe(
560 Flag.withDescription("Branch name for the new worktree."),
561 Flag.optional,
562 ),
563 wait: waitFlag,
564 json: jsonFlag,
565}).pipe(
566 Command.withDescription("Start a thread in a project and print its id."),
567 Command.withHandler((flags) =>
568 Effect.gen(function* () {
569 const message = yield* readMessageArgument(flags.message);
570 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
571 if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
572 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
573 }
574 const title = yield* decodeTitle(
575 Option.getOrElse(flags.title, () => titleFromMessage(message)),
576 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
577 yield* withThreadTools(
578 flags,
579 Effect.fn("cli.thread.start")(function* (tools) {
580 const project = yield* resolveProject(tools, flags.project);
581 const launched = yield* tools.call(
582 "t3_thread_launch",
583 {
584 projectId: project.id,
585 title,
586 message,
587 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
588 ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
589 ? {
590 modelSelection: {
591 instanceId: flags.provider.value,
592 model: flags.model.value,
593 },
594 }
595 : {}),
596 },
597 ThreadLaunchResult,
598 );
599 if (flags.wait && launched.runId !== null) {
600 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
601 return yield* finishRun(tools, {
602 threadId: launched.threadId,
603 runId: launched.runId,
604 json: flags.json,
605 });
606 }
607 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
608 }),
609 );
610 }).pipe(reportThreadErrors),
611 ),
612);
613​
614const threadSendCommand = Command.make("send", {
615 ...projectLocationFlags,
616 thread: threadArgument,
617 message: messageArgument,
618 wait: waitFlag,
619 json: jsonFlag,
620}).pipe(
621 Command.withDescription(
622 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
623 ),
624 Command.withHandler((flags) =>
625 Effect.gen(function* () {
626 const threadId = yield* decodeThreadId(flags.thread);
627 const message = yield* readMessageArgument(flags.message);
628 yield* withThreadTools(
629 flags,
630 Effect.fn("cli.thread.send")(function* (tools) {
631 const sent = yield* tools.call(
632 "t3_thread_send",
633 { threadId, message, mode: "queue" },
634 OrchestratorMcpThreadSendResult,
635 );
636 if (flags.wait) {
637 return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
638 }
639 yield* flags.json
640 ? printJson(sent)
641 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
642 }),
643 );
644 }).pipe(reportThreadErrors),
645 ),
646);
647​
648const threadShowCommand = Command.make("show", {
649 ...projectLocationFlags,
650 thread: threadArgument,
651 messages: Flag.Int("messages").pipe(
652 Flag.withDescription("How many of the latest messages to print."),
653 Flag.withDefault(10),
654 ),
655 json: jsonFlag,
656}).pipe(
657 Command.withDescription("Show a thread's state and its latest messages."),
658 Command.withHandler((flags) =>
659 Effect.gen(function* () {
660 const threadId = yield* decodeThreadId(flags.thread);
661 yield* withThreadTools(
662 flags,
663 Effect.fn("cli.thread.show")(function* (tools) {
664 const { thread, items } = yield* readTimeline(tools, threadId, "messages");
665 const conversation = items.filter(
666 (item) => item.type === "user_message" || item.type === "assistant_message",
667 );
668 const latest = conversation.slice(Math.max(0, conversation.length - flags.messages));
669 const messages = yield* Effect.forEach(latest, (item) =>
670 readFullText(tools, threadId, item).pipe(
671 Effect.map((text) => ({
672 role: item.type === "user_message" ? "user" : "assistant",
673 runId: item.runId,
674 text,
675 })),
676 ),
677 );
678 if (flags.json) {
679 return yield* printJson({ thread, messages });
680 }
681 yield* Console.log(thread.title);
682 yield* Console.log(
683 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
684 " ",
685 ),
686 );
687 if (thread.worktreePath !== null) {
688 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
689 }
690 if (thread.pendingRequestCount > 0) {
691 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
692 }
693 for (const entry of messages) {
694 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
695 }
696 }),
697 );
698 }).pipe(reportThreadErrors),
699 ),
700);
701​
702export const threadCommand = Command.make("thread").pipe(
703 Command.withDescription("Start, message, and read threads on the running server."),
704 Command.withSubcommands([
705 threadListCommand,
706 threadStartCommand,
707 threadSendCommand,
708 threadShowCommand,
709 ]),
710);