@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/README.md +63 -0
- package/application.ts +203 -69
- package/ask.ts +183 -0
- package/background.ts +764 -0
- package/commands.ts +12 -1
- package/config.ts +29 -0
- package/index.ts +503 -28
- package/mode.ts +2 -2
- package/package.json +72 -70
- package/run-store.ts +7 -0
- package/runner.ts +97 -4
- package/types.ts +59 -1
- package/ui/format.ts +36 -8
- package/ui/panel-frame.ts +126 -0
- package/ui/peek-view.ts +34 -5
- package/ui/running-view.ts +55 -10
- package/ui/tool-card.ts +129 -0
- package/ui/version.ts +69 -0
- package/version.ts +9 -13
package/index.ts
CHANGED
|
@@ -25,9 +25,10 @@ import { formatDuration, loadConfig, parseDuration, saveConfig } from "./config.
|
|
|
25
25
|
import * as fsSync from "node:fs";
|
|
26
26
|
import { delegateVersion } from "./version.ts";
|
|
27
27
|
import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
|
|
28
|
+
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool } from "./ask.ts";
|
|
28
29
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
29
30
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
30
|
-
import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
31
|
+
import { STRICT_OVERLAY, STRICT_ACTIVE_TOOLS, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
31
32
|
import { DelegateApplicationImpl } from "./application.ts";
|
|
32
33
|
import { DELEGATE_MODE_CUSTOM_TYPE } from "./types.ts";
|
|
33
34
|
import type {
|
|
@@ -40,9 +41,22 @@ import type {
|
|
|
40
41
|
} from "./types.ts";
|
|
41
42
|
import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "./ui/settings-panel.ts";
|
|
42
43
|
import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectValueCell } from "./ui/format.ts";
|
|
44
|
+
import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "./ui/tool-card.ts";
|
|
43
45
|
import { RunningView, type RunningViewState } from "./ui/running-view.ts";
|
|
44
46
|
import { PeekView } from "./ui/peek-view.ts";
|
|
45
47
|
import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
|
|
48
|
+
import {
|
|
49
|
+
BackgroundManager,
|
|
50
|
+
BACKGROUND_RESULT_TYPE,
|
|
51
|
+
backgroundResultDisplay,
|
|
52
|
+
formatBackgroundDetailText,
|
|
53
|
+
formatBackgroundInventoryText,
|
|
54
|
+
formatBackgroundStartedText,
|
|
55
|
+
makeReceiptReader,
|
|
56
|
+
validateBackgroundDescription,
|
|
57
|
+
type BackgroundDetailView,
|
|
58
|
+
type BackgroundLiveView,
|
|
59
|
+
} from "./background.ts";
|
|
46
60
|
|
|
47
61
|
/** Stable command-driven handoff custom message type (§6.4). */
|
|
48
62
|
const HANDOFF_CUSTOM_TYPE = "delegate-handoff";
|
|
@@ -173,6 +187,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
173
187
|
// it registers ONLY the mandatory structured-handoff tool.
|
|
174
188
|
if (process.env.PI_DELEGATE_CHILD === "1") {
|
|
175
189
|
registerChildHandoffTool(pi);
|
|
190
|
+
// R17/R18: background children get the ask_parent channel (a
|
|
191
|
+
// foreground child asking would deadlock the parent turn by
|
|
192
|
+
// construction — enforced here at registration, not by prompt).
|
|
193
|
+
const askDir = process.env.PI_DELEGATE_ASK_DIR;
|
|
194
|
+
if (askDir) {
|
|
195
|
+
registerAskParentTool(pi, {
|
|
196
|
+
askDir,
|
|
197
|
+
timeoutMs: Number(process.env.PI_DELEGATE_ASK_TIMEOUT_MS) > 0 ? Number(process.env.PI_DELEGATE_ASK_TIMEOUT_MS) : 600_000,
|
|
198
|
+
maxQuestions: Number(process.env.PI_DELEGATE_ASK_MAX) > 0 ? Number(process.env.PI_DELEGATE_ASK_MAX) : 5,
|
|
199
|
+
});
|
|
200
|
+
}
|
|
176
201
|
return;
|
|
177
202
|
}
|
|
178
203
|
// 2. Construct state — no child, no timers at load time.
|
|
@@ -183,6 +208,39 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
183
208
|
// Startup orphan recovery (§10.6): receipts only; never kills PIDs.
|
|
184
209
|
app.markOrphansOnStartup();
|
|
185
210
|
|
|
211
|
+
// R15: footer state — composes strict-mode + live background count.
|
|
212
|
+
let liveBgCount = 0;
|
|
213
|
+
let footerUi: { setStatus(key: string, text?: string): void } | null = null;
|
|
214
|
+
const refreshFooter = () => {
|
|
215
|
+
const parts: string[] = [];
|
|
216
|
+
if (app.isStrict()) parts.push("delegate: strict");
|
|
217
|
+
if (liveBgCount > 0) parts.push(`▴${liveBgCount}bg`);
|
|
218
|
+
try {
|
|
219
|
+
footerUi?.setStatus("delegate", parts.length ? parts.join(" · ") : undefined);
|
|
220
|
+
} catch {
|
|
221
|
+
// headless: no footer
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
// R8–R13: background run manager. Delivery + ledger writes are ports so
|
|
226
|
+
// the manager stays Pi-free and unit-testable; formatRunText is captured
|
|
227
|
+
// by closure (defined below, called only at terminal delivery).
|
|
228
|
+
const background = new BackgroundManager({
|
|
229
|
+
sendMessage: (message, options) => {
|
|
230
|
+
pi.sendMessage(message, options);
|
|
231
|
+
},
|
|
232
|
+
appendEntry: (customType, data) => {
|
|
233
|
+
pi.appendEntry(customType, data);
|
|
234
|
+
},
|
|
235
|
+
maxBackgroundRuns: () => app.backgroundLimit(),
|
|
236
|
+
formatRun: (res) => formatRunText(res),
|
|
237
|
+
readReceipt: makeReceiptReader(agentDir),
|
|
238
|
+
onInventoryChange: (count) => {
|
|
239
|
+
liveBgCount = count;
|
|
240
|
+
refreshFooter();
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
|
|
186
244
|
const say = (ctx: { hasUI: boolean; ui: { notify(message: string, level?: "info" | "warning" | "error"): void } }, text: string, level: "info" | "warning" | "error" = "info") => {
|
|
187
245
|
// Essential output uses stdout (§6.1); notify is supplemental only.
|
|
188
246
|
// In headless RPC, console.log is captured by the host — surface the
|
|
@@ -227,7 +285,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
227
285
|
source: "tool" | "command",
|
|
228
286
|
ctx: ExtensionContext,
|
|
229
287
|
timeoutMs?: number,
|
|
230
|
-
extras?: { model?: string; resumeFrom?: string },
|
|
288
|
+
extras?: { model?: string; resumeFrom?: string; background?: boolean; description?: string },
|
|
231
289
|
): DelegateRequest => ({
|
|
232
290
|
task,
|
|
233
291
|
role,
|
|
@@ -240,6 +298,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
240
298
|
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
241
299
|
...(extras?.model ? { model: extras.model } : {}),
|
|
242
300
|
...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
|
|
301
|
+
...(extras?.background ? { background: true } : {}),
|
|
302
|
+
...(extras?.description ? { description: extras.description } : {}),
|
|
243
303
|
});
|
|
244
304
|
|
|
245
305
|
const refreshDoctor = (ctx: ExtensionContext) => {
|
|
@@ -366,6 +426,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
366
426
|
"(earlier turns included) with your task as the continuation prompt — no cold re-explanation. " +
|
|
367
427
|
"Works for runs whose receipt records a sessionPath (post-0.2.0) and whose session file still exists.",
|
|
368
428
|
})),
|
|
429
|
+
background: Type.Optional(Type.Boolean({
|
|
430
|
+
description:
|
|
431
|
+
"Run this delegation in the background: the call returns a runId immediately and the terminal report " +
|
|
432
|
+
"arrives later as a message. Use it for long builds, test matrices, or research that should not block " +
|
|
433
|
+
"this turn. Requires 'description'. Poll with the delegate_status pattern or wait for the report message.",
|
|
434
|
+
})),
|
|
435
|
+
description: Type.Optional(Type.String({
|
|
436
|
+
description:
|
|
437
|
+
"Required with background=true: a 3-to-6-word purpose summary for the user, e.g. 'Run full test matrix'. " +
|
|
438
|
+
"Describes the work, not the mechanism. Single line.",
|
|
439
|
+
})),
|
|
369
440
|
});
|
|
370
441
|
|
|
371
442
|
pi.registerTool({
|
|
@@ -381,6 +452,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
381
452
|
"Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
|
|
382
453
|
"Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
|
|
383
454
|
"Parallel delegate calls are fine: they queue and run back-to-back (one child at a time) — every call gets a real result; do not re-issue on 'queue full', wait for the in-flight results instead.",
|
|
455
|
+
"Use background=true (with a 3–6-word description) for long builds, test matrices, or research that should not block this turn: the call returns a runId immediately and the terminal report arrives later as a message. Check progress with delegate_status; do not wait inline.",
|
|
456
|
+
"Treat background terminal reports as internal work events: acknowledge them to the user with at most one line; do not re-narrate the handoff unless material.",
|
|
457
|
+
"On E_BACKGROUND_FULL, do not re-issue the task: check delegate_status and wait for terminal reports to free slots.",
|
|
458
|
+
"Steer live background runs with delegate_send (course corrections apply at the child's next model call); reserve resumeFrom for finished runs.",
|
|
384
459
|
"A timed-out run leaves a partialHandoff, a git checkpoint and a resumable child session: pass resumeFrom: <runId> to continue in the same context instead of re-explaining, and inspect the receipt's gitDelta before repairing anything.",
|
|
385
460
|
"Pin model: 'provider/model-id' when the child must not silently follow the parent's current model (e.g. after a mid-session model fallback).",
|
|
386
461
|
"For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
|
|
@@ -396,14 +471,64 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
396
471
|
} catch (error) {
|
|
397
472
|
return {
|
|
398
473
|
content: [{ type: "text" as const, text: (error as Error).message }],
|
|
474
|
+
details: {} satisfies Record<string, unknown>,
|
|
475
|
+
isError: true,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const modelExtra = typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined;
|
|
480
|
+
const resumeExtra = typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined;
|
|
481
|
+
|
|
482
|
+
// R8: background path — validate, slot-check, spawn, return runId.
|
|
483
|
+
if (params.background === true) {
|
|
484
|
+
const desc = validateBackgroundDescription(params.description);
|
|
485
|
+
if (!desc.ok) {
|
|
486
|
+
return {
|
|
487
|
+
content: [{ type: "text" as const, text: `description invalid: ${desc.error}` }],
|
|
399
488
|
details: {} satisfies Record<string, unknown>,
|
|
400
489
|
isError: true,
|
|
401
490
|
};
|
|
402
491
|
}
|
|
492
|
+
const slot = background.slotError();
|
|
493
|
+
if (slot) {
|
|
494
|
+
return {
|
|
495
|
+
content: [{ type: "text" as const, text: `${slot.code}: ${slot.message}` }],
|
|
496
|
+
details: { background: true, busy: true } satisfies Record<string, unknown>,
|
|
497
|
+
isError: true,
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
|
|
501
|
+
model: modelExtra,
|
|
502
|
+
resumeFrom: resumeExtra,
|
|
503
|
+
background: true,
|
|
504
|
+
description: desc.value,
|
|
505
|
+
});
|
|
506
|
+
refreshDoctor(ctx);
|
|
507
|
+
const attempt = app.runBackground(request, {
|
|
508
|
+
onAsk: (ask) => background.onAsk(ask),
|
|
509
|
+
});
|
|
510
|
+
if ("error" in attempt) {
|
|
511
|
+
return {
|
|
512
|
+
content: [{ type: "text" as const, text: formatRunText(attempt.error) }],
|
|
513
|
+
details: attempt.error.details satisfies DelegateDetails,
|
|
514
|
+
isError: true,
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
background.register(attempt.handle);
|
|
518
|
+
return {
|
|
519
|
+
content: [{ type: "text" as const, text: formatBackgroundStartedText(attempt.handle.runId, attempt.handle.role, attempt.handle.description) }],
|
|
520
|
+
details: {
|
|
521
|
+
runId: attempt.handle.runId,
|
|
522
|
+
role: attempt.handle.role,
|
|
523
|
+
background: true,
|
|
524
|
+
description: attempt.handle.description,
|
|
525
|
+
} satisfies Record<string, unknown>,
|
|
526
|
+
};
|
|
403
527
|
}
|
|
528
|
+
|
|
404
529
|
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
|
|
405
|
-
model:
|
|
406
|
-
resumeFrom:
|
|
530
|
+
model: modelExtra,
|
|
531
|
+
resumeFrom: resumeExtra,
|
|
407
532
|
});
|
|
408
533
|
refreshDoctor(ctx);
|
|
409
534
|
const hooks = {
|
|
@@ -438,45 +563,280 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
438
563
|
const role = typeof args.role === "string" ? args.role : config.defaultRole;
|
|
439
564
|
const task = typeof args.task === "string" ? args.task : "";
|
|
440
565
|
const modelBit = typeof args.model === "string" && args.model ? ` · ${shortModel(args.model)}` : "";
|
|
441
|
-
|
|
442
|
-
|
|
566
|
+
return renderToolCallCard(theme, {
|
|
567
|
+
title: "delegate",
|
|
568
|
+
subject: role,
|
|
569
|
+
qualifier: `${modelBit}: ${task.length > 64 ? `${task.slice(0, 61)}…` : task}`,
|
|
570
|
+
});
|
|
443
571
|
},
|
|
444
572
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
445
573
|
renderResult(result: any, options: any, theme: any) {
|
|
446
574
|
const d = result.details as DelegateDetails | undefined;
|
|
447
575
|
if (!d?.runId) {
|
|
448
576
|
const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
|
|
449
|
-
return
|
|
577
|
+
return renderToolPlainCard(text);
|
|
450
578
|
}
|
|
451
|
-
const fg = (kind: string, s: string) => (theme?.fg ? theme.fg(kind, s) : s);
|
|
452
579
|
const u = d.usage ?? ({} as DelegateDetails["usage"]);
|
|
453
580
|
// Neutral, non-color-alone state word (cancelled ≠ failed ≠ timeout).
|
|
454
|
-
const
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
581
|
+
const bits = [
|
|
582
|
+
`${Math.round(d.durationMs / 1000)}s`,
|
|
583
|
+
...(d.model ? [shortModel(d.model)] : []),
|
|
584
|
+
`↑${formatTokens(u.input)} ↓${formatTokens(u.output)}`,
|
|
585
|
+
...(u.cost ? [formatCost(u.cost)] : []),
|
|
586
|
+
];
|
|
459
587
|
const header = `→ ${d.runId.slice(-16)}`;
|
|
460
|
-
const color = g.color;
|
|
461
588
|
if (!options?.expanded) {
|
|
462
|
-
const lines = [fg("accent", header), fg(color, bits.join(" "))];
|
|
463
589
|
// Inline tail ≤5 — partial handoff (timeout/cancel) or reason, never bare.
|
|
464
590
|
const tailSrc: string = d.partialHandoff ?? (d.state === "succeeded" ? "" : (result.content ?? []).map((c: { text?: string }) => c.text ?? "").join(" ").split("\n")[0] ?? "");
|
|
465
591
|
const tail = tailSrc ? tailSrc.split("\n").map((l: string) => l.trim()).filter(Boolean).slice(0, 5) : [];
|
|
466
|
-
|
|
467
|
-
if (d.outputTruncated && d.transcriptPath)
|
|
468
|
-
return
|
|
592
|
+
const detailLines: ToolCardLine[] = tail.map((t) => ({ text: ` ${t}` }));
|
|
593
|
+
if (d.outputTruncated && d.transcriptPath) detailLines.push({ text: ` transcript: ${d.transcriptPath}` });
|
|
594
|
+
return renderToolResultCard(theme, { header, lead: d.role, state: d.state, stateBits: bits, detailLines });
|
|
469
595
|
}
|
|
470
596
|
// Expanded: identity + canonical summary + resume hint.
|
|
471
597
|
const summary = formatRunSummary(result as unknown as DelegateRunResult);
|
|
472
|
-
const
|
|
473
|
-
if (
|
|
474
|
-
if (d.
|
|
475
|
-
|
|
476
|
-
|
|
598
|
+
const detailLines: ToolCardLine[] = [];
|
|
599
|
+
if (d.sessionPath && d.state !== "succeeded") detailLines.push({ text: ` resume: resumeFrom ${d.runId}` });
|
|
600
|
+
if (d.transcriptPath) detailLines.push({ text: ` transcript: ${d.transcriptPath}` });
|
|
601
|
+
return renderToolResultCard(theme, {
|
|
602
|
+
header,
|
|
603
|
+
lead: d.role,
|
|
604
|
+
state: d.state,
|
|
605
|
+
stateBits: bits,
|
|
606
|
+
plainLines: summary ? summary.split("\n") : undefined,
|
|
607
|
+
detailLines,
|
|
608
|
+
});
|
|
477
609
|
},
|
|
478
610
|
});
|
|
479
611
|
|
|
612
|
+
// ── R14: delegate_status tool (background inventory / run detail) ─────
|
|
613
|
+
|
|
614
|
+
const backgroundLiveViews = (): BackgroundLiveView[] =>
|
|
615
|
+
background.liveRuns().map((r) => {
|
|
616
|
+
const stream = app.getBackgroundStream(r.runId);
|
|
617
|
+
return {
|
|
618
|
+
runId: r.runId,
|
|
619
|
+
role: r.role,
|
|
620
|
+
description: r.description,
|
|
621
|
+
detached: r.detached,
|
|
622
|
+
...(stream?.update ? { phase: stream.update.phase, elapsedMs: stream.update.elapsedMs, ...(stream.update.openTools?.length ? { openTools: stream.update.openTools } : {}), ...(stream.update.model ? { model: stream.update.model } : {}) } : {}),
|
|
623
|
+
};
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
const backgroundStatusText = (): string =>
|
|
627
|
+
formatBackgroundInventoryText({
|
|
628
|
+
limit: app.backgroundLimit(),
|
|
629
|
+
live: backgroundLiveViews(),
|
|
630
|
+
queue: app.queuedRunCount(),
|
|
631
|
+
recent: app.backgroundRecentRuns(3),
|
|
632
|
+
});
|
|
633
|
+
|
|
634
|
+
const backgroundDetailText = (runId: string, limit?: number): string => {
|
|
635
|
+
const receipt = (() => {
|
|
636
|
+
try {
|
|
637
|
+
return app.inspect(runId, false).metadata;
|
|
638
|
+
} catch {
|
|
639
|
+
return null;
|
|
640
|
+
}
|
|
641
|
+
})();
|
|
642
|
+
const stream = app.getBackgroundStream(runId);
|
|
643
|
+
if (!receipt && !stream) return `[delegate background] unknown run ${runId}`;
|
|
644
|
+
const maxEvents = limit ?? 8;
|
|
645
|
+
let activityTail: string[] = [];
|
|
646
|
+
if (stream && stream.events.length > 0) {
|
|
647
|
+
activityTail = renderFeedEvents([...stream.events], { startMs: Date.now() - (stream.update?.elapsedMs ?? 0), maxChars: 140, maxEvents }).slice(-maxEvents);
|
|
648
|
+
} else if (receipt?.transcriptPath) {
|
|
649
|
+
try {
|
|
650
|
+
const { startMs, events } = feedEventsFromTranscript(receipt.transcriptPath);
|
|
651
|
+
activityTail = renderFeedEvents(events, { startMs, maxChars: 140, maxEvents }).slice(-maxEvents);
|
|
652
|
+
} catch {
|
|
653
|
+
// transcript read is best-effort
|
|
654
|
+
}
|
|
655
|
+
}
|
|
656
|
+
const live = stream?.update ? { phase: stream.update.phase, elapsedMs: stream.update.elapsedMs, ...(stream.update.openTools?.length ? { openTools: stream.update.openTools } : {}) } : undefined;
|
|
657
|
+
return formatBackgroundDetailText({
|
|
658
|
+
runId,
|
|
659
|
+
role: (receipt?.role ?? background.liveRuns().find((r) => r.runId === runId)?.role ?? "general") as "general" | "research",
|
|
660
|
+
...(receipt?.description ? { description: receipt.description } : {}),
|
|
661
|
+
state: (receipt?.state ?? "running") as never,
|
|
662
|
+
...(receipt?.model ? { model: receipt.model } : {}),
|
|
663
|
+
...(receipt?.startedAt ? { startedAt: receipt.startedAt } : {}),
|
|
664
|
+
...(receipt?.finishedAt ? { finishedAt: receipt.finishedAt } : {}),
|
|
665
|
+
...(receipt?.startedAt && receipt?.finishedAt ? { durationMs: Date.parse(receipt.finishedAt) - Date.parse(receipt.startedAt) } : {}),
|
|
666
|
+
...(live ? { live } : {}),
|
|
667
|
+
activityTail,
|
|
668
|
+
...(receipt?.finalHandoff ? { handoffPreview: receipt.finalHandoff } : receipt?.partialHandoff ? { handoffPreview: receipt.partialHandoff } : {}),
|
|
669
|
+
...(receipt?.sessionPath ? { sessionPath: receipt.sessionPath } : {}),
|
|
670
|
+
background: true,
|
|
671
|
+
});
|
|
672
|
+
};
|
|
673
|
+
|
|
674
|
+
const DelegateStatusParams = Type.Object({
|
|
675
|
+
runId: Type.Optional(Type.String({ description: "Optional runId returned by a background delegate call. Omit to list all background runs." })),
|
|
676
|
+
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 50, description: "Optional cap for recent-activity lines (default 8)." })),
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
pi.registerTool({
|
|
680
|
+
name: "delegate_status",
|
|
681
|
+
label: "Background run status",
|
|
682
|
+
description:
|
|
683
|
+
"Check asynchronous (background) delegate runs. Without runId: slot usage, every live background run (state, elapsed, in-flight tool), and the recent terminal runs. " +
|
|
684
|
+
"With runId: one run's detail — live activity tail or post-mortem feed, handoff preview, and the resumeFrom hint for interrupted runs. " +
|
|
685
|
+
"Background runs deliver their terminal report as a message automatically; this tool is for checking progress, not for waiting.",
|
|
686
|
+
promptSnippet: "Check background delegate runs (inventory or one run's detail)",
|
|
687
|
+
promptGuidelines: [
|
|
688
|
+
"Poll delegate_status sparingly — background terminal reports arrive as messages on their own; do not busy-poll.",
|
|
689
|
+
],
|
|
690
|
+
parameters: DelegateStatusParams,
|
|
691
|
+
async execute(_toolCallId, params) {
|
|
692
|
+
const runId = typeof params.runId === "string" ? params.runId.trim() : "";
|
|
693
|
+
const text = runId
|
|
694
|
+
? backgroundDetailText(runId, typeof params.limit === "number" ? params.limit : undefined)
|
|
695
|
+
: backgroundStatusText();
|
|
696
|
+
return { content: [{ type: "text" as const, text }], details: { runId: runId || undefined } satisfies Record<string, unknown> };
|
|
697
|
+
},
|
|
698
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
699
|
+
renderCall(args: any, theme: any) {
|
|
700
|
+
const runId = typeof args.runId === "string" && args.runId ? args.runId.slice(-12) : "all";
|
|
701
|
+
return renderToolCallCard(theme, { title: "delegate_status", subject: "background", qualifier: runId });
|
|
702
|
+
},
|
|
703
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
704
|
+
renderResult(result: any, theme: any) {
|
|
705
|
+
const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
|
|
706
|
+
const first = text.split("\n").slice(0, 6).join("\n");
|
|
707
|
+
return renderToolPlainCard(first || text);
|
|
708
|
+
},
|
|
709
|
+
});
|
|
710
|
+
|
|
711
|
+
// ── R16: delegate_send tool (parent → child steering) ──────────────────
|
|
712
|
+
|
|
713
|
+
pi.registerTool({
|
|
714
|
+
name: "delegate_send",
|
|
715
|
+
label: "Steer background run",
|
|
716
|
+
description:
|
|
717
|
+
"Send a steering message to a LIVE background delegate run. The message is queued before the child's next model call (pi steering semantics — it never interrupts in-flight work). " +
|
|
718
|
+
"Use it for course corrections and additional instructions on a running background task. " +
|
|
719
|
+
"Foreground runs cannot be steered; finished runs must be continued with delegate({ resumeFrom: … }).",
|
|
720
|
+
promptSnippet: "Steer a live background delegate run",
|
|
721
|
+
promptGuidelines: [
|
|
722
|
+
"Prefer delegate_send for course corrections on live background runs; use resumeFrom only after a run finished.",
|
|
723
|
+
],
|
|
724
|
+
parameters: Type.Object({
|
|
725
|
+
runId: Type.String({ description: "The runId returned by the background delegate call." }),
|
|
726
|
+
message: Type.String({ minLength: 1, description: "The instruction for the child. Be specific and self-contained — it is applied to the child's ongoing task context." }),
|
|
727
|
+
}),
|
|
728
|
+
async execute(_toolCallId, params) {
|
|
729
|
+
const runId = typeof params.runId === "string" ? params.runId.trim() : "";
|
|
730
|
+
const message = typeof params.message === "string" ? params.message : "";
|
|
731
|
+
if (!runId || !message) {
|
|
732
|
+
return {
|
|
733
|
+
content: [{ type: "text" as const, text: "delegate_send requires runId and message." }],
|
|
734
|
+
details: {} as Record<string, unknown>,
|
|
735
|
+
isError: true,
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
const result = background.send(runId, message);
|
|
739
|
+
if (!result.ok) {
|
|
740
|
+
return {
|
|
741
|
+
content: [{ type: "text" as const, text: `E_STEER_FAILED: ${result.error}` }],
|
|
742
|
+
details: { runId } as Record<string, unknown>,
|
|
743
|
+
isError: true,
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
return {
|
|
747
|
+
content: [{ type: "text" as const, text: `Steering accepted for background run ${runId}. The child applies it at its next model call; watch for the terminal report or check delegate_status.` }],
|
|
748
|
+
details: { runId, steered: true } as Record<string, unknown>,
|
|
749
|
+
};
|
|
750
|
+
},
|
|
751
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
752
|
+
renderCall(args: any, theme: any) {
|
|
753
|
+
const runId = typeof args.runId === "string" ? args.runId.slice(-12) : "?";
|
|
754
|
+
return renderToolCallCard(theme, { title: "delegate_send", subject: "steer", qualifier: runId });
|
|
755
|
+
},
|
|
756
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
757
|
+
renderResult(result: any, theme: any) {
|
|
758
|
+
const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
|
|
759
|
+
return renderToolPlainCard(text.split("\n")[0] ?? text);
|
|
760
|
+
},
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
// ── R17: delegate_answer tool (unblock a waiting child) ────────────────
|
|
764
|
+
|
|
765
|
+
pi.registerTool({
|
|
766
|
+
name: "delegate_answer",
|
|
767
|
+
label: "Answer child question",
|
|
768
|
+
description:
|
|
769
|
+
"Answer a delegated child's pending ask_parent question. The blocked child resumes the moment your answer lands. " +
|
|
770
|
+
"Be terse and directive; do not narrate the exchange to the user unless material. If you cannot answer, say so — the child falls back to its best judgment when the ask budget expires.",
|
|
771
|
+
promptSnippet: "Answer a delegated child's pending question",
|
|
772
|
+
promptGuidelines: [
|
|
773
|
+
"Answer pending child questions promptly with delegate_answer — the child is blocked until you do.",
|
|
774
|
+
],
|
|
775
|
+
parameters: Type.Object({
|
|
776
|
+
runId: Type.String({ description: "The runId from the delegate-child-question message." }),
|
|
777
|
+
answer: Type.String({ minLength: 1, maxLength: 2000, description: "Your answer, self-contained and directive. The child sees exactly this text." }),
|
|
778
|
+
}),
|
|
779
|
+
async execute(_toolCallId, params) {
|
|
780
|
+
const runId = typeof params.runId === "string" ? params.runId.trim() : "";
|
|
781
|
+
const answer = typeof params.answer === "string" ? params.answer.trim() : "";
|
|
782
|
+
if (!runId || !answer) {
|
|
783
|
+
return {
|
|
784
|
+
content: [{ type: "text" as const, text: "delegate_answer requires runId and answer." }],
|
|
785
|
+
details: {} as Record<string, unknown>,
|
|
786
|
+
isError: true,
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
const result = background.answer(runId, answer, "model");
|
|
790
|
+
if (!result.ok) {
|
|
791
|
+
return {
|
|
792
|
+
content: [{ type: "text" as const, text: `E_ANSWER_FAILED: ${result.error}` }],
|
|
793
|
+
details: { runId } as Record<string, unknown>,
|
|
794
|
+
isError: true,
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
return {
|
|
798
|
+
content: [{ type: "text" as const, text: `Answer delivered to background run ${runId}; the child is resuming.` }],
|
|
799
|
+
details: { runId, answered: true } as Record<string, unknown>,
|
|
800
|
+
};
|
|
801
|
+
},
|
|
802
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
803
|
+
renderCall(args: any, theme: any) {
|
|
804
|
+
const runId = typeof args.runId === "string" ? args.runId.slice(-12) : "?";
|
|
805
|
+
return renderToolCallCard(theme, { title: "delegate_answer", subject: "answer", qualifier: runId });
|
|
806
|
+
},
|
|
807
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
808
|
+
renderResult(result: any, theme: any) {
|
|
809
|
+
const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
|
|
810
|
+
return renderToolPlainCard(text.split("\n")[0] ?? text);
|
|
811
|
+
},
|
|
812
|
+
});
|
|
813
|
+
|
|
814
|
+
// ── R15/R17/R18: question + note renderers (? asks / ℹ note) ──────────
|
|
815
|
+
|
|
816
|
+
pi.registerMessageRenderer(CHILD_QUESTION_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
817
|
+
const d = (message.details ?? {}) as { runId?: string; description?: string; topic?: string };
|
|
818
|
+
const raw = message.content;
|
|
819
|
+
const text =
|
|
820
|
+
typeof raw === "string" ? raw
|
|
821
|
+
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
822
|
+
: "";
|
|
823
|
+
const parts = text.split("\n\n");
|
|
824
|
+
const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
|
|
825
|
+
return new Text(`? background ${d.runId ?? "?"}${d.description ? ` · ${d.description}` : ""}: asks (${d.topic ?? "?"})\n\n${body}`, 0, 0);
|
|
826
|
+
});
|
|
827
|
+
|
|
828
|
+
pi.registerMessageRenderer(CHILD_NOTE_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
829
|
+
const d = (message.details ?? {}) as { runId?: string; description?: string; topic?: string };
|
|
830
|
+
const raw = message.content;
|
|
831
|
+
const text =
|
|
832
|
+
typeof raw === "string" ? raw
|
|
833
|
+
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
834
|
+
: "";
|
|
835
|
+
const parts = text.split("\n\n");
|
|
836
|
+
const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
|
|
837
|
+
return new Text(`ℹ background ${d.runId ?? "?"}${d.description ? ` · ${d.description}` : ""}: note (${d.topic ?? "?"})\n\n${body}`, 0, 0);
|
|
838
|
+
});
|
|
839
|
+
|
|
480
840
|
// ── Handoff custom message renderer (§6.4) ─────────────────────────────
|
|
481
841
|
|
|
482
842
|
pi.registerMessageRenderer(HANDOFF_CUSTOM_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
@@ -489,6 +849,18 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
489
849
|
return new Text(`[delegate ${d.runId ?? "?"} · ${d.role ?? "?"} · ${d.state ?? "?"}]\n\n${text}`, 0, 0);
|
|
490
850
|
});
|
|
491
851
|
|
|
852
|
+
// ── R15: background result renderer (neutral glyph+word, no model-only text)
|
|
853
|
+
|
|
854
|
+
pi.registerMessageRenderer(BACKGROUND_RESULT_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
855
|
+
const d = (message.details ?? {}) as { runId?: string; state?: string; description?: string };
|
|
856
|
+
const raw = message.content;
|
|
857
|
+
const text =
|
|
858
|
+
typeof raw === "string" ? raw
|
|
859
|
+
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
860
|
+
: "";
|
|
861
|
+
return new Text(backgroundResultDisplay(text, d), 0, 0);
|
|
862
|
+
});
|
|
863
|
+
|
|
492
864
|
// ── Command execution ───────────────────────────────────────────────────
|
|
493
865
|
|
|
494
866
|
const sendHandoffMessage = (res: DelegateRunResult) => {
|
|
@@ -627,6 +999,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
627
999
|
lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
|
|
628
1000
|
const queued = app.queuedRunCount();
|
|
629
1001
|
lines.push(`queue: ${queued} waiting (concurrent calls serialize; limit ${app.queueLimit()})`);
|
|
1002
|
+
lines.push(backgroundStatusText());
|
|
1003
|
+
for (const q of background.pendingQuestions()) {
|
|
1004
|
+
lines.push(`pending question: ${q.runId} (${q.topic}) — answer with the delegate_answer tool`);
|
|
1005
|
+
}
|
|
630
1006
|
if (s.lastRun) {
|
|
631
1007
|
const dur = s.lastRun.durationMs != null ? `${Math.round(s.lastRun.durationMs / 1000)}s` : "";
|
|
632
1008
|
lines.push(`last run: ${s.lastRun.runId} ${s.lastRun.role} ${s.lastRun.state} ${dur}`.trimEnd());
|
|
@@ -660,11 +1036,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
660
1036
|
"/delegate research <task> research role",
|
|
661
1037
|
"/delegate <task> general-role shorthand",
|
|
662
1038
|
"/delegate cancel [run-id] cancel the active run",
|
|
1039
|
+
"/delegate answer <run-id> <text> answer a blocked background child's question",
|
|
663
1040
|
"/delegate resume <run-id> <task> resume a prior run's child session",
|
|
664
1041
|
"/delegate inspect [run-id] inspect a run (default: recent/active)",
|
|
665
1042
|
"/delegate paths config + run store paths",
|
|
666
1043
|
"/delegate doctor diagnostics",
|
|
667
1044
|
"/delegate help this help",
|
|
1045
|
+
"",
|
|
1046
|
+
"Background runs: delegate({ background: true, description: … }) spawns and returns",
|
|
1047
|
+
"immediately; the terminal report arrives as a message. Models poll the",
|
|
1048
|
+
"delegate_status tool; the dashboard shows live background runs.",
|
|
668
1049
|
].join("\n");
|
|
669
1050
|
|
|
670
1051
|
const doctorText = (): string => {
|
|
@@ -734,7 +1115,31 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
734
1115
|
}
|
|
735
1116
|
case "cancel": {
|
|
736
1117
|
const res = await app.cancel(intent.runId);
|
|
737
|
-
|
|
1118
|
+
if (res.ok) {
|
|
1119
|
+
say(ctx, `[delegate] ${res.message}`);
|
|
1120
|
+
return;
|
|
1121
|
+
}
|
|
1122
|
+
// R8: background runs cancel by explicit runId (no foreground active).
|
|
1123
|
+
if (intent.runId && background.cancel(intent.runId)) {
|
|
1124
|
+
say(ctx, `[delegate] Cancellation requested for background run ${intent.runId}.`);
|
|
1125
|
+
return;
|
|
1126
|
+
}
|
|
1127
|
+
const live = background.liveRuns();
|
|
1128
|
+
if (live.length > 0) {
|
|
1129
|
+
say(ctx, `[delegate] No foreground run active. Live background runs: ${live.map((r) => r.runId).join(", ")} — cancel with /delegate cancel <run-id>.`, "warning");
|
|
1130
|
+
return;
|
|
1131
|
+
}
|
|
1132
|
+
say(ctx, `[delegate] ${res.message}`, "warning");
|
|
1133
|
+
return;
|
|
1134
|
+
}
|
|
1135
|
+
case "answer": {
|
|
1136
|
+
// R19: user intercept — answer a blocked child directly.
|
|
1137
|
+
const result = background.answer(intent.runId, intent.text, "user");
|
|
1138
|
+
if (result.ok) {
|
|
1139
|
+
say(ctx, `[delegate] Answer delivered to background run ${intent.runId}; the child is resuming.`);
|
|
1140
|
+
} else {
|
|
1141
|
+
say(ctx, `[delegate] ${result.error}`, "warning");
|
|
1142
|
+
}
|
|
738
1143
|
return;
|
|
739
1144
|
}
|
|
740
1145
|
case "inspect":
|
|
@@ -929,6 +1334,34 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
929
1334
|
sections.push({ title: "Live", rows });
|
|
930
1335
|
}
|
|
931
1336
|
|
|
1337
|
+
// R15: background runs section (live + recent terminal).
|
|
1338
|
+
{
|
|
1339
|
+
const bgLive = backgroundLiveViews();
|
|
1340
|
+
const bgRecent = app.backgroundRecentRuns(3);
|
|
1341
|
+
if (bgLive.length > 0 || bgRecent.length > 0) {
|
|
1342
|
+
const rows: PanelRow[] = [];
|
|
1343
|
+
for (const r of bgLive) {
|
|
1344
|
+
const g = r.phase ? stateGlyph(r.phase.startsWith("tool:") ? "running" : r.phase) : stateGlyph("starting");
|
|
1345
|
+
rows.push({
|
|
1346
|
+
key: `bg-${r.runId}`,
|
|
1347
|
+
label: `${g.glyph} ${r.role}`,
|
|
1348
|
+
value: `${r.description}${r.elapsedMs !== undefined ? ` · ${Math.round(r.elapsedMs / 1000)}s` : ""}${r.openTools?.length ? ` · ⏳ ${r.openTools.slice(0, 2).join(",")}` : ""}${r.detached ? " · branch inactive" : ""}`,
|
|
1349
|
+
kind: "info",
|
|
1350
|
+
});
|
|
1351
|
+
}
|
|
1352
|
+
for (const r of bgRecent) {
|
|
1353
|
+
const g = stateGlyph(r.state as never);
|
|
1354
|
+
rows.push({ key: `bg-last-${r.runId}`, label: `${g.glyph} last`, value: `${r.role} ${g.word}${r.durationMs != null ? ` · ${Math.round(r.durationMs / 1000)}s` : ""} · ${r.runId.slice(-12)}`, kind: "info", valueStyle: "muted" });
|
|
1355
|
+
}
|
|
1356
|
+
// R19: pending child questions are answerable from the panel.
|
|
1357
|
+
for (const q of background.pendingQuestions()) {
|
|
1358
|
+
rows.push({ key: `bg-answer-${q.runId}`, label: `? Answer ${q.runId.slice(-12)}`, value: `child blocked (${q.topic})`, kind: "action" });
|
|
1359
|
+
}
|
|
1360
|
+
rows.push({ key: "bg-slots", label: "Slots", value: `${bgLive.length}/${app.backgroundLimit()} active`, kind: "info", valueStyle: "muted" });
|
|
1361
|
+
sections.push({ title: "Background runs", rows });
|
|
1362
|
+
}
|
|
1363
|
+
}
|
|
1364
|
+
|
|
932
1365
|
sections.push({
|
|
933
1366
|
title: "Actions",
|
|
934
1367
|
rows: [
|
|
@@ -1029,6 +1462,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1029
1462
|
await openPeek(ctx);
|
|
1030
1463
|
continue;
|
|
1031
1464
|
}
|
|
1465
|
+
// R19: answer a pending child question from the panel.
|
|
1466
|
+
if (action.startsWith("bg-answer-")) {
|
|
1467
|
+
const qRunId = action.slice("bg-answer-".length);
|
|
1468
|
+
const answer = await ctx.ui.editor(`Answer child ${qRunId.slice(-12)}`, "");
|
|
1469
|
+
if (answer && answer.trim()) {
|
|
1470
|
+
const result = background.answer(qRunId, answer.trim(), "user");
|
|
1471
|
+
say(ctx, result.ok ? `[delegate] Answer delivered to background run ${qRunId}.` : `[delegate] ${result.error}`, result.ok ? "info" : "warning");
|
|
1472
|
+
}
|
|
1473
|
+
continue;
|
|
1474
|
+
}
|
|
1032
1475
|
if (action === "cancel") {
|
|
1033
1476
|
const ok = await ctx.ui.confirm("Cancel active run?", "SIGTERM then SIGKILL; a partial handoff is returned if the child produced one.");
|
|
1034
1477
|
if (ok) {
|
|
@@ -1088,9 +1531,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1088
1531
|
|
|
1089
1532
|
// ── 7. Lifecycle ────────────────────────────────────────────────────────
|
|
1090
1533
|
|
|
1091
|
-
const hydrateFromSession = (ctx: ExtensionContext) => {
|
|
1534
|
+
const hydrateFromSession = (ctx: ExtensionContext): SessionEntryLike[] => {
|
|
1535
|
+
let branch: SessionEntryLike[] = [];
|
|
1092
1536
|
try {
|
|
1093
|
-
|
|
1537
|
+
branch = ctx.sessionManager.getBranch() as SessionEntryLike[];
|
|
1094
1538
|
app.hydrateFromBranch(branch);
|
|
1095
1539
|
} catch (error) {
|
|
1096
1540
|
// Replay failure keeps the stricter of both states (§8.2).
|
|
@@ -1098,18 +1542,33 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1098
1542
|
}
|
|
1099
1543
|
if (app.isStrict()) {
|
|
1100
1544
|
ctx.ui.setStatus("delegate", "delegate: strict");
|
|
1545
|
+
footerUi = ctx.ui;
|
|
1546
|
+
refreshFooter();
|
|
1101
1547
|
// Repair visibility immediately in case the session had drifted.
|
|
1102
1548
|
try {
|
|
1103
|
-
syncStrictToolSet(app.getModeRuntime(), pi.getActiveTools(), () => pi.setActiveTools(
|
|
1549
|
+
syncStrictToolSet(app.getModeRuntime(), pi.getActiveTools(), () => pi.setActiveTools(STRICT_ACTIVE_TOOLS));
|
|
1104
1550
|
} catch {
|
|
1105
1551
|
// gate remains authoritative
|
|
1106
1552
|
}
|
|
1107
1553
|
}
|
|
1554
|
+
footerUi = ctx.ui;
|
|
1555
|
+
refreshFooter();
|
|
1108
1556
|
refreshDoctor(ctx);
|
|
1557
|
+
return branch;
|
|
1109
1558
|
};
|
|
1110
1559
|
|
|
1111
1560
|
pi.on("session_start", async (_event, ctx) => {
|
|
1112
1561
|
hydrateFromSession(ctx);
|
|
1562
|
+
// R12/R13: adopt the branch; deliver undelivered terminals once.
|
|
1563
|
+
try {
|
|
1564
|
+
const branch = ctx.sessionManager.getBranch() as SessionEntryLike[];
|
|
1565
|
+
const { resent, notes } = background.start(branch);
|
|
1566
|
+
if (resent.length > 0 || notes.length > 0) {
|
|
1567
|
+
console.log(`[delegate] background reconcile: ${resent.length} resent${notes.length ? `; ${notes.join("; ")}` : ""}`);
|
|
1568
|
+
}
|
|
1569
|
+
} catch (error) {
|
|
1570
|
+
console.log(`[delegate] background reconcile failed: ${(error as Error).message}`);
|
|
1571
|
+
}
|
|
1113
1572
|
if ((unknownKeys.length > 0 || recoveredFromCorrupt) && ctx.hasUI) {
|
|
1114
1573
|
const parts: string[] = [];
|
|
1115
1574
|
if (unknownKeys.length > 0) parts.push(`unknown config keys ignored: ${unknownKeys.join(", ")}`);
|
|
@@ -1118,9 +1577,24 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1118
1577
|
}
|
|
1119
1578
|
});
|
|
1120
1579
|
|
|
1580
|
+
pi.on("session_before_tree", async () => {
|
|
1581
|
+
// R13: no background delivery while a tree switch is in flight.
|
|
1582
|
+
background.beforeTree();
|
|
1583
|
+
});
|
|
1584
|
+
|
|
1121
1585
|
pi.on("session_tree", async (_event, ctx) => {
|
|
1122
1586
|
// Branch navigation: mode follows the new leaf (§8.2, E2E-03).
|
|
1123
1587
|
hydrateFromSession(ctx);
|
|
1588
|
+
// R12/R13: re-adopt the new branch, resume buffered delivery.
|
|
1589
|
+
try {
|
|
1590
|
+
const branch = ctx.sessionManager.getBranch() as SessionEntryLike[];
|
|
1591
|
+
const { resent, notes } = background.afterTree(branch);
|
|
1592
|
+
if (resent.length > 0 || notes.length > 0) {
|
|
1593
|
+
console.log(`[delegate] background re-adopt: ${resent.length} resent${notes.length ? `; ${notes.join("; ")}` : ""}`);
|
|
1594
|
+
}
|
|
1595
|
+
} catch (error) {
|
|
1596
|
+
console.log(`[delegate] background re-adopt failed: ${(error as Error).message}`);
|
|
1597
|
+
}
|
|
1124
1598
|
});
|
|
1125
1599
|
|
|
1126
1600
|
pi.on("before_agent_start", async (event: { systemPrompt?: string }, ctx) => {
|
|
@@ -1142,8 +1616,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1142
1616
|
});
|
|
1143
1617
|
|
|
1144
1618
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1145
|
-
// Owned
|
|
1619
|
+
// Owned children get cancelled; UI indicators cleared.
|
|
1146
1620
|
app.cancelActiveOnShutdown();
|
|
1621
|
+
background.shutdown();
|
|
1147
1622
|
try {
|
|
1148
1623
|
ctx.ui.setStatus("delegate", undefined);
|
|
1149
1624
|
} catch {
|