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
511export const titleFromMessage = (message: string) => {
512 const firstLine = message.trim().split("\n")[0]?.trim() ?? "";
513 if (firstLine.length <= TITLE_MAX_CHARS) return firstLine;
514 let end = TITLE_MAX_CHARS - 1;
515 const previous = firstLine.charCodeAt(end - 1);
516 const next = firstLine.charCodeAt(end);
517 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
518 end -= 1;
519 }
520 return `${firstLine.slice(0, end).trimEnd()}…`;
521};
522
523const launchWorkspaceStrategy = (input: {
524 readonly worktree: Option.Option<string>;
525 readonly branch: Option.Option<string>;
526}) =>
527 Option.match(input.worktree, {
528 onNone: () =>
529 Option.isSome(input.branch)
530 ? Effect.fail(new ThreadUsageError({ detail: "--branch needs --worktree <base-ref>." }))
531 : Effect.void,
532 onSome: (baseRef) =>
533 Effect.succeed({
534 type: "worktree" as const,
535 baseRef,
536 ...Option.match(input.branch, { onNone: () => ({}), onSome: (branch) => ({ branch }) }),
537 }),
538 });
539
540const jsonFlag = Flag.Boolean("json").pipe(
541 Flag.withDescription("Print JSON instead of text."),
542 Flag.withDefault(false),
543);
544const waitFlag = Flag.Boolean("wait").pipe(
545 Flag.withDescription(
546 "Wait for the agent to finish and print its reply. Exits 1 if the run fails and 2 if it waits for an answer.",
547 ),
548 Flag.withDefault(false),
549);
550const messageArgument = Argument.String("message").pipe(
551 Argument.withDescription("Message for the agent, or - to read it from stdin."),
552);
553const threadArgument = Argument.String("thread").pipe(Argument.withDescription("Thread id."));
554
555const decodeThreadIdValue = Schema.decodeUnknownEffect(ThreadId);
556const decodeTitle = Schema.decodeUnknownEffect(TrimmedNonEmptyString);
557const decodeThreadId = (value: string) =>
558 decodeThreadIdValue(value.trim()).pipe(
559 Effect.mapError(() => new ThreadUsageError({ detail: `'${value}' is not a thread id.` })),
560 );
561
562const threadListCommand = Command.make("list", {
563 ...projectLocationFlags,
564 project: Flag.String("project").pipe(
565 Flag.withDescription("Project id or a path inside the project. Defaults to this directory."),
566 Flag.withDefault("."),
567 ),
568 json: jsonFlag,
569}).pipe(
570 Command.withDescription("List a project's threads, newest first."),
571 Command.withHandler((flags) =>
572 withThreadTools(
573 flags,
574 Effect.fn("cli.thread.list")(function* (tools) {
575 const project = yield* resolveProject(tools, flags.project);
576 const threads: Array<OrchestratorMcpThreadListItem> = [];
577 let cursor: number | null = 0;
578 while (cursor !== null) {
579 const page: OrchestratorMcpThreadListResult = yield* tools.call(
580 "t3_thread_list",
581 { projectId: project.id, includeSubagents: false, limit: 100, cursor },
582 OrchestratorMcpThreadListResult,
583 );
584 threads.push(...page.threads);
585 cursor = page.nextCursor;
586 }
587 if (flags.json) {
588 return yield* printJson(threads);
589 }
590 for (const thread of threads) {
591 yield* Console.log(`${thread.threadId} ${thread.status.padEnd(11)} ${thread.title}`);
592 }
593 }),
594 ).pipe(reportThreadErrors),
595 ),
596);
597
598const threadStartCommand = Command.make("start", {
599 ...projectLocationFlags,
600 project: Argument.String("project").pipe(
601 Argument.withDescription("Project id or a path inside the project, such as ."),
602 ),
603 message: messageArgument,
604 title: Flag.String("title").pipe(
605 Flag.withDescription("Thread title. Defaults to the message's first line."),
606 Flag.optional,
607 ),
608 provider: Flag.String("provider").pipe(
609 Flag.withDescription("Provider instance id. Pass with --model."),
610 Flag.optional,
611 ),
612 model: Flag.String("model").pipe(
613 Flag.withDescription("Model slug. Defaults to the project's default model."),
614 Flag.optional,
615 ),
616 worktree: Flag.String("worktree").pipe(
617 Flag.withDescription(
618 "Run in a new git worktree based on this branch, tag, or commit, instead of the project folder.",
619 ),
620 Flag.optional,
621 ),
622 branch: Flag.String("branch").pipe(
623 Flag.withDescription("Branch name for the new worktree."),
624 Flag.optional,
625 ),
626 wait: waitFlag,
627 json: jsonFlag,
628}).pipe(
629 Command.withDescription("Start a thread in a project and print its id."),
630 Command.withHandler((flags) =>
631 Effect.gen(function* () {
632 const message = yield* readMessageArgument(flags.message);
633 const workspaceStrategy = yield* launchWorkspaceStrategy(flags);
634 if (Option.isSome(flags.provider) !== Option.isSome(flags.model)) {
635 return yield* new ThreadUsageError({ detail: "--provider and --model go together." });
636 }
637 const title = yield* decodeTitle(
638 Option.getOrElse(flags.title, () => titleFromMessage(message)),
639 ).pipe(Effect.mapError(() => new ThreadUsageError({ detail: "The title is empty." })));
640 yield* withThreadTools(
641 flags,
642 Effect.fn("cli.thread.start")(function* (tools) {
643 const project = yield* resolveProject(tools, flags.project);
644 const launched = yield* tools.call(
645 "t3_thread_launch",
646 {
647 projectId: project.id,
648 title,
649 message,
650 ...(workspaceStrategy === undefined ? {} : { workspaceStrategy }),
651 ...(Option.isSome(flags.provider) && Option.isSome(flags.model)
652 ? {
653 modelSelection: {
654 instanceId: flags.provider.value,
655 model: flags.model.value,
656 },
657 }
658 : {}),
659 },
660 ThreadLaunchResult,
661 );
662 if (flags.wait && launched.runId !== null) {
663 if (!flags.json) yield* Console.error(`Thread ${launched.threadId}`);
664 return yield* finishRun(tools, {
665 threadId: launched.threadId,
666 runId: launched.runId,
667 json: flags.json,
668 });
669 }
670 yield* flags.json ? printJson(launched) : Console.log(launched.threadId);
671 }),
672 );
673 }).pipe(reportThreadErrors),
674 ),
675);
676
677const threadSendCommand = Command.make("send", {
678 ...projectLocationFlags,
679 thread: threadArgument,
680 message: messageArgument,
681 wait: waitFlag,
682 json: jsonFlag,
683}).pipe(
684 Command.withDescription(
685 "Send a message to a thread. A busy thread gets it as its next turn; nothing is interrupted.",
686 ),
687 Command.withHandler((flags) =>
688 Effect.gen(function* () {
689 const threadId = yield* decodeThreadId(flags.thread);
690 const message = yield* readMessageArgument(flags.message);
691 yield* withThreadTools(
692 flags,
693 Effect.fn("cli.thread.send")(function* (tools) {
694 const sent = yield* tools.call(
695 "t3_thread_send",
696 { threadId, message, mode: "queue" },
697 OrchestratorMcpThreadSendResult,
698 );
699 if (flags.wait) {
700 return yield* finishRun(tools, { threadId, runId: sent.runId, json: flags.json });
701 }
702 yield* flags.json
703 ? printJson(sent)
704 : Console.log(sent.delivery === "queued" ? "Queued." : "Sent.");
705 }),
706 );
707 }).pipe(reportThreadErrors),
708 ),
709);
710
711const threadShowCommand = Command.make("show", {
712 ...projectLocationFlags,
713 thread: threadArgument,
714 messages: Flag.Int("messages").pipe(
715 Flag.withDescription("How many of the latest messages to print."),
716 Flag.withDefault(10),
717 ),
718 json: jsonFlag,
719}).pipe(
720 Command.withDescription("Show a thread's state and its latest messages."),
721 Command.withHandler((flags) =>
722 Effect.gen(function* () {
723 const threadId = yield* decodeThreadId(flags.thread);
724 yield* withThreadTools(
725 flags,
726 Effect.fn("cli.thread.show")(function* (tools) {
727 const { thread, messages: latest } = yield* readLatestMessages(
728 tools,
729 threadId,
730 flags.messages,
731 );
732 const messages = yield* Effect.forEach(latest, (item) =>
733 readFullText(tools, threadId, item).pipe(
734 Effect.map((text) => ({
735 role: item.type === "user_message" ? "user" : "assistant",
736 runId: item.runId,
737 text,
738 })),
739 ),
740 );
741 if (flags.json) {
742 return yield* printJson({ thread, messages });
743 }
744 yield* Console.log(thread.title);
745 yield* Console.log(
746 [thread.threadId, thread.status, `${thread.providerInstanceId}/${thread.model}`].join(
747 " ",
748 ),
749 );
750 if (thread.worktreePath !== null) {
751 yield* Console.log(`${thread.branch ?? "(no branch)"} ${thread.worktreePath}`);
752 }
753 if (thread.pendingRequestCount > 0) {
754 yield* Console.log(`Waiting for ${thread.pendingRequestCount} answer(s).`);
755 }
756 for (const entry of messages) {
757 yield* Console.log(`\n[${entry.role}]\n${entry.text}`);
758 }
759 }),
760 );
761 }).pipe(reportThreadErrors),
762 ),
763);
764
765export const threadCommand = Command.make("thread").pipe(
766 Command.withDescription("Start, message, and read threads on the running server."),
767 Command.withSubcommands([
768 threadListCommand,
769 threadStartCommand,
770 threadSendCommand,
771 threadShowCommand,
772 ]),
773);