@xzzpig/pi-subagents 0.20.0 → 0.21.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.
Files changed (140) hide show
  1. package/CHANGELOG.md +154 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +72 -7
  9. package/docs/configuration.md +58 -7
  10. package/docs/extension-api.md +36 -11
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +34 -17
  13. package/docs/models.md +1 -1
  14. package/docs/observability.md +10 -5
  15. package/docs/tool-reference.md +117 -84
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +16 -7
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +191 -145
  32. package/src/api/preflight.ts +8 -4
  33. package/src/extension/config.ts +21 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +114 -132
  40. package/src/extension/reply-workflow-script.ts +20 -11
  41. package/src/extension/rpc.ts +11 -6
  42. package/src/extension/schemas.ts +34 -30
  43. package/src/extension/subagent-guide.ts +86 -6
  44. package/src/extension/subagent-options.ts +47 -0
  45. package/src/extension/tool-activation.ts +3 -2
  46. package/src/extension/tool-description.ts +51 -68
  47. package/src/inspectors/actions.ts +37 -11
  48. package/src/inspectors/plugins.ts +3 -2
  49. package/src/inspectors/tmux/actions.ts +204 -0
  50. package/src/inspectors/tmux/client.ts +85 -0
  51. package/src/inspectors/tmux/plugin.ts +21 -0
  52. package/src/integrations/herdr-status.ts +18 -49
  53. package/src/integrations/program-status.ts +215 -0
  54. package/src/intercom/native-supervisor-channel.ts +77 -4
  55. package/src/intercom/result-intercom.ts +3 -2
  56. package/src/intercom/supervisor-ui.ts +2 -174
  57. package/src/missions/store.ts +25 -5
  58. package/src/profiles/profiles.ts +24 -21
  59. package/src/runs/background/active-async-capacity.ts +58 -8
  60. package/src/runs/background/async-execution.ts +143 -38
  61. package/src/runs/background/async-job-tracker.ts +11 -4
  62. package/src/runs/background/async-resume.ts +5 -2
  63. package/src/runs/background/await-async-run.ts +14 -9
  64. package/src/runs/background/binary-bootstrap.ts +2 -1
  65. package/src/runs/background/calendar-schedule.ts +90 -0
  66. package/src/runs/background/chain-root-attachment.ts +9 -5
  67. package/src/runs/background/fleet-view.ts +5 -5
  68. package/src/runs/background/notify.ts +185 -12
  69. package/src/runs/background/result-files.ts +116 -5
  70. package/src/runs/background/result-watcher.ts +99 -66
  71. package/src/runs/background/resume-guidance.ts +2 -2
  72. package/src/runs/background/run-child-session.ts +16 -2
  73. package/src/runs/background/run-id-resolver.ts +8 -5
  74. package/src/runs/background/run-status.ts +21 -16
  75. package/src/runs/background/runner-child-launch.ts +1 -0
  76. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  77. package/src/runs/background/scheduled-runs.ts +256 -61
  78. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  79. package/src/runs/background/subagent-runner.ts +32 -12
  80. package/src/runs/background/subagent-wait.ts +38 -19
  81. package/src/runs/background/terminal-run-index.ts +46 -1
  82. package/src/runs/background/wait-completions.ts +1 -0
  83. package/src/runs/background/wait-tool.ts +33 -23
  84. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  85. package/src/runs/foreground/async-stop-action.ts +48 -22
  86. package/src/runs/foreground/execution.ts +94 -52
  87. package/src/runs/foreground/foreground-history.ts +1 -0
  88. package/src/runs/foreground/subagent-executor.ts +207 -77
  89. package/src/runs/shared/child-commands.ts +2 -1
  90. package/src/runs/shared/child-hooks.ts +4 -3
  91. package/src/runs/shared/child-launch.ts +3 -0
  92. package/src/runs/shared/child-session.ts +41 -24
  93. package/src/runs/shared/child-tool-plan.ts +13 -26
  94. package/src/runs/shared/dynamic-fanout.ts +1 -1
  95. package/src/runs/shared/fork-command-result.ts +10 -0
  96. package/src/runs/shared/herdr-placed-run.ts +5 -4
  97. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  98. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  99. package/src/runs/shared/model-resolution.ts +30 -1
  100. package/src/runs/shared/nested-events.ts +5 -0
  101. package/src/runs/shared/parallel-handoff.ts +56 -8
  102. package/src/runs/shared/parallel-utils.ts +2 -0
  103. package/src/runs/shared/partial-output.ts +48 -0
  104. package/src/runs/shared/runner-launcher.ts +25 -0
  105. package/src/runs/shared/single-output.ts +53 -0
  106. package/src/runs/shared/structured-output.ts +14 -7
  107. package/src/runs/shared/subagent-control.ts +3 -3
  108. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  109. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  110. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  111. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  112. package/src/runs/shared/worktree-lock.ts +29 -0
  113. package/src/runs/shared/worktree.ts +12 -1
  114. package/src/shared/atomic-json.ts +4 -2
  115. package/src/shared/edit-distance.ts +33 -0
  116. package/src/shared/file-lease.ts +74 -0
  117. package/src/shared/formatters.ts +1 -5
  118. package/src/shared/model-info.ts +22 -0
  119. package/src/shared/package-version.ts +17 -0
  120. package/src/shared/parent-wake.ts +79 -0
  121. package/src/shared/pruned-fork.ts +7 -1
  122. package/src/shared/runtime-module-path.ts +19 -0
  123. package/src/shared/settings-file-lease.ts +36 -0
  124. package/src/shared/types.ts +36 -2
  125. package/src/shared/utils.ts +8 -6
  126. package/src/slash/slash-commands.ts +3 -3
  127. package/src/slash/subagents-admin.ts +2 -1
  128. package/src/tui/fleet-native-transcript.ts +2 -0
  129. package/src/tui/fleet-transcript.ts +12 -3
  130. package/src/tui/fleet.ts +11 -8
  131. package/src/tui/render.ts +27 -19
  132. package/src/tui/subagent-messages.ts +305 -0
  133. package/src/watchdog/diff-tool.ts +2 -2
  134. package/src/watchdog/register-main.ts +2 -22
  135. package/src/watchdog/render.ts +2 -24
  136. package/src/watchdog/runtime.ts +6 -4
  137. package/src/watchdog/settings.ts +18 -13
  138. package/src/watchdog/tool-actions.ts +2 -2
  139. package/src/workflows/scripted-workflow.ts +20 -6
  140. package/src/workflows/workflow-resources.ts +11 -0
@@ -0,0 +1,215 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { AsyncJobState } from "../shared/types.ts";
3
+ import { sanitizeDisplayText } from "../shared/display-text.ts";
4
+
5
+ /**
6
+ * Reports each subagent run to the terminal with OSC 7501, the Program Status Protocol
7
+ * (https://www.superlogical.com/rex/docs/build/program-status). Pi owns the root record;
8
+ * runs live under `subagents/`.
9
+ */
10
+
11
+ type ProgramState = "working" | "blocked" | "done" | "error" | "idle";
12
+
13
+ const ID_ROOT = "subagents";
14
+ const MAX_RECORDS = 64;
15
+ const MAX_MSG_BYTES = 2048;
16
+ const MAX_TITLE_BYTES = 192;
17
+ const RUN_SEGMENT_CHARS = 12;
18
+ // 32-character segment limit, minus the run part and the `.` separator.
19
+ const MAX_KEY_CHARS = 32 - RUN_SEGMENT_CHARS - 1;
20
+
21
+ export interface ProgramStatusReporterOptions {
22
+ /** `programStatus` from the user config; only `false` turns it off. */
23
+ enabled: boolean;
24
+ getJobs: () => Iterable<AsyncJobState>;
25
+ /** Pending native supervisor requests that expect a reply. */
26
+ getPendingRequests: () => Iterable<{ id: string; runId: string }>;
27
+ write?: (data: string) => void;
28
+ isTTY?: boolean;
29
+ env?: Record<string, string | undefined>;
30
+ }
31
+
32
+ export interface ProgramStatusReporter {
33
+ /** Only the interactive TUI session on a real terminal reports. */
34
+ sessionStarted(input: { hasUI: boolean; mode?: string }): void;
35
+ sync(): void;
36
+ agentStarted(): void;
37
+ agentSettled(): void;
38
+ /**
39
+ * Stops reporting. Unless Pi is quitting, clears every record sent, since the runtime that replaces
40
+ * this one cannot clear them. On quit, finished records stay for the user, as the spec intends.
41
+ */
42
+ dispose(shutdownReason?: string): void;
43
+ }
44
+
45
+ // `.` is left out so it can only appear as the run/key separator.
46
+ function segment(value: string): string {
47
+ return value.replace(/[^A-Za-z0-9_+-]/g, "-");
48
+ }
49
+
50
+ function runSegment(runId: string): string {
51
+ return segment(runId.replace(/-/g, "").slice(0, RUN_SEGMENT_CHARS));
52
+ }
53
+
54
+ // A clear removes the record's descendants too, so workflow children are siblings of their run,
55
+ // never nested under another record of ours: `subagents/<run>.<key>`, one segment of at most 32 characters.
56
+ // A key that needs any change gets a hash of the original, so keys differing only in replaced characters stay distinct.
57
+ function keySegment(key: string): string {
58
+ if (key.length <= MAX_KEY_CHARS && /^[A-Za-z0-9_+-]+$/.test(key)) return key;
59
+ return `${segment(key).slice(0, 12)}-${createHash("sha1").update(key).digest("hex").slice(0, 6)}`;
60
+ }
61
+
62
+ function recordId(job: AsyncJobState): string | undefined {
63
+ if (job.parentWorkflowRunId && job.workflowKey) {
64
+ const parent = runSegment(job.parentWorkflowRunId);
65
+ return parent ? `${ID_ROOT}/${parent}.${keySegment(job.workflowKey)}` : undefined;
66
+ }
67
+ const run = runSegment(job.asyncId);
68
+ return run ? `${ID_ROOT}/${run}` : undefined;
69
+ }
70
+
71
+ function programState(job: AsyncJobState, blocked: boolean): ProgramState {
72
+ switch (job.status) {
73
+ case "queued":
74
+ case "running":
75
+ return blocked ? "blocked" : "working";
76
+ case "complete":
77
+ return "done";
78
+ case "failed":
79
+ case "partial":
80
+ case "rejected":
81
+ return "error";
82
+ case "stopped":
83
+ case "paused":
84
+ return "idle";
85
+ }
86
+ }
87
+
88
+ function jobLabel(job: AsyncJobState): string {
89
+ if (job.workflowKey) return job.workflowKey;
90
+ if (job.mode === "workflow") return "workflow";
91
+ const agents = [...new Set(job.agents ?? [])];
92
+ if (agents.length === 0) return "subagent";
93
+ return agents.length > 3 ? `${agents.slice(0, 3).join(", ")} +${agents.length - 3}` : agents.join(", ");
94
+ }
95
+
96
+ // Prompt text never goes into the record: it is shown outside the terminal grid.
97
+ function message(job: AsyncJobState, state: ProgramState): string {
98
+ switch (state) {
99
+ case "working":
100
+ return job.currentTool ? `Running ${job.currentTool}` : "Running";
101
+ case "blocked":
102
+ return "Waiting for a reply";
103
+ case "done":
104
+ return "Finished";
105
+ case "error":
106
+ return job.status === "partial" ? "Finished with failures" : job.status === "rejected" ? "Rejected" : "Failed";
107
+ case "idle":
108
+ return job.status === "paused" ? "Paused" : "Stopped";
109
+ }
110
+ }
111
+
112
+ function encodeText(text: string, maxBytes: number): string {
113
+ let bytes = Buffer.from(sanitizeDisplayText(text), "utf-8");
114
+ if (bytes.length > maxBytes) {
115
+ let end = maxBytes;
116
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end--;
117
+ bytes = bytes.subarray(0, end);
118
+ }
119
+ return bytes.toString("base64");
120
+ }
121
+
122
+ function programStatusReport(fields: { state: ProgramState | "clear"; id: string; kind?: "question"; title?: string; msg?: string }): string {
123
+ const pairs = [`state=${fields.state}`, `id=${fields.id}`];
124
+ if (fields.state !== "clear") pairs.push("app=pi-subagents");
125
+ if (fields.kind) pairs.push(`kind=${fields.kind}`);
126
+ if (fields.title !== undefined) pairs.push(`title=${encodeText(fields.title, MAX_TITLE_BYTES)}`);
127
+ if (fields.msg !== undefined) pairs.push(`msg=${encodeText(fields.msg, MAX_MSG_BYTES)}`);
128
+ return `\x1b]7501;${pairs.join(":")}\x1b\\`;
129
+ }
130
+
131
+ export function registerProgramStatusReporter(options: ProgramStatusReporterOptions): ProgramStatusReporter {
132
+ const write = options.write ?? ((data: string) => { process.stdout.write(data); });
133
+ const env = options.env ?? process.env;
134
+ const isTTY = options.isTTY ?? process.stdout.isTTY === true;
135
+ const sent = new Map<string, string>();
136
+ let active = false;
137
+ let parentIdle = true;
138
+ // A request counts as waiting on the user only after the parent settled without answering it.
139
+ let unansweredAtSettle = new Set<string>();
140
+ // Pi clears every OSC 7501 record when it suspends on Ctrl+Z and re-reports only its own root
141
+ // record on resume, so the records this extension shows are sent again.
142
+ const resend = (): void => {
143
+ if (!active) return;
144
+ for (const report of sent.values()) write(report);
145
+ };
146
+ let listeningForResume = false;
147
+
148
+ // The shown records are recomputed from the current jobs on every sync: active runs first, then
149
+ // finished ones, each most recently updated first, up to the cap. Only the difference is written.
150
+ const sync = (): void => {
151
+ if (!active) return;
152
+ const blockedRuns = new Set<string>();
153
+ if (parentIdle) {
154
+ for (const request of options.getPendingRequests()) {
155
+ if (unansweredAtSettle.has(request.id)) blockedRuns.add(request.runId);
156
+ }
157
+ }
158
+ const candidates: Array<{ id: string; report: string; active: boolean; updatedAt: number }> = [];
159
+ for (const job of options.getJobs()) {
160
+ const id = recordId(job);
161
+ if (!id) continue;
162
+ const state = programState(job, blockedRuns.has(job.asyncId));
163
+ const report = programStatusReport({ state, id, ...(state === "blocked" ? { kind: "question" as const } : {}), title: jobLabel(job), msg: message(job, state) });
164
+ candidates.push({ id, report, active: state === "working" || state === "blocked", updatedAt: job.updatedAt ?? job.startedAt ?? 0 });
165
+ }
166
+ candidates.sort((left, right) => Number(right.active) - Number(left.active) || right.updatedAt - left.updatedAt || (left.id < right.id ? -1 : left.id > right.id ? 1 : 0));
167
+ const desired = new Map<string, string>();
168
+ for (const candidate of candidates) {
169
+ if (desired.size === MAX_RECORDS) break;
170
+ if (!desired.has(candidate.id)) desired.set(candidate.id, candidate.report);
171
+ }
172
+ for (const id of sent.keys()) {
173
+ if (desired.has(id)) continue;
174
+ sent.delete(id);
175
+ write(programStatusReport({ state: "clear", id }));
176
+ }
177
+ for (const [id, report] of desired) {
178
+ if (sent.get(id) === report) continue;
179
+ sent.set(id, report);
180
+ write(report);
181
+ }
182
+ };
183
+
184
+ return {
185
+ sessionStarted({ hasUI, mode }) {
186
+ active = options.enabled && hasUI && mode === "tui" && isTTY && env.TERM !== "dumb" && env.PI_PROGRAM_STATUS !== "0";
187
+ if (active && !listeningForResume && process.platform !== "win32") {
188
+ process.on("SIGCONT", resend);
189
+ listeningForResume = true;
190
+ }
191
+ sync();
192
+ },
193
+ sync,
194
+ agentStarted() {
195
+ parentIdle = false;
196
+ sync();
197
+ },
198
+ agentSettled() {
199
+ parentIdle = true;
200
+ unansweredAtSettle = new Set([...options.getPendingRequests()].map((request) => request.id));
201
+ sync();
202
+ },
203
+ dispose(shutdownReason) {
204
+ if (active && shutdownReason !== "quit") {
205
+ for (const id of sent.keys()) write(programStatusReport({ state: "clear", id }));
206
+ }
207
+ sent.clear();
208
+ active = false;
209
+ if (listeningForResume) {
210
+ process.off("SIGCONT", resend);
211
+ listeningForResume = false;
212
+ }
213
+ },
214
+ };
215
+ }
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
5
- import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
5
+ import type { AgentBeforeSettleEvent, AgentBeforeSettleEventResult, ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
6
6
  import { Type } from "typebox";
7
7
  import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-config.ts";
8
8
  import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
@@ -88,6 +88,7 @@ interface NativeSupervisorChannelDeps {
88
88
  getChannelDirs?: () => { dirs: string[]; retire?: () => void };
89
89
  /** Retained scheduled states for the current runtime owner, never foreign owners. */
90
90
  getCurrentOwnerStates?: () => Iterable<SubagentState>;
91
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
91
92
  platform?: NodeJS.Platform;
92
93
  watch?: SupervisorWatch;
93
94
  timers?: Pick<typeof globalThis, "setInterval" | "clearInterval" | "setImmediate" | "clearImmediate">;
@@ -511,7 +512,7 @@ function requestVisibleText(request: PendingSupervisorRequest): string {
511
512
  if (request.interview !== undefined) lines.push(JSON.stringify(request.interview, null, "\t"));
512
513
  }
513
514
  if (request.expectsReply) lines.push("", `Reply with: ${supervisorReplyHint(request.id)}`);
514
- lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, index: ${request.childIndex}, message: "..." })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
515
+ lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, message: "...", options: { index: ${request.childIndex} } })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
515
516
  return lines.join("\n").trimEnd();
516
517
  }
517
518
 
@@ -607,8 +608,8 @@ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, Pendin
607
608
  const request = resolvePendingRequest(pending, input);
608
609
  const reply = writeReply(request, input.message ?? "");
609
610
  appendSupervisorReplyEntry(pi, request, reply);
610
- onLifecycle(request, "resolved");
611
611
  pending.delete(request.id);
612
+ onLifecycle(request, "resolved");
612
613
  clearForegroundSupervisorAttention(request, pending, state);
613
614
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
614
615
  }
@@ -636,6 +637,9 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
636
637
  return state;
637
638
  };
638
639
  const pending = new Map<string, PendingSupervisorRequest>();
640
+ // One continuation and one warning per request; never auto-answer or loop.
641
+ const settleNotices = new Map<string, "reminded" | "warned" | "handled">();
642
+ let unsubscribeSettle: (() => void) | undefined;
639
643
  const requestCorrelations = new Map<string, SupervisorRequestCorrelation>();
640
644
  const correlationKey = (request: { runId: string; agent: string; childIndex: number; toolCallId?: string }): string | undefined => {
641
645
  if (!request.toolCallId) return undefined;
@@ -664,7 +668,9 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
664
668
  pruneRequestCorrelations();
665
669
  };
666
670
  const observeRequestLifecycle: SupervisorRequestLifecycleObserver = (request, lifecycle) => {
671
+ settleNotices.delete(request.id);
667
672
  if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
673
+ updateSettleSubscription();
668
674
  };
669
675
  const getSupervisorRequestState = (event: ControlEvent): SupervisorRequestState => {
670
676
  if (event.currentTool === "intercom" || event.index === undefined) return "unknown";
@@ -751,11 +757,12 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
751
757
  }
752
758
  rememberPendingRequest(request);
753
759
  pending.set(request.id, request);
760
+ updateSettleSubscription();
754
761
  markForegroundSupervisorAttention(request, state);
755
762
  // The ask is already queued above. A sendMessage failure (no UI, stale context) must not
756
763
  // lose it, and must not abort the loop before the remaining asks register.
757
764
  try {
758
- pi.sendMessage({
765
+ (deps.parentWake ?? pi).sendMessage({
759
766
  customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
760
767
  content: requestVisibleText(request),
761
768
  display: true,
@@ -785,6 +792,70 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
785
792
  if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
786
793
  }
787
794
  channels?.retire?.();
795
+ updateSettleSubscription();
796
+ };
797
+
798
+ const handleBeforeSettle = (event: AgentBeforeSettleEvent): AgentBeforeSettleEventResult | undefined => {
799
+ if (!started || event.outcome !== "completed")
800
+ return;
801
+ refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
802
+ if (event.continue || event.context.pendingMessages.length)
803
+ return;
804
+ const messages = event.context.contextMessages;
805
+ const requests = [...pending.values()].filter(request => {
806
+ if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
807
+ const index = messages.findLastIndex(message => message.role === "custom"
808
+ && message.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE
809
+ && (message.details as { requestId?: string } | undefined)?.requestId === request.id);
810
+ const acted = index !== -1 && messages.slice(index + 1).some(message => message.role === "assistant"
811
+ && message.content.some(part => part.type === "toolCall" || (part.type === "text" && part.text.trim())));
812
+ if (index === -1 || acted) {
813
+ settleNotices.set(request.id, "handled");
814
+ return false;
815
+ }
816
+ return true;
817
+ });
818
+ updateSettleSubscription();
819
+ if (!requests.length) return;
820
+ const unanswered = requests.filter(request => !settleNotices.has(request.id));
821
+ if (unanswered.length) {
822
+ for (const request of unanswered)
823
+ settleNotices.set(request.id, "reminded");
824
+ return {
825
+ entries: [...event.entries, {
826
+ type: "custom_message",
827
+ customType: "subagent-supervisor-unanswered",
828
+ content: "Silent supervisor wake. Pending request IDs: " + requests.map(request => request.id).join(", ") + ". Check subagent_supervisor({ action: \"pending\" }) and reply within existing authority, or explicitly ask the user for approval. Do not auto-approve.",
829
+ display: true,
830
+ details: { requestIds: requests.map(request => request.id) },
831
+ }],
832
+ continue: true,
833
+ };
834
+ }
835
+ const unflagged = requests.filter(request => settleNotices.get(request.id) !== "warned");
836
+ if (!unflagged.length)
837
+ return;
838
+ for (const request of unflagged)
839
+ settleNotices.set(request.id, "warned");
840
+ updateSettleSubscription();
841
+ return {
842
+ entries: [...event.entries, {
843
+ type: "custom_message",
844
+ customType: "subagent-supervisor-blocked",
845
+ content: "BLOCKED: unanswered supervisor request IDs: " + unflagged.map(request => request.id).join(", ") + ". Reminder budget exhausted; no reply or approval sent. Inspect subagent_supervisor({ action: \"pending\" }).",
846
+ display: true,
847
+ details: { blocked: true, requestIds: unflagged.map(request => request.id) },
848
+ }],
849
+ };
850
+ };
851
+ const updateSettleSubscription = (): void => {
852
+ const needed = started && [...pending.values()].some(request => request.expectsReply
853
+ && settleNotices.get(request.id) !== "warned" && settleNotices.get(request.id) !== "handled");
854
+ if (needed && !unsubscribeSettle) unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
855
+ if (!needed) {
856
+ unsubscribeSettle?.();
857
+ unsubscribeSettle = undefined;
858
+ }
788
859
  };
789
860
 
790
861
  const startPolling = (): void => {
@@ -901,6 +972,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
901
972
  },
902
973
  dispose: () => {
903
974
  started = false;
975
+ updateSettleSubscription();
904
976
  try {
905
977
  rootWatcher?.close();
906
978
  } catch {
@@ -918,6 +990,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
918
990
  if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
919
991
  deferredWatcherRefresh = undefined;
920
992
  pending.clear();
993
+ settleNotices.clear();
921
994
  requestCorrelations.clear();
922
995
  seenFiles.clear();
923
996
  },
@@ -231,7 +231,7 @@ function asyncResumeGuidance(input: {
231
231
  }
232
232
  if (resumable.length > 0) {
233
233
  const firstIndex = resumable[0]?.index ?? input.children.indexOf(resumable[0]!);
234
- return `Revive child: subagent({ action: "resume", id: "${input.asyncId}", index: ${firstIndex}, message: "..." })`;
234
+ return `Revive child: subagent({ action: "resume", id: "${input.asyncId}", message: "...", options: { index: ${firstIndex} } })`;
235
235
  }
236
236
  return "Resume: unavailable; no child session file was persisted.";
237
237
  }
@@ -279,7 +279,7 @@ function formatSubagentResultIntercomMessage(input: {
279
279
  for (let index = 0; index < input.children.length; index++) {
280
280
  const child = input.children[index]!;
281
281
  lines.push("");
282
- lines.push(`${index + 1}. ${child.agent} — process ${child.status} · output ${child.outputState ?? "unknown"}`);
282
+ lines.push(`${index + 1}. ${child.agent} — process ${child.status} · output ${child.outputState ?? "unknown"}${child.outputPartial ? " (partial)" : ""}`);
283
283
  if (child.intercomTarget) lines.push(`${input.source === "async" ? "Previous intercom target" : "Run intercom target"}: ${child.intercomTarget}`);
284
284
  if (child.artifactPath) lines.push(`Output artifact: ${child.artifactPath}`);
285
285
  if (child.sessionPath) lines.push(`Session: ${child.sessionPath}`);
@@ -295,6 +295,7 @@ export function buildSubagentResultIntercomPayload(input: GroupedResultIntercomM
295
295
  const children = input.children.map((child) => ({
296
296
  ...child,
297
297
  outputState: child.outputState ?? "unknown",
298
+ ...(child.outputPartial ? { outputPartial: true } : {}),
298
299
  summary: child.summary.trim() || "(no output)",
299
300
  children: compactNestedResultChildren(child.children),
300
301
  }));
@@ -1,7 +1,3 @@
1
- import type { EntryRenderOptions, MessageRenderOptions, Theme } from "@earendil-works/pi-coding-agent";
2
- import { truncateToWidth, visibleWidth, wrapTextWithAnsi, type Component } from "@earendil-works/pi-tui";
3
- import { safeTerminalText } from "../shared/display-text.ts";
4
-
5
1
  export const SUPERVISOR_REQUEST_MESSAGE_TYPE = "subagent_supervisor_request";
6
2
  export const SUPERVISOR_REPLY_ENTRY_TYPE = "subagent_supervisor_reply";
7
3
 
@@ -32,68 +28,10 @@ export interface SupervisorReplyEntryData {
32
28
  createdAt: number;
33
29
  }
34
30
 
35
- interface SupervisorMessageLike {
36
- content: unknown;
37
- details?: unknown;
38
- }
39
-
40
- interface SupervisorEntryLike {
41
- data?: unknown;
42
- }
43
-
44
- const MAX_FIELD_CHARS = 512;
45
- const MAX_BODY_CHARS = 8_000;
46
- const MAX_INTERVIEW_CHARS = 4_000;
47
- const MAX_RENDER_LINES = 36;
48
- const TRUNCATION_MARKER = "[truncated]";
49
-
50
31
  export function supervisorReplyHint(requestId: string): string {
51
32
  return `subagent_supervisor({ action: "reply", replyTo: "${requestId}", message: "..." })`;
52
33
  }
53
34
 
54
- function boundedText(value: string, maxChars: number): string {
55
- const safe = safeTerminalText(value);
56
- if (safe.length <= maxChars) return safe;
57
- const prefixLength = Math.max(0, maxChars - TRUNCATION_MARKER.length - 1);
58
- let prefix = "";
59
- for (const character of safe) {
60
- if (prefix.length + character.length > prefixLength) break;
61
- prefix += character;
62
- }
63
- return `${prefix} ${TRUNCATION_MARKER}`;
64
- }
65
-
66
- function displayText(value: string, maxChars: number, expanded: boolean): string {
67
- return expanded ? safeTerminalText(value) : boundedText(value, maxChars);
68
- }
69
-
70
- function boundedField(value: unknown, fallback = "unknown"): string {
71
- return boundedText(typeof value === "string" ? value : value === undefined ? fallback : String(value), MAX_FIELD_CHARS);
72
- }
73
-
74
- function contentText(content: unknown): string {
75
- if (typeof content === "string") return content;
76
- if (!Array.isArray(content)) return "";
77
- return content
78
- .map((part) => {
79
- if (!part || typeof part !== "object") return "";
80
- const text = (part as { text?: unknown }).text;
81
- return typeof text === "string" ? text : "";
82
- })
83
- .filter(Boolean)
84
- .join("\n");
85
- }
86
-
87
- function interviewText(interview: unknown, expanded: boolean): string {
88
- let serialized: string;
89
- try {
90
- serialized = JSON.stringify(interview, null, 2) ?? String(interview);
91
- } catch {
92
- serialized = "[unavailable]";
93
- }
94
- return displayText(serialized, MAX_INTERVIEW_CHARS, expanded);
95
- }
96
-
97
35
  function isRecord(value: unknown): value is Record<string, unknown> {
98
36
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
99
37
  }
@@ -106,7 +44,7 @@ function optionalString(value: unknown): boolean {
106
44
  return value === undefined || typeof value === "string";
107
45
  }
108
46
 
109
- function requestDetails(value: unknown): SupervisorRequestMessageDetails | undefined {
47
+ export function parseSupervisorRequestDetails(value: unknown): SupervisorRequestMessageDetails | undefined {
110
48
  if (!isRecord(value)) return undefined;
111
49
  if (!optionalString(value.id) || !optionalString(value.requestId) || !optionalString(value.replyHint) || !optionalString(value.requestBody) || !optionalString(value.runId) || !optionalString(value.agent) || !optionalString(value.childTarget)) return undefined;
112
50
  if (value.reason !== undefined && !isSupervisorReason(value.reason)) return undefined;
@@ -115,7 +53,7 @@ function requestDetails(value: unknown): SupervisorRequestMessageDetails | undef
115
53
  return value;
116
54
  }
117
55
 
118
- function replyData(value: unknown): SupervisorReplyEntryData | undefined {
56
+ export function parseSupervisorReplyData(value: unknown): SupervisorReplyEntryData | undefined {
119
57
  if (!isRecord(value)) return undefined;
120
58
  if (typeof value.requestId !== "string" || typeof value.runId !== "string" || typeof value.agent !== "string" || typeof value.message !== "string") return undefined;
121
59
  if (value.reason !== undefined && !isSupervisorReason(value.reason)) return undefined;
@@ -132,113 +70,3 @@ function replyData(value: unknown): SupervisorReplyEntryData | undefined {
132
70
  createdAt: value.createdAt,
133
71
  };
134
72
  }
135
-
136
- function withRequestId(details: SupervisorRequestMessageDetails): string {
137
- return boundedField(details.requestId ?? details.id);
138
- }
139
-
140
- function requestHeading(reason: SupervisorReason | undefined): string {
141
- if (reason === "interview_request") return "⚠ Supervisor interview request";
142
- if (reason === "progress_update") return "ℹ Supervisor progress update";
143
- return "⚠ Supervisor decision request";
144
- }
145
-
146
- function requestLines(message: SupervisorMessageLike, details: SupervisorRequestMessageDetails, expanded: boolean): string[] {
147
- const requestId = withRequestId(details);
148
- const lines = [
149
- `Reason: ${boundedField(details.reason)}`,
150
- `Run: ${boundedField(details.runId)}`,
151
- `Agent: ${boundedField(details.agent)}`,
152
- `Child index: ${boundedField(details.childIndex)}`,
153
- ];
154
- if (details.childTarget) lines.push(`Child target: ${boundedField(details.childTarget)}`);
155
- lines.push(`Request ID: ${requestId}`);
156
- if (details.expectsReply) lines.push(`Reply with: ${displayText(details.replyHint ?? supervisorReplyHint(requestId), MAX_BODY_CHARS, expanded)}`);
157
- lines.push("", "Request:", displayText((details.requestBody ?? contentText(message.content)) || "(no request body)", MAX_BODY_CHARS, expanded));
158
- if (details.interview !== undefined) lines.push("", "Interview shape:", interviewText(details.interview, expanded));
159
- return lines;
160
- }
161
-
162
- function replyLines(data: SupervisorReplyEntryData, expanded: boolean): string[] {
163
- const requestId = boundedField(data.requestId);
164
- const lines = [
165
- ...(data.reason ? [`Reason: ${boundedField(data.reason)}`] : []),
166
- `Run: ${boundedField(data.runId)}`,
167
- `Agent: ${boundedField(data.agent)}`,
168
- `Child index: ${boundedField(data.childIndex)}`,
169
- ];
170
- if (data.childTarget) lines.push(`Child target: ${boundedField(data.childTarget)}`);
171
- lines.push(`Reply to: ${requestId}`, "", "Reply:", displayText(data.message || "(empty reply)", MAX_BODY_CHARS, expanded));
172
- return lines;
173
- }
174
-
175
- function renderCard(lines: string[], heading: string, theme: Theme, width: number, expanded: boolean): string[] {
176
- const safeWidth = Math.max(0, Math.floor(width));
177
- if (safeWidth < 3) return [truncateToWidth(heading, safeWidth, "")];
178
- const bodyWidth = safeWidth - 2;
179
- const headerText = truncateToWidth(` ${heading} `, bodyWidth, "");
180
- const headerPadding = Math.max(0, bodyWidth - visibleWidth(headerText));
181
- const border = (text: string) => theme.fg("accent", text);
182
- const rendered = [border(`╭${headerText}${"─".repeat(headerPadding)}╮`)];
183
- let hidden = false;
184
- let interiorLines = 0;
185
- for (const line of lines) {
186
- const wrapped = wrapTextWithAnsi(line, Math.max(1, bodyWidth));
187
- for (const wrappedLine of wrapped.length > 0 ? wrapped : [""]) {
188
- if (!expanded && interiorLines >= MAX_RENDER_LINES) {
189
- hidden = true;
190
- break;
191
- }
192
- const text = truncateToWidth(wrappedLine, bodyWidth, "");
193
- rendered.push(border(`│${text}${" ".repeat(Math.max(0, bodyWidth - visibleWidth(text)))}│`));
194
- interiorLines++;
195
- }
196
- if (hidden) break;
197
- }
198
- if (hidden) {
199
- const text = truncateToWidth(TRUNCATION_MARKER, bodyWidth, "");
200
- rendered.push(border(`│${text}${" ".repeat(Math.max(0, bodyWidth - visibleWidth(text)))}│`));
201
- }
202
- rendered.push(border(`╰${"─".repeat(bodyWidth)}╯`));
203
- return rendered;
204
- }
205
-
206
- class SupervisorCardComponent implements Component {
207
- private readonly expanded: boolean;
208
- private readonly heading: string;
209
- private readonly lines: string[];
210
- private readonly theme: Theme;
211
-
212
- constructor(heading: string, lines: string[], theme: Theme, expanded: boolean) {
213
- this.expanded = expanded;
214
- this.heading = heading;
215
- this.lines = lines;
216
- this.theme = theme;
217
- }
218
-
219
- invalidate(): void {}
220
-
221
- render(width: number): string[] {
222
- return renderCard(this.lines, this.heading, this.theme, width, this.expanded);
223
- }
224
- }
225
-
226
- export function renderSupervisorRequest(
227
- message: SupervisorMessageLike,
228
- options: MessageRenderOptions,
229
- theme: Theme,
230
- ): Component | undefined {
231
- const details = requestDetails(message.details);
232
- if (!details) return undefined;
233
- return new SupervisorCardComponent(requestHeading(details.reason), requestLines(message, details, options.expanded), theme, options.expanded);
234
- }
235
-
236
- export function renderSupervisorReply(
237
- entry: SupervisorEntryLike,
238
- options: EntryRenderOptions,
239
- theme: Theme,
240
- ): Component | undefined {
241
- const data = replyData(entry.data);
242
- if (!data) return undefined;
243
- return new SupervisorCardComponent("↩ Supervisor reply to child", replyLines(data, options.expanded), theme, options.expanded);
244
- }
@@ -282,18 +282,38 @@ export function validateMissionStoreConfig(value: unknown, label = "config.missi
282
282
  };
283
283
  }
284
284
 
285
+ // Resolve the existing prefix and keep the missing components in the store key.
286
+ function canonicalProjectRoot(root: string): string {
287
+ const missing: string[] = [];
288
+ let current = root;
289
+ for (;;) {
290
+ try {
291
+ return path.join(fs.realpathSync.native(current), ...missing.reverse());
292
+ } catch (error) {
293
+ // Only a missing component walks upward; EACCES, ELOOP and the rest must surface.
294
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
295
+ const parent = path.dirname(current);
296
+ if (parent === current) return root;
297
+ missing.push(path.basename(current));
298
+ current = parent;
299
+ }
300
+ }
301
+ }
302
+
285
303
  export function resolveMissionStoreLocation(input: {
286
304
  projectRoot: string;
287
305
  config?: MissionStoreConfig;
288
306
  agentDir?: string;
289
307
  }): MissionStoreLocation {
290
- const projectRoot = path.resolve(input.projectRoot);
308
+ const givenRoot = path.resolve(input.projectRoot);
309
+ const configuredDir = input.config?.directory;
310
+ // The default store is keyed by a hash of the root, so two paths to one directory
311
+ // must hash the same. Configured paths keep expanding against the root as given.
312
+ const projectRoot = configuredDir ? givenRoot : canonicalProjectRoot(givenRoot);
291
313
  const agentDir = input.agentDir ?? getAgentDir();
292
- const missionDir = input.config?.directory
293
- ? expandConfiguredPath(input.config.directory, projectRoot)
294
- : projectMissionDirectory(agentDir, projectRoot);
314
+ const missionDir = configuredDir ? expandConfiguredPath(configuredDir, givenRoot) : projectMissionDirectory(agentDir, projectRoot);
295
315
  const globalIndexDir = input.config?.globalIndexDir
296
- ? expandConfiguredPath(input.config.globalIndexDir, projectRoot)
316
+ ? expandConfiguredPath(input.config.globalIndexDir, givenRoot)
297
317
  : path.join(agentDir, "missions", "index");
298
318
  return {
299
319
  projectRoot,