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