@xzzpig/pi-subagents 0.20.0 → 0.22.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 (144) hide show
  1. package/CHANGELOG.md +164 -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/fork-supervisor-routing.md +77 -0
  13. package/docs/missions.md +34 -17
  14. package/docs/models.md +1 -1
  15. package/docs/observability.md +10 -5
  16. package/docs/tool-reference.md +117 -84
  17. package/docs/watchdog.md +8 -6
  18. package/docs/workflows.md +16 -7
  19. package/index.ts +5 -0
  20. package/package.json +6 -3
  21. package/prompts/council.md +1 -1
  22. package/skills/pi-subagents/SKILL.md +1 -1
  23. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  24. package/skills/pi-subagents/references/execution-controls.md +16 -16
  25. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  26. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  27. package/src/agents/advertised-agent-prompt.ts +9 -1
  28. package/src/agents/agent-management.ts +4 -0
  29. package/src/agents/agent-memory.ts +3 -3
  30. package/src/agents/agent-scope.ts +4 -0
  31. package/src/agents/agent-serializer.ts +8 -1
  32. package/src/agents/agents.ts +191 -145
  33. package/src/api/preflight.ts +8 -4
  34. package/src/api/supervisor-routing.ts +196 -0
  35. package/src/extension/config.ts +21 -2
  36. package/src/extension/context-injection.ts +6 -1
  37. package/src/extension/control-notices.ts +1 -9
  38. package/src/extension/declaration-pinning.ts +164 -0
  39. package/src/extension/doctor.ts +7 -10
  40. package/src/extension/fanout-child.ts +7 -8
  41. package/src/extension/index.ts +143 -134
  42. package/src/extension/reply-workflow-script.ts +20 -11
  43. package/src/extension/rpc.ts +11 -6
  44. package/src/extension/schemas.ts +34 -30
  45. package/src/extension/subagent-guide.ts +86 -6
  46. package/src/extension/subagent-options.ts +47 -0
  47. package/src/extension/tool-activation.ts +3 -2
  48. package/src/extension/tool-description.ts +51 -68
  49. package/src/inspectors/actions.ts +37 -11
  50. package/src/inspectors/plugins.ts +3 -2
  51. package/src/inspectors/tmux/actions.ts +204 -0
  52. package/src/inspectors/tmux/client.ts +85 -0
  53. package/src/inspectors/tmux/plugin.ts +21 -0
  54. package/src/integrations/herdr-status.ts +18 -49
  55. package/src/integrations/program-status.ts +215 -0
  56. package/src/intercom/fork-supervisor-routing.ts +533 -0
  57. package/src/intercom/native-supervisor-channel.ts +152 -13
  58. package/src/intercom/result-intercom.ts +3 -2
  59. package/src/intercom/supervisor-ui.ts +2 -174
  60. package/src/missions/store.ts +25 -5
  61. package/src/profiles/profiles.ts +24 -21
  62. package/src/runs/background/active-async-capacity.ts +58 -8
  63. package/src/runs/background/async-execution.ts +143 -38
  64. package/src/runs/background/async-job-tracker.ts +11 -4
  65. package/src/runs/background/async-resume.ts +5 -2
  66. package/src/runs/background/await-async-run.ts +14 -9
  67. package/src/runs/background/binary-bootstrap.ts +2 -1
  68. package/src/runs/background/calendar-schedule.ts +90 -0
  69. package/src/runs/background/chain-root-attachment.ts +9 -5
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +16 -2
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-child-launch.ts +1 -0
  79. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  80. package/src/runs/background/scheduled-runs.ts +256 -61
  81. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  82. package/src/runs/background/subagent-runner.ts +32 -12
  83. package/src/runs/background/subagent-wait.ts +38 -19
  84. package/src/runs/background/terminal-run-index.ts +46 -1
  85. package/src/runs/background/wait-completions.ts +1 -0
  86. package/src/runs/background/wait-tool.ts +33 -23
  87. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  88. package/src/runs/foreground/async-stop-action.ts +48 -22
  89. package/src/runs/foreground/execution.ts +94 -52
  90. package/src/runs/foreground/foreground-history.ts +1 -0
  91. package/src/runs/foreground/subagent-executor.ts +232 -77
  92. package/src/runs/shared/child-commands.ts +2 -1
  93. package/src/runs/shared/child-hooks.ts +4 -3
  94. package/src/runs/shared/child-launch.ts +3 -0
  95. package/src/runs/shared/child-session.ts +41 -24
  96. package/src/runs/shared/child-tool-plan.ts +13 -26
  97. package/src/runs/shared/dynamic-fanout.ts +1 -1
  98. package/src/runs/shared/fork-command-result.ts +10 -0
  99. package/src/runs/shared/herdr-placed-run.ts +5 -4
  100. package/src/runs/shared/mcp-direct-tool-allowlist.ts +5 -3
  101. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  102. package/src/runs/shared/model-resolution.ts +30 -1
  103. package/src/runs/shared/nested-events.ts +5 -0
  104. package/src/runs/shared/parallel-handoff.ts +56 -8
  105. package/src/runs/shared/parallel-utils.ts +2 -0
  106. package/src/runs/shared/partial-output.ts +48 -0
  107. package/src/runs/shared/runner-launcher.ts +25 -0
  108. package/src/runs/shared/single-output.ts +53 -0
  109. package/src/runs/shared/structured-output.ts +14 -7
  110. package/src/runs/shared/subagent-control.ts +3 -3
  111. package/src/runs/shared/subagent-prompt-runtime.ts +47 -24
  112. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  113. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  114. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  115. package/src/runs/shared/worktree-lock.ts +29 -0
  116. package/src/runs/shared/worktree.ts +12 -1
  117. package/src/shared/atomic-json.ts +4 -2
  118. package/src/shared/edit-distance.ts +33 -0
  119. package/src/shared/file-lease.ts +74 -0
  120. package/src/shared/formatters.ts +1 -5
  121. package/src/shared/model-info.ts +22 -0
  122. package/src/shared/package-version.ts +17 -0
  123. package/src/shared/parent-wake.ts +79 -0
  124. package/src/shared/pruned-fork.ts +7 -1
  125. package/src/shared/runtime-module-path.ts +19 -0
  126. package/src/shared/settings-file-lease.ts +36 -0
  127. package/src/shared/types.ts +36 -2
  128. package/src/shared/utils.ts +8 -6
  129. package/src/slash/prompt-template-bridge.ts +21 -20
  130. package/src/slash/slash-commands.ts +3 -3
  131. package/src/slash/subagents-admin.ts +2 -1
  132. package/src/tui/fleet-native-transcript.ts +2 -0
  133. package/src/tui/fleet-transcript.ts +12 -3
  134. package/src/tui/fleet.ts +11 -8
  135. package/src/tui/render.ts +27 -19
  136. package/src/tui/subagent-messages.ts +305 -0
  137. package/src/watchdog/diff-tool.ts +2 -2
  138. package/src/watchdog/register-main.ts +2 -22
  139. package/src/watchdog/render.ts +2 -24
  140. package/src/watchdog/runtime.ts +6 -4
  141. package/src/watchdog/settings.ts +18 -13
  142. package/src/watchdog/tool-actions.ts +2 -2
  143. package/src/workflows/scripted-workflow.ts +20 -6
  144. package/src/workflows/workflow-resources.ts +11 -0
@@ -2,10 +2,11 @@ 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";
9
+ import type { SupervisorDispatcher } from "./fork-supervisor-routing.ts";
9
10
  import { writeAtomicJson } from "../shared/atomic-json.ts";
10
11
  import { shouldUseNativeFsWatch } from "../shared/watch-strategy.ts";
11
12
  import { MODEL_ONLY_TOOL } from "../shared/extension-context.ts";
@@ -88,6 +89,13 @@ interface NativeSupervisorChannelDeps {
88
89
  getChannelDirs?: () => { dirs: string[]; retire?: () => void };
89
90
  /** Retained scheduled states for the current runtime owner, never foreign owners. */
90
91
  getCurrentOwnerStates?: () => Iterable<SubagentState>;
92
+ parentWake?: Pick<ExtensionAPI, "sendMessage">;
93
+ /**
94
+ * Owner-side responder dispatcher. When a registered responder claims an ask,
95
+ * this channel skips the parent wake and detach emission for that ask and
96
+ * never lets a generic reply overwrite it. Unset means default behaviour.
97
+ */
98
+ supervisorDispatcher?: SupervisorDispatcher;
91
99
  platform?: NodeJS.Platform;
92
100
  watch?: SupervisorWatch;
93
101
  timers?: Pick<typeof globalThis, "setInterval" | "clearInterval" | "setImmediate" | "clearImmediate">;
@@ -176,8 +184,15 @@ async function waitForReply(channelDir: string, requestId: string, deadline: num
176
184
  while (Date.now() <= deadline) {
177
185
  if (signal?.aborted) throw new Error("Supervisor request cancelled.");
178
186
  if (fs.existsSync(file)) {
179
- const parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<SupervisorReply>;
180
- if (parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
187
+ let parsed: Partial<SupervisorReply> | undefined;
188
+ try {
189
+ parsed = JSON.parse(fs.readFileSync(file, "utf-8")) as Partial<SupervisorReply>;
190
+ } catch {
191
+ // A partially written or corrupt reply file must not crash the child;
192
+ // keep polling until the deadline instead.
193
+ parsed = undefined;
194
+ }
195
+ if (parsed && parsed.type === "subagent.supervisor.reply" && parsed.requestId === requestId && typeof parsed.message === "string") {
181
196
  return parsed as SupervisorReply;
182
197
  }
183
198
  }
@@ -511,7 +526,7 @@ function requestVisibleText(request: PendingSupervisorRequest): string {
511
526
  if (request.interview !== undefined) lines.push(JSON.stringify(request.interview, null, "\t"));
512
527
  }
513
528
  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.)" : ""}`);
529
+ 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
530
  return lines.join("\n").trimEnd();
516
531
  }
517
532
 
@@ -528,7 +543,11 @@ function writeReply(request: PendingSupervisorRequest, message: string): Supervi
528
543
  return reply;
529
544
  }
530
545
 
531
- function appendSupervisorReplyEntry(pi: ExtensionAPI, request: PendingSupervisorRequest, reply: SupervisorReply): void {
546
+ /** Internal: exported so the journal-failure content oracle can exercise the real boundary. */
547
+ export function appendSupervisorReplyEntry(pi: ExtensionAPI, request: PendingSupervisorRequest, reply: SupervisorReply): void {
548
+ // SAFETY: newer hosts expose appendEntry on ExtensionAPI while older SDK
549
+ // typings omit it. The narrowed shape is optional and every use below is
550
+ // guarded by a typeof check, so no unchecked property is read.
532
551
  const appendEntry = (pi as unknown as {
533
552
  appendEntry?: (customType: string, data?: SupervisorReplyEntryData) => void;
534
553
  }).appendEntry;
@@ -544,9 +563,10 @@ function appendSupervisorReplyEntry(pi: ExtensionAPI, request: PendingSupervisor
544
563
  message: reply.message,
545
564
  createdAt: reply.createdAt,
546
565
  });
547
- } catch (error) {
566
+ } catch {
548
567
  // The reply file is authoritative; a UI journal failure must not undo a delivered reply.
549
- console.error("Failed to journal native supervisor reply:", error);
568
+ // Fixed text only: an external exception body/stack must never reach diagnostics.
569
+ console.error("Failed to journal native supervisor reply: error details omitted");
550
570
  }
551
571
  }
552
572
 
@@ -584,7 +604,7 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
584
604
  }));
585
605
  }
586
606
 
587
- function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
607
+ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState, isClaimed: (requestId: string) => boolean = () => false): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
588
608
  return {
589
609
  name: NATIVE_SUPERVISOR_TOOL_NAME,
590
610
  ...MODEL_ONLY_TOOL,
@@ -600,15 +620,20 @@ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, Pendin
600
620
  return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
601
621
  }
602
622
  if (input.action === "pending" || input.action === "list") {
603
- const lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);
604
- return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(pending) } };
623
+ // Responder-managed asks are not the parent model's to answer.
624
+ const answerable = [...pending.values()].filter((request) => request.expectsReply && !isClaimed(request.id));
625
+ const lines = answerable.map(formatPendingLine);
626
+ return { content: [{ type: "text", text: lines.length ? lines.join("\n") : "No pending supervisor requests." }], details: { pending: publicPendingRequests(new Map(answerable.map((request) => [request.id, request]))) } };
605
627
  }
606
628
  if (input.action === "reply") {
607
629
  const request = resolvePendingRequest(pending, input);
630
+ if (isClaimed(request.id)) {
631
+ throw new Error(`Supervisor request ${request.id} is responder-managed; it can only be answered by its registered responder.`);
632
+ }
608
633
  const reply = writeReply(request, input.message ?? "");
609
634
  appendSupervisorReplyEntry(pi, request, reply);
610
- onLifecycle(request, "resolved");
611
635
  pending.delete(request.id);
636
+ onLifecycle(request, "resolved");
612
637
  clearForegroundSupervisorAttention(request, pending, state);
613
638
  return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
614
639
  }
@@ -636,6 +661,12 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
636
661
  return state;
637
662
  };
638
663
  const pending = new Map<string, PendingSupervisorRequest>();
664
+ // Asks claimed by a registered responder: never woken, never detached, never
665
+ // answered through the generic parent tool.
666
+ const claimedAsks = new Set<string>();
667
+ // One continuation and one warning per request; never auto-answer or loop.
668
+ const settleNotices = new Map<string, "reminded" | "warned" | "handled">();
669
+ let unsubscribeSettle: (() => void) | undefined;
639
670
  const requestCorrelations = new Map<string, SupervisorRequestCorrelation>();
640
671
  const correlationKey = (request: { runId: string; agent: string; childIndex: number; toolCallId?: string }): string | undefined => {
641
672
  if (!request.toolCallId) return undefined;
@@ -664,7 +695,10 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
664
695
  pruneRequestCorrelations();
665
696
  };
666
697
  const observeRequestLifecycle: SupervisorRequestLifecycleObserver = (request, lifecycle) => {
698
+ settleNotices.delete(request.id);
667
699
  if (lifecycle !== "wrong-session") rememberResolvedRequest(request);
700
+ if (lifecycle !== "pending") deps.supervisorDispatcher?.observe(request.id, lifecycle);
701
+ updateSettleSubscription();
668
702
  };
669
703
  const getSupervisorRequestState = (event: ControlEvent): SupervisorRequestState => {
670
704
  if (event.currentTool === "intercom" || event.index === undefined) return "unknown";
@@ -710,7 +744,25 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
710
744
  };
711
745
 
712
746
  const registerParentTools = (): void => {
713
- if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState));
747
+ if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState, (requestId) => claimedAsks.has(requestId)));
748
+ };
749
+
750
+ /**
751
+ * Write a responder's answer through the same file-authoritative path the
752
+ * native reply uses, after re-confirming the ask is still answerable.
753
+ */
754
+ const deliverClaimedReply = (request: PendingSupervisorRequest, message: string): void => {
755
+ if (!pending.has(request.id)) throw new Error(`Supervisor ask ${request.id} is no longer pending.`);
756
+ if (!requestMatchesOwner(request, state)) throw new Error(`Supervisor ask ${request.id} no longer belongs to the live owner session.`);
757
+ if (fs.existsSync(replyPath(request.channelDir, request.id))) throw new Error(`Supervisor ask ${request.id} already has a reply.`);
758
+ const now = Date.now();
759
+ if (request.expectsReply && now > requestExpiresAt(request, now)) throw new Error(`Supervisor ask ${request.id} has expired.`);
760
+ const reply = writeReply(request, message);
761
+ appendSupervisorReplyEntry(pi, request, reply);
762
+ pending.delete(request.id);
763
+ claimedAsks.delete(request.id);
764
+ observeRequestLifecycle(request, "resolved");
765
+ clearForegroundSupervisorAttention(request, pending, state);
714
766
  };
715
767
 
716
768
  const cleanupStaleChannelsIfDue = (): void => {
@@ -751,11 +803,30 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
751
803
  }
752
804
  rememberPendingRequest(request);
753
805
  pending.set(request.id, request);
806
+ updateSettleSubscription();
754
807
  markForegroundSupervisorAttention(request, state);
808
+ // Exclusive takeover: a registered responder claims this exact bound
809
+ // route before any parent wake or detach is emitted. A claim is final
810
+ // for this ask; failures inside the responder fail the audit closed
811
+ // instead of falling back to the default notification path.
812
+ const claimed = deps.supervisorDispatcher?.claim({
813
+ askId: request.id,
814
+ runId: request.runId,
815
+ agent: request.agent,
816
+ childIndex: request.childIndex,
817
+ reason: request.reason,
818
+ message: request.message,
819
+ ...(request.interview !== undefined ? { interview: request.interview } : {}),
820
+ ...(request.expiresAt !== undefined ? { deadlineAt: request.expiresAt } : {}),
821
+ }, (message) => deliverClaimedReply(request, message)) === true;
822
+ if (claimed) {
823
+ claimedAsks.add(request.id);
824
+ continue;
825
+ }
755
826
  // The ask is already queued above. A sendMessage failure (no UI, stale context) must not
756
827
  // lose it, and must not abort the loop before the remaining asks register.
757
828
  try {
758
- pi.sendMessage({
829
+ (deps.parentWake ?? pi).sendMessage({
759
830
  customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
760
831
  content: requestVisibleText(request),
761
832
  display: true,
@@ -785,6 +856,71 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
785
856
  if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
786
857
  }
787
858
  channels?.retire?.();
859
+ updateSettleSubscription();
860
+ };
861
+
862
+ const handleBeforeSettle = (event: AgentBeforeSettleEvent): AgentBeforeSettleEventResult | undefined => {
863
+ if (!started || event.outcome !== "completed")
864
+ return;
865
+ refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
866
+ if (event.continue || event.context.pendingMessages.length)
867
+ return;
868
+ const messages = event.context.contextMessages;
869
+ const requests = [...pending.values()].filter(request => {
870
+ if (claimedAsks.has(request.id)) return false;
871
+ if (!request.expectsReply || settleNotices.get(request.id) === "warned" || settleNotices.get(request.id) === "handled") return false;
872
+ const index = messages.findLastIndex(message => message.role === "custom"
873
+ && message.customType === SUPERVISOR_REQUEST_MESSAGE_TYPE
874
+ && (message.details as { requestId?: string } | undefined)?.requestId === request.id);
875
+ const acted = index !== -1 && messages.slice(index + 1).some(message => message.role === "assistant"
876
+ && message.content.some(part => part.type === "toolCall" || (part.type === "text" && part.text.trim())));
877
+ if (index === -1 || acted) {
878
+ settleNotices.set(request.id, "handled");
879
+ return false;
880
+ }
881
+ return true;
882
+ });
883
+ updateSettleSubscription();
884
+ if (!requests.length) return;
885
+ const unanswered = requests.filter(request => !settleNotices.has(request.id));
886
+ if (unanswered.length) {
887
+ for (const request of unanswered)
888
+ settleNotices.set(request.id, "reminded");
889
+ return {
890
+ entries: [...event.entries, {
891
+ type: "custom_message",
892
+ customType: "subagent-supervisor-unanswered",
893
+ 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.",
894
+ display: true,
895
+ details: { requestIds: requests.map(request => request.id) },
896
+ }],
897
+ continue: true,
898
+ };
899
+ }
900
+ const unflagged = requests.filter(request => settleNotices.get(request.id) !== "warned");
901
+ if (!unflagged.length)
902
+ return;
903
+ for (const request of unflagged)
904
+ settleNotices.set(request.id, "warned");
905
+ updateSettleSubscription();
906
+ return {
907
+ entries: [...event.entries, {
908
+ type: "custom_message",
909
+ customType: "subagent-supervisor-blocked",
910
+ 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\" }).",
911
+ display: true,
912
+ details: { blocked: true, requestIds: unflagged.map(request => request.id) },
913
+ }],
914
+ };
915
+ };
916
+ const updateSettleSubscription = (): void => {
917
+ const needed = started && [...pending.values()].some(request => request.expectsReply
918
+ && settleNotices.get(request.id) !== "warned" && settleNotices.get(request.id) !== "handled");
919
+ if (needed && !unsubscribeSettle) unsubscribeSettle = pi.on?.("agent_before_settle", handleBeforeSettle);
920
+ if (!needed) {
921
+ unsubscribeSettle?.();
922
+ unsubscribeSettle = undefined;
923
+ }
788
924
  };
789
925
 
790
926
  const startPolling = (): void => {
@@ -901,6 +1037,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
901
1037
  },
902
1038
  dispose: () => {
903
1039
  started = false;
1040
+ updateSettleSubscription();
904
1041
  try {
905
1042
  rootWatcher?.close();
906
1043
  } catch {
@@ -918,6 +1055,8 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
918
1055
  if (deferredWatcherRefresh) timers.clearImmediate(deferredWatcherRefresh);
919
1056
  deferredWatcherRefresh = undefined;
920
1057
  pending.clear();
1058
+ claimedAsks.clear();
1059
+ settleNotices.clear();
921
1060
  requestCorrelations.clear();
922
1061
  seenFiles.clear();
923
1062
  },
@@ -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,
@@ -5,6 +5,7 @@ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-a
5
5
  import { BUILTIN_AGENT_NAMES, validateOptionalMachine } from "../agents/agents.ts";
6
6
  import { getPiSpawnCommand } from "../runs/shared/pi-spawn.ts";
7
7
  import { findModelInfo, getSupportedThinkingLevels, splitKnownThinkingSuffix, toModelInfo } from "../shared/model-info.ts";
8
+ import { withSettingsFileLease } from "../shared/settings-file-lease.ts";
8
9
  import { getAgentDir } from "../shared/utils.ts";
9
10
 
10
11
  export const DEFAULT_PROVIDER_MODELS_MAX_AGE_DAYS = 7;
@@ -483,27 +484,29 @@ export function readSubagentProfile(name: string): { filePath: string; profile:
483
484
  export function applySubagentProfile(name: string): { filePath: string; settingsPath: string } {
484
485
  const { filePath, profile } = readSubagentProfile(name);
485
486
  const settingsPath = getUserSettingsPath();
486
- const settings = readSettingsFile(settingsPath);
487
- const existing = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
488
- ? settings.subagents as Record<string, unknown>
489
- : {};
490
- // A profile owns the complete agent mapping, but unrelated subagent settings
491
- // (notably disableBuiltins, modelScope, watchdog, etc.) survive profile switches.
492
- // Machine placement is not a model choice, so an existing pin survives a profile switch too.
493
- const agentOverrides: Record<string, ProfileAgentOverride> = { ...profile.subagents.agentOverrides };
494
- const existingOverrides = existing.agentOverrides && typeof existing.agentOverrides === "object" && !Array.isArray(existing.agentOverrides)
495
- ? existing.agentOverrides as Record<string, unknown>
496
- : {};
497
- for (const [name, value] of Object.entries(existingOverrides)) {
498
- const machine = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>).machine : undefined;
499
- if (typeof machine === "string" && agentOverrides[name]?.machine === undefined) agentOverrides[name] = { ...agentOverrides[name], machine };
500
- }
501
- settings.subagents = {
502
- ...existing,
503
- ...profile.subagents,
504
- agentOverrides,
505
- };
506
- writeJsonFile(settingsPath, settings);
487
+ withSettingsFileLease(settingsPath, () => {
488
+ const settings = readSettingsFile(settingsPath);
489
+ const existing = settings.subagents && typeof settings.subagents === "object" && !Array.isArray(settings.subagents)
490
+ ? settings.subagents as Record<string, unknown>
491
+ : {};
492
+ // A profile owns the complete agent mapping, but unrelated subagent settings
493
+ // (notably disableBuiltins, modelScope, watchdog, etc.) survive profile switches.
494
+ // Machine placement is not a model choice, so an existing pin survives a profile switch too.
495
+ const agentOverrides: Record<string, ProfileAgentOverride> = { ...profile.subagents.agentOverrides };
496
+ const existingOverrides = existing.agentOverrides && typeof existing.agentOverrides === "object" && !Array.isArray(existing.agentOverrides)
497
+ ? existing.agentOverrides as Record<string, unknown>
498
+ : {};
499
+ for (const [name, value] of Object.entries(existingOverrides)) {
500
+ const machine = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>).machine : undefined;
501
+ if (typeof machine === "string" && agentOverrides[name]?.machine === undefined) agentOverrides[name] = { ...agentOverrides[name], machine };
502
+ }
503
+ settings.subagents = {
504
+ ...existing,
505
+ ...profile.subagents,
506
+ agentOverrides,
507
+ };
508
+ writeJsonFile(settingsPath, settings);
509
+ });
507
510
  return { filePath, settingsPath };
508
511
  }
509
512