@aoshizuku/pi-subagent 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/manager.ts ADDED
@@ -0,0 +1,588 @@
1
+ // Agent records, the shared FIFO queue, the single terminal writer, follow-ups, stops, persistence and restore
2
+ // (docs/06 §1, §3, §4, §6-§9).
3
+
4
+ import { type ContextFill, emptyUsage, type ProgressSnapshot, type ToolCallEntry, type UsageTotals } from "./observer.js";
5
+ import {
6
+ type AgentStatus,
7
+ ChildRun,
8
+ type ChildSession,
9
+ type ChildSessionFactory,
10
+ type ChildSpec,
11
+ errorMessage,
12
+ PARENT_INTERRUPTED,
13
+ type RunOutcome,
14
+ SESSION_ENDED,
15
+ STOPPED_BY_PARENT,
16
+ STOPPED_BY_USER,
17
+ type TerminalStatus,
18
+ } from "./run.js";
19
+
20
+ export type StoppedBy = "parent" | "user";
21
+
22
+ export interface AgentRecord {
23
+ agentId: string;
24
+ type: string;
25
+ description: string;
26
+ /** The task of the latest run (the original prompt, or the agent_send message of a continuation). */
27
+ prompt: string;
28
+ status: AgentStatus;
29
+ /** Why a run did not complete: provider error text, parent interrupted, session ended... */
30
+ reason?: string;
31
+ createdAt: number;
32
+ startedAt?: number;
33
+ endedAt?: number;
34
+ /** provider/id actually used. */
35
+ model: string;
36
+ /** Whether the latest run is a background run (notified on completion). */
37
+ background: boolean;
38
+ /** 1 for the first run; agent_send to a finished agent adds one. */
39
+ runs: number;
40
+ maxTurns?: number;
41
+ sessionFile?: string;
42
+ resultFile?: string;
43
+ /** Final report text of the latest run. Memory only: the result file is the durable copy. */
44
+ text?: string;
45
+ notes: string[];
46
+ /** Statistics of the latest run; live while it runs. */
47
+ stats: { turns: number; toolCalls: number; usage: UsageTotals };
48
+ /** All runs together (docs/07 §3.5). */
49
+ totalUsage: UsageTotals;
50
+ /** Latest known fill of the child's context window; it carries over into a continuation. */
51
+ context?: ContextFill;
52
+ /** The context reached the type's context limit: agent_send cannot continue this agent (docs/06 §6). */
53
+ contextLimited?: boolean;
54
+ /** Set when an explicit stop ended the run; decides whether the model is notified (docs/06 §5.2). */
55
+ stoppedBy?: StoppedBy;
56
+ /** The latest run's end has been handed to the model, or must never be. Memory only. */
57
+ notified: boolean;
58
+ /** Tool calls of the latest run, for the detail overlay. Memory only. */
59
+ activity?: ToolCallEntry[];
60
+ }
61
+
62
+ /** What pi.appendEntry stores: everything but the memory-only fields. */
63
+ export type AgentEntry = Omit<AgentRecord, "notified" | "activity" | "text">;
64
+
65
+ export const ENTRY_TYPE = "subagent";
66
+
67
+ export interface CreateRecordInput {
68
+ type: string;
69
+ description: string;
70
+ prompt: string;
71
+ model: string;
72
+ background?: boolean;
73
+ maxTurns?: number;
74
+ }
75
+
76
+ export interface ManagerOptions {
77
+ factory: ChildSessionFactory;
78
+ /** Read on every dequeue, so a reloaded config applies to the next start. */
79
+ maxConcurrent: () => number;
80
+ /** Number for the first `ag-<n>` id. */
81
+ firstId?: number;
82
+ now?: () => number;
83
+ /** Status transitions (queued, running, terminal): persist a snapshot. */
84
+ persist?: (record: AgentRecord) => void;
85
+ /** Called once per run when it reaches a terminal state, before that state is persisted. */
86
+ onFinished?: (record: AgentRecord) => void;
87
+ }
88
+
89
+ export interface ExecuteOptions {
90
+ spec: ChildSpec;
91
+ task: string;
92
+ signal?: AbortSignal;
93
+ /** Called with the 1-based queue position while waiting (and again when it changes). */
94
+ onQueued?: (position: number) => void;
95
+ onStart?: () => void;
96
+ onProgress?: (snapshot: ProgressSnapshot) => void;
97
+ }
98
+
99
+ export type SendResult = { kind: "steered" } | { kind: "appended" } | { kind: "finished" };
100
+
101
+ interface Waiter {
102
+ agentId: string;
103
+ resolve: (started: { ok: true } | { ok: false; reason: string }) => void;
104
+ onQueued?: (position: number) => void;
105
+ }
106
+
107
+ interface RunHandle {
108
+ run?: ChildRun;
109
+ session?: ChildSession;
110
+ /** The task has been handed to session.prompt(); later messages are steered. */
111
+ prompted: boolean;
112
+ /** A stop that landed before the run object existed. */
113
+ stopRequest?: string;
114
+ }
115
+
116
+ const TERMINAL: readonly AgentStatus[] = ["completed", "failed", "aborted", "max_turns", "context_limit"];
117
+ export const SHUTDOWN_WAIT_MS = 5000;
118
+ export const STOP_WAIT_MS = 5000;
119
+ export const APPENDED_INSTRUCTION = "\n\nAdditional instruction from the parent:\n";
120
+
121
+ export function isTerminal(status: AgentStatus): status is TerminalStatus {
122
+ return TERMINAL.includes(status);
123
+ }
124
+
125
+ export function isActive(status: AgentStatus): boolean {
126
+ return status === "queued" || status === "running";
127
+ }
128
+
129
+ export function addUsage(a: UsageTotals, b: UsageTotals): UsageTotals {
130
+ return {
131
+ input: a.input + b.input,
132
+ output: a.output + b.output,
133
+ cacheRead: a.cacheRead + b.cacheRead,
134
+ cacheWrite: a.cacheWrite + b.cacheWrite,
135
+ cost: a.cost + b.cost,
136
+ };
137
+ }
138
+
139
+ export class AgentManager {
140
+ private readonly records = new Map<string, AgentRecord>();
141
+ private readonly queue: Waiter[] = [];
142
+ /** Agents holding a concurrency slot. */
143
+ private readonly slots = new Set<string>();
144
+ private readonly runs = new Map<string, RunHandle>();
145
+ /** Task text not yet handed to a session; agent_send appends to it while queued. */
146
+ private readonly tasks = new Map<string, string>();
147
+ /** Settles when the agent's current execute() is over. */
148
+ private readonly done = new Map<string, Promise<AgentRecord>>();
149
+ /** Usage of earlier runs, so totalUsage stays live during a continuation. */
150
+ private readonly usageBefore = new Map<string, UsageTotals>();
151
+ private readonly listeners = new Set<(record: AgentRecord) => void>();
152
+ /** `${agentId}#${run}` -> the record as that run ended; kept when agent_send reopens the agent. */
153
+ private readonly outcomes = new Map<string, AgentRecord>();
154
+ private nextId: number;
155
+ private closed = false;
156
+ private readonly now: () => number;
157
+
158
+ constructor(private readonly options: ManagerOptions) {
159
+ this.nextId = Math.max(1, options.firstId ?? 1);
160
+ this.now = options.now ?? Date.now;
161
+ }
162
+
163
+ create(input: CreateRecordInput): AgentRecord {
164
+ const record: AgentRecord = {
165
+ agentId: `ag-${this.nextId++}`,
166
+ type: input.type,
167
+ description: input.description,
168
+ prompt: input.prompt,
169
+ model: input.model,
170
+ background: input.background ?? false,
171
+ maxTurns: input.maxTurns,
172
+ status: "queued",
173
+ createdAt: this.now(),
174
+ runs: 1,
175
+ notes: [],
176
+ stats: { turns: 0, toolCalls: 0, usage: emptyUsage() },
177
+ totalUsage: emptyUsage(),
178
+ notified: false,
179
+ };
180
+ this.records.set(record.agentId, record);
181
+ this.transition(record);
182
+ return record;
183
+ }
184
+
185
+ get(agentId: string): AgentRecord | undefined {
186
+ return this.records.get(agentId);
187
+ }
188
+
189
+ list(): AgentRecord[] {
190
+ return [...this.records.values()];
191
+ }
192
+
193
+ get runningCount(): number {
194
+ return this.slots.size;
195
+ }
196
+
197
+ get queuedCount(): number {
198
+ return this.queue.length;
199
+ }
200
+
201
+ /** 1-based position in the queue, 0 when not queued. */
202
+ position(agentId: string): number {
203
+ return this.queue.findIndex((waiter) => waiter.agentId === agentId) + 1;
204
+ }
205
+
206
+ /** Called on every change, progress included (HUD, detail overlay). Returns an unsubscribe function. */
207
+ subscribe(listener: (record: AgentRecord) => void): () => void {
208
+ this.listeners.add(listener);
209
+ return () => this.listeners.delete(listener);
210
+ }
211
+
212
+ /** Live progress of a running agent, undefined otherwise. */
213
+ progress(agentId: string): ProgressSnapshot | undefined {
214
+ return this.runs.get(agentId)?.run?.observer.snapshot();
215
+ }
216
+
217
+ /** How run `run` of an agent ended (a snapshot of its record then); undefined while it runs or when unknown. */
218
+ runOutcome(agentId: string, run: number): AgentRecord | undefined {
219
+ return this.outcomes.get(runKey(agentId, run));
220
+ }
221
+
222
+ /**
223
+ * Load records from persisted entries (the last entry per id wins). Agents that were still queued or running
224
+ * belonged to a pi process that is gone: they become aborted ("session ended"). Returns those, so the caller
225
+ * can persist the correction. Ids continue after the highest restored one. Every run's last entry also
226
+ * becomes that run's outcome, so a background card of an earlier run still finds how it ended.
227
+ */
228
+ restore(entries: readonly AgentEntry[]): AgentRecord[] {
229
+ const latest = new Map<string, AgentEntry>();
230
+ const perRun = new Map<string, AgentEntry>();
231
+ for (const entry of entries) {
232
+ if (!entry || typeof entry.agentId !== "string") continue;
233
+ latest.set(entry.agentId, entry);
234
+ perRun.set(runKey(entry.agentId, entry.runs ?? 1), entry);
235
+ }
236
+ const closed: AgentRecord[] = [];
237
+ for (const entry of latest.values()) {
238
+ const record = this.fromEntry(entry);
239
+ if (isActive(entry.status)) closed.push(record);
240
+ this.records.set(record.agentId, record);
241
+ const n = Number(/^ag-(\d+)$/.exec(record.agentId)?.[1]);
242
+ if (Number.isFinite(n) && n >= this.nextId) this.nextId = n + 1;
243
+ }
244
+ for (const [key, entry] of perRun) {
245
+ const record = latest.get(entry.agentId) === entry ? this.records.get(entry.agentId) : this.fromEntry(entry);
246
+ if (record && isTerminal(record.status)) this.outcomes.set(key, { ...record });
247
+ }
248
+ return closed;
249
+ }
250
+
251
+ /** A persisted entry as a record; one still queued or running is closed as "session ended". */
252
+ private fromEntry(entry: AgentEntry): AgentRecord {
253
+ const record: AgentRecord = {
254
+ ...entry,
255
+ background: entry.background ?? false,
256
+ runs: entry.runs ?? 1,
257
+ notes: entry.notes ?? [],
258
+ stats: entry.stats ?? { turns: 0, toolCalls: 0, usage: emptyUsage() },
259
+ totalUsage: entry.totalUsage ?? emptyUsage(),
260
+ // The old process either notified it or can no longer; never notify on restore.
261
+ notified: true,
262
+ };
263
+ if (isActive(record.status)) {
264
+ record.status = "aborted";
265
+ record.reason = SESSION_ENDED;
266
+ record.endedAt = this.now();
267
+ }
268
+ return record;
269
+ }
270
+
271
+ /**
272
+ * The only way into a terminal state. Effective once per run: a later call only backfills the report
273
+ * text when the first one had none (for example a stop that landed before the run returned).
274
+ */
275
+ finish(agentId: string, outcome: RunOutcome, stats?: AgentRecord["stats"]): boolean {
276
+ const record = this.records.get(agentId);
277
+ if (!record) return false;
278
+ if (isTerminal(record.status)) {
279
+ if (!record.text && outcome.text) record.text = outcome.text;
280
+ if (stats) this.setStats(record, stats);
281
+ this.outcomes.set(runKey(agentId, record.runs), { ...record });
282
+ return false;
283
+ }
284
+ record.status = outcome.status;
285
+ record.reason = outcome.status === "completed" ? undefined : outcome.reason;
286
+ record.text = outcome.text;
287
+ record.notes = [...record.notes, ...outcome.notes];
288
+ record.endedAt = this.now();
289
+ if (stats) this.setStats(record, stats);
290
+ // Before the snapshot is persisted, so the caller can attach the result file to it.
291
+ this.options.onFinished?.(record);
292
+ // Before listeners hear of it, so a card redrawn by the transition finds its run's outcome.
293
+ this.outcomes.set(runKey(agentId, record.runs), { ...record });
294
+ this.transition(record);
295
+ return true;
296
+ }
297
+
298
+ /** Queue -> create session -> run -> finish -> dispose. Resolves with the record in its terminal state. */
299
+ execute(record: AgentRecord, options: ExecuteOptions): Promise<AgentRecord> {
300
+ const id = record.agentId;
301
+ this.tasks.set(id, options.task);
302
+ const promise = this.executeRun(record, options).finally(() => {
303
+ if (this.done.get(id) === promise) this.done.delete(id);
304
+ this.tasks.delete(id);
305
+ });
306
+ this.done.set(id, promise);
307
+ return promise;
308
+ }
309
+
310
+ /**
311
+ * agent_send: a running agent gets the message as a steering user message; a queued one (or one whose
312
+ * session is still being built) gets it appended to its task. A finished agent must be reopened.
313
+ */
314
+ async send(agentId: string, message: string): Promise<SendResult> {
315
+ const record = this.records.get(agentId);
316
+ if (!record || isTerminal(record.status)) return { kind: "finished" };
317
+ const handle = this.runs.get(agentId);
318
+ if (handle?.prompted && handle.session) {
319
+ await handle.session.steerUser(message);
320
+ return { kind: "steered" };
321
+ }
322
+ this.tasks.set(agentId, `${this.tasks.get(agentId) ?? record.prompt}${APPENDED_INSTRUCTION}${message}`);
323
+ return { kind: "appended" };
324
+ }
325
+
326
+ /** Prepare a finished agent for another run on its transcript (docs/06 §6). Execute it afterwards. */
327
+ reopen(agentId: string, input: { prompt: string; model: string; background: boolean; maxTurns?: number }): AgentRecord {
328
+ const record = this.records.get(agentId);
329
+ if (!record) throw new Error(`unknown agent ${agentId}`);
330
+ if (!isTerminal(record.status)) throw new Error(`${agentId} is still ${record.status}`);
331
+ if (record.contextLimited) throw new Error(`${agentId} reached its context limit and cannot be continued`);
332
+ this.usageBefore.set(agentId, { ...record.totalUsage });
333
+ Object.assign(record, {
334
+ status: "queued",
335
+ prompt: input.prompt,
336
+ model: input.model,
337
+ background: input.background,
338
+ maxTurns: input.maxTurns,
339
+ runs: record.runs + 1,
340
+ reason: undefined,
341
+ text: undefined,
342
+ notes: [],
343
+ startedAt: undefined,
344
+ endedAt: undefined,
345
+ stoppedBy: undefined,
346
+ notified: false,
347
+ activity: undefined,
348
+ stats: { turns: 0, toolCalls: 0, usage: emptyUsage() },
349
+ } satisfies Partial<AgentRecord>);
350
+ this.transition(record);
351
+ return record;
352
+ }
353
+
354
+ /**
355
+ * agent_stop (by "parent") or a user stop (by "user"). Queued: leaves the queue. Running: aborted, waiting at
356
+ * most `waitMs` for the run to return its partial report; after that the record is finished regardless.
357
+ * Already finished: returned as is.
358
+ */
359
+ async stop(agentId: string, by: StoppedBy, waitMs = STOP_WAIT_MS): Promise<AgentRecord | undefined> {
360
+ const record = this.records.get(agentId);
361
+ if (!record || isTerminal(record.status)) return record;
362
+ const reason = by === "parent" ? STOPPED_BY_PARENT : STOPPED_BY_USER;
363
+ record.stoppedBy = by;
364
+
365
+ const index = this.queue.findIndex((waiter) => waiter.agentId === agentId);
366
+ if (index !== -1) {
367
+ const [waiter] = this.queue.splice(index, 1);
368
+ this.finish(agentId, { status: "aborted", reason, text: "", notes: [] });
369
+ waiter?.resolve({ ok: false, reason });
370
+ this.pump();
371
+ return record;
372
+ }
373
+
374
+ const handle = this.runs.get(agentId);
375
+ if (handle?.run) void handle.run.stop("aborted", reason).catch(() => {});
376
+ else if (handle) handle.stopRequest = reason;
377
+ const pending = this.done.get(agentId);
378
+ if (pending) {
379
+ let timer: NodeJS.Timeout | undefined;
380
+ await Promise.race([
381
+ pending.then(
382
+ () => {},
383
+ () => {},
384
+ ),
385
+ new Promise<void>((resolve) => {
386
+ timer = setTimeout(resolve, waitMs);
387
+ }),
388
+ ]);
389
+ if (timer) clearTimeout(timer);
390
+ }
391
+ // A hung provider request must not leave the agent "running" forever.
392
+ this.finish(agentId, { status: "aborted", reason, text: "", notes: [] });
393
+ return record;
394
+ }
395
+
396
+ /** Start queued agents while slots are free; call after maxConcurrent changes. */
397
+ pump(): void {
398
+ while (!this.closed && this.queue.length > 0 && this.slots.size < this.options.maxConcurrent()) {
399
+ const waiter = this.queue.shift();
400
+ if (!waiter) break;
401
+ this.slots.add(waiter.agentId);
402
+ waiter.resolve({ ok: true });
403
+ }
404
+ this.queue.forEach((waiter, index) => waiter.onQueued?.(index + 1));
405
+ }
406
+
407
+ /**
408
+ * session_shutdown: drop the queue, mark running agents aborted, abort them and wait at most
409
+ * `waitMs` so a hung provider request cannot hold pi's exit, then dispose every session.
410
+ */
411
+ async shutdown(waitMs = SHUTDOWN_WAIT_MS): Promise<void> {
412
+ this.closed = true;
413
+ for (const waiter of this.queue.splice(0)) waiter.resolve({ ok: false, reason: SESSION_ENDED });
414
+ const aborts: Array<Promise<void>> = [];
415
+ for (const [id, handle] of this.runs) {
416
+ this.finish(id, { status: "aborted", reason: SESSION_ENDED, text: "", notes: [] });
417
+ if (handle.run) aborts.push(handle.run.stop("aborted", SESSION_ENDED).catch(() => {}));
418
+ else handle.stopRequest = SESSION_ENDED;
419
+ }
420
+ let timer: NodeJS.Timeout | undefined;
421
+ await Promise.race([
422
+ Promise.all(aborts),
423
+ new Promise<void>((resolve) => {
424
+ timer = setTimeout(resolve, waitMs);
425
+ }),
426
+ ]);
427
+ if (timer) clearTimeout(timer);
428
+ for (const handle of this.runs.values()) disposeQuietly(handle.session);
429
+ this.listeners.clear();
430
+ }
431
+
432
+ private async executeRun(record: AgentRecord, options: ExecuteOptions): Promise<AgentRecord> {
433
+ const id = record.agentId;
434
+ const slot = await this.acquire(id, options.signal, options.onQueued);
435
+ if (!slot.ok) {
436
+ this.finish(id, { status: "aborted", reason: slot.reason, text: "", notes: [] });
437
+ return record;
438
+ }
439
+
440
+ const handle: RunHandle = { prompted: false };
441
+ this.runs.set(id, handle);
442
+ record.status = "running";
443
+ record.startedAt = this.now();
444
+ this.transition(record);
445
+ options.onStart?.();
446
+ try {
447
+ handle.session = await this.options.factory.create(options.spec);
448
+ record.sessionFile = handle.session.sessionFile;
449
+ if (handle.session.model) record.model = handle.session.model;
450
+ // The "running" entry was written before the session existed. Persist again so a parent that
451
+ // crashes mid-run restores a record that still points at the transcript and can be continued.
452
+ if (record.sessionFile) this.options.persist?.(record);
453
+ const run = new ChildRun(handle.session, {
454
+ maxTurns: options.spec.type.maxTurns,
455
+ contextLimit: options.spec.type.contextLimit,
456
+ cwd: options.spec.cwd,
457
+ onProgress: (snapshot) => {
458
+ this.setStats(record, { turns: snapshot.turns, toolCalls: snapshot.toolCalls, usage: snapshot.usage });
459
+ if (snapshot.context) record.context = snapshot.context;
460
+ if (snapshot.contextLimited && !record.contextLimited) {
461
+ record.contextLimited = true;
462
+ // Persist now: a parent that crashes mid-run must not restore it as continuable.
463
+ this.options.persist?.(record);
464
+ }
465
+ options.onProgress?.(snapshot);
466
+ this.changed(record);
467
+ },
468
+ });
469
+ handle.run = run;
470
+ record.activity = run.observer.activity;
471
+ // Shutdown, a stop or the parent's abort may have landed while the session was being built.
472
+ if (this.closed) void run.stop("aborted", SESSION_ENDED);
473
+ else if (handle.stopRequest) void run.stop("aborted", handle.stopRequest);
474
+ const task = this.tasks.get(id) ?? options.task;
475
+ handle.prompted = true;
476
+ const outcome = await run.run(task, options.signal);
477
+ // agent_end and the final turn_end refresh it without an onProgress; take it before finish persists.
478
+ if (run.observer.context) record.context = { ...run.observer.context };
479
+ if (run.observer.contextLimited) record.contextLimited = true;
480
+ this.finish(id, outcome, statsOf(run));
481
+ } catch (error) {
482
+ const aborted = this.closed || options.signal?.aborted || handle.stopRequest !== undefined;
483
+ this.finish(id, {
484
+ status: aborted ? "aborted" : "failed",
485
+ reason: this.closed
486
+ ? SESSION_ENDED
487
+ : options.signal?.aborted
488
+ ? PARENT_INTERRUPTED
489
+ : (handle.stopRequest ?? errorMessage(error)),
490
+ text: "",
491
+ notes: [],
492
+ });
493
+ } finally {
494
+ this.runs.delete(id);
495
+ disposeQuietly(handle.session);
496
+ this.release(id);
497
+ }
498
+ return record;
499
+ }
500
+
501
+ private setStats(record: AgentRecord, stats: AgentRecord["stats"]): void {
502
+ record.stats = { turns: stats.turns, toolCalls: stats.toolCalls, usage: { ...stats.usage } };
503
+ record.totalUsage = addUsage(this.usageBefore.get(record.agentId) ?? emptyUsage(), stats.usage);
504
+ }
505
+
506
+ private acquire(
507
+ agentId: string,
508
+ signal: AbortSignal | undefined,
509
+ onQueued: ((position: number) => void) | undefined,
510
+ ): Promise<{ ok: true } | { ok: false; reason: string }> {
511
+ if (this.closed) return Promise.resolve({ ok: false, reason: SESSION_ENDED });
512
+ if (signal?.aborted) return Promise.resolve({ ok: false, reason: PARENT_INTERRUPTED });
513
+ const record = this.records.get(agentId);
514
+ if (record && isTerminal(record.status)) return Promise.resolve({ ok: false, reason: record.reason ?? "aborted" });
515
+ if (this.queue.length === 0 && this.slots.size < this.options.maxConcurrent()) {
516
+ this.slots.add(agentId);
517
+ return Promise.resolve({ ok: true });
518
+ }
519
+ return new Promise((resolve) => {
520
+ const onAbort = (): void => {
521
+ const index = this.queue.indexOf(waiter);
522
+ if (index === -1) return;
523
+ this.queue.splice(index, 1);
524
+ resolve({ ok: false, reason: PARENT_INTERRUPTED });
525
+ this.pump();
526
+ };
527
+ const waiter: Waiter = {
528
+ agentId,
529
+ onQueued,
530
+ resolve: (result) => {
531
+ signal?.removeEventListener("abort", onAbort);
532
+ resolve(result);
533
+ },
534
+ };
535
+ this.queue.push(waiter);
536
+ signal?.addEventListener("abort", onAbort, { once: true });
537
+ onQueued?.(this.queue.length);
538
+ });
539
+ }
540
+
541
+ private release(agentId: string): void {
542
+ if (this.slots.delete(agentId)) this.pump();
543
+ }
544
+
545
+ /** A status transition: persisted and announced. */
546
+ private transition(record: AgentRecord): void {
547
+ this.options.persist?.(record);
548
+ this.changed(record);
549
+ }
550
+
551
+ private changed(record: AgentRecord): void {
552
+ for (const listener of [...this.listeners]) {
553
+ try {
554
+ listener(record);
555
+ } catch {
556
+ // A UI listener must not break a run.
557
+ }
558
+ }
559
+ }
560
+ }
561
+
562
+ function runKey(agentId: string, run: number): string {
563
+ return `${agentId}#${run}`;
564
+ }
565
+
566
+ /** The persisted form of a record. */
567
+ export function toEntry(record: AgentRecord): AgentEntry {
568
+ const { notified: _notified, activity: _activity, text: _text, ...entry } = record;
569
+ return {
570
+ ...entry,
571
+ notes: [...entry.notes],
572
+ stats: { ...entry.stats, usage: { ...entry.stats.usage } },
573
+ totalUsage: { ...entry.totalUsage },
574
+ ...(entry.context ? { context: { ...entry.context } } : {}),
575
+ };
576
+ }
577
+
578
+ function statsOf(run: ChildRun): AgentRecord["stats"] {
579
+ return { turns: run.observer.turns, toolCalls: run.observer.toolCalls, usage: { ...run.observer.usage } };
580
+ }
581
+
582
+ function disposeQuietly(session: ChildSession | undefined): void {
583
+ try {
584
+ session?.dispose();
585
+ } catch {
586
+ // Disposal must not mask the run's outcome.
587
+ }
588
+ }
package/src/models.ts ADDED
@@ -0,0 +1,80 @@
1
+ // Model and thinking-level resolution for a child session (docs/02 §3).
2
+
3
+ import type { ThinkingLevel } from "./config.js";
4
+
5
+ export interface ModelRef {
6
+ provider: string;
7
+ id: string;
8
+ }
9
+
10
+ /** The parent's model catalogue, narrowed to what resolution needs (backed by ctx.modelRegistry). */
11
+ export interface ModelCatalog {
12
+ find(provider: string, id: string): ModelRef | undefined;
13
+ /** Models whose provider has credentials. */
14
+ available(): readonly ModelRef[];
15
+ hasAuth(model: ModelRef): boolean;
16
+ }
17
+
18
+ export interface ModelRequest {
19
+ /** `model` call parameter: errors are reported to the caller. */
20
+ param?: string;
21
+ /** Model from the plugin config or the type file: falls back to the parent model with a note. */
22
+ configured?: string;
23
+ parent?: ModelRef;
24
+ }
25
+
26
+ export interface ModelResolution {
27
+ /** Undefined only when there is no parent model either; pi then picks its default. */
28
+ model?: ModelRef;
29
+ notes: string[];
30
+ }
31
+
32
+ export function formatModel(model: ModelRef | undefined): string {
33
+ return model ? `${model.provider}/${model.id}` : "(default)";
34
+ }
35
+
36
+ type Lookup = { ok: true; model: ModelRef } | { ok: false; error: string };
37
+
38
+ /** Accepts `provider/id` or a bare id that matches exactly one available model. */
39
+ export function lookupModel(spec: string, catalog: ModelCatalog): Lookup {
40
+ const text = spec.trim();
41
+ const slash = text.indexOf("/");
42
+ if (slash > 0) {
43
+ const found = catalog.find(text.slice(0, slash), text.slice(slash + 1));
44
+ if (found) {
45
+ return catalog.hasAuth(found)
46
+ ? { ok: true, model: found }
47
+ : { ok: false, error: `model ${formatModel(found)} has no credentials configured` };
48
+ }
49
+ }
50
+ // Bare id; ids may themselves contain "/" (for example OpenRouter's), so also try the whole text.
51
+ const matches = catalog.available().filter((model) => model.id === text);
52
+ if (matches.length === 1 && matches[0]) return { ok: true, model: matches[0] };
53
+ if (matches.length > 1) {
54
+ return { ok: false, error: `model id "${text}" is ambiguous; use one of: ${matches.map(formatModel).join(", ")}` };
55
+ }
56
+ return { ok: false, error: `model "${text}" not found among models with credentials` };
57
+ }
58
+
59
+ /** Resolution order: call parameter > config / type file > parent model. Throws only for the call parameter. */
60
+ export function resolveModel(request: ModelRequest, catalog: ModelCatalog): ModelResolution {
61
+ if (request.param?.trim()) {
62
+ const found = lookupModel(request.param, catalog);
63
+ if (!found.ok) throw new Error(`Invalid model parameter: ${found.error}. Omit model to use the default.`);
64
+ return { model: found.model, notes: [] };
65
+ }
66
+ if (request.configured?.trim()) {
67
+ const found = lookupModel(request.configured, catalog);
68
+ if (found.ok) return { model: found.model, notes: [] };
69
+ return {
70
+ model: request.parent,
71
+ notes: [`model ${request.configured.trim()} unavailable (${found.error}), used ${formatModel(request.parent)}`],
72
+ };
73
+ }
74
+ return { model: request.parent, notes: [] };
75
+ }
76
+
77
+ /** Resolution order: call parameter > config / type file > parent. pi clamps it to the model (sdk.ts:270-276). */
78
+ export function resolveThinking(param: ThinkingLevel | undefined, configured: ThinkingLevel | undefined, parent: ThinkingLevel | undefined): ThinkingLevel | undefined {
79
+ return param ?? configured ?? parent;
80
+ }