pi-session-subagents 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/roster.ts ADDED
@@ -0,0 +1,198 @@
1
+ import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import type { AgentToolUpdateCallback, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
4
+ import { isSubagentTool } from "./copy";
5
+ import { buildReport, ReportOutbox } from "./report";
6
+ import { normalizeName, slugify } from "./text";
7
+ import { openInspector } from "./ui/conversation-viewer";
8
+ import { SubagentWidget } from "./ui/widget";
9
+ import { Worker } from "./worker";
10
+ import { closeWorkerSession, createWorkerSession, resolveWorkerCwd } from "./worker-session";
11
+
12
+ export interface SpawnOptions {
13
+ name?: string;
14
+ task?: string;
15
+ model?: string;
16
+ cwd?: string;
17
+ tools?: string[];
18
+ thinking?: ThinkingLevel;
19
+ timeoutMs?: number;
20
+ }
21
+
22
+ export class Roster {
23
+ readonly reports: ReportOutbox;
24
+ private readonly workers = new Map<string, Worker>();
25
+ private readonly widget: SubagentWidget;
26
+ private ctx: ExtensionContext | undefined;
27
+ private disposed = false;
28
+
29
+ constructor(
30
+ private readonly pi: ExtensionAPI,
31
+ private readonly createSession = createWorkerSession,
32
+ ) {
33
+ this.reports = new ReportOutbox(pi);
34
+ this.widget = new SubagentWidget(
35
+ () => this.list(),
36
+ (name) => {
37
+ const ctx = this.ctx;
38
+ if (!ctx) return;
39
+ openInspector(ctx, this.list(), name).catch((error) =>
40
+ ctx.ui.notify(
41
+ `Could not open ${name}: ${error instanceof Error ? error.message : String(error)}`,
42
+ "error",
43
+ ),
44
+ );
45
+ },
46
+ );
47
+ }
48
+
49
+ attach(ctx: ExtensionContext): void {
50
+ this.ctx = ctx;
51
+ this.widget.attach(ctx);
52
+ }
53
+
54
+ list(): Worker[] {
55
+ return [...this.workers.values()].sort((a, b) => a.createdAt - b.createdAt);
56
+ }
57
+
58
+ find(name: string): Worker {
59
+ const normalized = normalizeName(name);
60
+ const worker =
61
+ this.workers.get(name) ?? this.list().find((candidate) => normalizeName(candidate.name) === normalized);
62
+ if (!worker) throw new Error(`Unknown subagent: ${name}`);
63
+ return worker;
64
+ }
65
+
66
+ completions(prefix: string): AutocompleteItem[] | null {
67
+ const items = this.list()
68
+ .filter((worker) => worker.name.startsWith(prefix))
69
+ .map((worker) => ({ value: worker.name, label: `${worker.name} [${worker.status}]` }));
70
+ return items.length > 0 ? items : null;
71
+ }
72
+
73
+ async spawn(options: SpawnOptions, ctx: ExtensionContext, signal?: AbortSignal): Promise<Worker> {
74
+ if (this.disposed) throw new Error("Cannot create a worker after session shutdown.");
75
+ const cwd = resolveWorkerCwd(ctx.cwd, options.cwd);
76
+ const tools = pickTools(this.pi.getActiveTools(), options.tools);
77
+ const { session, modelLabel, warnings } = await this.createSession(ctx, {
78
+ cwd,
79
+ model: options.model,
80
+ thinking: options.thinking ?? this.pi.getThinkingLevel(),
81
+ tools,
82
+ onExtensionError: (warning) => {
83
+ if (!this.disposed && this.ctx?.hasUI) this.ctx.ui.notify(warning, "warning");
84
+ },
85
+ });
86
+ if (this.disposed || signal?.aborted) {
87
+ await closeWorkerSession(session);
88
+ throw new Error(
89
+ this.disposed ? "Worker creation was interrupted by session shutdown." : "Worker creation was cancelled.",
90
+ );
91
+ }
92
+ const worker = new Worker(
93
+ this.uniqueName(options.name),
94
+ session,
95
+ { modelLabel, cwd, requestedTools: tools, warnings },
96
+ (ended) => this.runEnded(ended),
97
+ );
98
+ this.workers.set(worker.name, worker);
99
+ const task = options.task?.trim();
100
+ if (task) worker.start(task, options.timeoutMs);
101
+ this.changed();
102
+ return worker;
103
+ }
104
+
105
+ async message(
106
+ name: string,
107
+ text: string,
108
+ timeoutMs?: number,
109
+ ): Promise<{ worker: Worker; mode: "steer" | "start" | "handled" }> {
110
+ const worker = this.find(name);
111
+ if (worker.status === "running") return { worker, mode: await worker.steer(text) };
112
+ worker.start(text, timeoutMs);
113
+ this.changed();
114
+ return { worker, mode: "start" };
115
+ }
116
+
117
+ async stop(name: string): Promise<Worker> {
118
+ const worker = this.find(name);
119
+ await this.remove(worker);
120
+ return worker;
121
+ }
122
+
123
+ async stopAll(): Promise<void> {
124
+ await Promise.all(this.list().map((worker) => this.remove(worker)));
125
+ }
126
+
127
+ async waitFor(
128
+ names: string[] | undefined,
129
+ timeoutMs: number | undefined,
130
+ signal: AbortSignal | undefined,
131
+ onUpdate: AgentToolUpdateCallback<{ waiting: string[] }> | undefined,
132
+ ): Promise<Worker[]> {
133
+ const targets = names?.length
134
+ ? names.map((name) => this.find(name))
135
+ : this.list().filter((worker) => worker.status === "running");
136
+ const deadline = new AbortController();
137
+ const timer = timeoutMs ? setTimeout(() => deadline.abort(), timeoutMs) : undefined;
138
+ const stop = signal ? AbortSignal.any([signal, deadline.signal]) : deadline.signal;
139
+ const stopped = new Promise<void>((resolve) => stop.addEventListener("abort", () => resolve(), { once: true }));
140
+ try {
141
+ while (true) {
142
+ const running = targets.filter((worker) => worker.status === "running");
143
+ if (signal?.aborted) throw new Error("Aborted");
144
+ if (running.length === 0 || deadline.signal.aborted) return running;
145
+ const waiting = running.map((worker) => worker.name);
146
+ onUpdate?.({
147
+ content: [{ type: "text", text: `Waiting on ${waiting.length} subagent(s): ${waiting.join(", ")}` }],
148
+ details: { waiting },
149
+ });
150
+ await Promise.race([stopped, ...running.map((worker) => worker.settled())]);
151
+ }
152
+ } finally {
153
+ clearTimeout(timer);
154
+ }
155
+ }
156
+
157
+ async dispose(): Promise<void> {
158
+ this.disposed = true;
159
+ this.reports.clear();
160
+ this.widget.dispose();
161
+ await Promise.allSettled(this.list().map((worker) => this.remove(worker)));
162
+ }
163
+
164
+ private remove(worker: Worker): Promise<void> {
165
+ if (this.workers.get(worker.name) === worker) this.workers.delete(worker.name);
166
+ const closing = worker.close();
167
+ this.changed();
168
+ return closing;
169
+ }
170
+
171
+ private runEnded(worker: Worker): void {
172
+ this.changed();
173
+ this.reports.deliver(buildReport(worker), this.ctx);
174
+ }
175
+
176
+ private changed(): void {
177
+ if (!this.disposed) this.widget.refresh();
178
+ }
179
+
180
+ private uniqueName(preferred: string | undefined): string {
181
+ const base = slugify(preferred?.trim() || "worker");
182
+ if (!this.workers.has(base)) return base;
183
+ let count = 2;
184
+ while (this.workers.has(`${base}-${count}`)) count++;
185
+ return `${base}-${count}`;
186
+ }
187
+ }
188
+
189
+ function pickTools(parentTools: string[], requested: string[] | undefined): string[] {
190
+ const available = parentTools.filter((name) => !isSubagentTool(name));
191
+ if (!requested) return available;
192
+ const unavailable = requested.filter((name) => !available.includes(name));
193
+ if (unavailable.length)
194
+ throw new Error(
195
+ `Tools not active in the parent session: ${unavailable.join(", ")}. Available: ${available.join(", ") || "(none)"}.`,
196
+ );
197
+ return [...new Set(requested)];
198
+ }
package/src/text.ts ADDED
@@ -0,0 +1,77 @@
1
+ import type { AssistantMessage } from "@earendil-works/pi-ai";
2
+
3
+ export const RESULT_PAGE_CHARS = 12_000;
4
+
5
+ export function normalizeName(input: string): string {
6
+ return input.toLowerCase().replace(/[^a-z0-9]+/g, "");
7
+ }
8
+
9
+ export function slugify(input: string): string {
10
+ return (
11
+ input
12
+ .toLowerCase()
13
+ .replace(/[^a-z0-9]+/g, "-")
14
+ .replace(/^-+|-+$/g, "") || "worker"
15
+ );
16
+ }
17
+
18
+ export function clip(text: string, max = 140): string {
19
+ return text.length > max ? `${text.slice(0, max - 3)}...` : text;
20
+ }
21
+
22
+ export function lastLine(text: string): string {
23
+ return (
24
+ text
25
+ .split("\n")
26
+ .map((line) => line.trim())
27
+ .filter(Boolean)
28
+ .at(-1) ?? ""
29
+ );
30
+ }
31
+
32
+ export function shortModelLabel(label: string): string {
33
+ return label.split("/")[1] ?? label;
34
+ }
35
+
36
+ export function formatDuration(ms: number): string {
37
+ return `${(Math.max(0, ms) / 1000).toFixed(1)}s`;
38
+ }
39
+
40
+ export function formatTokens(count: number): string {
41
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M tok`;
42
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k tok`;
43
+ return `${count} tok`;
44
+ }
45
+
46
+ export function messageText(message: Pick<AssistantMessage, "content"> | undefined): string {
47
+ return (message?.content ?? [])
48
+ .flatMap((part) => (part.type === "text" ? [part.text] : []))
49
+ .join("\n")
50
+ .trim();
51
+ }
52
+
53
+ export function getResultPage(
54
+ text: string,
55
+ offset = 0,
56
+ ): { content: string; offset: number; nextOffset?: number; totalChars: number } {
57
+ const start = Math.min(Math.max(0, offset), text.length);
58
+ let end = Math.min(start + RESULT_PAGE_CHARS, text.length);
59
+ const lastUnit = text.charCodeAt(end - 1);
60
+ const splitsSurrogatePair = end < text.length && lastUnit >= 0xd800 && lastUnit <= 0xdbff;
61
+ if (splitsSurrogatePair) end--;
62
+ return {
63
+ content: text.slice(start, end),
64
+ offset: start,
65
+ nextOffset: end < text.length ? end : undefined,
66
+ totalChars: text.length,
67
+ };
68
+ }
69
+
70
+ export function summarizeToolArgs(args: unknown): string {
71
+ if (!args || typeof args !== "object") return "";
72
+ const { path, command, pattern } = args as Record<string, unknown>;
73
+ if (typeof path === "string") return path;
74
+ if (typeof command === "string") return clip(command.replace(/\s+/g, " "), 70);
75
+ if (typeof pattern === "string") return pattern;
76
+ return clip(JSON.stringify(args), 70);
77
+ }
package/src/tools.ts ADDED
@@ -0,0 +1,361 @@
1
+ import type { AgentToolResult, AgentToolUpdateCallback, ThinkingLevel } from "@earendil-works/pi-agent-core";
2
+ import {
3
+ DEFAULT_MAX_BYTES,
4
+ defineTool,
5
+ sessionEntryToContextMessages,
6
+ type Theme,
7
+ type ToolDefinition,
8
+ type ToolRenderResultOptions,
9
+ truncateTail,
10
+ } from "@earendil-works/pi-coding-agent";
11
+ import { Text } from "@earendil-works/pi-tui";
12
+ import { type TSchema, Type } from "typebox";
13
+ import { TOOL_COPY, type ToolName } from "./copy";
14
+ import type { Roster } from "./roster";
15
+ import { clip, formatDuration, getResultPage, messageText, shortModelLabel, summarizeToolArgs } from "./text";
16
+ import type { Worker } from "./worker";
17
+
18
+ const THINKING_LEVELS: ThinkingLevel[] = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
19
+
20
+ function tool<P extends TSchema, D>(
21
+ name: ToolName,
22
+ definition: Omit<ToolDefinition<P, D>, "name" | "label" | "description" | "promptSnippet">,
23
+ ) {
24
+ return defineTool<P, D>({ ...definition, ...TOOL_COPY[name], name, defaultActive: false });
25
+ }
26
+
27
+ export function subagentTools(roster: Roster) {
28
+ return [
29
+ tool("spawn_subagent", {
30
+ parameters: Type.Object({
31
+ name: Type.Optional(
32
+ Type.String({
33
+ description:
34
+ "Optional brief subagent name such as 'qa', 'frontend', or 'backend'. Defaults to 'worker'.",
35
+ }),
36
+ ),
37
+ task: Type.Optional(
38
+ Type.String({
39
+ description:
40
+ "Optional task to start immediately. Omit or leave blank to create an idle worker without a model call.",
41
+ }),
42
+ ),
43
+ model: Type.Optional(
44
+ Type.String({ description: "Fuzzy model name such as 'opus', 'gpt-4.1', or provider/id" }),
45
+ ),
46
+ cwd: Type.Optional(
47
+ Type.String({
48
+ description:
49
+ "Working directory for the subagent, absolute or relative to your cwd. Defaults to your cwd.",
50
+ }),
51
+ ),
52
+ tools: Type.Optional(
53
+ Type.Array(Type.String(), {
54
+ description:
55
+ "Tool names for the worker, for example read, grep, find, ls for read-only exploration. Each must be active in this session. Defaults to all of your active tools.",
56
+ }),
57
+ ),
58
+ // A plain string enum, which every provider accepts. pi-ai's StringEnum is untyped for TypeBox.
59
+ thinking: Type.Optional(
60
+ Type.Unsafe<ThinkingLevel>({
61
+ type: "string",
62
+ enum: THINKING_LEVELS,
63
+ description: "Reasoning level for the worker. Defaults to yours.",
64
+ }),
65
+ ),
66
+ timeoutMs: Type.Optional(
67
+ Type.Integer({
68
+ minimum: 1,
69
+ description:
70
+ "Deadline in milliseconds for the initial task. On expiry the run is aborted and reported as an error; the worker stays available. Defaults to no limit.",
71
+ }),
72
+ ),
73
+ }),
74
+ async execute(_id, params, signal, _onUpdate: unknown, ctx) {
75
+ const worker = await roster.spawn(params, ctx, signal);
76
+ const capabilities = worker.capabilities();
77
+ const thinking = worker.session.thinkingLevel;
78
+ const model = worker.info.modelLabel;
79
+ const summary = worker.task
80
+ ? `Spawned ${worker.name} (${model}, thinking ${thinking}) and started: ${worker.task}`
81
+ : `Spawned ${worker.name} (${model}, thinking ${thinking}), idle and ready. No model call made.`;
82
+ return {
83
+ content: [
84
+ {
85
+ type: "text",
86
+ text: [
87
+ summary,
88
+ "Model/auth runtime: independent. Parent-only runtime overrides are not inherited.",
89
+ `Enabled tools: ${capabilities.enabledTools.join(", ") || "(none)"}`,
90
+ ...(capabilities.missingTools.length
91
+ ? [`Missing requested tools: ${capabilities.missingTools.join(", ")}`]
92
+ : []),
93
+ ...capabilities.warnings.map((warning) => `Warning: ${warning}`),
94
+ ].join("\n"),
95
+ },
96
+ ],
97
+ details: {
98
+ name: worker.name,
99
+ model,
100
+ thinking,
101
+ cwd: worker.info.cwd,
102
+ task: worker.task,
103
+ missingTools: capabilities.missingTools,
104
+ warnings: capabilities.warnings,
105
+ },
106
+ };
107
+ },
108
+ renderCall: (args, theme) =>
109
+ callLine(theme, "spawn_subagent", args.name || args.model || "worker", args.task?.trim() || "(idle)"),
110
+ renderResult: (result, options, theme, context) =>
111
+ resultLine(result, options, theme, context, () => {
112
+ const { name, model, thinking, task, missingTools, warnings } = result.details;
113
+ return [
114
+ theme.fg("success", "✓ ") +
115
+ theme.bold(name) +
116
+ theme.fg("muted", ` · ${shortModelLabel(model)} · ${thinking} · ${task ? "started" : "idle"}`),
117
+ ...(missingTools.length ? [theme.fg("warning", `Missing tools: ${missingTools.join(", ")}`)] : []),
118
+ ...warnings.map((warning) => theme.fg("warning", warning)),
119
+ ].join("\n");
120
+ }),
121
+ }),
122
+
123
+ tool("list_subagents", {
124
+ parameters: Type.Object({}),
125
+ async execute() {
126
+ const workers = roster.list();
127
+ const text = workers.length
128
+ ? workers
129
+ .map(
130
+ (worker) =>
131
+ `${worker.name} [${worker.status} · ${shortModelLabel(worker.info.modelLabel)}] — ${clip(worker.task || "(idle)", 90)}`,
132
+ )
133
+ .join("\n")
134
+ : "No subagents.";
135
+ return { content: [{ type: "text", text }], details: undefined };
136
+ },
137
+ renderCall: (_args, theme) => new Text(theme.fg("toolTitle", theme.bold("list_subagents")), 0, 0),
138
+ }),
139
+
140
+ tool("inspect_subagent", {
141
+ parameters: Type.Object({
142
+ name: Type.String({ description: "Subagent name" }),
143
+ tailLines: Type.Optional(
144
+ Type.Integer({ minimum: 1, description: "Number of recent conversation lines to include, up to 50KB" }),
145
+ ),
146
+ includeResult: Type.Optional(
147
+ Type.Boolean({ description: "Include a page of the latest run's result. Defaults to false." }),
148
+ ),
149
+ runId: Type.Optional(
150
+ Type.Integer({
151
+ minimum: 1,
152
+ description:
153
+ "Expected run id when reading a result. Pass the report's runId to avoid reading output from a later assignment or another worker.",
154
+ }),
155
+ ),
156
+ resultOffset: Type.Optional(
157
+ Type.Integer({
158
+ minimum: 0,
159
+ description:
160
+ "Character offset into the result, starting at 0. Use the next offset returned by the previous page.",
161
+ }),
162
+ ),
163
+ }),
164
+ async execute(_id, params) {
165
+ const worker = roster.find(params.name);
166
+ return {
167
+ content: [{ type: "text", text: inspectText(worker, params) }],
168
+ details: { name: worker.name, status: worker.status, runId: worker.runId },
169
+ };
170
+ },
171
+ renderCall: (args, theme) =>
172
+ callLine(
173
+ theme,
174
+ "inspect_subagent",
175
+ args.name,
176
+ args.includeResult ? "result" : args.tailLines ? `last ${args.tailLines} lines` : undefined,
177
+ ),
178
+ }),
179
+
180
+ tool("message_subagent", {
181
+ parameters: Type.Object({
182
+ name: Type.String({ description: "Subagent name" }),
183
+ message: Type.String({ description: "Instruction to send" }),
184
+ timeoutMs: Type.Optional(
185
+ Type.Integer({
186
+ minimum: 1,
187
+ description:
188
+ "Deadline in milliseconds for the task this message starts. Ignored when the message steers a running worker.",
189
+ }),
190
+ ),
191
+ }),
192
+ async execute(_id, params) {
193
+ const { worker, mode } = await roster.message(params.name, params.message, params.timeoutMs);
194
+ const verb =
195
+ mode === "steer"
196
+ ? "Steered"
197
+ : mode === "start"
198
+ ? "Started"
199
+ : "An input handler in the worker consumed the message for";
200
+ return {
201
+ content: [{ type: "text", text: `${verb} ${worker.name}: ${params.message}` }],
202
+ details: { name: worker.name, mode },
203
+ };
204
+ },
205
+ renderCall: (args, theme) => callLine(theme, "message_subagent", args.name, args.message),
206
+ renderResult: (result, options, theme, context) =>
207
+ resultLine(result, options, theme, context, () => {
208
+ const { name, mode } = result.details;
209
+ return (
210
+ theme.fg(
211
+ "success",
212
+ mode === "steer" ? "↪ steered " : mode === "start" ? "▶ started " : "✓ handled by ",
213
+ ) + theme.bold(name)
214
+ );
215
+ }),
216
+ }),
217
+
218
+ tool("await_subagents", {
219
+ parameters: Type.Object({
220
+ names: Type.Optional(
221
+ Type.Array(Type.String(), { description: "Subagents to wait for. Defaults to all running subagents." }),
222
+ ),
223
+ timeoutMs: Type.Optional(
224
+ Type.Integer({
225
+ minimum: 1,
226
+ description: "Stop waiting after this many milliseconds. The workers keep running.",
227
+ }),
228
+ ),
229
+ }),
230
+ async execute(_id, params, signal, onUpdate: AgentToolUpdateCallback<{ waiting: string[] }> | undefined) {
231
+ const waiting = (await roster.waitFor(params.names, params.timeoutMs, signal, onUpdate)).map(
232
+ (worker) => worker.name,
233
+ );
234
+ const text = waiting.length
235
+ ? `Stopped waiting after ${formatDuration(params.timeoutMs ?? 0)}. Still running: ${waiting.join(", ")}.`
236
+ : "All awaited subagents have finished.";
237
+ return { content: [{ type: "text", text }], details: { waiting } };
238
+ },
239
+ renderCall: (args, theme) =>
240
+ callLine(
241
+ theme,
242
+ "await_subagents",
243
+ args.names?.join(", ") || "all running",
244
+ args.timeoutMs ? `timeout ${formatDuration(args.timeoutMs)}` : undefined,
245
+ ),
246
+ renderResult: (result, options, theme, context) =>
247
+ resultLine(result, options, theme, context, () =>
248
+ result.details.waiting.length
249
+ ? theme.fg("warning", `… still running: ${result.details.waiting.join(", ")}`)
250
+ : theme.fg("success", "✓ all finished"),
251
+ ),
252
+ }),
253
+
254
+ tool("stop_subagent", {
255
+ parameters: Type.Object({ name: Type.String({ description: "Subagent name" }) }),
256
+ async execute(_id, params) {
257
+ const worker = await roster.stop(params.name);
258
+ return {
259
+ content: [{ type: "text", text: `Stopped and removed ${worker.name}.` }],
260
+ details: { name: worker.name },
261
+ };
262
+ },
263
+ renderCall: (args, theme) => callLine(theme, "stop_subagent", args.name),
264
+ renderResult: (result, options, theme, context) =>
265
+ resultLine(
266
+ result,
267
+ options,
268
+ theme,
269
+ context,
270
+ () => theme.fg("muted", "■ removed ") + theme.bold(result.details.name),
271
+ ),
272
+ }),
273
+ ];
274
+ }
275
+
276
+ function inspectText(
277
+ worker: Worker,
278
+ options: { tailLines?: number; includeResult?: boolean; resultOffset?: number; runId?: number },
279
+ ): string {
280
+ const capabilities = worker.capabilities();
281
+ const stats = worker.stats();
282
+ const lines = [
283
+ `Name: ${worker.name}`,
284
+ `Status: ${worker.status}`,
285
+ `Run: ${worker.runId || "(none yet)"}`,
286
+ `Model: ${worker.info.modelLabel}`,
287
+ `Thinking: ${worker.session.thinkingLevel}`,
288
+ `Working directory: ${worker.info.cwd}`,
289
+ "Model/auth runtime: independent, using configured credentials and provider discovery",
290
+ `Tools: ${capabilities.enabledTools.join(", ") || "(none)"}`,
291
+ `Callable tools: ${capabilities.callableTools.join(", ") || "(none)"}`,
292
+ `Missing requested tools: ${capabilities.missingTools.join(", ") || "(none)"}`,
293
+ ...capabilities.warnings.map((warning) => `Warning: ${warning}`),
294
+ `Task: ${worker.task || "(idle)"}`,
295
+ `Latest: ${worker.activity() || "(no output yet)"}`,
296
+ `Turns: ${stats.turns}`,
297
+ `Tool uses: ${stats.toolUses}`,
298
+ `Session file: ${worker.session.sessionManager.getSessionFile() || "(none)"}`,
299
+ ...(worker.error ? [`Error: ${worker.error}`] : []),
300
+ ];
301
+ if (options.includeResult) {
302
+ if (options.runId !== undefined && options.runId !== worker.runId) {
303
+ throw new Error(
304
+ `Run ${options.runId} is not ${worker.name}'s latest run (${worker.runId || "none"}). Earlier output remains in its report card and session file.`,
305
+ );
306
+ }
307
+ const page = getResultPage(stats.outcome, options.resultOffset);
308
+ lines.push(
309
+ "",
310
+ `Result characters ${page.offset} to ${page.offset + page.content.length} of ${page.totalChars}:`,
311
+ page.content || "(no result)",
312
+ );
313
+ if (page.nextOffset !== undefined)
314
+ lines.push(`Continue with includeResult: true, runId: ${worker.runId}, resultOffset: ${page.nextOffset}.`);
315
+ }
316
+ if (options.tailLines) {
317
+ const transcript = worker.session.sessionManager
318
+ .getBranch()
319
+ .flatMap(sessionEntryToContextMessages)
320
+ .flatMap((message) => {
321
+ if (message.role === "user") {
322
+ const text =
323
+ typeof message.content === "string"
324
+ ? message.content
325
+ : message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
326
+ return text.trim() ? [`[user] ${text}`] : [];
327
+ }
328
+ if (message.role !== "assistant") return [];
329
+ const text = messageText(message);
330
+ return [
331
+ ...(text ? [`[assistant] ${text}`] : []),
332
+ ...message.content.flatMap((part) =>
333
+ part.type === "toolCall" ? [`[tool] ${part.name} ${summarizeToolArgs(part.arguments)}`.trim()] : [],
334
+ ),
335
+ ];
336
+ })
337
+ .join("\n");
338
+ const tail = truncateTail(transcript, { maxLines: options.tailLines, maxBytes: DEFAULT_MAX_BYTES });
339
+ if (tail.content)
340
+ lines.push("", `Recent transcript (last ${tail.outputLines} of ${tail.totalLines} lines):`, tail.content);
341
+ }
342
+ return lines.join("\n");
343
+ }
344
+
345
+ function callLine(theme: Theme, tool: string, subject: string, detail?: string): Text {
346
+ const suffix = detail ? theme.fg("dim", " — ") + theme.fg("muted", clip(detail.replace(/\s+/g, " "), 60)) : "";
347
+ return new Text(`${theme.fg("toolTitle", theme.bold(tool))} ${theme.fg("accent", subject)}${suffix}`, 0, 0);
348
+ }
349
+
350
+ function resultLine(
351
+ result: AgentToolResult<unknown>,
352
+ options: ToolRenderResultOptions,
353
+ theme: Theme,
354
+ context: { isError: boolean },
355
+ summary: () => string,
356
+ ): Text {
357
+ const text = result.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n");
358
+ if (context.isError) return new Text(theme.fg("error", text), 0, 0);
359
+ if (options.isPartial) return new Text(theme.fg("muted", text), 0, 0);
360
+ return new Text(summary(), 0, 0);
361
+ }