@luxass/pi-subagents 0.0.0-stage → 0.0.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/manager.ts ADDED
@@ -0,0 +1,722 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+
5
+ import type { Usage } from "@earendil-works/pi-ai";
6
+ import {
7
+ getAgentDir,
8
+ SessionManager,
9
+ type AgentSession,
10
+ type AgentSessionEvent,
11
+ type ExtensionAPI,
12
+ type ExtensionContext,
13
+ type ModelRuntime,
14
+ } from "@earendil-works/pi-coding-agent";
15
+
16
+ import { isSubagentName, type SubagentDefinition } from "./agents.ts";
17
+ import {
18
+ addSubagentUsage,
19
+ emptySubagentUsage,
20
+ hasSubagentUsage,
21
+ SUBAGENT_USAGE_ENTRY,
22
+ type SubagentRunUsage,
23
+ } from "./costs.ts";
24
+ import { subagentMessageText } from "./message-text.ts";
25
+ import {
26
+ createSubagentRuntime,
27
+ createSubagentSession,
28
+ resolveSubagentPolicy,
29
+ type SubagentOverrides,
30
+ type SubagentPolicy,
31
+ type SubagentSession,
32
+ type SubagentThinking,
33
+ } from "./session.ts";
34
+ import type { SubagentSettings } from "./settings.ts";
35
+
36
+ type AgentMessage = AgentSession["messages"][number];
37
+
38
+ /** Status of one named agent. Names stay reserved after a run ends. */
39
+ export type SubagentStatus =
40
+ | "queued"
41
+ | "running"
42
+ | "stopping"
43
+ | "completed"
44
+ | "stopped"
45
+ | "failed"
46
+ | "interrupted";
47
+
48
+ /** Token counters for the latest start or continuation. */
49
+ export interface SubagentTokens {
50
+ input: number;
51
+ output: number;
52
+ cacheRead: number;
53
+ cacheWrite: number;
54
+ total: number;
55
+ }
56
+
57
+ /** Custom entry type that stores agent records in the main session. */
58
+ export const SUBAGENT_RECORD_ENTRY = "subagents-record";
59
+
60
+ /** Whether the main model may still receive this run's result automatically. */
61
+ export type SubagentReceipt = "pending" | "unread" | "consumed" | "delivered" | "suppressed";
62
+
63
+ /** One named agent and its latest run. Saved in the main session with `pi.appendEntry`. */
64
+ export interface SubagentRecord {
65
+ sessionId: string;
66
+ id: string;
67
+ name: string;
68
+ agentType: string;
69
+ /** First line of the latest prompt, shown in the UI. */
70
+ task: string;
71
+ status: SubagentStatus;
72
+ /** Counts starts and continuations, from 1. It rises when a run is scheduled. */
73
+ run: number;
74
+ requestId: number;
75
+ background: boolean;
76
+ receipt: SubagentReceipt;
77
+ stoppedBy?: "model" | "user";
78
+ sessionFile?: string;
79
+ model: string;
80
+ thinking: SubagentThinking;
81
+ maxTurns: number;
82
+ tools: string[];
83
+ queuedAt: number;
84
+ startedAt?: number;
85
+ endedAt?: number;
86
+ activity: string;
87
+ turns: number;
88
+ toolUses: number;
89
+ tokens: SubagentTokens;
90
+ contextPercent: number | null;
91
+ partial: boolean;
92
+ result: string;
93
+ error?: string;
94
+ }
95
+
96
+ /** Statuses after which a run can no longer change. */
97
+ export function isSubagentFinished(status: SubagentStatus): boolean {
98
+ return (
99
+ status === "completed" ||
100
+ status === "stopped" ||
101
+ status === "failed" ||
102
+ status === "interrupted"
103
+ );
104
+ }
105
+
106
+ /** Parameters of one `Agent` call after schema validation. */
107
+ export interface SubagentLaunch extends SubagentOverrides {
108
+ subagent_type?: string;
109
+ name?: string;
110
+ prompt: string;
111
+ resume?: string;
112
+ run_in_background?: boolean;
113
+ }
114
+
115
+ interface LiveRun {
116
+ policy: SubagentPolicy;
117
+ prompt: string;
118
+ child?: SubagentSession;
119
+ /** Messages the conversation held before this run, so its result comes only from this run. */
120
+ firstMessage?: number;
121
+ /** Corrections that arrived before the session existed. */
122
+ pendingSteers: string[];
123
+ /** What this run's model replies used so far. A run that used nothing saves no usage entry. */
124
+ usage: Usage;
125
+ /** True once the run's usage entry is written, so it is written once. */
126
+ usageSaved?: boolean;
127
+ /** Resolves a waiting foreground `Agent` call. */
128
+ release?: (outcome: "finished" | "background") => void;
129
+ }
130
+
131
+ function emptyTokens(): SubagentTokens {
132
+ return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };
133
+ }
134
+
135
+ /**
136
+ * The last answer of one run. `firstMessage` is the message count before the run's prompt, so a
137
+ * continued run that writes nothing reports nothing, not the previous run's answer or error.
138
+ */
139
+ function lastAssistantText(
140
+ messages: readonly AgentMessage[],
141
+ firstMessage: number,
142
+ ): { text: string; error?: string } {
143
+ for (let index = messages.length - 1; index >= firstMessage; index--) {
144
+ const message = messages[index];
145
+ if (message?.role !== "assistant") continue;
146
+ const text = subagentMessageText(message.content).trim();
147
+ if (message.stopReason === "error")
148
+ return { text, error: message.errorMessage ?? "The model request failed." };
149
+ if (text) return { text };
150
+ }
151
+ return { text: "" };
152
+ }
153
+
154
+ function describeToolCall(name: string, args: unknown): string {
155
+ const input = (args ?? {}) as Record<string, unknown>;
156
+ const detail = [input.path, input.command, input.pattern, input.query].find(
157
+ (value): value is string => typeof value === "string",
158
+ );
159
+ return detail ? `${name} ${detail.split("\n")[0]}` : name;
160
+ }
161
+
162
+ /** Owns every agent of one main session: names, queue, runs, and persistence. */
163
+ export class SubagentManager {
164
+ readonly records = new Map<string, SubagentRecord>();
165
+ private readonly live = new Map<string, LiveRun>();
166
+ private readonly queue: string[] = [];
167
+ private readonly listeners = new Set<() => void>();
168
+ /** How each earlier run of a continued agent ended, by `<id>:<run>`, for its `Agent` card. */
169
+ private readonly earlierRuns = new Map<string, SubagentRecord>();
170
+ /** Cost of the runs whose usage entry is saved in this session. */
171
+ private savedCost = 0;
172
+ /** Number of saved usage entries in this session. */
173
+ private savedRuns = 0;
174
+ /** The last saved conversation read for `/agents`, so drawing it does not read the file again. */
175
+ private savedTranscript: { key: string; messages: readonly AgentMessage[] } | undefined;
176
+ private runtime: Promise<ModelRuntime> | undefined;
177
+ private closed = false;
178
+ /** Main-session request counter, advanced on `agent_start`. */
179
+ requestId = 0;
180
+ /** Called once a run settles, so delivery can decide what the main model receives. */
181
+ onRunSettled: (record: SubagentRecord) => void = () => {};
182
+
183
+ constructor(
184
+ private readonly pi: ExtensionAPI,
185
+ private readonly ctx: ExtensionContext,
186
+ readonly sessionId: string,
187
+ public definitions: Map<string, SubagentDefinition>,
188
+ public settings: SubagentSettings,
189
+ ) {}
190
+
191
+ /** Agent types the model may start: loaded definitions minus `disabledAgents`. */
192
+ availableTypes(): SubagentDefinition[] {
193
+ return [...this.definitions.values()].filter(
194
+ (definition) => !this.settings.disabledAgents.includes(definition.name),
195
+ );
196
+ }
197
+
198
+ /** Records in creation order, for the widget and `/agents`. */
199
+ list(): SubagentRecord[] {
200
+ return [...this.records.values()];
201
+ }
202
+
203
+ /** Finds an agent by the task name returned from `Agent`. */
204
+ find(name: string): SubagentRecord | undefined {
205
+ return this.list().find((record) => record.name === name);
206
+ }
207
+
208
+ /**
209
+ * The agent as one of its runs left it: the live record for its current run, or the saved
210
+ * outcome of an earlier run. Without a run number it is the live record.
211
+ */
212
+ runOutcome(id: string, run: number | undefined): SubagentRecord | undefined {
213
+ const record = this.records.get(id);
214
+ if (run === undefined || record?.run === run) return record;
215
+ return this.earlierRuns.get(`${id}:${run}`) ?? record;
216
+ }
217
+
218
+ /** Subscribes UI to record changes. Returns the unsubscribe function. */
219
+ subscribe(listener: () => void): () => void {
220
+ this.listeners.add(listener);
221
+ return () => this.listeners.delete(listener);
222
+ }
223
+
224
+ /**
225
+ * Restores this session's saved agents. Unfinished runs become interrupted and never deliver.
226
+ * A finished result that was still waiting stays unread, so it is delivered now.
227
+ */
228
+ restore(): void {
229
+ for (const entry of this.ctx.sessionManager.getEntries()) {
230
+ if (entry.type === "custom" && entry.customType === SUBAGENT_USAGE_ENTRY) {
231
+ this.savedCost += (entry.data as SubagentRunUsage).usage.cost.total;
232
+ this.savedRuns++;
233
+ }
234
+ if (entry.type !== "custom" || entry.customType !== SUBAGENT_RECORD_ENTRY) continue;
235
+ const record = entry.data as SubagentRecord | undefined;
236
+ if (record?.sessionId !== this.sessionId) continue;
237
+ this.records.set(record.id, { ...record });
238
+ // Entries are in time order, so the last finished entry of a run is how that run ended.
239
+ if (isSubagentFinished(record.status)) {
240
+ this.earlierRuns.set(`${record.id}:${record.run}`, { ...record });
241
+ }
242
+ }
243
+ for (const record of this.records.values()) {
244
+ if (!isSubagentFinished(record.status)) {
245
+ record.status = "interrupted";
246
+ record.activity = "interrupted";
247
+ record.endedAt ??= Date.now();
248
+ // An interrupted run has no result to send, now or later.
249
+ record.receipt = "suppressed";
250
+ }
251
+ // New requests must not share a number with earlier ones, or grouping would mix them.
252
+ this.requestId = Math.max(this.requestId, record.requestId + 1);
253
+ }
254
+ }
255
+
256
+ /** Starts a new named agent or continues a finished one. Throws before reserving anything if invalid. */
257
+ launch(params: SubagentLaunch): SubagentRecord {
258
+ if (this.closed) throw new Error("Agents are shutting down.");
259
+ const prompt = params.prompt.trim();
260
+ if (!prompt) throw new Error("Agent needs a non-empty prompt.");
261
+ const background = params.run_in_background ?? this.settings.backgroundByDefault;
262
+ if (params.resume) return this.resume(params.resume, prompt, params, background);
263
+
264
+ const type = params.subagent_type;
265
+ const name = params.name;
266
+ if (!type || !name)
267
+ throw new Error(
268
+ "A new agent needs subagent_type, name, and prompt. Use resume to continue one.",
269
+ );
270
+ if (!isSubagentName(name))
271
+ throw new Error(`Task name "${name}" must be lowercase words joined by hyphens.`);
272
+ if (this.find(name))
273
+ throw new Error(`Task name "${name}" is already used in this session. Choose a new name.`);
274
+ if (this.definitions.has(name))
275
+ throw new Error(`Task name "${name}" is an agent type. Choose a different name.`);
276
+ const definition = this.requireType(type);
277
+ const policy = resolveSubagentPolicy({
278
+ definition,
279
+ overrides: params,
280
+ ctx: this.ctx,
281
+ pi: this.pi,
282
+ settings: this.settings,
283
+ });
284
+
285
+ const record: SubagentRecord = {
286
+ sessionId: this.sessionId,
287
+ id: randomUUID(),
288
+ name,
289
+ agentType: definition.name,
290
+ task: "",
291
+ status: "queued",
292
+ run: 0,
293
+ requestId: this.requestId,
294
+ background,
295
+ receipt: "pending",
296
+ model: `${policy.model.provider}/${policy.model.id}`,
297
+ thinking: policy.thinking,
298
+ maxTurns: policy.maxTurns,
299
+ tools: policy.tools,
300
+ queuedAt: Date.now(),
301
+ activity: "queued",
302
+ turns: 0,
303
+ toolUses: 0,
304
+ tokens: emptyTokens(),
305
+ contextPercent: null,
306
+ partial: false,
307
+ result: "",
308
+ };
309
+ this.records.set(record.id, record);
310
+ this.schedule(record, policy, prompt);
311
+ return record;
312
+ }
313
+
314
+ private resume(
315
+ name: string,
316
+ prompt: string,
317
+ overrides: SubagentOverrides,
318
+ background: boolean,
319
+ ): SubagentRecord {
320
+ const record = this.find(name);
321
+ if (!record) throw new Error(`No agent named "${name}" exists in this session.`);
322
+ if (!isSubagentFinished(record.status)) {
323
+ throw new Error(
324
+ `Agent "${name}" is ${record.status}. Wait for it to finish, or use steer_subagent.`,
325
+ );
326
+ }
327
+ // A run that just ended is still closing its session. A new run started now would be finished
328
+ // by the old one: wrong status, no steering, and its result reported before it exists.
329
+ if (this.live.has(record.id)) {
330
+ throw new Error(`Agent "${name}" is still finishing its last run. Try again in a moment.`);
331
+ }
332
+ const startsConversation = this.continuesWithoutConversation(record);
333
+ if (!startsConversation && (!record.sessionFile || !existsSync(record.sessionFile))) {
334
+ throw new Error(`Agent "${name}" has no saved conversation to continue.`);
335
+ }
336
+ const definition = this.requireType(record.agentType);
337
+ const policy = resolveSubagentPolicy({
338
+ definition,
339
+ overrides,
340
+ ctx: this.ctx,
341
+ pi: this.pi,
342
+ settings: this.settings,
343
+ });
344
+ // The card of the run that just ended keeps showing that run, not the new one.
345
+ this.earlierRuns.set(`${record.id}:${record.run}`, { ...record });
346
+ Object.assign(record, {
347
+ status: "queued",
348
+ requestId: this.requestId,
349
+ background,
350
+ receipt: "pending",
351
+ stoppedBy: undefined,
352
+ model: `${policy.model.provider}/${policy.model.id}`,
353
+ thinking: policy.thinking,
354
+ maxTurns: policy.maxTurns,
355
+ tools: policy.tools,
356
+ queuedAt: Date.now(),
357
+ // Without a saved conversation the run creates one.
358
+ sessionFile: startsConversation ? undefined : record.sessionFile,
359
+ // The previous run's result and times do not describe the run that is about to start.
360
+ startedAt: undefined,
361
+ endedAt: undefined,
362
+ activity: "queued",
363
+ partial: false,
364
+ result: "",
365
+ error: undefined,
366
+ } satisfies Partial<SubagentRecord>);
367
+ this.schedule(record, policy, prompt);
368
+ return record;
369
+ }
370
+
371
+ /**
372
+ * True for an agent the session interrupted before it saved a conversation, such as one that was
373
+ * still queued at a reload. Continuing it starts its conversation with the new prompt.
374
+ */
375
+ continuesWithoutConversation(record: SubagentRecord): boolean {
376
+ const saved = Boolean(record.sessionFile && existsSync(record.sessionFile));
377
+ return record.status === "interrupted" && !saved;
378
+ }
379
+
380
+ private requireType(type: string): SubagentDefinition {
381
+ const definition = this.definitions.get(type);
382
+ if (!definition) {
383
+ const known = this.availableTypes()
384
+ .map((item) => item.name)
385
+ .join(", ");
386
+ throw new Error(`Agent type "${type}" is unavailable. Available types: ${known || "none"}.`);
387
+ }
388
+ if (this.settings.disabledAgents.includes(type))
389
+ throw new Error(`Agent type "${type}" is disabled in settings.`);
390
+ return definition;
391
+ }
392
+
393
+ private schedule(record: SubagentRecord, policy: SubagentPolicy, prompt: string): void {
394
+ this.live.set(record.id, {
395
+ policy,
396
+ prompt,
397
+ pendingSteers: [],
398
+ usage: emptySubagentUsage(),
399
+ });
400
+ record.run++;
401
+ record.task = prompt.split("\n")[0] ?? "";
402
+ this.persist(record);
403
+ // Foreground calls bypass the background cap.
404
+ if (record.background && this.runningBackground() >= this.settings.maxConcurrent) {
405
+ this.queue.push(record.id);
406
+ this.notify();
407
+ return;
408
+ }
409
+ void this.run(record);
410
+ }
411
+
412
+ private runningBackground(): number {
413
+ return this.list().filter(
414
+ (record) =>
415
+ record.background && (record.status === "running" || record.status === "stopping"),
416
+ ).length;
417
+ }
418
+
419
+ private pump(): void {
420
+ while (
421
+ !this.closed &&
422
+ this.queue.length &&
423
+ this.runningBackground() < this.settings.maxConcurrent
424
+ ) {
425
+ const id = this.queue.shift();
426
+ const record = id ? this.records.get(id) : undefined;
427
+ if (record?.status === "queued") void this.run(record);
428
+ }
429
+ }
430
+
431
+ private async run(record: SubagentRecord): Promise<void> {
432
+ const live = this.live.get(record.id);
433
+ if (!live) return;
434
+ Object.assign(record, {
435
+ status: "running",
436
+ model: `${live.policy.model.provider}/${live.policy.model.id}`,
437
+ startedAt: Date.now(),
438
+ activity: "starting",
439
+ turns: 0,
440
+ toolUses: 0,
441
+ tokens: emptyTokens(),
442
+ contextPercent: null,
443
+ result: "",
444
+ } satisfies Partial<SubagentRecord>);
445
+ this.persist(record);
446
+ try {
447
+ this.runtime ??= createSubagentRuntime(this.ctx);
448
+ const child = await createSubagentSession({
449
+ ctx: this.ctx,
450
+ pi: this.pi,
451
+ runtime: await this.runtime,
452
+ policy: live.policy,
453
+ sessionId: record.id,
454
+ sessionDirectory: join(getAgentDir(), "subagents", this.sessionId),
455
+ sessionFile: record.sessionFile,
456
+ onEvent: (event) => this.track(record, live, event),
457
+ });
458
+ live.child = child;
459
+ live.firstMessage = child.session.messages.length;
460
+ // A reload, /new, or quit can arrive while the session is being created. shutdown() could not
461
+ // dispose a session that did not exist yet, so the run ends here and `finally` disposes it.
462
+ if (this.closed) return;
463
+ record.sessionFile = child.session.sessionManager.getSessionFile();
464
+ if (record.status === "stopping") throw new Error("stopped");
465
+ const steers = live.pendingSteers.splice(0);
466
+ const prompt = steers.length ? `${live.prompt}\n\n${steers.join("\n\n")}` : live.prompt;
467
+ await child.run(prompt);
468
+ const { text, error } = lastAssistantText(child.session.messages, live.firstMessage);
469
+ record.result = text;
470
+ record.partial = child.partial;
471
+ if (record.stoppedBy) record.status = "stopped";
472
+ else if (error)
473
+ Object.assign(record, { status: "failed", error } satisfies Partial<SubagentRecord>);
474
+ else record.status = "completed";
475
+ } catch (error) {
476
+ // After shutdown the record is already saved as interrupted, and stays that way.
477
+ if (this.closed) return;
478
+ if (record.stoppedBy) record.status = "stopped";
479
+ else
480
+ Object.assign(record, {
481
+ status: "failed",
482
+ error: String(error),
483
+ } satisfies Partial<SubagentRecord>);
484
+ if (live.child && live.firstMessage !== undefined) {
485
+ record.result ||= lastAssistantText(live.child.session.messages, live.firstMessage).text;
486
+ }
487
+ } finally {
488
+ await live.child?.dispose().catch(() => undefined);
489
+ }
490
+ if (this.closed) return;
491
+ this.finish(record, live);
492
+ }
493
+
494
+ private finish(record: SubagentRecord, live: LiveRun): void {
495
+ record.endedAt = Date.now();
496
+ record.activity = record.status;
497
+ this.live.delete(record.id);
498
+ // A waiting foreground call returns the result itself, so it counts as read.
499
+ const foreground = Boolean(live.release);
500
+ if (foreground) record.receipt = "consumed";
501
+ else if (record.stoppedBy === "model") record.receipt = "suppressed";
502
+ else if (record.receipt === "pending") record.receipt = "unread";
503
+ live.release?.("finished");
504
+ this.saveRunUsage(record, live);
505
+ this.persist(record);
506
+ if (!foreground) this.onRunSettled(record);
507
+ this.pump();
508
+ }
509
+
510
+ private track(record: SubagentRecord, live: LiveRun, event: AgentSessionEvent): void {
511
+ if (event.type === "turn_start") record.activity = "thinking";
512
+ else if (event.type === "message_update" && event.message.role === "assistant")
513
+ record.activity = "writing";
514
+ else if (event.type === "tool_execution_start") {
515
+ record.toolUses++;
516
+ record.activity = describeToolCall(event.toolName, event.args);
517
+ } else if (event.type === "message_end" && event.message.role === "assistant") {
518
+ const usage = event.message.usage;
519
+ // The turn limit stops an extra turn before it says anything. That turn does not count.
520
+ const stoppedBeforeOutput =
521
+ event.message.stopReason === "aborted" && event.message.content.length === 0;
522
+ if (!stoppedBeforeOutput) record.turns++;
523
+ record.tokens = {
524
+ input: record.tokens.input + usage.input,
525
+ output: record.tokens.output + usage.output,
526
+ cacheRead: record.tokens.cacheRead + usage.cacheRead,
527
+ cacheWrite: record.tokens.cacheWrite + usage.cacheWrite,
528
+ total: record.tokens.total + usage.input + usage.output + usage.cacheWrite,
529
+ };
530
+ record.contextPercent =
531
+ live.child?.session.getContextUsage()?.percent ?? record.contextPercent;
532
+ addSubagentUsage(live.usage, usage);
533
+ } else return;
534
+ this.notify();
535
+ }
536
+
537
+ /** Waits for a foreground run. Resolves early when Ctrl+B moves it to the background. */
538
+ waitForeground(
539
+ record: SubagentRecord,
540
+ signal: AbortSignal | undefined,
541
+ ): Promise<"finished" | "background" | "aborted"> {
542
+ const live = this.live.get(record.id);
543
+ if (!live || isSubagentFinished(record.status)) return Promise.resolve("finished");
544
+ return new Promise((resolvePromise) => {
545
+ const onAbort = () => {
546
+ live.release = undefined;
547
+ // The aborted tool call already tells the model, so nothing arrives later.
548
+ record.receipt = "suppressed";
549
+ // Esc in the main session stops the agents it waits for.
550
+ void this.stop(record.name, "user");
551
+ resolvePromise("aborted");
552
+ };
553
+ if (signal?.aborted) return onAbort();
554
+ signal?.addEventListener("abort", onAbort, { once: true });
555
+ live.release = (outcome) => {
556
+ signal?.removeEventListener("abort", onAbort);
557
+ live.release = undefined;
558
+ resolvePromise(outcome);
559
+ };
560
+ });
561
+ }
562
+
563
+ /** Whether a foreground agent is running, for Ctrl+B and the hint. */
564
+ hasForeground(): boolean {
565
+ return this.list().some((record) => !record.background && record.status === "running");
566
+ }
567
+
568
+ /** Moves every running foreground agent to the background without stopping it. */
569
+ moveForegroundToBackground(): number {
570
+ let moved = 0;
571
+ for (const record of this.list()) {
572
+ if (record.background || record.status !== "running") continue;
573
+ record.background = true;
574
+ this.persist(record);
575
+ this.live.get(record.id)?.release?.("background");
576
+ moved++;
577
+ }
578
+ this.notify();
579
+ return moved;
580
+ }
581
+
582
+ /** Sends a correction from the main model to a running or queued agent. */
583
+ async steer(name: string, message: string): Promise<SubagentRecord> {
584
+ const record = this.find(name);
585
+ if (!record) throw new Error(`No agent named "${name}" exists in this session.`);
586
+ const live = this.live.get(record.id);
587
+ if (!live || isSubagentFinished(record.status) || record.status === "stopping") {
588
+ throw new Error(`Agent "${name}" is ${record.status}. Use Agent with resume to continue it.`);
589
+ }
590
+ if (live.child) await live.child.session.steer(message, undefined, { source: "extension" });
591
+ else live.pendingSteers.push(message);
592
+ return record;
593
+ }
594
+
595
+ /** Stops one running or queued agent. Other agents are unaffected. */
596
+ async stop(name: string, by: "model" | "user"): Promise<SubagentRecord> {
597
+ const record = this.find(name);
598
+ if (!record) throw new Error(`No agent named "${name}" exists in this session.`);
599
+ // The first stop decides who stopped it. A later stop from the model must not hide the report
600
+ // of an agent the user stopped.
601
+ if (isSubagentFinished(record.status) || record.status === "stopping") return record;
602
+ record.stoppedBy = by;
603
+ const live = this.live.get(record.id);
604
+ if (record.status === "queued") {
605
+ const position = this.queue.indexOf(record.id);
606
+ if (position >= 0) this.queue.splice(position, 1);
607
+ record.status = "stopped";
608
+ if (live) this.finish(record, live);
609
+ return record;
610
+ }
611
+ record.status = "stopping";
612
+ record.activity = "stopping";
613
+ this.notify();
614
+ await live?.child?.session.abort();
615
+ return record;
616
+ }
617
+
618
+ /**
619
+ * Saves what a run used as one entry in the main session, so costs survive a reload and other
620
+ * extensions can add them up. A run that used no tokens saves nothing.
621
+ */
622
+ private saveRunUsage(record: SubagentRecord, live: LiveRun): void {
623
+ if (live.usageSaved || !hasSubagentUsage(live.usage)) return;
624
+ live.usageSaved = true;
625
+ const data: SubagentRunUsage = {
626
+ sessionId: this.sessionId,
627
+ id: record.id,
628
+ name: record.name,
629
+ agentType: record.agentType,
630
+ run: record.run,
631
+ provider: live.policy.model.provider,
632
+ model: live.policy.model.id,
633
+ usage: live.usage,
634
+ };
635
+ this.pi.appendEntry(SUBAGENT_USAGE_ENTRY, data);
636
+ this.savedCost += live.usage.cost.total;
637
+ this.savedRuns++;
638
+ }
639
+
640
+ /** Whether any agent run in this session has used a model, saved or still running. */
641
+ hasAgentUsage(): boolean {
642
+ return (
643
+ this.savedRuns > 0 || [...this.live.values()].some((live) => hasSubagentUsage(live.usage))
644
+ );
645
+ }
646
+
647
+ /** What this session's agent runs cost so far: saved runs plus runs still going. */
648
+ agentCost(): number {
649
+ let cost = this.savedCost;
650
+ for (const live of this.live.values()) {
651
+ if (!live.usageSaved) cost += live.usage.cost.total;
652
+ }
653
+ return cost;
654
+ }
655
+
656
+ /** Marks a result as returned to the model, so it is never delivered again. */
657
+ markReceipt(record: SubagentRecord, receipt: SubagentReceipt): void {
658
+ record.receipt = receipt;
659
+ this.persist(record);
660
+ }
661
+
662
+ /** Transcript for `/agents`: the live session, or the saved session file. */
663
+ transcript(record: SubagentRecord): readonly AgentMessage[] {
664
+ const child = this.live.get(record.id)?.child;
665
+ if (child) return child.session.messages;
666
+ if (!record.sessionFile) return [];
667
+ // A saved conversation changes only with a new run or status, so one read per state is enough.
668
+ // The viewer asks on every render, many times a second while any agent runs.
669
+ const key = `${record.id}:${record.run}:${record.status}`;
670
+ if (this.savedTranscript?.key !== key) {
671
+ let messages: readonly AgentMessage[];
672
+ try {
673
+ messages = SessionManager.open(record.sessionFile).buildSessionContext().messages;
674
+ } catch {
675
+ messages = [];
676
+ }
677
+ this.savedTranscript = { key, messages };
678
+ }
679
+ return this.savedTranscript.messages;
680
+ }
681
+
682
+ /** Tool definitions of a live agent, so `/agents` draws its calls the way Pi does. */
683
+ toolDefinition(record: SubagentRecord, toolName: string) {
684
+ return this.live.get(record.id)?.child?.session.getToolDefinition(toolName);
685
+ }
686
+
687
+ /** Marks unfinished work interrupted and stops it. */
688
+ async shutdown(): Promise<void> {
689
+ if (this.closed) return;
690
+ this.closed = true;
691
+ this.queue.length = 0;
692
+ const running: Promise<void>[] = [];
693
+ for (const record of this.list()) {
694
+ if (isSubagentFinished(record.status)) continue;
695
+ Object.assign(record, {
696
+ status: "interrupted",
697
+ activity: "interrupted",
698
+ receipt: "suppressed",
699
+ endedAt: Date.now(),
700
+ } satisfies Partial<SubagentRecord>);
701
+ const live = this.live.get(record.id);
702
+ // An interrupted run still cost what it used so far.
703
+ if (live) this.saveRunUsage(record, live);
704
+ this.persist(record);
705
+ live?.release?.("finished");
706
+ if (live?.child) running.push(live.child.dispose());
707
+ }
708
+ await Promise.allSettled(running);
709
+ this.live.clear();
710
+ this.listeners.clear();
711
+ }
712
+
713
+ private persist(record: SubagentRecord): void {
714
+ this.pi.appendEntry(SUBAGENT_RECORD_ENTRY, { ...record });
715
+ this.notify();
716
+ }
717
+
718
+ /** Tells UI listeners that a record changed. */
719
+ notify(): void {
720
+ for (const listener of this.listeners) listener();
721
+ }
722
+ }