@maheidem/pi-delegate 0.3.2 → 0.6.1

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/background.ts ADDED
@@ -0,0 +1,764 @@
1
+ /**
2
+ * delegate — background run manager (R8–R13).
3
+ *
4
+ * Pi-free: delivery and ledger writes are injected ports (wired in
5
+ * index.ts), so every behavior here is unit-testable with fakes. The
6
+ * session JSONL is the source of truth for background-run ownership
7
+ * (`delegate.background` custom entries, schema v1); receipts remain the
8
+ * detailed durable record. Semantics ported from pi-async-fork
9
+ * (SPEC §1): serialized at-least-once delivery with branch-scan dedup,
10
+ * generation guard across session replacement, delivery pause across
11
+ * tree switches, and reconcile-on-activation for runs that finished
12
+ * while their owning branch was inactive.
13
+ */
14
+
15
+ import type {
16
+ BackgroundCreatedEntry,
17
+ BackgroundFinishedEntry,
18
+ BackgroundRunHandle,
19
+ BackgroundRunRecord,
20
+ DelegateError,
21
+ DelegateRunResult,
22
+ RoleName,
23
+ RunMetadataV1,
24
+ RunState,
25
+ RunTerminalState,
26
+ SessionEntryLike,
27
+ } from "./types.ts";
28
+ import { isTerminalRunState } from "./types.ts";
29
+ import { isPidAlive, readRunMetadata } from "./run-store.ts";
30
+ import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE } from "./ask.ts";
31
+ export { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE };
32
+
33
+ /** R11: ledger custom-entry type (session JSONL). */
34
+ export const BACKGROUND_LEDGER_TYPE = "delegate.background";
35
+ /** R10: terminal-result custom-message type. */
36
+ export const BACKGROUND_RESULT_TYPE = "delegate-background-result";
37
+
38
+ /** R12: was a terminal result for this run already delivered on the branch? */
39
+ export function wasResultDelivered(branch: readonly SessionEntryLike[], runId: string): boolean {
40
+ return branch.some((entry) => {
41
+ if (entry?.type !== "custom_message") return false;
42
+ if (entry.customType !== BACKGROUND_RESULT_TYPE) return false;
43
+ const details = (entry as { details?: unknown }).details;
44
+ return Boolean(details && typeof details === "object" &&
45
+ (details as { runId?: unknown }).runId === runId);
46
+ });
47
+ }
48
+
49
+ function isBackgroundLedgerEntry(data: unknown): data is BackgroundCreatedEntry | BackgroundFinishedEntry {
50
+ if (!data || typeof data !== "object") return false;
51
+ const raw = data as Record<string, unknown>;
52
+ if (raw.v !== 1) return false;
53
+ if (raw.type === "created") {
54
+ return typeof raw.runId === "string"
55
+ && (raw.role === "general" || raw.role === "research")
56
+ && typeof raw.description === "string"
57
+ && typeof raw.createdAt === "string";
58
+ }
59
+ if (raw.type === "finished") {
60
+ return typeof raw.runId === "string" && typeof raw.finishedAt === "string"
61
+ && typeof raw.state === "string" && isTerminalRunState(raw.state as RunTerminalState);
62
+ }
63
+ return false;
64
+ }
65
+
66
+ /** R11: project the branch root-to-tip into background-run records.
67
+ * Malformed entries are skipped and counted — never fatal. */
68
+ export function projectBackgroundRuns(branch: readonly SessionEntryLike[]): {
69
+ records: Map<string, BackgroundRunRecord>;
70
+ skipped: number;
71
+ } {
72
+ const records = new Map<string, BackgroundRunRecord>();
73
+ let skipped = 0;
74
+ for (const entry of branch) {
75
+ if (entry?.type !== "custom" || entry.customType !== BACKGROUND_LEDGER_TYPE) continue;
76
+ if (!isBackgroundLedgerEntry(entry.data)) {
77
+ skipped += 1;
78
+ continue;
79
+ }
80
+ const data = entry.data;
81
+ if (data.type === "created") {
82
+ records.set(data.runId, { created: data });
83
+ } else {
84
+ const existing = records.get(data.runId);
85
+ if (existing && !existing.finished) {
86
+ records.set(data.runId, { ...existing, finished: data });
87
+ } else if (!existing) {
88
+ // finished without created on this branch: unowned, skip
89
+ skipped += 1;
90
+ }
91
+ }
92
+ }
93
+ return { records, skipped };
94
+ }
95
+
96
+ /**
97
+ * R8: background `description` validation (pi-async-fork rule, SPEC §1):
98
+ * trimmed outer whitespace, 3–6 whitespace-separated words, single line —
99
+ * C0/C1 controls and U+2028/U+2029 rejected. Returns the normalized value
100
+ * or an error message.
101
+ */
102
+ export function validateBackgroundDescription(raw: unknown): { ok: true; value: string } | { ok: false; error: string } {
103
+ if (typeof raw !== "string") return { ok: false, error: "description must be a string." };
104
+ const value = raw.trim();
105
+ if (!value) return { ok: false, error: "description is required for background runs." };
106
+ if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(value)) {
107
+ return { ok: false, error: "description must be a single line (control characters rejected)." };
108
+ }
109
+ const words = value.split(/\s+/).filter(Boolean);
110
+ if (words.length < 3 || words.length > 6) {
111
+ return { ok: false, error: `description must be 3 to 6 words (got ${words.length}).` };
112
+ }
113
+ return { ok: true, value };
114
+ }
115
+
116
+ /** State word for headers (same mapping as the foreground result header). */
117
+ export function backgroundStateWord(state: RunTerminalState): string {
118
+ if (state === "succeeded") return "completed";
119
+ if (state === "cancelled") return "cancelled";
120
+ if (state.startsWith("timed_out")) return state.replace("_", " ");
121
+ return state;
122
+ }
123
+
124
+ /**
125
+ * R10: the model-visible terminal envelope (SPEC §5, byte-exact).
126
+ * `runText` is the deterministic foreground-style result rendering
127
+ * (formatRunText) reused verbatim.
128
+ */
129
+ export function formatBackgroundResultEnvelope(
130
+ runId: string,
131
+ role: RoleName,
132
+ description: string,
133
+ state: RunTerminalState,
134
+ runText: string,
135
+ ): string {
136
+ return (
137
+ `[delegate background ${runId} · ${role} · ${description}: ${backgroundStateWord(state)}]\n` +
138
+ "\n" +
139
+ "This is the terminal report of a background delegation. The run has finished and\n" +
140
+ "cannot receive steering. Treat it as an internal work event: write user-visible\n" +
141
+ "text only if material, and do not re-narrate the handoff.\n" +
142
+ "\n" +
143
+ runText
144
+ );
145
+ }
146
+
147
+ /** R8: the immediate tool-result content for a background spawn. */
148
+ export function formatBackgroundStartedText(runId: string, role: RoleName, description: string): string {
149
+ return (
150
+ `[delegate background started · ${runId} · ${role} · ${description}]\n` +
151
+ "The run executes outside this turn. Poll it with the delegate_status tool\n" +
152
+ "(delegate_status({ runId: \"" + runId + "\" })). The terminal report arrives as a\n" +
153
+ "message when the run finishes — do not wait inline for it."
154
+ );
155
+ }
156
+
157
+ /** R17: the question envelope (SPEC §5, byte-exact; wakes the parent). */
158
+ export function formatChildQuestionEnvelope(runId: string, role: RoleName, description: string, topic: string, question: string): string {
159
+ return (
160
+ `[delegate background ${runId} · ${role} · ${description}: asks]\n` +
161
+ "\n" +
162
+ `A delegated child is blocked waiting for your answer (topic: ${topic}). Answer\n` +
163
+ `with the delegate_answer tool: delegate_answer({ runId: "${runId}", answer: "…" }).\n` +
164
+ "Be terse and directive; the child resumes the moment your answer lands. Do not\n" +
165
+ "narrate this exchange to the user unless it is material. If you cannot answer,\n" +
166
+ "say so — the child proceeds with its best judgment after the ask budget expires.\n" +
167
+ "\n" +
168
+ question
169
+ );
170
+ }
171
+
172
+ /** R18: the note envelope (SPEC §5, byte-exact; NEVER wakes the parent). */
173
+ export function formatChildNoteEnvelope(runId: string, role: RoleName, description: string, topic: string, note: string): string {
174
+ return (
175
+ `[delegate background ${runId} · ${role} · ${description}: note]\n` +
176
+ "\n" +
177
+ `A delegated child filed a non-blocking note (topic: ${topic}). No answer is\n` +
178
+ "expected or possible. Treat it as an internal work event.\n" +
179
+ "\n" +
180
+ note
181
+ );
182
+ }
183
+
184
+ /** R12: rebuild a DelegateRunResult from a receipt (replay/reconcile path). */
185
+ export function receiptToRunResult(metadata: RunMetadataV1): DelegateRunResult {
186
+ const ok = metadata.state === "succeeded";
187
+ const durationMs = metadata.startedAt && metadata.finishedAt
188
+ ? Math.max(0, Date.parse(metadata.finishedAt) - Date.parse(metadata.startedAt))
189
+ : 0;
190
+ return {
191
+ ok,
192
+ handoff: metadata.finalHandoff ?? "",
193
+ details: {
194
+ schemaVersion: 1,
195
+ runId: metadata.runId,
196
+ role: metadata.role,
197
+ state: metadata.state as RunTerminalState,
198
+ startedAt: metadata.startedAt ?? metadata.createdAt,
199
+ finishedAt: metadata.finishedAt ?? metadata.createdAt,
200
+ durationMs,
201
+ model: metadata.model,
202
+ ...(metadata.thinkingLevel ? { thinkingLevel: metadata.thinkingLevel } : {}),
203
+ exitCode: metadata.exitCode,
204
+ stopReason: metadata.stopReason,
205
+ usage: metadata.usage,
206
+ outputBytes: metadata.outputBytes ?? 0,
207
+ outputTruncated: metadata.outputTruncated ?? false,
208
+ ...(metadata.partialHandoff ? { partialHandoff: metadata.partialHandoff } : {}),
209
+ ...(metadata.sessionPath ? { sessionPath: metadata.sessionPath } : {}),
210
+ transcriptPath: metadata.transcriptPath,
211
+ stderrPath: metadata.stderrPath,
212
+ displayItems: [],
213
+ },
214
+ ...(metadata.errorCode
215
+ ? { error: { code: metadata.errorCode, message: metadata.errorMessage ?? "" } }
216
+ : {}),
217
+ };
218
+ }
219
+
220
+ export interface BackgroundManagerPorts {
221
+ /** pi.sendMessage(message, options) — wired by the adapter. */
222
+ sendMessage(message: {
223
+ customType: string;
224
+ content: string;
225
+ display: true;
226
+ details: Record<string, unknown>;
227
+ }, options: { deliverAs: "steer"; triggerTurn: boolean }): unknown;
228
+ /** pi.appendEntry(customType, data) — wired by the adapter. */
229
+ appendEntry(customType: string, data: unknown): unknown;
230
+ /** Live config accessor (slot limit). */
231
+ maxBackgroundRuns(): number;
232
+ /** Renders a terminal DelegateRunResult to text (formatRunText). */
233
+ formatRun: (res: DelegateRunResult) => string;
234
+ /** Receipt lookup for reconcile (run store). */
235
+ readReceipt(runId: string): RunMetadataV1 | null;
236
+ /** Injected for testability (defaults to run-store isPidAlive). */
237
+ isPidAlive?: (pid: number) => boolean;
238
+ /** R15: optional footer hook — live background count changes. */
239
+ onInventoryChange?: (liveCount: number) => void;
240
+ }
241
+
242
+ interface ManagedRun {
243
+ handle: BackgroundRunHandle;
244
+ generation: number;
245
+ /** Set when the owning branch is not the active one (delivery deferred). */
246
+ detached: boolean;
247
+ done: boolean;
248
+ }
249
+
250
+ /**
251
+ * R9/R10/R12/R13: slot accounting, ledger writes, serialized delivery,
252
+ * generation guard, tree pause, reconcile.
253
+ */
254
+ export class BackgroundManager {
255
+ readonly #ports: BackgroundManagerPorts;
256
+ readonly #runs = new Map<string, ManagedRun>();
257
+ #generation = 0;
258
+ #paused = false;
259
+ #deliveryTail: Promise<void> = Promise.resolve();
260
+ #pendingFlush: Array<() => void> = [];
261
+ /** R17: runId → pending ask (one live question per run). */
262
+ readonly #pendingAsks = new Map<string, { toolCallId: string; topic: string; askedAt: string }>();
263
+ /** runIds with a created entry on the currently active branch. */
264
+ #branchOwned = new Set<string>();
265
+ /** Latest branch snapshot (for dedup scans between refreshes). */
266
+ #branchSnapshot: readonly SessionEntryLike[] = [];
267
+ /** Delivered during this manager lifetime (in-memory dedup supplement). */
268
+ #delivered = new Set<string>();
269
+ readonly #isPidAlive: (pid: number) => boolean;
270
+
271
+ constructor(ports: BackgroundManagerPorts) {
272
+ this.#ports = ports;
273
+ this.#isPidAlive = ports.isPidAlive ?? isPidAlive;
274
+ }
275
+
276
+ // ── Slots (R9) ────────────────────────────────────────────────────────
277
+
278
+ private liveCount(): number {
279
+ let n = 0;
280
+ for (const run of this.#runs.values()) if (!run.done) n += 1;
281
+ return n;
282
+ }
283
+
284
+ /** Sync pre-spawn slot check; null = a slot is free. */
285
+ slotError(): DelegateError | null {
286
+ const live = this.liveCount();
287
+ if (live >= this.#ports.maxBackgroundRuns()) {
288
+ return {
289
+ code: "E_BACKGROUND_FULL",
290
+ message: `${live} background runs active (limit ${this.#ports.maxBackgroundRuns()}); wait for terminal reports or check delegate_status.`,
291
+ };
292
+ }
293
+ return null;
294
+ }
295
+
296
+ // ── Registration + terminal path (R8/R10/R11) ─────────────────────────
297
+
298
+ /** Register a spawned handle: ledger `created`, completion wiring. */
299
+ register(handle: BackgroundRunHandle): void {
300
+ const generation = this.#generation;
301
+ this.#runs.set(handle.runId, { handle, generation, detached: false, done: false });
302
+ this.#branchOwned.add(handle.runId);
303
+ this.appendLedger({
304
+ v: 1,
305
+ type: "created",
306
+ runId: handle.runId,
307
+ role: handle.role,
308
+ description: handle.description,
309
+ createdAt: new Date().toISOString(),
310
+ });
311
+ void handle.completion.then((result) => {
312
+ this.onTerminal(handle.runId, result);
313
+ });
314
+ this.#ports.onInventoryChange?.(this.liveCount());
315
+ }
316
+
317
+ private onTerminal(runId: string, result: DelegateRunResult): void {
318
+ const run = this.#runs.get(runId);
319
+ if (!run) return; // unknown run: reconcile owns it
320
+ run.done = true;
321
+ this.#ports.onInventoryChange?.(this.liveCount());
322
+ if (run.generation !== this.#generation) return; // stale session: receipt only
323
+ if (!this.#branchOwned.has(runId) || run.detached) {
324
+ // Owning branch inactive: no entry write, no delivery here.
325
+ // R12 reconcile delivers when the branch re-activates.
326
+ return;
327
+ }
328
+ this.finalizeAndDeliver(runId, run.handle.role, run.handle.description, result);
329
+ }
330
+
331
+ /** R10/R11: finished entry first, then exactly one result message. */
332
+ private finalizeAndDeliver(runId: string, role: RoleName, description: string, result: DelegateRunResult): void {
333
+ if (this.wasDelivered(runId)) return;
334
+ this.appendLedger({
335
+ v: 1,
336
+ type: "finished",
337
+ runId,
338
+ state: result.details.state,
339
+ finishedAt: result.details.finishedAt,
340
+ });
341
+ this.deliver({
342
+ customType: BACKGROUND_RESULT_TYPE,
343
+ content: formatBackgroundResultEnvelope(
344
+ runId,
345
+ role,
346
+ description,
347
+ result.details.state,
348
+ this.#ports.formatRun(result),
349
+ ),
350
+ display: true,
351
+ details: { runId, role, state: result.details.state, description, kind: "result" },
352
+ });
353
+ }
354
+
355
+ // ── Delivery (serialized, pausable; R10/R13) ──────────────────────────
356
+
357
+ private deliver(message: {
358
+ customType: string;
359
+ content: string;
360
+ display: true;
361
+ details: Record<string, unknown>;
362
+ }): void {
363
+ const send = () => {
364
+ this.#deliveryTail = this.#deliveryTail
365
+ .catch(() => undefined)
366
+ .then(() => {
367
+ this.#ports.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
368
+ this.#delivered.add(String(message.details.runId));
369
+ });
370
+ };
371
+ if (this.#paused) this.#pendingFlush.push(send);
372
+ else send();
373
+ }
374
+
375
+ private appendLedger(entry: BackgroundCreatedEntry | BackgroundFinishedEntry): void {
376
+ try {
377
+ this.#ports.appendEntry(BACKGROUND_LEDGER_TYPE, entry);
378
+ } catch {
379
+ // ledger write failure is diagnostic-only; the receipt remains
380
+ // the durable record and reconcile re-derives the state.
381
+ }
382
+ }
383
+
384
+ private wasDelivered(runId: string): boolean {
385
+ return this.#delivered.has(runId) || wasResultDelivered(this.#branchSnapshot, runId);
386
+ }
387
+
388
+ // ── Lifecycle (R12/R13) ───────────────────────────────────────────────
389
+
390
+ /** session_start: new generation, adopt the projected branch. */
391
+ start(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
392
+ this.#generation += 1;
393
+ this.#paused = false;
394
+ for (const run of this.#runs.values()) {
395
+ // Runs from a previous session of this process are stale for
396
+ // direct delivery; reconcile re-adopts those the new branch owns.
397
+ run.generation = -1;
398
+ run.detached = true;
399
+ }
400
+ return this.reconcile(branch);
401
+ }
402
+
403
+ /** session_before_tree: pause delivery (buffered until afterTree). */
404
+ beforeTree(): void {
405
+ this.#paused = true;
406
+ }
407
+
408
+ /** session_tree: re-adopt the new branch, resume delivery. */
409
+ afterTree(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
410
+ this.#paused = false;
411
+ const result = this.reconcile(branch);
412
+ const pending = this.#pendingFlush;
413
+ this.#pendingFlush = [];
414
+ for (const flush of pending) flush();
415
+ return result;
416
+ }
417
+
418
+ /** session_shutdown (R13): cancel every live child; no ledger writes. */
419
+ shutdown(): void {
420
+ this.#generation += 1;
421
+ this.#paused = true;
422
+ for (const run of this.#runs.values()) {
423
+ if (!run.done) run.handle.cancel("cancelled");
424
+ }
425
+ }
426
+
427
+ /**
428
+ * R12: rebuild ownership from the branch, deliver undelivered terminals
429
+ * exactly once, report foreign/live runs without touching them.
430
+ */
431
+ reconcile(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
432
+ this.#branchSnapshot = branch;
433
+ const { records, skipped } = projectBackgroundRuns(branch);
434
+ this.#branchOwned = new Set(records.keys());
435
+ const resent: string[] = [];
436
+ const notes: string[] = [];
437
+ if (skipped > 0) notes.push(`${skipped} malformed delegate.background entr${skipped === 1 ? "y" : "ies"} skipped`);
438
+
439
+ for (const [runId, record] of records) {
440
+ const managed = this.#runs.get(runId);
441
+ if (managed && !managed.done) {
442
+ // Live child of this process: re-adopt for the new branch.
443
+ managed.generation = this.#generation;
444
+ managed.detached = false;
445
+ continue;
446
+ }
447
+ if (record.finished) {
448
+ if (!this.wasDelivered(runId)) {
449
+ const receipt = this.#ports.readReceipt(runId);
450
+ if (receipt) {
451
+ this.deliverResultFromReceipt(runId, record, receipt);
452
+ resent.push(runId);
453
+ } else {
454
+ notes.push(`run ${runId}: finished entry but receipt purged; session JSONL is the record`);
455
+ }
456
+ }
457
+ continue;
458
+ }
459
+ // created, not finished: check the receipt.
460
+ const receipt = this.#ports.readReceipt(runId);
461
+ if (!receipt) {
462
+ notes.push(`run ${runId}: no receipt (purged); nothing to reconcile`);
463
+ continue;
464
+ }
465
+ if (isTerminalRunState(receipt.state)) {
466
+ // Finished while its branch was inactive (or crash between
467
+ // receipt finalization and the ledger write): append the
468
+ // missing finished entry, then deliver once.
469
+ if (!this.wasDelivered(runId)) {
470
+ this.appendLedger({
471
+ v: 1,
472
+ type: "finished",
473
+ runId,
474
+ state: receipt.state,
475
+ finishedAt: receipt.finishedAt ?? new Date().toISOString(),
476
+ });
477
+ this.deliverResultFromReceipt(runId, record, receipt);
478
+ resent.push(runId);
479
+ }
480
+ continue;
481
+ }
482
+ if (typeof receipt.pid === "number" && this.#isPidAlive(receipt.pid)) {
483
+ notes.push(`run ${runId}: nonterminal, owned by another live session (pid ${receipt.pid}) — not touched`);
484
+ continue;
485
+ }
486
+ // Nonterminal, dead pid: children die with the parent process;
487
+ // markOrphanedRuns (startup) finalized the receipt as crashed.
488
+ const refreshed = this.#ports.readReceipt(runId);
489
+ if (refreshed && isTerminalRunState(refreshed.state) && !this.wasDelivered(runId)) {
490
+ this.appendLedger({
491
+ v: 1,
492
+ type: "finished",
493
+ runId,
494
+ state: refreshed.state,
495
+ finishedAt: refreshed.finishedAt ?? new Date().toISOString(),
496
+ });
497
+ this.deliverResultFromReceipt(runId, record, refreshed);
498
+ resent.push(runId);
499
+ }
500
+ }
501
+ return { resent, notes };
502
+ }
503
+
504
+ private deliverResultFromReceipt(
505
+ runId: string,
506
+ record: BackgroundRunRecord,
507
+ receipt: RunMetadataV1,
508
+ ): void {
509
+ const role = record.created.role;
510
+ const description = record.created.description;
511
+ const result = receiptToRunResult(receipt);
512
+ this.deliver({
513
+ customType: BACKGROUND_RESULT_TYPE,
514
+ content: formatBackgroundResultEnvelope(
515
+ runId,
516
+ role,
517
+ description,
518
+ result.details.state,
519
+ this.#ports.formatRun(result),
520
+ ),
521
+ display: true,
522
+ details: { runId, role, state: result.details.state, description, kind: "result" },
523
+ });
524
+ }
525
+
526
+ // ── R17/R18: ask channel ─────────────────────────────────────────────
527
+
528
+ /** Fired by the runner hook for every ask_parent start/end (M4). */
529
+ onAsk(ask: {
530
+ runId: string;
531
+ phase: "start" | "end";
532
+ kind: "question" | "note";
533
+ topic: string;
534
+ text: string;
535
+ toolCallId: string;
536
+ }): void {
537
+ const run = this.#runs.get(ask.runId);
538
+ if (!run) return;
539
+ if (run.generation !== this.#generation) return; // stale session: no delivery
540
+ if (ask.phase === "end") {
541
+ const pending = this.#pendingAsks.get(ask.runId);
542
+ if (pending?.toolCallId === ask.toolCallId) this.#pendingAsks.delete(ask.runId);
543
+ return;
544
+ }
545
+ if (ask.kind === "note") {
546
+ this.deliverNote(run, ask);
547
+ return;
548
+ }
549
+ // question: wake the parent (a blocked child is material); register pending.
550
+ const superseded = this.#pendingAsks.get(ask.runId);
551
+ if (superseded) this.#pendingAsks.delete(ask.runId);
552
+ this.#pendingAsks.set(ask.runId, { toolCallId: ask.toolCallId, topic: ask.topic, askedAt: new Date().toISOString() });
553
+ this.enqueueAskMessage({
554
+ customType: CHILD_QUESTION_TYPE,
555
+ content: formatChildQuestionEnvelope(ask.runId, run.handle.role, run.handle.description, ask.topic, ask.text),
556
+ display: true,
557
+ details: { runId: ask.runId, toolCallId: ask.toolCallId, role: run.handle.role, description: run.handle.description, topic: ask.topic, kind: "question" },
558
+ triggerTurn: true,
559
+ });
560
+ }
561
+
562
+ private deliverNote(run: ManagedRun, ask: { topic: string; text: string; toolCallId: string }): void {
563
+ this.enqueueAskMessage({
564
+ customType: CHILD_NOTE_TYPE,
565
+ content: formatChildNoteEnvelope(run.handle.runId, run.handle.role, run.handle.description, ask.topic, ask.text),
566
+ display: true,
567
+ details: { runId: run.handle.runId, role: run.handle.role, description: run.handle.description, topic: ask.topic, kind: "note" },
568
+ triggerTurn: false,
569
+ });
570
+ }
571
+
572
+ /** Notes and questions share the serialized tail; notes never wake. */
573
+ private enqueueAskMessage(message: {
574
+ customType: string;
575
+ content: string;
576
+ display: true;
577
+ details: Record<string, unknown>;
578
+ triggerTurn: boolean;
579
+ }): void {
580
+ const send = () => {
581
+ this.#deliveryTail = this.#deliveryTail.catch(() => undefined).then(() => {
582
+ this.#ports.sendMessage(message, { deliverAs: "steer", triggerTurn: message.triggerTurn });
583
+ });
584
+ };
585
+ if (this.#paused) this.#pendingFlush.push(send);
586
+ else send();
587
+ }
588
+
589
+ /** R17: route a delegate_answer call to the blocked child. */
590
+ answer(runId: string, answerText: string, answeredBy: "model" | "user"): { ok: true } | { ok: false; error: string } {
591
+ const run = this.#runs.get(runId);
592
+ if (!run) {
593
+ return { ok: false, error: `unknown or expired background run ${runId}.` };
594
+ }
595
+ const pending = this.#pendingAsks.get(runId);
596
+ if (!pending) {
597
+ return { ok: false, error: `background run ${runId} has no pending question (it may have timed out or already been answered).` };
598
+ }
599
+ if (!run.handle.writeAnswer) {
600
+ return { ok: false, error: `background run ${runId} does not support answering.` };
601
+ }
602
+ try {
603
+ run.handle.writeAnswer(pending.toolCallId, { answeredBy, answeredAt: new Date().toISOString(), answer: answerText });
604
+ this.#pendingAsks.delete(runId);
605
+ return { ok: true };
606
+ } catch (error) {
607
+ return { ok: false, error: `could not deliver the answer: ${(error as Error).message}` };
608
+ }
609
+ }
610
+
611
+ /** R14/R19: pending questions for status surfaces. */
612
+ pendingQuestions(): Array<{ runId: string; topic: string; askedAt: string }> {
613
+ return [...this.#pendingAsks.entries()].map(([runId, p]) => ({ runId, topic: p.topic, askedAt: p.askedAt }));
614
+ }
615
+
616
+ // ── Introspection (status surface, R14 lands in M2) ───────────────────
617
+
618
+ liveRuns(): Array<{ runId: string; role: RoleName; description: string; detached: boolean }> {
619
+ return [...this.#runs.values()]
620
+ .filter((r) => !r.done)
621
+ .map((r) => ({ runId: r.handle.runId, role: r.handle.role, description: r.handle.description, detached: r.detached }));
622
+ }
623
+
624
+ /** Cancel one background run (user path). */
625
+ cancel(runId: string): boolean {
626
+ const run = this.#runs.get(runId);
627
+ if (!run || run.done) return false;
628
+ run.handle.cancel("cancelled");
629
+ return true;
630
+ }
631
+
632
+ /** R16: steer one live background run (RPC follow_up). */
633
+ send(runId: string, message: string): { ok: true } | { ok: false; error: string } {
634
+ const run = this.#runs.get(runId);
635
+ if (!run) {
636
+ return {
637
+ ok: false,
638
+ error: `unknown or expired background run ${runId}. It is not a live background run of this session (foreground runs cannot be steered — the parent turn is blocked on them; finished runs continue via delegate({ resumeFrom: … })).`,
639
+ };
640
+ }
641
+ if (run.done) {
642
+ return { ok: false, error: `background run ${runId} already finished; continue it with delegate({ resumeFrom: "${runId}", … }) instead.` };
643
+ }
644
+ if (!run.handle.steer) {
645
+ return { ok: false, error: `background run ${runId} does not support steering.` };
646
+ }
647
+ return run.handle.steer(message);
648
+ }
649
+ }
650
+
651
+ // ── R14: status text builders (pure; the adapter feeds data in) ────────
652
+
653
+ export interface BackgroundLiveView {
654
+ runId: string;
655
+ role: RoleName;
656
+ description: string;
657
+ phase?: string;
658
+ elapsedMs?: number;
659
+ openTools?: string[];
660
+ model?: string;
661
+ detached?: boolean;
662
+ }
663
+
664
+ export interface BackgroundRecentView {
665
+ runId: string;
666
+ role: RoleName;
667
+ description?: string;
668
+ state: RunTerminalState;
669
+ durationMs?: number;
670
+ }
671
+
672
+ export function formatBackgroundInventoryText(data: {
673
+ limit: number;
674
+ live: BackgroundLiveView[];
675
+ queue: number;
676
+ recent: BackgroundRecentView[];
677
+ }): string {
678
+ const lines: string[] = [];
679
+ const live = data.live;
680
+ lines.push(`background: ${live.length}/${data.limit} slots active${data.queue > 0 ? ` · queue ${data.queue}` : ""}`);
681
+ for (const r of live) {
682
+ const bits = [r.runId, r.role, r.description];
683
+ if (r.phase) bits.push(r.phase);
684
+ if (r.elapsedMs !== undefined) bits.push(`${Math.round(r.elapsedMs / 1000)}s`);
685
+ if (r.openTools?.length) bits.push(`⏳ ${r.openTools.slice(0, 2).join(",")}`);
686
+ if (r.detached) bits.push("(branch inactive)");
687
+ lines.push(` · ${bits.join(" · ")}`);
688
+ }
689
+ if (live.length === 0) lines.push(" · none");
690
+ for (const r of data.recent.slice(0, 3)) {
691
+ lines.push(` last: ${r.runId} ${r.role} ${backgroundStateWord(r.state)}${r.durationMs != null ? ` in ${Math.round(r.durationMs / 1000)}s` : ""}`);
692
+ }
693
+ return lines.join("\n");
694
+ }
695
+
696
+ export interface BackgroundDetailView {
697
+ runId: string;
698
+ role: RoleName;
699
+ description?: string;
700
+ state: RunState | RunTerminalState;
701
+ model?: string;
702
+ startedAt?: string;
703
+ finishedAt?: string;
704
+ durationMs?: number;
705
+ live?: { phase: string; elapsedMs: number; openTools?: string[] };
706
+ activityTail: string[];
707
+ handoffPreview?: string;
708
+ sessionPath?: string;
709
+ background: boolean;
710
+ }
711
+
712
+ export function formatBackgroundDetailText(d: BackgroundDetailView): string {
713
+ const lines = [`[delegate background ${d.runId}]`];
714
+ const state = isTerminalRunState(d.state as RunTerminalState)
715
+ ? backgroundStateWord(d.state as RunTerminalState)
716
+ : String(d.state);
717
+ lines.push(`state: ${state} · role: ${d.role}${d.description ? ` · ${d.description}` : ""}`);
718
+ if (d.model) lines.push(`model: ${d.model}`);
719
+ if (d.live) {
720
+ lines.push(`live: ${d.live.phase} · ${Math.round(d.live.elapsedMs / 1000)}s elapsed${d.live.openTools?.length ? ` · in flight: ${d.live.openTools.join(", ")}` : ""}`);
721
+ } else if (d.durationMs != null) {
722
+ lines.push(`duration: ${Math.round(d.durationMs / 1000)}s${d.finishedAt ? ` · finished ${d.finishedAt}` : ""}`);
723
+ }
724
+ if (d.activityTail.length > 0) {
725
+ lines.push("", "recent activity:");
726
+ for (const a of d.activityTail) lines.push(` ${a}`);
727
+ }
728
+ if (d.handoffPreview) {
729
+ lines.push("", "handoff (first lines):");
730
+ for (const h of d.handoffPreview.split("\n").slice(0, 12)) lines.push(` ${h}`);
731
+ }
732
+ if (isTerminalRunState(d.state as RunTerminalState) && d.state !== "succeeded" && d.sessionPath) {
733
+ lines.push("", `resume: delegate({ resumeFrom: "${d.runId}" }) continues this run's child session.`);
734
+ }
735
+ return lines.join("\n");
736
+ }
737
+
738
+ /** R15: display text for a delivered background result message: neutral
739
+ * glyph header + report body, with the model-only classification paragraph
740
+ * stripped (never shown to the user). */
741
+ export function backgroundResultDisplay(content: string, details: { runId?: string; state?: string; description?: string }): string {
742
+ const parts = content.split("\n\n");
743
+ const body = parts.length > 2 ? parts.slice(2).join("\n\n") : content;
744
+ const state = (details.state ?? "?") as RunTerminalState;
745
+ const word = backgroundStateWord(state);
746
+ const glyph = state === "succeeded" ? "✓" : state === "cancelled" ? "⊘" : state.startsWith("timed_out") ? "⏱" : "⚠";
747
+ const runId = details.runId ?? "?";
748
+ const desc = details.description ? ` · ${details.description}` : "";
749
+ const bodyLines = body.split("\n");
750
+ const head = bodyLines[0] ?? "";
751
+ const shown = [head.split("\n")[0], ...bodyLines.slice(1)].join("\n").split("\n").slice(0, 14).join("\n");
752
+ return `${glyph} background ${runId}${desc}: ${word}\n\n${shown}`;
753
+ }
754
+
755
+ /** Default receipt reader bound to an agentDir (used by the adapter). */
756
+ export function makeReceiptReader(agentDir: string): (runId: string) => RunMetadataV1 | null {
757
+ return (runId) => {
758
+ try {
759
+ return readRunMetadata(agentDir, runId);
760
+ } catch {
761
+ return null;
762
+ }
763
+ };
764
+ }