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 { 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 }
51}
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 }
62}
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 }
72}
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 }
81}
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 }
91}
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 }
104}
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 }
115}
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/**
337 * The latest `count` user and assistant messages, oldest first. Positions
338 * count every timeline item, so the read starts near the end and widens
339 * backward only while tool and plan items leave too few messages.
340 */
341export const readLatestMessages = Effect.fn("cli.thread.readLatestMessages")(function* (
342 tools: ThreadTools,
343 threadId: ThreadId,
344 count: number,
345) {
346 let { thread } = yield* tools.call(
347 "t3_thread_read",
348 { threadId, limit: 1, runLimit: 1 },
349 OrchestratorMcpThreadReadResult,
350 );
351 let messages: Array<OrchestratorMcpThreadTimelineItem> = [];
352 // The newest window has no upper bound, so items added since the first
353 // read are still shown.
354 let before: number | undefined;
355 let start = thread.itemCount;
356 let span = Math.max(count, READ_PAGE_LIMIT);
357 do {
358 const end = before;
359 start = Math.max(0, start - span);
360 const window: Array<OrchestratorMcpThreadTimelineItem> = [];
361 let afterPosition = start - 1;
362 let page: OrchestratorMcpThreadReadResult;
363 do {
364 page = yield* tools.call(
365 "t3_thread_read",
366 {
367 threadId,
368 view: "messages",
369 limit: READ_PAGE_LIMIT,
370 runLimit: 1,
371 ...(afterPosition < 0 ? {} : { afterPosition }),
372 },
373 OrchestratorMcpThreadReadResult,
374 );
375 window.push(
376 ...page.items.filter(
377 (item) =>
378 (item.type === "user_message" || item.type === "assistant_message") &&
379 (end === undefined || item.position < end),
380 ),
381 );
382 afterPosition = page.nextPosition ?? Number.POSITIVE_INFINITY;
383 } while (page.hasMore && afterPosition < (end ?? Number.POSITIVE_INFINITY) - 1);
384 thread = page.thread;
385 // A window can hold the whole --messages count, too many to spread as arguments.
386 messages = window.concat(messages);
387 before = start;
388 span *= 2;
389 } while (messages.length < count && start > 0);
390 return { thread, messages: messages.slice(Math.max(0, messages.length - count)) };
391});
392
393/** Item text past the read's per-item cap. */
394const readFullText = Effect.fn("cli.thread.readFullText")(function* (
395 tools: ThreadTools,
396 threadId: ThreadId,
397 item: OrchestratorMcpThreadTimelineItem,
398) {
399 let text = item.text ?? "";
400 let nextTextOffset = item.textTruncated ? (item.nextTextOffset ?? null) : null;
401 while (nextTextOffset !== null) {
402 const page = yield* tools.call(
403 "t3_thread_read",
404 { threadId, itemId: item.itemId, textOffset: nextTextOffset, runLimit: 1 },
405 OrchestratorMcpThreadReadResult,
406 );
407 const chunk = page.items.find((candidate) => candidate.itemId === item.itemId);
408 if (chunk === undefined) break;
409 text += chunk.text ?? "";
410 nextTextOffset = chunk.textTruncated ? (chunk.nextTextOffset ?? null) : null;
411 }
412 return text;
413});
414
415/** The run's last assistant message, or its last error when it did not complete. */
416const runResultText = Effect.fn("cli.thread.runResultText")(function* (
417 tools: ThreadTools,
418 threadId: ThreadId,
419 runId: RunId,
420 type: "assistant_message" | "error",
421) {
422 const { items } = yield* readTimeline(
423 tools,
424 threadId,
425 type === "assistant_message" ? "messages" : "activity",
426 );
427 const item = items.findLast((candidate) => candidate.runId === runId && candidate.type === type);
428 return item === undefined ? null : yield* readFullText(tools, threadId, item);
429});
430
431type WaitOutcome =
432 | {
433 readonly type: "ended";
434 readonly runId: RunId | null;
435 readonly status: OrchestratorMcpThreadStatus;
436 }
437 | { readonly type: "needs_input" };
438
439/**
440 * Waits for this exact run, following a restart to its continuation, so a
441 * message another client sends meanwhile cannot stand in for its result.
442 */
443export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
444 tools: ThreadTools,
445 threadId: ThreadId,
446 runId: RunId,
447) {
448 const waitSlice = (timeoutMs: number) =>
449 tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
450 const ended = (waited: OrchestratorMcpThreadWaitResult) =>
451 ({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
452 while (true) {
453 const waited = yield* waitSlice(WAIT_SLICE_MS);
454 if (!waited.timedOut) return ended(waited);
455 // A pending request on this run, or on an earlier run this one is queued
456 // behind, blocks it until someone answers.
457 const { thread } = yield* tools.call(
458 "t3_thread_read",
459 { threadId, limit: 1, runLimit: 1 },
460 OrchestratorMcpThreadReadResult,
461 );
462 if (thread.pendingRequestCount > 0) {
463 // The count is thread-wide: if this run ended since the slice, the
464 // request belongs to a later run.
465 const recheck = yield* waitSlice(1);
466 return recheck.timedOut ? ({ type: "needs_input" } satisfies WaitOutcome) : ended(recheck);
467 }
468 }
469});
470
471/**
472 * With --json the result always reaches stdout, so a script keeps the thread
473 * id even when the run fails.
474 */
475const finishRun = Effect.fn("cli.thread.finishRun")(function* (
476 tools: ThreadTools,
477 input: {
478 readonly threadId: ThreadId;
479 readonly runId: RunId;
480 readonly json: boolean;
481 },
482) {
483 const outcome = yield* waitForRun(tools, input.threadId, input.runId);
484 const runId = outcome.type === "ended" ? (outcome.runId ?? input.runId) : input.runId;
485 const status = outcome.type === "ended" ? outcome.status : "waiting";
486 const reply =
487 status === "completed"
488 ? yield* runResultText(tools, input.threadId, runId, "assistant_message")
489 : null;
490 const error =
491 status === "completed" || status === "waiting"
492 ? null
493 : yield* runResultText(tools, input.threadId, runId, "error");
494 if (input.json) {
495 yield* printJson({ threadId: input.threadId, runId, status, reply, error });
496 } else if (reply !== null) {
497 yield* Console.log(reply);
498 }
499 if (outcome.type === "needs_input") {
500 return yield* new ThreadNeedsInputError({ threadId: input.threadId });
501 }
502 if (status !== "completed") {
503 return yield* new ThreadRunEndedError({
504 threadId: input.threadId,
505 status,
506 ...(error === null ? {} : { error }),
507 });
508 }
509});
510
511const titleFromMessage = (message: string) => {
512 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
513 return firstLine.length > TITLE_MAX_CHARS
514 ? `${firstLine.slice(0, TITLE_MAX_CHARS - 1).trimEnd()}…`
515 : firstLine;
516};
517
518const launchWorkspaceStrategy = (input: {
519 readonly worktree: Option.Option<string>;
520 readonly branch: Option.Option<string>;
521}) =>
522 Option.match(input.worktree, {
523 onNone: () =>
524 Option.isSome(input.branch)
525 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
526 : Effect.void,
527 onSome: (baseRef) =>
528 Effect.succeed({
529 type: "worktree" as const,
530 baseRef,
531 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
532 }),
533 });
534
535const jsonFlag = Flag.Boolean("json").pipe(
536 Flag.withDescription("Print JSON instead of text."),
537 Flag.withDefault(false),
538);
539const waitFlag = Flag.Boolean("wait").pipe(
540 Flag.withDescription(
541 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
542 ),
543 Flag.withDefault(false),
544);
545const messageArgument = Argument.String("message").pipe(
546 Argument.withDescription("Message for the agent, or - to read it from stdin."),
547);
548const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
549
550const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
551const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
552const decodeThreadId = (value: string) =>
553 decodeThreadIdValue(value.trim()).pipe(
554 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
555 );
556
557const threadListCommand = Command.make("list", {
558 ...projectLocationFlags,
559 project: Flag.String("project").pipe(
560 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
561 Flag.withDefault("."),
562 ),
563 json: jsonFlag,
564}).pipe(
565 Command.withDescription("List a project's threads, newest first."),
566 Command.withHandler((flags) =>
567 withThreadTools(
568 flags,
569 Effect.fn("cli.thread.list")(function* (tools) {
570 const project = yield* resolveProject(tools, flags.project);
571 const threads: Array<OrchestratorMcpThreadListItem> = [];
572 let cursor: number | null = 0;
573 while (cursor !== null) {
574 const page: OrchestratorMcpThreadListResult = yield* tools.call(
575 "t3_thread_list",
576 { projectId: project.id, includeSubagents: false, limit: 100, cursor },
577 OrchestratorMcpThreadListResult,
578 );
579 threads.push(...page.threads);
580 cursor = page.nextCursor;
581 }
582 if (flags.json) {
583 return yield* printJson(threads);
584 }
585 for (const thread of threads) {
586 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
587 }
588 }),
589 ).pipe(reportThreadErrors),
590 ),
591);
592
593const threadStartCommand = Command.make("start", {
594 ...projectLocationFlags,
595 project: Argument.String("project").pipe(
596 Argument.withDescription("Project id or a path inside the project, such as ."),
597 ),
598 message: messageArgument,
599 title: Flag.String("title").pipe(
600 Flag.withDescription("Thread title. Defaults to the message's first line."),
601 Flag.optional,
602 ),
603 provider: Flag.String("provider").pipe(
604 Flag.withDescription("Provider instance id. Pass with --model."),
605 Flag.optional,
606 ),
607 model: Flag.String("model").pipe(
608 Flag.withDescription("Model slug. Defaults to the project's default model."),
609 Flag.optional,
610 ),
611 worktree: Flag.String("worktree").pipe(
612 Flag.withDescription(
613 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
614 ),
615 Flag.optional,
616 ),
617 branch: Flag.String("branch").pipe(
618 Flag.withDescription("Branch name for the new worktree."),
619 Flag.optional,
620 ),
621 wait: waitFlag,
622 json: jsonFlag,
623}).pipe(
624 Command.withDescription("Start a thread in a project and print its id."),
625 Command.withHandler((flags) =>
626 Effect.gen(function* () {
627 const message = yield* readMessageArgument(flags.message);
628 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
629 if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
630 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
631 }
632 const title = yield* decodeTitle(
633 Option.getOrElse(flags.title, () => titleFromMessage(message)),
634 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
635 yield* withThreadTools(
636 flags,
637 Effect.fn("cli.thread.start")(function* (tools) {
638 const project = yield* resolveProject(tools, flags.project);
639 const launched = yield* tools.call(
640 "t3_thread_launch",
641 {
642 projectId: project.id,
643 title,
644 message,
645 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
646 ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
647 ? {
648 modelSelection: {
649 instanceId: flags.provider.value,
650 model: flags.model.value,
651 },
652 }
653 : {}),
654 },
655 ThreadLaunchResult,
656 );
657 if (flags.wait && launched.runId !== null) {
658 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
659 return yield* finishRun(tools, {
660 threadId: launched.threadId,
661 runId: launched.runId,
662 json: flags.json,
663 });
664 }
665 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
666 }),
667 );
668 }).pipe(reportThreadErrors),
669 ),
670);
671
672const threadSendCommand = Command.make("send", {
673 ...projectLocationFlags,
674 thread: threadArgument,
675 message: messageArgument,
676 wait: waitFlag,
677 json: jsonFlag,
678}).pipe(
679 Command.withDescription(
680 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
681 ),
682 Command.withHandler((flags) =>
683 Effect.gen(function* () {
684 const threadId = yield* decodeThreadId(flags.thread);
685 const message = yield* readMessageArgument(flags.message);
686 yield* withThreadTools(
687 flags,
688 Effect.fn("cli.thread.send")(function* (tools) {
689 const sent = yield* tools.call(
690 "t3_thread_send",
691 { threadId, message, mode: "queue" },
692 OrchestratorMcpThreadSendResult,
693 );
694 if (flags.wait) {
695 return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
696 }
697 yield* flags.json
698 ? printJson(sent)
699 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
700 }),
701 );
702 }).pipe(reportThreadErrors),
703 ),
704);
705
706const threadShowCommand = Command.make("show", {
707 ...projectLocationFlags,
708 thread: threadArgument,
709 messages: Flag.Int("messages").pipe(
710 Flag.withDescription("How many of the latest messages to print."),
711 Flag.withDefault(10),
712 ),
713 json: jsonFlag,
714}).pipe(
715 Command.withDescription("Show a thread's state and its latest messages."),
716 Command.withHandler((flags) =>
717 Effect.gen(function* () {
718 const threadId = yield* decodeThreadId(flags.thread);
719 yield* withThreadTools(
720 flags,
721 Effect.fn("cli.thread.show")(function* (tools) {
722 const { thread, messages: latest } = yield* readLatestMessages(
723 tools,
724 threadId,
725 flags.messages,
726 );
727 const messages = yield* Effect.forEach(latest, (item) =>
728 readFullText(tools, threadId, item).pipe(
729 Effect.map((text) => ({
730 role: item.type === "user_message" ? "user" : "assistant",
731 runId: item.runId,
732 text,
733 })),
734 ),
735 );
736 if (flags.json) {
737 return yield* printJson({ thread, messages });
738 }
739 yield* Console.log(thread.title);
740 yield* Console.log(
741 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
742 " ",
743 ),
744 );
745 if (thread.worktreePath !== null) {
746 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
747 }
748 if (thread.pendingRequestCount > 0) {
749 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
750 }
751 for (const entry of messages) {
752 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
753 }
754 }),
755 );
756 }).pipe(reportThreadErrors),
757 ),
758);
759
760export const threadCommand = Command.make("thread").pipe(
761 Command.withDescription("Start, message, and read threads on the running server."),
762 Command.withSubcommands([
763 threadListCommand,
764 threadStartCommand,
765 threadSendCommand,
766 threadShowCommand,
767 ]),
768);