@maheidem/pi-delegate 0.8.0 → 0.10.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/CHANGELOG.md +17 -0
- package/README.md +83 -0
- package/extensions/application.ts +68 -17
- package/extensions/ask.ts +50 -0
- package/extensions/config.ts +206 -25
- package/extensions/index.ts +175 -44
- package/extensions/rpc-jsonl.ts +25 -0
- package/extensions/run-store.ts +32 -8
- package/extensions/runner.ts +103 -28
- package/extensions/types.ts +55 -0
- package/extensions/ui/event-card.ts +96 -0
- package/extensions/ui/peek-view.ts +24 -2
- package/extensions/ui/running-view.ts +119 -16
- package/package.json +1 -1
- package/roles/general.md +5 -0
- package/roles/research.md +5 -0
package/extensions/index.ts
CHANGED
|
@@ -19,23 +19,24 @@ import {
|
|
|
19
19
|
type ExtensionCommandContext,
|
|
20
20
|
type ExtensionContext,
|
|
21
21
|
} from "@earendil-works/pi-coding-agent";
|
|
22
|
-
import { Text } from "@earendil-works/pi-tui";
|
|
23
22
|
|
|
24
|
-
import { CONFIG_PATH, formatDuration, loadConfig, parseDuration, saveConfig } from "./config.ts";
|
|
23
|
+
import { CONFIG_PATH, formatDuration, loadConfig, parseDuration, resolveChildConfig, saveConfig } from "./config.ts";
|
|
25
24
|
import { COMMAND_NAME } from "./metadata.ts";
|
|
26
25
|
import * as fsSync from "node:fs";
|
|
27
26
|
import { delegateVersion } from "./version.ts";
|
|
28
27
|
import { HandoffToolParams, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
|
|
29
|
-
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool } from "./ask.ts";
|
|
28
|
+
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE, registerAskParentTool, resolveAskEnv } from "./ask.ts";
|
|
30
29
|
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
31
30
|
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
32
31
|
import { STRICT_OVERLAY, STRICT_ACTIVE_TOOLS, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
33
32
|
import { DelegateApplicationImpl } from "./application.ts";
|
|
34
33
|
import { DELEGATE_MODE_CUSTOM_TYPE } from "./types.ts";
|
|
35
34
|
import type {
|
|
35
|
+
ChildLiveState,
|
|
36
36
|
DelegateDetails,
|
|
37
37
|
DelegateRequest,
|
|
38
38
|
DelegateRunResult,
|
|
39
|
+
ResolvedChildConfig,
|
|
39
40
|
RunAttemptResult,
|
|
40
41
|
RunStreamUpdate,
|
|
41
42
|
SessionEntryLike,
|
|
@@ -45,6 +46,7 @@ import { shortModel, formatTokens, formatCost, stateGlyph, progressBar, projectV
|
|
|
45
46
|
import { renderToolCallCard, renderToolPlainCard, renderToolResultCard, type ToolCardLine } from "@maheidem/pi-panel-kit";
|
|
46
47
|
import { RunningView, type RunningViewState } from "./ui/running-view.ts";
|
|
47
48
|
import { PeekView } from "./ui/peek-view.ts";
|
|
49
|
+
import { EventCard, eventCardSpec } from "./ui/event-card.ts";
|
|
48
50
|
import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
|
|
49
51
|
import {
|
|
50
52
|
BackgroundManager,
|
|
@@ -201,13 +203,22 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
201
203
|
// R17/R18: background children get the ask_parent channel (a
|
|
202
204
|
// foreground child asking would deadlock the parent turn by
|
|
203
205
|
// construction — enforced here at registration, not by prompt).
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
askDir,
|
|
208
|
-
timeoutMs:
|
|
209
|
-
maxQuestions:
|
|
210
|
-
}
|
|
206
|
+
const askAgentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
|
|
207
|
+
const ask = resolveAskEnv(
|
|
208
|
+
{
|
|
209
|
+
askDir: process.env.PI_DELEGATE_ASK_DIR,
|
|
210
|
+
timeoutMs: process.env.PI_DELEGATE_ASK_TIMEOUT_MS,
|
|
211
|
+
maxQuestions: process.env.PI_DELEGATE_ASK_MAX,
|
|
212
|
+
},
|
|
213
|
+
askAgentDir,
|
|
214
|
+
);
|
|
215
|
+
if (ask) {
|
|
216
|
+
try {
|
|
217
|
+
fsSync.mkdirSync(ask.askDir, { recursive: true, mode: 0o700 });
|
|
218
|
+
} catch {
|
|
219
|
+
// read-only/unwritable ask dir — fail closed below.
|
|
220
|
+
}
|
|
221
|
+
registerAskParentTool(pi, ask);
|
|
211
222
|
}
|
|
212
223
|
return;
|
|
213
224
|
}
|
|
@@ -299,22 +310,43 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
299
310
|
source: "tool" | "command",
|
|
300
311
|
ctx: ExtensionContext,
|
|
301
312
|
timeoutMs?: number,
|
|
302
|
-
extras?: { model?: string; resumeFrom?: string; background?: boolean; description?: string },
|
|
303
|
-
): DelegateRequest =>
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
313
|
+
extras?: { model?: string; thinking?: string; resumeFrom?: string; background?: boolean; description?: string },
|
|
314
|
+
): DelegateRequest => {
|
|
315
|
+
const parentModel = modelString(ctx);
|
|
316
|
+
const parentThinking = thinkingOf(ctx);
|
|
317
|
+
const projectRoot = ctx.cwd ?? process.cwd();
|
|
318
|
+
// Resolution: per-invocation (tool arg) > project child config > parent's current.
|
|
319
|
+
let registeredTools: string[] | undefined;
|
|
320
|
+
try {
|
|
321
|
+
registeredTools = pi.getAllTools().map((t: { name: string }) => t.name);
|
|
322
|
+
} catch {
|
|
323
|
+
registeredTools = undefined;
|
|
324
|
+
}
|
|
325
|
+
const childConfig = resolveChildConfig({
|
|
326
|
+
perInvocation: extras ? { model: extras.model, thinking: extras.thinking } : undefined,
|
|
327
|
+
baseConfig: config,
|
|
328
|
+
projectRoot,
|
|
329
|
+
parentModel,
|
|
330
|
+
parentThinking,
|
|
331
|
+
registeredTools,
|
|
332
|
+
});
|
|
333
|
+
return {
|
|
334
|
+
task,
|
|
335
|
+
role,
|
|
336
|
+
source,
|
|
337
|
+
cwd: projectRoot,
|
|
338
|
+
parentModel,
|
|
339
|
+
thinkingLevel: parentThinking,
|
|
340
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
341
|
+
projectRoot,
|
|
342
|
+
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
|
343
|
+
...(extras?.model ? { model: extras.model } : {}),
|
|
344
|
+
...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
|
|
345
|
+
...(extras?.background ? { background: true } : {}),
|
|
346
|
+
...(extras?.description ? { description: extras.description } : {}),
|
|
347
|
+
childConfig,
|
|
348
|
+
};
|
|
349
|
+
};
|
|
318
350
|
|
|
319
351
|
const refreshDoctor = (ctx: ExtensionContext) => {
|
|
320
352
|
try {
|
|
@@ -434,6 +466,11 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
434
466
|
"Optional child model pin as 'provider/model-id'. Without it the child silently inherits the parent's CURRENT model — " +
|
|
435
467
|
"if the parent switches models mid-session (e.g. a usage-limit fallback), children follow. Pin this for model-sensitive work.",
|
|
436
468
|
})),
|
|
469
|
+
thinking: Type.Optional(Type.String({
|
|
470
|
+
description:
|
|
471
|
+
"Optional child thinking level (e.g. 'off', 'low', 'medium', 'high', 'xhigh'). Without it the child inherits the parent's level. " +
|
|
472
|
+
"Overrides the project child config's thinking pin.",
|
|
473
|
+
})),
|
|
437
474
|
resumeFrom: Type.Optional(Type.String({
|
|
438
475
|
description:
|
|
439
476
|
"Resume a prior run's durable child session: pass its runId. The new child re-enters that exact context " +
|
|
@@ -458,21 +495,22 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
458
495
|
"Delegate a self-contained subtask to an isolated child Pi session with a bounded final handoff. " +
|
|
459
496
|
"Roles: general (implementation, write-capable) and research (read-only web research via Firecrawl, optionally supplemented by Reddit). " +
|
|
460
497
|
"The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task. " +
|
|
461
|
-
|
|
498
|
+
"Execution mode you choose per call: foreground (background: false) — the very next step depends on the result, or you want to nudge the child interactively; background (default) — independent parallel work, long-running exploration, or work that finishes after you continue. " +
|
|
499
|
+
"Always pass a 3–6-word description.",
|
|
462
500
|
promptSnippet: "Delegate a bounded subtask (implementation or research) to an isolated child session",
|
|
463
501
|
promptGuidelines: [
|
|
464
502
|
"Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
|
|
465
503
|
"Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
|
|
466
504
|
"Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
|
|
467
505
|
"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.",
|
|
468
|
-
"
|
|
469
|
-
"
|
|
506
|
+
"Pick the execution mode by what the next step needs: FOREGROUND (background: false) when the very next step depends on the child's result or you want to nudge it interactively — the foreground panel accepts follow-up messages via enter; BACKGROUND (the default) for independent parallel work, long-running exploration, or work that finishes after you continue. When in doubt, choose background.",
|
|
507
|
+
"Background is the default: the call returns a runId immediately and the terminal report arrives later as a message; check progress with delegate_status and do not wait inline.",
|
|
470
508
|
"A 3–6-word description is REQUIRED for every delegation, foreground included.",
|
|
471
509
|
"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.",
|
|
472
510
|
"On E_BACKGROUND_FULL, do not re-issue the task: check delegate_status and wait for terminal reports to free slots.",
|
|
473
|
-
"
|
|
511
|
+
"Use delegate_send to correct or redirect a LIVE run (course corrections apply at the child's next model call) — never resumeFrom for corrections; reserve resumeFrom for finished runs whose work you want to continue in the same session.",
|
|
474
512
|
"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.",
|
|
475
|
-
"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).",
|
|
513
|
+
"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). Pin thinking (optional) to fix the child's thinking level; without it the child inherits the parent's level.",
|
|
476
514
|
"For long validation/benchmark subtasks set timeout to at least 2x the longest expected single tool call.",
|
|
477
515
|
"While delegation mode is active, all substantive work and verification must use delegate; the parent is coordination-only.",
|
|
478
516
|
],
|
|
@@ -492,6 +530,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
492
530
|
}
|
|
493
531
|
}
|
|
494
532
|
const modelExtra = typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined;
|
|
533
|
+
const thinkingExtra = typeof params.thinking === "string" && params.thinking.trim() ? params.thinking.trim() : undefined;
|
|
495
534
|
const resumeExtra = typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined;
|
|
496
535
|
|
|
497
536
|
// R22: description is required for EVERY delegation (both modes) —
|
|
@@ -519,6 +558,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
519
558
|
}
|
|
520
559
|
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
|
|
521
560
|
model: modelExtra,
|
|
561
|
+
thinking: thinkingExtra,
|
|
522
562
|
resumeFrom: resumeExtra,
|
|
523
563
|
background: true,
|
|
524
564
|
description: desc.value,
|
|
@@ -549,6 +589,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
549
589
|
|
|
550
590
|
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
|
|
551
591
|
model: modelExtra,
|
|
592
|
+
thinking: thinkingExtra,
|
|
552
593
|
resumeFrom: resumeExtra,
|
|
553
594
|
description: desc.value,
|
|
554
595
|
});
|
|
@@ -631,6 +672,14 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
631
672
|
// Expanded: identity + canonical summary + resume hint.
|
|
632
673
|
const summary = formatRunSummary(result as unknown as DelegateRunResult);
|
|
633
674
|
const detailLines: ToolCardLine[] = [];
|
|
675
|
+
if (d.childConfig) {
|
|
676
|
+
const bits: string[] = [];
|
|
677
|
+
if (d.childConfig.model) bits.push(`model ${d.childConfig.model}${d.childConfig.modelSource ? ` (${d.childConfig.modelSource === "per-invocation" ? "pinned" : d.childConfig.modelSource === "project" ? "project pin" : "inherited"})` : ""}`);
|
|
678
|
+
if (d.childConfig.thinking) bits.push(`thinking ${d.childConfig.thinking}`);
|
|
679
|
+
if (d.childConfig.tools !== undefined) bits.push(`tools ${d.childConfig.tools.length ? d.childConfig.tools.join(", ") : "(none — handoff only)"}`);
|
|
680
|
+
if (d.childConfig.context) bits.push(`context ${d.childConfig.context}`);
|
|
681
|
+
if (bits.length) detailLines.push({ text: ` child: ${bits.join(" · ")}` });
|
|
682
|
+
}
|
|
634
683
|
if (d.sessionPath && d.state !== "succeeded") detailLines.push({ text: ` resume: resumeFrom ${d.runId}` });
|
|
635
684
|
if (d.transcriptPath) detailLines.push({ text: ` transcript: ${d.transcriptPath}` });
|
|
636
685
|
return renderToolResultCard(theme, {
|
|
@@ -848,7 +897,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
848
897
|
|
|
849
898
|
// ── R15/R17/R18: question + note renderers (? asks / ℹ note) ──────────
|
|
850
899
|
|
|
851
|
-
pi.registerMessageRenderer(CHILD_QUESTION_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
900
|
+
pi.registerMessageRenderer(CHILD_QUESTION_TYPE, (message: { content?: string | unknown[]; details?: unknown }, _options: unknown, theme: any) => {
|
|
852
901
|
const d = (message.details ?? {}) as { runId?: string; description?: string; topic?: string };
|
|
853
902
|
const raw = message.content;
|
|
854
903
|
const text =
|
|
@@ -857,10 +906,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
857
906
|
: "";
|
|
858
907
|
const parts = text.split("\n\n");
|
|
859
908
|
const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
|
|
860
|
-
|
|
909
|
+
const text2 = `? background ${(d.runId ?? "?").slice(-12)}${d.description ? ` · ${d.description}` : ""}: asks (${d.topic ?? "?"})\n\n${body}`;
|
|
910
|
+
const spec = eventCardSpec(text2);
|
|
911
|
+
return new EventCard(theme, spec ?? { label: text2, bodyLines: [] });
|
|
861
912
|
});
|
|
862
913
|
|
|
863
|
-
pi.registerMessageRenderer(CHILD_NOTE_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
914
|
+
pi.registerMessageRenderer(CHILD_NOTE_TYPE, (message: { content?: string | unknown[]; details?: unknown }, _options: unknown, theme: any) => {
|
|
864
915
|
const d = (message.details ?? {}) as { runId?: string; description?: string; topic?: string };
|
|
865
916
|
const raw = message.content;
|
|
866
917
|
const text =
|
|
@@ -869,43 +920,51 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
869
920
|
: "";
|
|
870
921
|
const parts = text.split("\n\n");
|
|
871
922
|
const body = parts.length > 2 ? parts.slice(2).join("\n\n") : text;
|
|
872
|
-
|
|
923
|
+
const text2 = `ℹ background ${(d.runId ?? "?").slice(-12)}${d.description ? ` · ${d.description}` : ""}: note (${d.topic ?? "?"})\n\n${body}`;
|
|
924
|
+
const spec = eventCardSpec(text2);
|
|
925
|
+
return new EventCard(theme, spec ?? { label: text2, bodyLines: [] });
|
|
873
926
|
});
|
|
874
927
|
|
|
875
928
|
// ── Handoff custom message renderer (§6.4) ─────────────────────────────
|
|
876
929
|
|
|
877
|
-
pi.registerMessageRenderer(HANDOFF_CUSTOM_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
930
|
+
pi.registerMessageRenderer(HANDOFF_CUSTOM_TYPE, (message: { content?: string | unknown[]; details?: unknown }, _options: unknown, theme: any) => {
|
|
878
931
|
const d = (message.details ?? {}) as { runId?: string; role?: string; state?: string };
|
|
879
932
|
const raw = message.content;
|
|
880
933
|
const text =
|
|
881
934
|
typeof raw === "string" ? raw
|
|
882
935
|
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
883
936
|
: "";
|
|
884
|
-
|
|
937
|
+
const text2 = `[delegate ${d.runId ?? "?"} · ${d.role ?? "?"} · ${d.state ?? "?"}]\n\n${text}`;
|
|
938
|
+
const spec = eventCardSpec(text2);
|
|
939
|
+
return new EventCard(theme, spec ?? { label: text2, bodyLines: [] });
|
|
885
940
|
});
|
|
886
941
|
|
|
887
942
|
// ── R23: progress renderer (neutral ● glyph, classification stripped) ───
|
|
888
943
|
|
|
889
|
-
pi.registerMessageRenderer(PROGRESS_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
944
|
+
pi.registerMessageRenderer(PROGRESS_TYPE, (message: { content?: string | unknown[]; details?: unknown }, _options: unknown, theme: any) => {
|
|
890
945
|
const d = (message.details ?? {}) as { runId?: string; description?: string };
|
|
891
946
|
const raw = message.content;
|
|
892
947
|
const text =
|
|
893
948
|
typeof raw === "string" ? raw
|
|
894
949
|
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
895
950
|
: "";
|
|
896
|
-
|
|
951
|
+
const text2 = progressDisplay(text, d);
|
|
952
|
+
const spec = eventCardSpec(text2);
|
|
953
|
+
return new EventCard(theme, spec ?? { label: text2, bodyLines: [] });
|
|
897
954
|
});
|
|
898
955
|
|
|
899
956
|
// ── R15: background result renderer (neutral glyph+word, no model-only text)
|
|
900
957
|
|
|
901
|
-
pi.registerMessageRenderer(BACKGROUND_RESULT_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
958
|
+
pi.registerMessageRenderer(BACKGROUND_RESULT_TYPE, (message: { content?: string | unknown[]; details?: unknown }, _options: unknown, theme: any) => {
|
|
902
959
|
const d = (message.details ?? {}) as { runId?: string; state?: string; description?: string };
|
|
903
960
|
const raw = message.content;
|
|
904
961
|
const text =
|
|
905
962
|
typeof raw === "string" ? raw
|
|
906
963
|
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
907
964
|
: "";
|
|
908
|
-
|
|
965
|
+
const text2 = backgroundResultDisplay(text, d);
|
|
966
|
+
const spec = eventCardSpec(text2);
|
|
967
|
+
return new EventCard(theme, spec ?? { label: text2, bodyLines: [] });
|
|
909
968
|
});
|
|
910
969
|
|
|
911
970
|
// ── Command execution ───────────────────────────────────────────────────
|
|
@@ -944,6 +1003,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
944
1003
|
phase: "starting",
|
|
945
1004
|
elapsedMs: 0,
|
|
946
1005
|
feedLines: [],
|
|
1006
|
+
...(request.childConfig ? { childPinned: request.childConfig } : {}),
|
|
947
1007
|
};
|
|
948
1008
|
// Live feed: every child event lands in the ring; the panel renders
|
|
949
1009
|
// the bounded tail on each host refresh (1 s + event-driven).
|
|
@@ -985,11 +1045,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
985
1045
|
}
|
|
986
1046
|
viewState.hardMs = hardMs;
|
|
987
1047
|
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
1048
|
+
// get_state: ask the child for its live state on first render and every
|
|
1049
|
+
// ~5 s after — best-effort, never blocks the UI.
|
|
1050
|
+
let stateRequestedAt = 0;
|
|
1051
|
+
const requestState = () => {
|
|
1052
|
+
stateRequestedAt = Date.now();
|
|
1053
|
+
app.requestChildState();
|
|
1054
|
+
};
|
|
988
1055
|
const outcome = await ctx.ui.custom<{ cancelled?: boolean } | undefined>(
|
|
989
1056
|
(tui, theme, keybindings, done) => {
|
|
1057
|
+
requestState();
|
|
990
1058
|
refreshTimer = setInterval(() => {
|
|
991
1059
|
viewState.elapsedMs = feedStartMs ? Date.now() - feedStartMs : viewState.elapsedMs;
|
|
992
1060
|
viewState.feedLines = feedLines();
|
|
1061
|
+
viewState.childLive = app.activeRunChildState();
|
|
1062
|
+
if (Date.now() - stateRequestedAt >= 5000) requestState();
|
|
993
1063
|
tui.requestRender();
|
|
994
1064
|
}, 1000);
|
|
995
1065
|
return new RunningView({
|
|
@@ -997,8 +1067,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
997
1067
|
keybindings,
|
|
998
1068
|
state: () => {
|
|
999
1069
|
viewState.feedLines = feedLines();
|
|
1070
|
+
viewState.childLive = app.activeRunChildState();
|
|
1000
1071
|
return viewState;
|
|
1001
1072
|
},
|
|
1073
|
+
onSteer: (message: string) => app.steerActiveRun(message),
|
|
1002
1074
|
done,
|
|
1003
1075
|
});
|
|
1004
1076
|
},
|
|
@@ -1147,13 +1219,48 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1147
1219
|
"delegate_status tool; the dashboard shows live background runs.",
|
|
1148
1220
|
].join("\n");
|
|
1149
1221
|
|
|
1150
|
-
const
|
|
1222
|
+
const childConfigSummary = (cc: ResolvedChildConfig | undefined): string | null => {
|
|
1223
|
+
if (!cc) return null;
|
|
1224
|
+
const parts: string[] = [];
|
|
1225
|
+
if (cc.model) {
|
|
1226
|
+
const sourceLabel = cc.modelSource === "per-invocation" ? "pinned" : cc.modelSource === "project" ? "pinned by project" : "inherited";
|
|
1227
|
+
parts.push(`${cc.model} (${sourceLabel})`);
|
|
1228
|
+
}
|
|
1229
|
+
if (cc.thinking) parts.push(`thinking ${cc.thinking}`);
|
|
1230
|
+
if (cc.tools !== undefined) parts.push(`tools: ${cc.tools.length ? cc.tools.join(", ") : "(none — handoff only)"}`);
|
|
1231
|
+
parts.push(`context ${cc.context ?? "standard"}`);
|
|
1232
|
+
if (cc.trustProject !== undefined) parts.push(`trust: ${cc.trustProject ? "approved" : "declined"}`);
|
|
1233
|
+
return parts.join(" · ");
|
|
1234
|
+
};
|
|
1235
|
+
|
|
1236
|
+
const doctorText = (ctx?: ExtensionCommandContext | ExtensionContext): string => {
|
|
1151
1237
|
const report = app.doctor();
|
|
1152
1238
|
const lines = [
|
|
1153
1239
|
`[delegate doctor] ${report.ok ? "OK" : "ISSUES FOUND"}`,
|
|
1154
1240
|
`version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`,
|
|
1155
1241
|
];
|
|
1156
1242
|
for (const c of report.checks) lines.push(` ${c.status === "ok" ? "✓" : c.status === "warning" ? "!" : "✗"} ${c.name}: ${c.detail}`);
|
|
1243
|
+
// Resolved child config (project overlay + per-invocation > parent):
|
|
1244
|
+
// shows the shape the next delegation will actually run with.
|
|
1245
|
+
if (ctx) {
|
|
1246
|
+
try {
|
|
1247
|
+
const parentModel = modelString(ctx as ExtensionContext);
|
|
1248
|
+
let registeredTools: string[] | undefined;
|
|
1249
|
+
try { registeredTools = pi.getAllTools().map((t: { name: string }) => t.name); } catch { registeredTools = undefined; }
|
|
1250
|
+
const childCfg = resolveChildConfig({
|
|
1251
|
+
baseConfig: config,
|
|
1252
|
+
projectRoot: ctx.cwd ?? process.cwd(),
|
|
1253
|
+
parentModel,
|
|
1254
|
+
parentThinking: thinkingOf(ctx as ExtensionContext),
|
|
1255
|
+
registeredTools,
|
|
1256
|
+
});
|
|
1257
|
+
const summary = childConfigSummary(childCfg);
|
|
1258
|
+
if (summary) lines.push(` child: ${summary}`);
|
|
1259
|
+
if (childCfg.diagnostics?.length) lines.push(` child diagnostics: ${childCfg.diagnostics.join("; ")}`);
|
|
1260
|
+
} catch {
|
|
1261
|
+
// best-effort display
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1157
1264
|
return lines.join("\n");
|
|
1158
1265
|
};
|
|
1159
1266
|
|
|
@@ -1164,6 +1271,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1164
1271
|
`[delegate inspect] ${m.runId}`,
|
|
1165
1272
|
`state: ${m.state} · role: ${m.role} · source: ${m.source}`,
|
|
1166
1273
|
`model: ${m.model}${m.thinkingLevel ? ` · thinking: ${m.thinkingLevel}` : ""}`,
|
|
1274
|
+
...(m.childConfig ? [`child: ${[m.childConfig.model, m.childConfig.thinking ? `thinking ${m.childConfig.thinking}` : null, m.childConfig.tools !== undefined ? `tools ${m.childConfig.tools.length ? m.childConfig.tools.join(", ") : "(none — handoff only)"}` : null, `context ${m.childConfig.context}`].filter(Boolean).join(" · ")}`] : []),
|
|
1167
1275
|
`created: ${m.createdAt}${m.startedAt ? ` · started: ${m.startedAt}` : ""}${m.finishedAt ? ` · finished: ${m.finishedAt}` : ""}`,
|
|
1168
1276
|
m.exitCode != null ? `exit: ${m.exitCode}` : "",
|
|
1169
1277
|
m.stopReason ? `stopReason: ${m.stopReason}` : "",
|
|
@@ -1200,7 +1308,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1200
1308
|
return;
|
|
1201
1309
|
}
|
|
1202
1310
|
case "doctor":
|
|
1203
|
-
say(ctx, doctorText());
|
|
1311
|
+
say(ctx, doctorText(ctx));
|
|
1204
1312
|
return;
|
|
1205
1313
|
case "status":
|
|
1206
1314
|
say(ctx, statusText(ctx));
|
|
@@ -1348,11 +1456,18 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1348
1456
|
live = false;
|
|
1349
1457
|
}
|
|
1350
1458
|
const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
|
|
1459
|
+
// Live child state only for the session's ACTIVE foreground run —
|
|
1460
|
+
// background runs have no runner handle in this session, and a
|
|
1461
|
+
// finished run's receipt copy is honest as "(pinned)".
|
|
1462
|
+
let childLive: ChildLiveState | undefined;
|
|
1463
|
+
try { childLive = app.activeRunId() === id ? app.activeRunChildState() : undefined; } catch { childLive = undefined; }
|
|
1351
1464
|
return {
|
|
1352
1465
|
title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${shortModel(meta.model)}` : ""} · ${meta.state}`,
|
|
1353
1466
|
summary: meta.transcriptPath,
|
|
1354
1467
|
lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
|
|
1355
1468
|
live,
|
|
1469
|
+
...(childLive ? { childLive } : {}),
|
|
1470
|
+
...(meta.childConfig ? { childPinned: meta.childConfig } : {}),
|
|
1356
1471
|
};
|
|
1357
1472
|
};
|
|
1358
1473
|
// Live-follow refresh timer; cleared the moment the overlay
|
|
@@ -1496,6 +1611,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1496
1611
|
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" : ""}`,
|
|
1497
1612
|
kind: "info",
|
|
1498
1613
|
});
|
|
1614
|
+
rows.push({
|
|
1615
|
+
key: `bg-send-${r.runId}`,
|
|
1616
|
+
label: `Send to ${r.runId.slice(-12)}…`,
|
|
1617
|
+
value: "steer the live child",
|
|
1618
|
+
kind: "action",
|
|
1619
|
+
});
|
|
1499
1620
|
}
|
|
1500
1621
|
for (const r of bgRecent) {
|
|
1501
1622
|
const g = stateGlyph(r.state as never);
|
|
@@ -1615,6 +1736,16 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1615
1736
|
await openPeek(ctx);
|
|
1616
1737
|
continue;
|
|
1617
1738
|
}
|
|
1739
|
+
// Interactive: steer a live background run via the existing delegate_send handle.
|
|
1740
|
+
if (action.startsWith("bg-send-")) {
|
|
1741
|
+
const runId = action.slice("bg-send-".length);
|
|
1742
|
+
const message = await ctx.ui.editor(`Steer background run ${runId.slice(-12)}`, "");
|
|
1743
|
+
if (message && message.trim()) {
|
|
1744
|
+
const result = background.send(runId, message.trim());
|
|
1745
|
+
say(ctx, result.ok ? `[delegate] steering message delivered to background run ${runId}.` : `[delegate] ${result.error}`, result.ok ? "info" : "warning");
|
|
1746
|
+
}
|
|
1747
|
+
continue;
|
|
1748
|
+
}
|
|
1618
1749
|
// R19: answer a pending child question from the panel.
|
|
1619
1750
|
if (action.startsWith("bg-answer-")) {
|
|
1620
1751
|
const qRunId = action.slice("bg-answer-".length);
|
|
@@ -1659,7 +1790,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1659
1790
|
continue;
|
|
1660
1791
|
}
|
|
1661
1792
|
if (action === "doctor") {
|
|
1662
|
-
say(ctx, doctorText());
|
|
1793
|
+
say(ctx, doctorText(ctx));
|
|
1663
1794
|
continue;
|
|
1664
1795
|
}
|
|
1665
1796
|
if (action === "status") {
|
package/extensions/rpc-jsonl.ts
CHANGED
|
@@ -22,6 +22,7 @@ export interface RpcRecord {
|
|
|
22
22
|
|
|
23
23
|
export type RpcRecordClassification =
|
|
24
24
|
| { kind: "prompt_response"; ok: boolean; id: string }
|
|
25
|
+
| { kind: "state_response"; ok: boolean; id: string; state: { model?: string; thinking?: string; isStreaming?: boolean } }
|
|
25
26
|
| { kind: "message_end"; stopReason?: string }
|
|
26
27
|
| { kind: "tool_event"; phase: "start" | "update" | "end"; id?: string; toolName?: string; args?: Record<string, unknown>; result?: { details?: unknown; isError?: boolean; textHead?: string } }
|
|
27
28
|
| { kind: "agent_settled" }
|
|
@@ -135,6 +136,30 @@ export function classifyRpcRecord(record: RpcRecord): RpcRecordClassification {
|
|
|
135
136
|
switch (obj.type) {
|
|
136
137
|
case "response": {
|
|
137
138
|
const ok = obj.error === undefined && obj.success !== false;
|
|
139
|
+
if (obj.command === "get_state") {
|
|
140
|
+
// Live child state (model / thinking / streaming). Tolerates the
|
|
141
|
+
// effort aliases (effort, reasoningEffort) — get_state exposes
|
|
142
|
+
// thinkingLevel on this pi version.
|
|
143
|
+
const data = isArgsObject(obj.data) ? (obj.data as Record<string, unknown>) : {};
|
|
144
|
+
const modelRec = isArgsObject(data.model) ? (data.model as Record<string, unknown>) : undefined;
|
|
145
|
+
const provider = modelRec && typeof modelRec.provider === "string" ? modelRec.provider : undefined;
|
|
146
|
+
const modelId = modelRec && typeof modelRec.id === "string" ? modelRec.id : undefined;
|
|
147
|
+
const thinking =
|
|
148
|
+
typeof data.thinkingLevel === "string" ? data.thinkingLevel
|
|
149
|
+
: typeof data.effort === "string" ? data.effort
|
|
150
|
+
: typeof data.reasoningEffort === "string" ? data.reasoningEffort
|
|
151
|
+
: undefined;
|
|
152
|
+
return {
|
|
153
|
+
kind: "state_response",
|
|
154
|
+
ok,
|
|
155
|
+
id: typeof obj.id === "string" ? obj.id : "",
|
|
156
|
+
state: {
|
|
157
|
+
...(provider && modelId ? { model: `${provider}/${modelId}` } : {}),
|
|
158
|
+
...(thinking ? { thinking } : {}),
|
|
159
|
+
...(typeof data.isStreaming === "boolean" ? { isStreaming: data.isStreaming } : {}),
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
138
163
|
return { kind: "prompt_response", ok, id: typeof obj.id === "string" ? obj.id : "" };
|
|
139
164
|
}
|
|
140
165
|
case "message_end": {
|
package/extensions/run-store.ts
CHANGED
|
@@ -22,6 +22,16 @@ import type {
|
|
|
22
22
|
import { EMPTY_USAGE, isTerminalRunState } from "./types.ts";
|
|
23
23
|
import { atomicWriteJson } from "./config.ts";
|
|
24
24
|
|
|
25
|
+
/** Debug-gated, secret-free diagnostic for non-fatal store failures. */
|
|
26
|
+
export function logStoreError(operation: string, error: unknown): void {
|
|
27
|
+
if (process.env.PI_DELEGATE_DEBUG !== "1" && process.env.PI_DELEGATE_DEBUG !== "true") return;
|
|
28
|
+
try {
|
|
29
|
+
console.error(`[delegate] run-store: ${operation}: ${(error as Error)?.message ?? String(error)}`);
|
|
30
|
+
} catch {
|
|
31
|
+
// never throw from a diagnostic path
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
25
35
|
export function makeRunId(now: Date = new Date()): string {
|
|
26
36
|
// del_<UTC-basic-timestamp>_<8-random-hex>, e.g. del_20260901T143022Z_a1b2c3d4
|
|
27
37
|
const stamp = now.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
|
|
@@ -55,8 +65,9 @@ function ensurePrivateDir(dir: string): void {
|
|
|
55
65
|
// mkdir mode does not re-tighten existing directories; enforce 0700.
|
|
56
66
|
try {
|
|
57
67
|
fs.chmodSync(dir, 0o700);
|
|
58
|
-
} catch {
|
|
68
|
+
} catch (error) {
|
|
59
69
|
// best effort on platforms without POSIX chmod semantics
|
|
70
|
+
logStoreError("ensurePrivateDir chmod", error);
|
|
60
71
|
}
|
|
61
72
|
}
|
|
62
73
|
|
|
@@ -100,6 +111,10 @@ export function openRun(agentDir: string, request: DelegateRequest): OpenedRun {
|
|
|
100
111
|
stderrPath: paths.stderrPath,
|
|
101
112
|
...(request.background ? { background: true } : {}),
|
|
102
113
|
...(request.description ? { description: request.description } : {}),
|
|
114
|
+
// Resolved child config (project overlay + per-invocation + parent) —
|
|
115
|
+
// recorded statically at creation so the receipt shows exactly what
|
|
116
|
+
// the child was launched with.
|
|
117
|
+
...(request.childConfig ? { childConfig: request.childConfig } : {}),
|
|
103
118
|
};
|
|
104
119
|
atomicWriteJson(paths.metadataPath, metadata);
|
|
105
120
|
|
|
@@ -197,7 +212,8 @@ export function readRunMetadata(agentDir: string, runId: string): RunMetadataV1
|
|
|
197
212
|
const paths = runPaths(agentDir, runId);
|
|
198
213
|
try {
|
|
199
214
|
return JSON.parse(fs.readFileSync(paths.metadataPath, "utf8")) as RunMetadataV1;
|
|
200
|
-
} catch {
|
|
215
|
+
} catch (error) {
|
|
216
|
+
logStoreError("readRunMetadata", error);
|
|
201
217
|
return null;
|
|
202
218
|
}
|
|
203
219
|
}
|
|
@@ -222,7 +238,8 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
|
|
|
222
238
|
let names: string[];
|
|
223
239
|
try {
|
|
224
240
|
names = fs.readdirSync(p.runsDir);
|
|
225
|
-
} catch {
|
|
241
|
+
} catch (error) {
|
|
242
|
+
logStoreError("listRuns readdir", error);
|
|
226
243
|
return [];
|
|
227
244
|
}
|
|
228
245
|
const summaries: RunSummary[] = [];
|
|
@@ -239,7 +256,8 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
|
|
|
239
256
|
let mtimeMs = 0;
|
|
240
257
|
try {
|
|
241
258
|
mtimeMs = fs.statSync(path.join(p.runsDir, name)).mtimeMs;
|
|
242
|
-
} catch {
|
|
259
|
+
} catch (error) {
|
|
260
|
+
logStoreError("listRuns stat", error);
|
|
243
261
|
mtimeMs = 0;
|
|
244
262
|
}
|
|
245
263
|
summaries.push({
|
|
@@ -257,8 +275,9 @@ export function listRuns(agentDir: string, limit = 50): RunSummary[] {
|
|
|
257
275
|
...(meta.background ? { background: true } : {}),
|
|
258
276
|
...(meta.description ? { description: meta.description } : {}),
|
|
259
277
|
});
|
|
260
|
-
} catch {
|
|
278
|
+
} catch (error) {
|
|
261
279
|
// unreadable metadata: leave alone; retention will not touch it
|
|
280
|
+
logStoreError("listRuns metadata", error);
|
|
262
281
|
}
|
|
263
282
|
}
|
|
264
283
|
summaries.sort((a, b) => b.mtimeMs - a.mtimeMs || (b.createdAt > a.createdAt ? 1 : -1));
|
|
@@ -294,7 +313,8 @@ export function pidCommandLine(pid: number): string | null {
|
|
|
294
313
|
.replace(/\0+/g, " ")
|
|
295
314
|
.trim();
|
|
296
315
|
return text.length > 0 ? text : null;
|
|
297
|
-
} catch {
|
|
316
|
+
} catch (error) {
|
|
317
|
+
logStoreError("pidCommandLine /proc", error);
|
|
298
318
|
return null;
|
|
299
319
|
}
|
|
300
320
|
}
|
|
@@ -306,7 +326,8 @@ export function pidCommandLine(pid: number): string | null {
|
|
|
306
326
|
if (out.error || out.status !== 0) return null;
|
|
307
327
|
const text = (out.stdout ?? "").trim();
|
|
308
328
|
return text.length > 0 ? text : null;
|
|
309
|
-
} catch {
|
|
329
|
+
} catch (error) {
|
|
330
|
+
logStoreError("pidCommandLine ps", error);
|
|
310
331
|
return null;
|
|
311
332
|
}
|
|
312
333
|
}
|
|
@@ -367,8 +388,9 @@ export function markOrphanedRuns(agentDir: string): string[] {
|
|
|
367
388
|
}));
|
|
368
389
|
if (next.state === "crashed") touched.push(summary.runId);
|
|
369
390
|
}
|
|
370
|
-
} catch {
|
|
391
|
+
} catch (error) {
|
|
371
392
|
// skip
|
|
393
|
+
logStoreError("markOrphanedRuns", error);
|
|
372
394
|
}
|
|
373
395
|
}
|
|
374
396
|
return touched;
|
|
@@ -393,6 +415,7 @@ export function enforceRetention(
|
|
|
393
415
|
try {
|
|
394
416
|
all = listRuns(agentDir, 10_000);
|
|
395
417
|
} catch (error) {
|
|
418
|
+
logStoreError("enforceRetention listRuns", error);
|
|
396
419
|
return { removed: 0, warnings: [`E_STORE: could not list runs: ${(error as Error).message}`] };
|
|
397
420
|
}
|
|
398
421
|
|
|
@@ -423,6 +446,7 @@ export function enforceRetention(
|
|
|
423
446
|
}
|
|
424
447
|
removed += 1;
|
|
425
448
|
} catch (error) {
|
|
449
|
+
logStoreError("enforceRetention remove", error);
|
|
426
450
|
warnings.push(
|
|
427
451
|
`E_STORE: retention could not remove ${candidate.runId}: ${(error as Error).message}`,
|
|
428
452
|
);
|