@vicary/pi-subagents 0.88.1 → 0.89.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 (88) hide show
  1. package/CHANGELOG.md +36 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-7OX6O7DQ.js → chunk-443LPCRI.js} +5 -5
  5. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  6. package/bundle/{chunk-6CG2VAG4.js → chunk-4ALRHKGE.js} +1 -1
  7. package/bundle/{chunk-4ZQBZDF3.js → chunk-6JD4XCA4.js} +76 -18
  8. package/bundle/{chunk-CGWNA6EJ.js → chunk-7JLNWAMO.js} +21 -21
  9. package/bundle/{chunk-LV3CPYXJ.js → chunk-7W2IQFP4.js} +4 -4
  10. package/bundle/{chunk-W6HIYD2Z.js → chunk-A3INCQ6Z.js} +1 -1
  11. package/bundle/{chunk-IYT7X46U.js → chunk-CFIYO2IV.js} +5 -5
  12. package/bundle/{chunk-CYKNHFXB.js → chunk-EPMRDKQT.js} +1 -1
  13. package/bundle/{chunk-RMZAAXIR.js → chunk-ETDE2VYK.js} +2 -2
  14. package/bundle/{chunk-4MVDMA5C.js → chunk-GHJ6BH5U.js} +13 -7
  15. package/bundle/{chunk-PYKBTBY6.js → chunk-HSHLPYCQ.js} +9 -9
  16. package/bundle/{chunk-D32H53HM.js → chunk-HZDLR73C.js} +1 -1
  17. package/bundle/{chunk-2DIEL4WG.js → chunk-JFACGAJT.js} +2 -2
  18. package/bundle/{chunk-L4YY2TOE.js → chunk-JRO2CU4D.js} +1 -1
  19. package/bundle/{chunk-KXW62VBU.js → chunk-KOLLMZ2X.js} +1 -1
  20. package/bundle/{chunk-AZPP3G4N.js → chunk-LEPIY76E.js} +34 -5
  21. package/bundle/{chunk-BKISQ5CJ.js → chunk-MJHQIUU7.js} +56 -34
  22. package/bundle/{chunk-47ZN7NKR.js → chunk-NONHDYXE.js} +1 -1
  23. package/bundle/{chunk-DSHQWGHO.js → chunk-NQ26PJSQ.js} +96 -96
  24. package/bundle/{chunk-2HKPEANZ.js → chunk-OVBUEVOT.js} +26 -15
  25. package/bundle/{chunk-JQTHG2ID.js → chunk-PFZZMVD5.js} +74 -31
  26. package/bundle/{chunk-YDZ7BZD5.js → chunk-S77ZKDLS.js} +1 -1
  27. package/bundle/{chunk-CPSUJHZE.js → chunk-SLLZJ5EC.js} +39 -10
  28. package/bundle/{chunk-V7SZMS6W.js → chunk-SWL2EITY.js} +2 -2
  29. package/bundle/{chunk-XIA5GSEU.js → chunk-UQT2EQ4U.js} +2 -2
  30. package/bundle/{chunk-5EMPFFO4.js → chunk-WW6GQBBS.js} +4 -4
  31. package/bundle/{chunk-GDR2ILWY.js → chunk-ZSCIHMUI.js} +50 -22
  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 +2 -2
  43. package/src/extension/herdr-pi-bridge.js +78 -22
  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/notify.d.ts +3 -0
  48. package/src/runs/background/notify.js +7 -2
  49. package/src/runs/background/run-status.js +3 -2
  50. package/src/runs/background/runner-child-launch.js +1 -0
  51. package/src/runs/background/subagent-runner.js +11 -8
  52. package/src/runs/foreground/execution.js +8 -7
  53. package/src/runs/foreground/subagent-executor.js +31 -5
  54. package/src/runs/shared/child-launch.d.ts +2 -0
  55. package/src/runs/shared/child-launch.js +1 -1
  56. package/src/runs/shared/child-session.d.ts +2 -1
  57. package/src/runs/shared/herdr-connection.d.ts +6 -0
  58. package/src/runs/shared/herdr-connection.js +11 -1
  59. package/src/runs/shared/herdr-machine.d.ts +2 -2
  60. package/src/runs/shared/herdr-machine.js +47 -22
  61. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  62. package/src/runs/shared/herdr-pane-host.js +48 -33
  63. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  64. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  65. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  66. package/src/runs/shared/herdr-placed-run.js +10 -8
  67. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  68. package/src/runs/shared/kept-branch-text.js +24 -0
  69. package/src/runs/shared/local-machine-access.d.ts +4 -1
  70. package/src/runs/shared/local-machine-access.js +6 -3
  71. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  72. package/src/runs/shared/mutation-evidence.js +18 -2
  73. package/src/runs/shared/parallel-handoff.js +19 -7
  74. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  75. package/src/runs/shared/placed-run-owner.js +15 -7
  76. package/src/runs/shared/rex-machine.d.ts +7 -3
  77. package/src/runs/shared/rex-machine.js +12 -9
  78. package/src/runs/shared/rex-pane-host.js +7 -27
  79. package/src/runs/shared/single-output.js +2 -2
  80. package/src/runs/shared/subagent-prompt-runtime.js +33 -0
  81. package/src/runs/shared/tool-availability.d.ts +4 -0
  82. package/src/runs/shared/tool-availability.js +7 -0
  83. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  84. package/src/runs/shared/worktree.d.ts +4 -14
  85. package/src/runs/shared/worktree.js +38 -8
  86. package/src/shared/types.d.ts +26 -2
  87. package/src/workflows/workflow-child-summary.d.ts +2 -1
  88. package/src/workflows/workflow-child-summary.js +14 -6
@@ -1,33 +1,34 @@
1
1
  import {
2
2
  rewriteSubagentPrompt
3
- } from "./chunk-AZPP3G4N.js";
3
+ } from "./chunk-LEPIY76E.js";
4
4
  import {
5
5
  package_default
6
- } from "./chunk-6CG2VAG4.js";
6
+ } from "./chunk-4ALRHKGE.js";
7
7
  import {
8
8
  WATCHDOG_DIFF_TOOL_NAME,
9
9
  captureWatchdogDiffBaseline,
10
10
  createWatchdogDiffTool
11
- } from "./chunk-IYT7X46U.js";
12
- import "./chunk-4ZQBZDF3.js";
13
- import "./chunk-CYKNHFXB.js";
11
+ } from "./chunk-CFIYO2IV.js";
12
+ import "./chunk-6JD4XCA4.js";
13
+ import "./chunk-EPMRDKQT.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-UQT2EQ4U.js";
21
+ import "./chunk-SLLZJ5EC.js";
22
22
  import "./chunk-NIXWDZZV.js";
23
- import "./chunk-47ZN7NKR.js";
23
+ import "./chunk-NONHDYXE.js";
24
24
  import "./chunk-7F6RKT6W.js";
25
25
  import {
26
26
  assertNoToolModifierEntries
27
- } from "./chunk-D32H53HM.js";
27
+ } from "./chunk-HZDLR73C.js";
28
28
  import "./chunk-YARY7JWU.js";
29
- import "./chunk-YDZ7BZD5.js";
29
+ import "./chunk-S77ZKDLS.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-GHJ6BH5U.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",
@@ -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 {
@@ -2,7 +2,7 @@ import {
2
2
  createAtomicJsonWriter,
3
3
  getAgentDir,
4
4
  readStatus
5
- } from "./chunk-4MVDMA5C.js";
5
+ } from "./chunk-GHJ6BH5U.js";
6
6
  import {
7
7
  DIRS,
8
8
  TEMP_ARTIFACTS_DIR,
@@ -5,7 +5,7 @@ import {
5
5
  PROJECT_SUBAGENTS_RELATIVE_DIR,
6
6
  canonicalSessionId,
7
7
  inspectSessionLease
8
- } from "./chunk-YDZ7BZD5.js";
8
+ } from "./chunk-S77ZKDLS.js";
9
9
  import {
10
10
  DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
11
11
  DEFAULT_GLOBAL_CONCURRENCY_LIMIT,
@@ -27,7 +27,7 @@ import {
27
27
  withFileLease,
28
28
  writeAtomicJson,
29
29
  writePrivateAtomicJson
30
- } from "./chunk-4MVDMA5C.js";
30
+ } from "./chunk-GHJ6BH5U.js";
31
31
  import {
32
32
  DIRS,
33
33
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -6451,8 +6451,13 @@ async function probeWorktreeSource(tx, cwd) {
6451
6451
  if (repoCheck.status !== 0 || repoCheck.stdout.trim() !== "true") throw new Error("worktree isolation requires a git repository");
6452
6452
  const toplevel = (await tx.gitChecked(cwd, ["rev-parse", "--show-toplevel"])).trim();
6453
6453
  const status = await tx.gitChecked(toplevel, ["status", "--porcelain", "--", `:!${PROJECT_SUBAGENTS_RELATIVE_DIR}`]);
6454
- if (status.trim().length > 0) {
6455
- throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
6454
+ const changes = status.split("\n").filter((line) => line.trim().length > 0);
6455
+ if (changes.length > 0) {
6456
+ const shown = changes.slice(0, 10).map((line) => ` ${line}`);
6457
+ if (changes.length > shown.length) shown.push(` \u2026 and ${changes.length - shown.length} more`);
6458
+ throw new Error(`worktree isolation requires a clean git working tree: ${toplevel} has ${changes.length} uncommitted change(s):
6459
+ ${shown.join("\n")}
6460
+ Commit or stash them first.`);
6456
6461
  }
6457
6462
  return toplevel;
6458
6463
  }
@@ -7103,6 +7108,7 @@ function cleanupSingleWorktree(setup, worktree, intent) {
7103
7108
  const errors = [];
7104
7109
  let worktreeRemoved = false;
7105
7110
  let branchRemoved = false;
7111
+ let keptBranchTip;
7106
7112
  if (intent.kind === "preserve" && intent.cleanupBlocker) {
7107
7113
  return {
7108
7114
  index: worktree.index,
@@ -7201,11 +7207,29 @@ function cleanupSingleWorktree(setup, worktree, intent) {
7201
7207
  errors.push(`worktree removal failed: ${error instanceof Error ? error.message : String(error)}`);
7202
7208
  }
7203
7209
  if (worktreeRemoved) {
7204
- try {
7205
- runGitChecked(setup.cwd, ["branch", "-D", worktree.branch]);
7206
- branchRemoved = true;
7207
- } catch (error) {
7208
- errors.push(`branch removal failed: ${error instanceof Error ? error.message : String(error)}`);
7210
+ let deleteBranch = true;
7211
+ if (intent.kind === "preserve") {
7212
+ try {
7213
+ const tip = runGitChecked(setup.cwd, ["rev-parse", "--verify", `refs/heads/${worktree.branch}^{commit}`]).trim();
7214
+ if (tip !== setup.baseCommit) {
7215
+ const containing = runGitChecked(setup.cwd, ["for-each-ref", "--contains", tip, "--format=%(refname)", "refs/heads", "refs/remotes", "refs/tags"]);
7216
+ if (!containing.split("\n").some((ref) => ref && ref !== `refs/heads/${worktree.branch}`)) {
7217
+ keptBranchTip = tip;
7218
+ deleteBranch = false;
7219
+ }
7220
+ }
7221
+ } catch (error) {
7222
+ deleteBranch = false;
7223
+ errors.push(`branch check failed: ${error instanceof Error ? error.message : String(error)}`);
7224
+ }
7225
+ }
7226
+ if (deleteBranch) {
7227
+ try {
7228
+ runGitChecked(setup.cwd, ["branch", "-D", worktree.branch]);
7229
+ branchRemoved = true;
7230
+ } catch (error) {
7231
+ errors.push(`branch removal failed: ${error instanceof Error ? error.message : String(error)}`);
7232
+ }
7209
7233
  }
7210
7234
  }
7211
7235
  return {
@@ -7217,6 +7241,7 @@ function cleanupSingleWorktree(setup, worktree, intent) {
7217
7241
  ...worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {},
7218
7242
  worktreeRemoved,
7219
7243
  branchRemoved,
7244
+ ...keptBranchTip ? { keptBranchTip } : {},
7220
7245
  ...errors.length ? { errors } : {}
7221
7246
  };
7222
7247
  }
@@ -7417,6 +7442,9 @@ function diffWorktrees(setup, agents, diffsDir) {
7417
7442
  setup.capturedDiffs = diffs;
7418
7443
  return diffs;
7419
7444
  }
7445
+ function isWorktreeCleanupTaskDone(task) {
7446
+ return task.worktreeRemoved && (task.branchRemoved || task.keptBranchTip !== void 0);
7447
+ }
7420
7448
  function cleanupWorktrees(setup, intent = { kind: "preserve", ...setup.capturedDiffs ? { capturedDiffs: setup.capturedDiffs } : {} }) {
7421
7449
  assertWorktreeMutationAllowed();
7422
7450
  const tasks = [];
@@ -7432,7 +7460,7 @@ function cleanupWorktrees(setup, intent = { kind: "preserve", ...setup.capturedD
7432
7460
  } catch (error) {
7433
7461
  errors.push(`worktree prune failed: ${error instanceof Error ? error.message : String(error)}`);
7434
7462
  }
7435
- const state = tasks.every((task) => task.worktreeRemoved && task.branchRemoved) && pruned ? "complete" : "partial";
7463
+ const state = tasks.every(isWorktreeCleanupTaskDone) && pruned ? "complete" : "partial";
7436
7464
  return {
7437
7465
  state,
7438
7466
  tasks,
@@ -7626,6 +7654,7 @@ export {
7626
7654
  resolveExpectedWorktreeAgentCwd,
7627
7655
  createWorktrees,
7628
7656
  diffWorktrees,
7657
+ isWorktreeCleanupTaskDone,
7629
7658
  cleanupWorktrees,
7630
7659
  formatWorktreeDiffSummary,
7631
7660
  validateModelResponseAliases
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  appendAgentRefinementOverlay
3
- } from "./chunk-XIA5GSEU.js";
3
+ } from "./chunk-UQT2EQ4U.js";
4
4
  import {
5
5
  buildAgentMemoryInjection,
6
6
  buildSkillInjection
7
- } from "./chunk-4MVDMA5C.js";
7
+ } from "./chunk-GHJ6BH5U.js";
8
8
 
9
9
  // src/runs/shared/effective-system-prompt.ts
10
10
  function appendSection(prompt, section) {
@@ -1,12 +1,12 @@
1
1
  import {
2
2
  getProjectSubagentsDir
3
- } from "./chunk-YDZ7BZD5.js";
3
+ } from "./chunk-S77ZKDLS.js";
4
4
  import {
5
5
  discoverAgents,
6
6
  formatUnknownAgentError,
7
7
  resolveAgentName,
8
8
  unknownAgentDiagnosticContext
9
- } from "./chunk-4MVDMA5C.js";
9
+ } from "./chunk-GHJ6BH5U.js";
10
10
 
11
11
  // src/agents/agent-refinements.ts
12
12
  import { createHash, randomUUID } from "node:crypto";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  buildWorkflowChatProgressRows
3
- } from "./chunk-LV3CPYXJ.js";
3
+ } from "./chunk-7W2IQFP4.js";
4
4
  import {
5
5
  aggregateStepStatus,
6
6
  contextModeBadge,
@@ -22,7 +22,7 @@ import {
22
22
  projectAsyncWorkflowRows,
23
23
  projectWorkflowChecklist,
24
24
  workflowGraphStageNodes
25
- } from "./chunk-4ZQBZDF3.js";
25
+ } from "./chunk-6JD4XCA4.js";
26
26
  import {
27
27
  isStaleExtensionContextError,
28
28
  isUnboundExtensionRuntimeError,
@@ -34,7 +34,7 @@ import {
34
34
  formatWorkflowJsonPreview,
35
35
  hostStepReportName,
36
36
  hostStepVerdictLabel
37
- } from "./chunk-CPSUJHZE.js";
37
+ } from "./chunk-SLLZJ5EC.js";
38
38
  import {
39
39
  snapshotExternalRuns
40
40
  } from "./chunk-UKG4V45O.js";
@@ -52,7 +52,7 @@ import {
52
52
  getSingleResultOutput,
53
53
  shortenPath,
54
54
  unresolvedChildWatchdogBlockers
55
- } from "./chunk-4MVDMA5C.js";
55
+ } from "./chunk-GHJ6BH5U.js";
56
56
  import {
57
57
  MAX_WIDGET_JOBS,
58
58
  WIDGET_ANIMATION_INTERVAL_MS,
@@ -3,8 +3,9 @@ import {
3
3
  REX_LOCAL_MACHINE,
4
4
  getAgentDir,
5
5
  getProjectConfigDir,
6
+ resolveLocalLaunchCwd,
6
7
  resolveRexLocalPlacement
7
- } from "./chunk-4MVDMA5C.js";
8
+ } from "./chunk-GHJ6BH5U.js";
8
9
 
9
10
  // src/runs/shared/herdr-machine.ts
10
11
  import { spawnSync as spawnSync2 } from "node:child_process";
@@ -54,12 +55,20 @@ function decodeHerdrJsonLine(line) {
54
55
  function shellQuoteRemote(value) {
55
56
  return `'${value.replaceAll("'", "'\\''")}'`;
56
57
  }
58
+ function shellScriptCommand(script, args = []) {
59
+ return `sh -c ${shellQuoteRemote(script)} sh${args.map((arg) => ` ${shellQuoteRemote(arg)}`).join("")}`;
60
+ }
57
61
  function remoteShellCommand(script, args = []) {
58
- return `sh -c ${shellQuoteRemote(`PATH="${HERDR_REMOTE_PATH}"; export PATH; ${script}`)} sh${args.map((arg) => ` ${shellQuoteRemote(arg)}`).join("")}`;
62
+ return shellScriptCommand(`PATH="${HERDR_REMOTE_PATH}"; export PATH; ${script}`, args);
59
63
  }
60
64
  function canonicalHerdrSession(session) {
61
65
  return session && session !== "default" ? session : null;
62
66
  }
67
+ function herdrLocalEnv(socket, session, source) {
68
+ const { HERDR_SESSION: _session, HERDR_CLIENT_SOCKET_PATH: _client, HERDR_PANE_ID: _pane, HERDR_ENV: _env, HERDR_SOCKET_PATH: _socket, ...env } = source;
69
+ const selected = canonicalHerdrSession(session);
70
+ return { ...env, HERDR_SOCKET_PATH: socket, ...selected ? { HERDR_SESSION: selected } : {} };
71
+ }
63
72
  function sshEnvCommand(session, command) {
64
73
  const selected = canonicalHerdrSession(session), assignment = selected ? ` HERDR_SESSION=${shellQuoteRemote(selected)}` : "";
65
74
  return `/usr/bin/env -u HERDR_SOCKET_PATH -u HERDR_SESSION${assignment} ${remoteShellCommand(command)}`;
@@ -393,20 +402,13 @@ function parseMachineCatalog(json) {
393
402
  });
394
403
  }
395
404
  function readHerdrMachineCatalog(env, herdrBin) {
396
- const result = spawnSync2(herdrBin, ["machine", "list", "--json"], {
397
- env,
398
- encoding: "utf-8",
399
- maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES,
400
- timeout: HERDR_MACHINE_LIST_TIMEOUT_MS,
401
- windowsHide: true
402
- });
403
- if (result.error) {
404
- const code = result.error.code;
405
- if (code === "ENOENT") throw new Error(`Herdr CLI '${herdrBin}' was not found on PATH. Saved-machine placement needs Herdr installed locally.`);
406
- throw new Error(`Failed to run herdr machine list --json: ${result.error.message}`);
407
- }
408
- if (result.status !== 0) throw new Error(`herdr machine list --json exited with code ${result.status}: ${(result.stderr || result.stdout).trim()}`);
409
- return parseMachineCatalog(result.stdout);
405
+ return parseMachineCatalog(runLocalHerdr(herdrBin, ["machine", "list", "--json"], env, `Herdr CLI '${herdrBin}' was not found on PATH. Saved-machine placement needs Herdr installed locally.`));
406
+ }
407
+ function runLocalHerdr(bin, args, env, notFound) {
408
+ const result = spawnSync2(bin, args, { env, encoding: "utf-8", maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES, timeout: HERDR_MACHINE_LIST_TIMEOUT_MS, windowsHide: true });
409
+ if (result.error) throw new Error(result.error.code === "ENOENT" ? notFound : `Failed to run herdr ${args.join(" ")}: ${result.error.message}`, { cause: result.error });
410
+ if (result.status !== 0) throw new Error(`herdr ${args.join(" ")} exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
411
+ return result.stdout;
410
412
  }
411
413
  function selectMachine(catalog, requested) {
412
414
  const byId = catalog.find((entry) => entry.id === requested);
@@ -513,12 +515,34 @@ function resolveHerdrMachinePlacement(input) {
513
515
  ...settings?.env ? { env: settings.env } : {}
514
516
  };
515
517
  }
518
+ function resolveHerdrLocalPlacement(input) {
519
+ if (process.platform === "win32") throw new Error("Machine 'local' runs the child in a Herdr pane, which is not supported on Windows.");
520
+ const env = input.env, paneId = env.HERDR_PANE_ID.trim(), bin = input.herdrBin ?? env.HERDR_BIN ?? "herdr", notFound = `Machine 'local' needs the Herdr CLI, but '${bin}' was not found on PATH.`;
521
+ let endpoint;
522
+ try {
523
+ endpoint = parseHerdrEndpoint(runLocalHerdr(bin, ["status", "server", "--json"], env, notFound), env.HERDR_SESSION);
524
+ } catch (error) {
525
+ throw new Error(`Machine 'local' could not confirm this pane's Herdr server: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
526
+ }
527
+ let pane;
528
+ try {
529
+ pane = JSON.parse(runLocalHerdr(bin, ["pane", "get", paneId], herdrLocalEnv(endpoint.socket, endpoint.session, env), notFound));
530
+ } catch (error) {
531
+ throw new Error(`Machine 'local' needs this Pi's Herdr pane ${paneId}, but the Herdr server at ${endpoint.socket} did not return it: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
532
+ }
533
+ const result = pane?.result;
534
+ if (result?.type !== "pane_info" || result.pane?.pane_id !== paneId) throw new Error(`The Herdr server at ${endpoint.socket} did not confirm pane ${paneId}.`);
535
+ return { provider: "herdr", id: REX_LOCAL_MACHINE, socket: endpoint.socket, ...endpoint.session ? { session: endpoint.session } : {}, cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd) };
536
+ }
516
537
  function resolveMachinePlacement(input) {
517
538
  const requested = validateMachineName(input.machine);
518
539
  const settings = input.settings ?? readMachineSettings(input.cwd, [requested]);
519
540
  if (requested === REX_LOCAL_MACHINE) {
520
- if (settings?.rex) throw new Error("Machine 'local' is reserved for a Rex pane on this machine; give the Rex SSH host in subagents.machines.local.rex another name.");
521
- return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env: input.env }) };
541
+ if (settings?.rex) throw new Error("Machine 'local' is reserved for a new tab on this machine; give the Rex SSH host in subagents.machines.local.rex another name.");
542
+ const env = input.env ?? process.env;
543
+ if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID?.trim()) return { machine: resolveHerdrLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, herdrBin: input.herdrBin }) };
544
+ if (env.REX_SESSION?.trim()) return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env }) };
545
+ throw new Error("Machine 'local' opens the child in a new tab of the terminal this Pi runs in, but this Pi is running in neither Herdr (HERDR_ENV=1 with HERDR_PANE_ID) nor Rex (REX_SESSION).");
522
546
  }
523
547
  if (settings?.rex) return { machine: { provider: "rex", id: requested, target: settings.rex.ssh, cwd: validateRemoteCwd(remoteMachineCwd(input.stepCwd, settings.cwd, requested), requested) } };
524
548
  return resolveHerdrMachinePlacement(input);
@@ -527,16 +551,17 @@ var PLACED_RESTORE_UNSUPPORTED = "Pane-native remote Pi does not support fork, r
527
551
  function formatHerdrMachineRunnerUnsupported(input) {
528
552
  if (input.machine === void 0) return void 0;
529
553
  const name = input.machine.trim();
554
+ const local = name === REX_LOCAL_MACHINE;
530
555
  let rex;
531
556
  try {
532
- rex = name === REX_LOCAL_MACHINE || userRexMachine(name);
557
+ rex = local || userRexMachine(name);
533
558
  } catch (error) {
534
559
  return error instanceof Error ? error.message : String(error);
535
560
  }
536
561
  if (rex) {
537
- if (input.runnerType !== void 0 && input.runnerType !== "pi") return `Agent '${input.agentName}' requested machine '${name}', but Rex supports native Pi children only. Remove the machine or use a native Pi agent.`;
562
+ if (input.runnerType !== void 0 && input.runnerType !== "pi") return `Agent '${input.agentName}' requested machine '${name}', but ${local ? "machine 'local' runs" : "Rex supports"} native Pi children only. Remove the machine or use a native Pi agent.`;
538
563
  if (input.worktree === true) return `Agent '${input.agentName}' requested machine '${name}', but managed worktrees cannot be combined with machine placement.`;
539
- if (process.platform === "win32") return `Machine '${name}' runs the child in a Rex pane, which is not supported on Windows.`;
564
+ if (process.platform === "win32") return `Machine '${name}' runs the child in ${local ? "a Herdr or Rex pane" : "a Rex pane"}, which is not supported on Windows.`;
540
565
  return void 0;
541
566
  }
542
567
  if (input.runnerType !== void 0 && input.runnerType !== "pi" && input.runnerType !== "external-cli") {
@@ -551,8 +576,11 @@ function formatHerdrMachineRunnerUnsupported(input) {
551
576
  }
552
577
 
553
578
  export {
554
- remoteShellCommand,
579
+ shellScriptCommand,
580
+ herdrLocalEnv,
555
581
  runBoundedCommand,
582
+ parseHerdrEndpoint,
583
+ SocketRpcClient,
556
584
  sshMachineAccess,
557
585
  connectHerdrMachine,
558
586
  resolveMachinePlacement,
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  requestAsyncStop
3
- } from "./chunk-W6HIYD2Z.js";
3
+ } from "./chunk-A3INCQ6Z.js";
4
4
  import "./chunk-NIXWDZZV.js";
5
- import "./chunk-4MVDMA5C.js";
5
+ import "./chunk-GHJ6BH5U.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";
package/bundle/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  HERDR_PI_MODE_ENV
3
- } from "./chunk-4QFZZV3O.js";
3
+ } from "./chunk-4AL6LDBY.js";
4
4
 
5
5
  // src/shared/package-version.ts
6
6
  import * as fs from "node:fs";
@@ -17,7 +17,7 @@ function readInstalledPackageVersion() {
17
17
  var loadedPackageVersion = readInstalledPackageVersion();
18
18
 
19
19
  // index.ts
20
- var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-JQTHG2ID.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-CGWNA6EJ.js")).default;
20
+ var registerExtension = process.env[HERDR_PI_MODE_ENV] === "1" ? (await import("./chunk-PFZZMVD5.js")).default : process.env.PI_SUBAGENT_CHILD === "1" ? void 0 : (await import("./chunk-7JLNWAMO.js")).default;
21
21
  function registerSubagentExtension(pi) {
22
22
  const installedVersion = readInstalledPackageVersion();
23
23
  if (installedVersion !== loadedPackageVersion) {
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  resolveIntercomSessionTarget
3
- } from "./chunk-47ZN7NKR.js";
3
+ } from "./chunk-NONHDYXE.js";
4
4
  import "./chunk-7F6RKT6W.js";
5
- import "./chunk-4MVDMA5C.js";
5
+ import "./chunk-GHJ6BH5U.js";
6
6
  import "./chunk-JEZOSEWG.js";
7
7
  import "./chunk-YFCK7H2S.js";
8
8
  import "./chunk-QXASAHIA.js";
@@ -2,22 +2,22 @@ import {
2
2
  buildEffectiveSystemPrompt,
3
3
  canPreferForkFromSnapshot,
4
4
  resolveSubagentLaunchContext
5
- } from "./chunk-V7SZMS6W.js";
6
- import "./chunk-XIA5GSEU.js";
5
+ } from "./chunk-SWL2EITY.js";
6
+ import "./chunk-UQT2EQ4U.js";
7
7
  import {
8
8
  loadConfig
9
- } from "./chunk-RMZAAXIR.js";
9
+ } from "./chunk-ETDE2VYK.js";
10
10
  import {
11
11
  nestedResultsPath,
12
12
  processTerminalCandidatePath,
13
13
  processTerminalPath,
14
14
  resultFilePath
15
- } from "./chunk-CPSUJHZE.js";
15
+ } from "./chunk-SLLZJ5EC.js";
16
16
  import {
17
17
  applyIntercomBridgeToAgent,
18
18
  resolveIntercomBridge,
19
19
  validateIntercomBridgeConfig
20
- } from "./chunk-47ZN7NKR.js";
20
+ } from "./chunk-NONHDYXE.js";
21
21
  import {
22
22
  AGENT_DEFINITION_PROJECTION_VERSION,
23
23
  resolveLaunchBinding,
@@ -26,7 +26,7 @@ import {
26
26
  import {
27
27
  applyThinkingSuffix,
28
28
  resolvePiLaunchToolPlan
29
- } from "./chunk-D32H53HM.js";
29
+ } from "./chunk-HZDLR73C.js";
30
30
  import {
31
31
  assertRequiredChildExtensionsAdmitted,
32
32
  resolveRequiredChildExtensions
@@ -34,7 +34,7 @@ import {
34
34
  import {
35
35
  getArtifactPaths,
36
36
  getArtifactsDir
37
- } from "./chunk-YDZ7BZD5.js";
37
+ } from "./chunk-S77ZKDLS.js";
38
38
  import {
39
39
  assertClaudeCodeModelScope,
40
40
  assertThinkingWithinCeiling,
@@ -61,7 +61,7 @@ import {
61
61
  resolveSkillsWithFallback,
62
62
  resolveStepBehavior,
63
63
  unknownAgentDiagnosticContext
64
- } from "./chunk-4MVDMA5C.js";
64
+ } from "./chunk-GHJ6BH5U.js";
65
65
  import {
66
66
  DIRS,
67
67
  SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
@@ -8,10 +8,10 @@ import {
8
8
  openProjectPane,
9
9
  projectPaneBindingPath,
10
10
  readProjectPaneBinding
11
- } from "./chunk-2DIEL4WG.js";
11
+ } from "./chunk-JFACGAJT.js";
12
12
  import "./chunk-7J4ZXMY7.js";
13
- import "./chunk-YDZ7BZD5.js";
14
- import "./chunk-4MVDMA5C.js";
13
+ import "./chunk-S77ZKDLS.js";
14
+ import "./chunk-GHJ6BH5U.js";
15
15
  import "./chunk-JEZOSEWG.js";
16
16
  import "./chunk-YFCK7H2S.js";
17
17
  import "./chunk-QXASAHIA.js";