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