pi-subagents 0.88.1 → 0.89.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +51 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  5. package/bundle/{chunk-5EMPFFO4.js → chunk-4FFKVLBG.js} +4 -4
  6. package/bundle/{chunk-L4YY2TOE.js → chunk-5TXWZB73.js} +1 -1
  7. package/bundle/{chunk-ZJ2BT5TI.js → chunk-6D54VW3E.js} +56 -34
  8. package/bundle/{chunk-YDZ7BZD5.js → chunk-77VQEATI.js} +1 -1
  9. package/bundle/{chunk-7OX6O7DQ.js → chunk-BERAWSQQ.js} +5 -5
  10. package/bundle/{chunk-LV3CPYXJ.js → chunk-C22YEYFZ.js} +4 -4
  11. package/bundle/{chunk-VTUUOLM4.js → chunk-CASL47ST.js} +34 -5
  12. package/bundle/{chunk-YQSTGPEU.js → chunk-F6PTAPQ3.js} +75 -32
  13. package/bundle/{chunk-FLNDHNPE.js → chunk-IGZTXGPG.js} +98 -29
  14. package/bundle/{chunk-CPSUJHZE.js → chunk-KCDPTXHT.js} +39 -10
  15. package/bundle/{chunk-PCZEQQAQ.js → chunk-LUNVS6KP.js} +26 -15
  16. package/bundle/{chunk-4MVDMA5C.js → chunk-LWH7IGI3.js} +21 -7
  17. package/bundle/{chunk-DSHQWGHO.js → chunk-MIX3MCIF.js} +96 -96
  18. package/bundle/{chunk-2DIEL4WG.js → chunk-OUM6SEVD.js} +2 -2
  19. package/bundle/{chunk-XIA5GSEU.js → chunk-Q4VH72JI.js} +2 -2
  20. package/bundle/{chunk-D32H53HM.js → chunk-R3NH5XAL.js} +1 -1
  21. package/bundle/{chunk-6OWNDN7R.js → chunk-ROJH7KPK.js} +2 -2
  22. package/bundle/{chunk-4ZQBZDF3.js → chunk-SG3NCWZW.js} +86 -20
  23. package/bundle/{chunk-KXW62VBU.js → chunk-SWGB2P5J.js} +1 -1
  24. package/bundle/{chunk-N6TAAIB3.js → chunk-TDXVQPZW.js} +5 -5
  25. package/bundle/{chunk-6CG2VAG4.js → chunk-TRN65L4F.js} +1 -1
  26. package/bundle/{chunk-GDR2ILWY.js → chunk-TXC7WIPL.js} +51 -22
  27. package/bundle/{chunk-PYKBTBY6.js → chunk-URKQZHVH.js} +9 -9
  28. package/bundle/{chunk-W6HIYD2Z.js → chunk-UUW7P6KJ.js} +1 -1
  29. package/bundle/{chunk-CYKNHFXB.js → chunk-VEEUXJDO.js} +1 -1
  30. package/bundle/{chunk-47ZN7NKR.js → chunk-YJIU5WF4.js} +1 -1
  31. package/bundle/{chunk-RMZAAXIR.js → chunk-YLU5JFW2.js} +2 -2
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +2 -2
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +10 -4
  38. package/docs/configuration.md +2 -0
  39. package/docs/extension-api.md +1 -1
  40. package/docs/tool-reference.md +1 -1
  41. package/docs/workflows.md +5 -3
  42. package/package.json +1 -1
  43. package/src/extension/herdr-pi-bridge.js +79 -23
  44. package/src/extension/schemas.js +1 -1
  45. package/src/extension/subagent-options.js +5 -0
  46. package/src/intercom/result-intercom.js +3 -2
  47. package/src/runs/background/async-job-tracker.js +85 -9
  48. package/src/runs/background/async-status.d.ts +2 -0
  49. package/src/runs/background/async-status.js +8 -3
  50. package/src/runs/background/notify.d.ts +3 -0
  51. package/src/runs/background/notify.js +7 -2
  52. package/src/runs/background/run-status.js +3 -2
  53. package/src/runs/background/runner-child-launch.js +1 -0
  54. package/src/runs/background/subagent-runner.js +11 -8
  55. package/src/runs/foreground/execution.js +8 -7
  56. package/src/runs/foreground/subagent-executor.js +31 -5
  57. package/src/runs/shared/child-launch.d.ts +2 -0
  58. package/src/runs/shared/child-launch.js +1 -1
  59. package/src/runs/shared/child-session.d.ts +2 -1
  60. package/src/runs/shared/herdr-connection.d.ts +6 -0
  61. package/src/runs/shared/herdr-connection.js +11 -1
  62. package/src/runs/shared/herdr-machine.d.ts +2 -2
  63. package/src/runs/shared/herdr-machine.js +49 -22
  64. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  65. package/src/runs/shared/herdr-pane-host.js +48 -33
  66. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  67. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  68. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  69. package/src/runs/shared/herdr-placed-run.js +10 -8
  70. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  71. package/src/runs/shared/kept-branch-text.js +24 -0
  72. package/src/runs/shared/local-machine-access.d.ts +4 -1
  73. package/src/runs/shared/local-machine-access.js +6 -3
  74. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  75. package/src/runs/shared/mutation-evidence.js +18 -2
  76. package/src/runs/shared/parallel-handoff.js +19 -7
  77. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  78. package/src/runs/shared/placed-run-owner.js +15 -7
  79. package/src/runs/shared/rex-machine.d.ts +7 -3
  80. package/src/runs/shared/rex-machine.js +12 -9
  81. package/src/runs/shared/rex-pane-host.js +7 -27
  82. package/src/runs/shared/single-output.js +2 -2
  83. package/src/runs/shared/subagent-prompt-runtime.js +34 -0
  84. package/src/runs/shared/tool-availability.d.ts +4 -0
  85. package/src/runs/shared/tool-availability.js +7 -0
  86. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  87. package/src/runs/shared/worktree.d.ts +4 -14
  88. package/src/runs/shared/worktree.js +38 -8
  89. package/src/shared/types.d.ts +26 -2
  90. package/src/shared/utils.d.ts +2 -0
  91. package/src/shared/utils.js +9 -0
  92. package/src/workflows/workflow-child-summary.d.ts +2 -1
  93. package/src/workflows/workflow-child-summary.js +14 -6
@@ -14,20 +14,20 @@ import {
14
14
  resolveCurrentSessionId,
15
15
  resolveWatchdogReviewModel,
16
16
  startWatchdogDiffBaselineCapture
17
- } from "./chunk-N6TAAIB3.js";
17
+ } from "./chunk-TDXVQPZW.js";
18
18
  import {
19
19
  agentStreamOptions,
20
20
  opencodeSessionHeaders
21
- } from "./chunk-4ZQBZDF3.js";
21
+ } from "./chunk-SG3NCWZW.js";
22
22
  import {
23
23
  registerNativeSupervisorClient
24
- } from "./chunk-CYKNHFXB.js";
24
+ } from "./chunk-VEEUXJDO.js";
25
25
  import {
26
26
  MODEL_ONLY_TOOL
27
27
  } from "./chunk-HXRB42AF.js";
28
28
  import {
29
29
  inheritedNestedRouteOf
30
- } from "./chunk-CPSUJHZE.js";
30
+ } from "./chunk-KCDPTXHT.js";
31
31
  import {
32
32
  CHILD_WATCHDOG_STATUS_EVENT,
33
33
  DEFAULT_WAIT_TOOL_NAME,
@@ -46,7 +46,7 @@ import {
46
46
  toolBudgetSoftNudge,
47
47
  validateAcceptanceReport,
48
48
  validateStructuredOutputValue
49
- } from "./chunk-4MVDMA5C.js";
49
+ } from "./chunk-LWH7IGI3.js";
50
50
  import {
51
51
  INTERCOM_SESSION_IDENTITY_EVENT
52
52
  } from "./chunk-JEZOSEWG.js";
@@ -84,6 +84,13 @@ function projectRuntimeAcknowledgedExtensions(ids) {
84
84
  // src/runs/shared/tool-availability.ts
85
85
  function formatChildToolDiagnostic(diagnostic, options = {}) {
86
86
  const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
87
+ if (diagnostic.undeclared?.length) {
88
+ const uncallable = diagnostic.uncallable?.length ? ` and added ${diagnostic.uncallable.join(", ")}, which this child cannot call` : "";
89
+ return [
90
+ `${subject} declares tools: ${diagnostic.required.join(", ")}, but an extension loaded in this child replaced the tools sent to the model: it left out ${diagnostic.undeclared.join(", ")}${uncallable}.`,
91
+ "The `tools` field is a strict allowlist. Set `extensions: []` or list only the extensions this child needs, or omit `tools` to use that extension's tool surface."
92
+ ].join("\n");
93
+ }
87
94
  if (options.host === "parent") {
88
95
  return [
89
96
  `${subject} ran as a foreground child, which never loads the parent's ambient extensions, and these child tools were unavailable: ${diagnostic.missing.join(", ")}.`,
@@ -533,7 +540,29 @@ function filterChildPromptOptions(options, inherited) {
533
540
  function rewritesChildPrompt(config) {
534
541
  return config.inheritProjectContext !== void 0 || config.inheritGlobalContext !== void 0 || config.inheritSkills !== void 0 || Boolean(config.fanoutChild);
535
542
  }
543
+ function registerDeclaredToolCheck(pi, config, required) {
544
+ pi.on("context_with_system", (event, ctx) => {
545
+ const declared = new Set(getCurrentTools(event.messages).map((tool) => tool.name));
546
+ if (required.every((name) => declared.has(name))) return void 0;
547
+ const active = new Set(pi.getActiveTools());
548
+ const undeclared = required.filter((name) => active.has(name) && !declared.has(name));
549
+ if (undeclared.length === 0) return void 0;
550
+ const registered = new Set(pi.getAllTools().map((tool) => tool.name));
551
+ const uncallable = config.forkCacheKey ? [] : [...declared].filter((name) => !active.has(name));
552
+ config.toolDiagnostic?.({
553
+ ...config.agent ? { agent: config.agent } : {},
554
+ required: [...required],
555
+ available: [...registered],
556
+ missing: [],
557
+ undeclared,
558
+ ...uncallable.length > 0 ? { uncallable } : {}
559
+ });
560
+ ctx.abort();
561
+ return void 0;
562
+ });
563
+ }
536
564
  function registerSubagentPromptBoundary(pi, config) {
565
+ if (config.requiredTools) registerDeclaredToolCheck(pi, config, config.requiredTools);
537
566
  if (!rewritesChildPrompt(config)) return;
538
567
  if (config.forkCacheKey) return;
539
568
  pi.on("before_agent_start", (event) => {
@@ -1,33 +1,34 @@
1
1
  import {
2
2
  rewriteSubagentPrompt
3
- } from "./chunk-VTUUOLM4.js";
3
+ } from "./chunk-CASL47ST.js";
4
4
  import {
5
5
  package_default
6
- } from "./chunk-6CG2VAG4.js";
6
+ } from "./chunk-TRN65L4F.js";
7
7
  import {
8
8
  WATCHDOG_DIFF_TOOL_NAME,
9
9
  captureWatchdogDiffBaseline,
10
10
  createWatchdogDiffTool
11
- } from "./chunk-N6TAAIB3.js";
12
- import "./chunk-4ZQBZDF3.js";
13
- import "./chunk-CYKNHFXB.js";
11
+ } from "./chunk-TDXVQPZW.js";
12
+ import "./chunk-SG3NCWZW.js";
13
+ import "./chunk-VEEUXJDO.js";
14
14
  import {
15
15
  MODEL_ONLY_TOOL
16
16
  } from "./chunk-HXRB42AF.js";
17
17
  import "./chunk-W2BZS6UC.js";
18
18
  import {
19
19
  appendAgentRefinementOverlay
20
- } from "./chunk-XIA5GSEU.js";
21
- import "./chunk-CPSUJHZE.js";
20
+ } from "./chunk-Q4VH72JI.js";
21
+ import "./chunk-KCDPTXHT.js";
22
22
  import "./chunk-NIXWDZZV.js";
23
- import "./chunk-47ZN7NKR.js";
23
+ import "./chunk-YJIU5WF4.js";
24
24
  import "./chunk-7F6RKT6W.js";
25
25
  import {
26
26
  assertNoToolModifierEntries
27
- } from "./chunk-D32H53HM.js";
27
+ } from "./chunk-R3NH5XAL.js";
28
28
  import "./chunk-YARY7JWU.js";
29
- import "./chunk-YDZ7BZD5.js";
29
+ import "./chunk-77VQEATI.js";
30
30
  import {
31
+ HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES,
31
32
  HERDR_PI_MAX_FRAME_BYTES,
32
33
  HERDR_PI_PROTOCOL,
33
34
  HERDR_PI_RUNTIME_DIR_ENV,
@@ -35,7 +36,7 @@ import {
35
36
  HerdrPiFrameDecoder,
36
37
  encodeHerdrPiFrame,
37
38
  validateHerdrPiRunId
38
- } from "./chunk-4QFZZV3O.js";
39
+ } from "./chunk-4AL6LDBY.js";
39
40
  import "./chunk-XA3DY6UG.js";
40
41
  import {
41
42
  buildAgentMemoryInjection,
@@ -43,7 +44,7 @@ import {
43
44
  discoverAgents,
44
45
  resolveExistingReadPaths,
45
46
  resolveSkills
46
- } from "./chunk-4MVDMA5C.js";
47
+ } from "./chunk-LWH7IGI3.js";
47
48
  import "./chunk-JEZOSEWG.js";
48
49
  import "./chunk-YFCK7H2S.js";
49
50
  import "./chunk-QXASAHIA.js";
@@ -63,6 +64,32 @@ function gitEvidence(cwd) {
63
64
  const dirty = run(["status", "--porcelain"]);
64
65
  return { ...head.status === 0 ? { head: head.stdout.trim() } : {}, ...branch.status === 0 ? { branch: branch.stdout.trim() } : {}, dirty: Boolean(dirty.stdout.trim()) };
65
66
  }
67
+ var TOOL_ARGS_FRAME_BUDGET = 64 * 1024;
68
+ function boundedToolArgs(args) {
69
+ if (!args || typeof args !== "object" || Array.isArray(args) || Buffer.byteLength(JSON.stringify(args)) <= TOOL_ARGS_FRAME_BUDGET) return args;
70
+ const shortened = Object.fromEntries(Object.entries(args).flatMap(([key, value]) => typeof value === "string" ? [[key, value.slice(0, 4096)]] : typeof value === "number" || typeof value === "boolean" ? [[key, value]] : []));
71
+ return Buffer.byteLength(JSON.stringify(shortened)) <= TOOL_ARGS_FRAME_BUDGET ? shortened : {};
72
+ }
73
+ var MESSAGE_FRAME_BUDGET = HERDR_PI_MAX_FRAME_BYTES - 64 * 1024;
74
+ var fitsMessageBudget = (value) => Buffer.byteLength(JSON.stringify(value)) <= MESSAGE_FRAME_BUDGET;
75
+ var omittedText = (what, bytes) => `[${what} omitted by the pi-subagents bridge: ${bytes} bytes did not fit in one bridge frame]`;
76
+ function boundedMessage(message) {
77
+ if (fitsMessageBudget(message)) return message;
78
+ const record = message;
79
+ const content = Array.isArray(record.content) ? record.content.map((block) => {
80
+ if (block.type === "image") return { type: "text", text: omittedText(`Image (${String(block.mimeType)})`, Buffer.byteLength(String(block.data))) };
81
+ if (block.type === "text" && typeof block.text === "string" && block.text.length > 65536) return { type: "text", text: `${block.text.slice(0, 65536)}
82
+ ${omittedText("The rest of this text", Buffer.byteLength(block.text.slice(65536)))}` };
83
+ if (block.type === "thinking" && typeof block.thinking === "string") return { type: "thinking", thinking: block.thinking.length > 4096 ? `${block.thinking.slice(0, 4096)}
84
+ ${omittedText("The rest of this thinking", Buffer.byteLength(block.thinking.slice(4096)))}` : block.thinking };
85
+ if (block.type === "toolCall") return { ...block, arguments: boundedToolArgs(block.arguments) };
86
+ return block;
87
+ }) : record.content;
88
+ const shrunk = { ...record, content, details: void 0 };
89
+ if (fitsMessageBudget(shrunk)) return shrunk;
90
+ const kept = Object.fromEntries(["role", "toolCallId", "toolName", "isError", "api", "provider", "model", "usage", "stopReason", "timestamp"].filter((key) => key in record).map((key) => [key, record[key]]));
91
+ return { ...kept, ...typeof record.errorMessage === "string" ? { errorMessage: record.errorMessage.slice(0, 4096) } : {}, content: [{ type: "text", text: omittedText("This message", Buffer.byteLength(JSON.stringify(message))) }] };
92
+ }
66
93
  function resolveRemoteHerdrResources(cwd, resources, remoteDefaultTools = []) {
67
94
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || resources.skills?.some((name) => !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)) || resources.toolCeiling?.some((name) => !/^[A-Za-z0-9_-]{1,64}$/u.test(name)) || resources.reads !== void 0 && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"))) throw new Error("Remote logical resource names are invalid.");
68
95
  const discovered = discoverAgents(cwd, "both").agents.filter((agent2) => agent2.name === resources.agent || agent2.aliases?.includes(resources.agent));
@@ -89,18 +116,10 @@ function registerHerdrPiBridge(pi) {
89
116
  const runId = validateHerdrPiRunId(process.env[HERDR_PI_RUN_ENV]);
90
117
  const runDir = process.env[HERDR_PI_RUNTIME_DIR_ENV];
91
118
  if (!runDir || !path.isAbsolute(runDir) || fs.lstatSync(runDir).isSymbolicLink()) throw new Error("Herdr bridge runtime directory was not authoritatively provisioned.");
92
- fs.chmodSync(runDir, 448);
93
119
  const socketPath = path.join(runDir, "bridge.sock");
94
120
  const manifestPath = path.join(runDir, "manifest.json");
95
- for (const candidate of [socketPath, manifestPath]) {
96
- try {
97
- const stat = fs.lstatSync(candidate);
98
- if (stat.isSymbolicLink()) throw new Error(`Refusing symlink at '${candidate}'.`);
99
- fs.rmSync(candidate, { force: true });
100
- } catch (error) {
101
- if (error.code !== "ENOENT") throw error;
102
- }
103
- }
121
+ const claims = globalThis[/* @__PURE__ */ Symbol.for("pi-subagents.herdr-bridge-claims")] ??= /* @__PURE__ */ new Set();
122
+ let claimed = false;
104
123
  let client;
105
124
  let context;
106
125
  let nativeSessionId;
@@ -115,8 +134,10 @@ function registerHerdrPiBridge(pi) {
115
134
  let journalBytes = 0;
116
135
  const journal = [];
117
136
  const send = (frame) => {
118
- const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: ++evidenceCursor };
137
+ const record = { protocol: HERDR_PI_PROTOCOL, runId, ...frame, cursor: evidenceCursor + 1 };
119
138
  const size = Buffer.byteLength(JSON.stringify(record));
139
+ if (size >= HERDR_PI_MAX_FRAME_BYTES) throw new Error(`pi-subagents bridge frame '${frame.type}' is ${size} bytes, over the ${HERDR_PI_MAX_FRAME_BYTES}-byte limit.`);
140
+ evidenceCursor++;
120
141
  journal.push(record);
121
142
  journalBytes += size;
122
143
  while (journal.length > 512 || journalBytes > 8 * 1024 * 1024) {
@@ -126,6 +147,7 @@ function registerHerdrPiBridge(pi) {
126
147
  if (!client || client.destroyed) return;
127
148
  client.write(encodeHerdrPiFrame(record));
128
149
  };
150
+ const sendReady = (ctx) => send({ type: "ready", packageVersion: package_default.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : void 0, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
129
151
  const sessionId = (ctx) => ctx.sessionManager?.getSessionId?.();
130
152
  pi.registerTool({
131
153
  name: "contact_supervisor",
@@ -166,7 +188,7 @@ ${answer}` }], details };
166
188
  api.sendUserMessage(request.text ?? "");
167
189
  } else if (request.operation === "steer") api.sendUserMessage(request.text ?? "", { deliverAs: "steer" });
168
190
  else if (request.operation === "follow-up") api.sendUserMessage(request.text ?? "", { deliverAs: "followUp" });
169
- else if (request.operation === "abort") api.abort();
191
+ else if (request.operation === "abort") ctx.abort();
170
192
  else {
171
193
  const entry = request.supervisorId ? supervisor.get(request.supervisorId) : void 0;
172
194
  if (!entry) throw new Error("Unknown supervisor request.");
@@ -188,23 +210,44 @@ ${answer}` }], details };
188
210
  ${resolvedSystemPrompt}` } : void 0;
189
211
  });
190
212
  on("session_start", (_event, ctx) => {
213
+ if (claims.has(runDir)) return;
191
214
  context = ctx;
192
215
  nativeSessionId = sessionId(ctx);
193
216
  if (!nativeSessionId) throw new Error("Pane-native Pi bridge requires a persisted native session identity.");
217
+ claims.add(runDir);
218
+ claimed = true;
219
+ fs.chmodSync(runDir, 448);
220
+ for (const candidate of [socketPath, manifestPath]) {
221
+ try {
222
+ const stat = fs.lstatSync(candidate);
223
+ if (stat.isSymbolicLink()) throw new Error(`Refusing symlink at '${candidate}'.`);
224
+ fs.rmSync(candidate, { force: true });
225
+ } catch (error) {
226
+ if (error.code !== "ENOENT") throw error;
227
+ }
228
+ }
229
+ server.listen(socketPath, () => {
230
+ fs.chmodSync(socketPath, 384);
231
+ });
194
232
  fs.writeFileSync(manifestPath, JSON.stringify({ protocol: HERDR_PI_PROTOCOL, packageVersion: package_default.version, runId, socketPath, nativeSessionId, pid: process.pid }), { mode: 384, flag: "wx" });
195
- send({ type: "ready", packageVersion: package_default.version, nativeSessionId, sessionFile: ctx.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: ctx.model?.provider && ctx.model.id ? `${ctx.model.provider}/${ctx.model.id}` : void 0, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
233
+ sendReady(ctx);
196
234
  });
197
235
  on("message_end", (event) => {
198
- const message = event.message;
199
- if (message?.role === "assistant") finalAssistant = message;
236
+ const message = boundedMessage(event.message);
237
+ if (message.role === "assistant") finalAssistant = message;
200
238
  send({ type: "event", requestId: activeRequestId, event: { ...event, message }, nativeSessionId });
201
239
  });
240
+ on("tool_execution_start", (event) => send({ type: "event", requestId: activeRequestId, event: { type: "tool_execution_start", toolCallId: event.toolCallId, toolName: event.toolName, args: boundedToolArgs(event.args) }, nativeSessionId }));
241
+ on("tool_execution_end", (event) => send({ type: "event", requestId: activeRequestId, event: { type: "tool_execution_end", toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError }, nativeSessionId }));
202
242
  on("agent_settled", (_event, ctx) => {
203
243
  const requestId = activeRequestId;
204
244
  send({ type: "settled", requestId, nativeSessionId, idle: ctx.isIdle(), pending: ctx.hasPendingMessages(), finalAssistant, finalGit: gitEvidence(process.cwd()) });
205
245
  if (ctx.isIdle() && !ctx.hasPendingMessages()) activeRequestId = void 0;
206
246
  });
207
247
  on("session_shutdown", () => {
248
+ if (!claimed) return;
249
+ claimed = false;
250
+ claims.delete(runDir);
208
251
  server.close();
209
252
  client?.destroy();
210
253
  try {
@@ -243,9 +286,12 @@ ${resolvedSystemPrompt}` } : void 0;
243
286
  const invalidSkills = resources.skills !== void 0 && (!Array.isArray(resources.skills) || resources.skills.some((name) => typeof name !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(name)));
244
287
  const invalidReads = resources.reads !== void 0 && resources.reads !== false && (!Array.isArray(resources.reads) || resources.reads.some((name) => typeof name !== "string"));
245
288
  if (typeof resources.agent !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(resources.agent) || invalidSkills || invalidReads) throw new Error("Remote logical resource names are invalid.");
289
+ const acceptancePrompt = resources.acceptancePrompt;
290
+ if (acceptancePrompt !== void 0 && (typeof acceptancePrompt !== "string" || Buffer.byteLength(acceptancePrompt) > HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES)) throw new Error("Bridge acceptance instructions are invalid or too large.");
246
291
  const resolved = resolveRemoteHerdrResources(process.cwd(), { agent: resources.agent, ...resources.skills ? { skills: resources.skills } : {}, ...resources.toolCeiling ? { toolCeiling: resources.toolCeiling } : {}, ...resources.reads !== void 0 ? { reads: resources.reads } : {} }, context ? pi.getActiveTools() : []);
247
- resolvedSystemPrompt = resolved.systemPrompt;
248
292
  resolvedContextPolicy = resolved;
293
+ resolvedSystemPrompt = acceptancePrompt ? `${resolved.systemPrompt}
294
+ ${acceptancePrompt}` : resolved.systemPrompt;
249
295
  if (resolved.tools.includes(WATCHDOG_DIFF_TOOL_NAME) && !pi.getAllTools().some((tool) => tool.name === WATCHDOG_DIFF_TOOL_NAME)) pi.registerTool(createWatchdogDiffTool(captureWatchdogDiffBaseline(process.cwd()), { workingTreeAtLaunch: true }));
250
296
  pi.setActiveTools(resolved.tools);
251
297
  const acknowledged = context ? pi.getActiveTools() : [];
@@ -275,10 +321,7 @@ ${resolvedSystemPrompt}` } : void 0;
275
321
  socket.on("close", () => {
276
322
  if (client === socket) client = void 0;
277
323
  });
278
- if (context && nativeSessionId) send({ type: "ready", packageVersion: package_default.version, nativeSessionId, sessionFile: context.sessionManager?.getSessionFile?.(), cwd: process.cwd(), tools: pi.getActiveTools(), model: context.model?.provider && context.model.id ? `${context.model.provider}/${context.model.id}` : void 0, configured, activeRequestId, evidenceCursor, evidenceFloor: journal[0]?.cursor ?? evidenceCursor + 1, initialGit: gitEvidence(process.cwd()) });
279
- });
280
- server.listen(socketPath, () => {
281
- fs.chmodSync(socketPath, 384);
324
+ if (context && nativeSessionId) sendReady(context);
282
325
  });
283
326
  }
284
327
  export {
@@ -10,10 +10,10 @@ import {
10
10
  setInlineWorkflowCoverage,
11
11
  setMainThinkingLevelSource,
12
12
  widgetRenderKey
13
- } from "./chunk-5EMPFFO4.js";
13
+ } from "./chunk-4FFKVLBG.js";
14
14
  import {
15
15
  package_default
16
- } from "./chunk-6CG2VAG4.js";
16
+ } from "./chunk-TRN65L4F.js";
17
17
  import {
18
18
  EXTERNAL_JOB_BRIDGE_REQUEST_DIR,
19
19
  REVIVAL_ORIGIN_FILE,
@@ -66,7 +66,7 @@ import {
66
66
  takeCompactionAbort,
67
67
  workflowResumeClaimState,
68
68
  workflowResumeRefusal
69
- } from "./chunk-PCZEQQAQ.js";
69
+ } from "./chunk-LUNVS6KP.js";
70
70
  import {
71
71
  SUBAGENT_CHILD_ENV,
72
72
  SUBAGENT_PARENT_SESSION_ENV,
@@ -86,14 +86,14 @@ import {
86
86
  resolvePiSessionId,
87
87
  resolveWaitToolConfig,
88
88
  setDeclarationPinning
89
- } from "./chunk-N6TAAIB3.js";
89
+ } from "./chunk-TDXVQPZW.js";
90
90
  import {
91
91
  deliverAsyncRunStop,
92
92
  ownerConfirmedDead,
93
93
  readSessionMessagesTail,
94
94
  resolveSubagentRunId,
95
95
  restoreForegroundRunHistory
96
- } from "./chunk-LV3CPYXJ.js";
96
+ } from "./chunk-C22YEYFZ.js";
97
97
  import {
98
98
  ASYNC_STATUS_SNAPSHOT_KIND,
99
99
  ASYNC_STATUS_SNAPSHOT_VERSION,
@@ -108,8 +108,9 @@ import {
108
108
  resolveAsyncRunLocation,
109
109
  resolveAsyncStatusChild,
110
110
  runLaunchDir,
111
- stopStoppableAsyncStatusChildren
112
- } from "./chunk-4ZQBZDF3.js";
111
+ stopStoppableAsyncStatusChildren,
112
+ summarizeAsyncStatus
113
+ } from "./chunk-SG3NCWZW.js";
113
114
  import {
114
115
  CONTACT_SUPERVISOR_TOOL_NAME,
115
116
  NATIVE_SUPERVISOR_TOOL_NAME,
@@ -119,7 +120,7 @@ import {
119
120
  parseSupervisorReplyData,
120
121
  parseSupervisorRequestDetails,
121
122
  topLevelSupervisorTool
122
- } from "./chunk-CYKNHFXB.js";
123
+ } from "./chunk-VEEUXJDO.js";
123
124
  import {
124
125
  MODEL_ONLY_TOOL,
125
126
  canRenderComponents,
@@ -145,7 +146,7 @@ import {
145
146
  resolveDisabledFeatureSurface,
146
147
  resolveMaxActiveAsyncRunsPerSession,
147
148
  resolveScheduledStoreRoot
148
- } from "./chunk-RMZAAXIR.js";
149
+ } from "./chunk-YLU5JFW2.js";
149
150
  import {
150
151
  ACTIVE_RUN_INDEX_DIR,
151
152
  MissionNotFoundError,
@@ -196,28 +197,28 @@ import {
196
197
  withWorkflowChildRunModel,
197
198
  writeAsyncResultFile,
198
199
  writeResultIndexForData
199
- } from "./chunk-CPSUJHZE.js";
200
- import "./chunk-W6HIYD2Z.js";
200
+ } from "./chunk-KCDPTXHT.js";
201
+ import "./chunk-UUW7P6KJ.js";
201
202
  import {
202
203
  shouldUseNativeFsWatch
203
204
  } from "./chunk-NIXWDZZV.js";
204
205
  import {
205
206
  validateIntercomBridgeConfig
206
- } from "./chunk-47ZN7NKR.js";
207
+ } from "./chunk-YJIU5WF4.js";
207
208
  import "./chunk-7F6RKT6W.js";
208
- import "./chunk-D32H53HM.js";
209
+ import "./chunk-R3NH5XAL.js";
209
210
  import "./chunk-YARY7JWU.js";
210
211
  import {
211
212
  listHerdrProjectPaneRoots,
212
213
  restoreHerdrProjectPaneSnapshots
213
- } from "./chunk-2DIEL4WG.js";
214
+ } from "./chunk-OUM6SEVD.js";
214
215
  import "./chunk-7J4ZXMY7.js";
215
216
  import {
216
217
  cleanupAllArtifactDirs,
217
218
  cleanupOldArtifacts,
218
219
  getArtifactPaths,
219
220
  getArtifactsDir
220
- } from "./chunk-YDZ7BZD5.js";
221
+ } from "./chunk-77VQEATI.js";
221
222
  import {
222
223
  listBackgroundWorkProviders
223
224
  } from "./chunk-XA3DY6UG.js";
@@ -225,12 +226,12 @@ import "./chunk-YYREO77V.js";
225
226
  import "./chunk-UKG4V45O.js";
226
227
  import {
227
228
  registerRuntimeAgentEventListener
228
- } from "./chunk-L4YY2TOE.js";
229
+ } from "./chunk-5TXWZB73.js";
229
230
  import {
230
231
  clearRuntimeAgentsForPi,
231
232
  listRuntimeAgentConfigs,
232
233
  mergeRuntimeAgents
233
- } from "./chunk-KXW62VBU.js";
234
+ } from "./chunk-SWGB2P5J.js";
234
235
  import {
235
236
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
236
237
  DEFAULT_WAIT_TOOL_NAME,
@@ -253,6 +254,7 @@ import {
253
254
  getPiSpawnCommand,
254
255
  getProjectConfigDir,
255
256
  getSupportedThinkingLevels,
257
+ isStatusAccessError,
256
258
  mergeBuiltinAgentOverride,
257
259
  parseFrontmatter,
258
260
  readStatus,
@@ -273,7 +275,7 @@ import {
273
275
  waitToolName,
274
276
  withSettingsFileLease,
275
277
  writeAtomicJson
276
- } from "./chunk-4MVDMA5C.js";
278
+ } from "./chunk-LWH7IGI3.js";
277
279
  import {
278
280
  DEFAULT_ARTIFACT_CONFIG,
279
281
  DIRS,
@@ -597,6 +599,8 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
597
599
  const runningJobIds = /* @__PURE__ */ new Set();
598
600
  const externalJobBridgeRuns = /* @__PURE__ */ new Set();
599
601
  const terminalPublications = /* @__PURE__ */ new Map();
602
+ const unreadableStatusRuns = /* @__PURE__ */ new Set();
603
+ const unverifiedRuns = /* @__PURE__ */ new Set();
600
604
  const supervisorNoticeTimers = /* @__PURE__ */ new Map();
601
605
  let rootWatcher;
602
606
  let nextLivenessAt = Date.now() + livenessIntervalMs;
@@ -919,9 +923,47 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
919
923
  runningJobIds.delete(asyncId);
920
924
  externalJobBridgeRuns.delete(asyncId);
921
925
  terminalPublications.delete(asyncId);
926
+ unreadableStatusRuns.delete(asyncId);
927
+ unverifiedRuns.delete(asyncId);
922
928
  clearSupervisorNotices(asyncId);
923
929
  };
930
+ const forgetJob = (asyncId) => {
931
+ cancelCleanup(asyncId);
932
+ closeJobWatcher(asyncId);
933
+ state.asyncJobs.delete(asyncId);
934
+ state.fleetJobs?.delete(asyncId);
935
+ options.onJobCleanup?.(asyncId);
936
+ };
924
937
  const refreshJob = (job) => {
938
+ if (unverifiedRuns.has(job.asyncId)) {
939
+ let stored = null;
940
+ let summary;
941
+ try {
942
+ stored = readStatus(job.asyncDir);
943
+ if (stored) summary = summarizeAsyncStatus(job.asyncDir, stored);
944
+ } catch (error) {
945
+ if (isStatusAccessError(error, job.asyncDir)) return false;
946
+ console.error(`[pi-subagents] Dropping restored async run '${job.asyncId}' at '${path2.join(job.asyncDir, "status.json")}': ${error instanceof Error ? error.message : String(error)}.`);
947
+ }
948
+ const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : void 0;
949
+ if (!stored || !summary || owners && !owners.has(stored.sessionId)) {
950
+ forgetJob(job.asyncId);
951
+ return true;
952
+ }
953
+ let restored;
954
+ try {
955
+ restored = summaryToJob(summary);
956
+ } catch (error) {
957
+ if (!unreadableStatusRuns.has(job.asyncId)) {
958
+ unreadableStatusRuns.add(job.asyncId);
959
+ console.error(`Cannot read async control events for '${job.asyncDir}'; keeping it as running until they are readable:`, error);
960
+ }
961
+ return false;
962
+ }
963
+ Object.assign(job, restored, { status: job.status, controlEventCursor: job.controlEventCursor ?? restored.controlEventCursor });
964
+ rememberFleetJob(state, job);
965
+ unverifiedRuns.delete(job.asyncId);
966
+ }
925
967
  const widgetExpanded = withLastUiContext((ctx) => ctx.ui.getToolsExpanded?.() ?? false) ?? false;
926
968
  const widgetStateBefore = widgetRenderKey(job, widgetExpanded);
927
969
  let nestedRefreshFailed = false;
@@ -967,6 +1009,7 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
967
1009
  }
968
1010
  });
969
1011
  const status = reconciliation.status ?? readStatus(job.asyncDir);
1012
+ unreadableStatusRuns.delete(job.asyncId);
970
1013
  if (!bridgeAlreadyRequired) {
971
1014
  const bridgeEligibility = externalJobBridgeEligibility(status?.steps);
972
1015
  if (bridgeEligibility === "required") externalJobBridgeRuns.add(job.asyncId);
@@ -1075,6 +1118,13 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1075
1118
  console.error(`Failed to service external job bridge for '${job.asyncDir}':`, bridgeError);
1076
1119
  }
1077
1120
  }
1121
+ if (isStatusAccessError(error, job.asyncDir)) {
1122
+ if (!unreadableStatusRuns.has(job.asyncId)) {
1123
+ unreadableStatusRuns.add(job.asyncId);
1124
+ console.error(`Cannot read async status for '${job.asyncDir}'; keeping its last known state until it is readable:`, error);
1125
+ }
1126
+ return widgetRenderKey(job, widgetExpanded) !== widgetStateBefore;
1127
+ }
1078
1128
  if (job.status !== "failed") {
1079
1129
  console.error(`Failed to read async status for '${job.asyncDir}':`, error);
1080
1130
  job.status = "failed";
@@ -1192,11 +1242,7 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1192
1242
  const owners = state.currentSessionId ? ownerSessionIds(state.currentSessionId) : void 0;
1193
1243
  for (const job of state.asyncJobs.values()) {
1194
1244
  if (owners && job.sessionId !== void 0 && !owners.has(job.sessionId)) {
1195
- cancelCleanup(job.asyncId);
1196
- closeJobWatcher(job.asyncId);
1197
- state.asyncJobs.delete(job.asyncId);
1198
- state.fleetJobs?.delete(job.asyncId);
1199
- options.onJobCleanup?.(job.asyncId);
1245
+ forgetJob(job.asyncId);
1200
1246
  widgetChanged = true;
1201
1247
  continue;
1202
1248
  }
@@ -1305,6 +1351,8 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1305
1351
  runningJobIds.clear();
1306
1352
  externalJobBridgeRuns.clear();
1307
1353
  terminalPublications.clear();
1354
+ unreadableStatusRuns.clear();
1355
+ unverifiedRuns.clear();
1308
1356
  clearSupervisorNotices();
1309
1357
  };
1310
1358
  const resetJobs = (ctx) => {
@@ -1328,8 +1376,17 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1328
1376
  state.statusProjectionSessionId = null;
1329
1377
  if (!state.currentSessionId) return;
1330
1378
  let runs;
1379
+ const unreadable = [];
1331
1380
  try {
1332
- runs = listAsyncRuns(asyncDirRoot, { states: ["queued", "running"], sessionId: state.currentSessionId, resultsDir, kill: options.kill, now: options.now, adoptCompletionOwnerId: state.completionOwnerId }, observeStatus);
1381
+ runs = listAsyncRuns(asyncDirRoot, {
1382
+ states: ["queued", "running"],
1383
+ sessionId: state.currentSessionId,
1384
+ resultsDir,
1385
+ kill: options.kill,
1386
+ now: options.now,
1387
+ adoptCompletionOwnerId: state.completionOwnerId,
1388
+ onUnreadableActiveRun: (runId, asyncDir) => unreadable.push({ runId, asyncDir })
1389
+ }, observeStatus);
1333
1390
  } catch (error) {
1334
1391
  console.error(`Failed to restore active async jobs from '${asyncDirRoot}':`, error);
1335
1392
  return;
@@ -1341,8 +1398,20 @@ function createAsyncJobTracker(pi, state, asyncDirRoot, options = {}) {
1341
1398
  rememberFleetJob(state, job);
1342
1399
  watchJob(job);
1343
1400
  }
1401
+ for (const { runId, asyncDir } of unreadable) {
1402
+ if (state.asyncJobs.has(runId)) continue;
1403
+ const job = { asyncId: runId, asyncDir, status: "running", sessionId: state.currentSessionId, updatedAt: Date.now() };
1404
+ try {
1405
+ job.controlEventCursor = restoredControlEventCursor(asyncDir);
1406
+ } catch {
1407
+ }
1408
+ state.asyncJobs.set(runId, job);
1409
+ runningJobIds.add(runId);
1410
+ unverifiedRuns.add(runId);
1411
+ watchJob(job);
1412
+ }
1344
1413
  state.statusProjectionSessionId = state.currentSessionId;
1345
- if (runs.length === 0) return;
1414
+ if (runs.length === 0 && unreadable.length === 0) return;
1346
1415
  ensurePoller();
1347
1416
  rerenderLastWidget();
1348
1417
  };
@@ -5370,7 +5439,7 @@ function registerSlashCommands(pi, state, options = {}) {
5370
5439
  }
5371
5440
  fleetOpen = true;
5372
5441
  try {
5373
- const { openSubagentFleet } = await import("./chunk-PYKBTBY6.js");
5442
+ const { openSubagentFleet } = await import("./chunk-URKQZHVH.js");
5374
5443
  await openSubagentFleet(ctx, state, { asyncDirRoot: DIRS.async, inspectorPlugins: () => getInspectorPlugins(pi), resultsDir: DIRS.results, fleetKeybindings: options.fleetKeybindings });
5375
5444
  } finally {
5376
5445
  fleetOpen = false;
@@ -8784,7 +8853,7 @@ function registerSubagentExtension(pi) {
8784
8853
  const ctx = withLastUiContext((current) => current);
8785
8854
  if (!ctx) return;
8786
8855
  try {
8787
- const { openSubagentFleet } = await import("./chunk-PYKBTBY6.js");
8856
+ const { openSubagentFleet } = await import("./chunk-URKQZHVH.js");
8788
8857
  await openSubagentFleet(ctx, state, { initialKey: itemKey, asyncDirRoot: DIRS.async, resultsDir: DIRS.results, fleetKeybindings: config.fleetKeybindings, inspectorPlugins: () => getInspectorPlugins(pi) });
8789
8858
  } catch (error) {
8790
8859
  if (isStaleExtensionContextError(error)) {
@@ -8993,7 +9062,7 @@ function registerSubagentExtension(pi) {
8993
9062
  let executor;
8994
9063
  let executorPromise;
8995
9064
  let executorModulePromise;
8996
- const loadExecutorModule = () => executorModulePromise ??= import("./chunk-ZJ2BT5TI.js");
9065
+ const loadExecutorModule = () => executorModulePromise ??= import("./chunk-6D54VW3E.js");
8997
9066
  const getExecutor = () => {
8998
9067
  executorPromise ??= loadExecutorModule().then(({ createSubagentExecutor }) => {
8999
9068
  executor = createSubagentExecutor(executorDeps);
@@ -9007,7 +9076,7 @@ function registerSubagentExtension(pi) {
9007
9076
  modulePreloadTimer = setTimeout(() => {
9008
9077
  loadExecutorModule().catch(() => {
9009
9078
  });
9010
- if (fleetViewEnabled) import("./chunk-PYKBTBY6.js").catch(() => {
9079
+ if (fleetViewEnabled) import("./chunk-URKQZHVH.js").catch(() => {
9011
9080
  });
9012
9081
  }, MODULE_PRELOAD_DELAY_MS);
9013
9082
  modulePreloadTimer.unref?.();