@vicary/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-YDZ7BZD5.js → chunk-77VQEATI.js} +1 -1
  8. package/bundle/{chunk-7OX6O7DQ.js → chunk-BERAWSQQ.js} +5 -5
  9. package/bundle/{chunk-LV3CPYXJ.js → chunk-C22YEYFZ.js} +4 -4
  10. package/bundle/{chunk-AZPP3G4N.js → chunk-DVOXHOTY.js} +34 -5
  11. package/bundle/{chunk-2HKPEANZ.js → chunk-JLZFSOEL.js} +26 -15
  12. package/bundle/{chunk-CPSUJHZE.js → chunk-KCDPTXHT.js} +39 -10
  13. package/bundle/{chunk-4MVDMA5C.js → chunk-LWH7IGI3.js} +21 -7
  14. package/bundle/{chunk-DSHQWGHO.js → chunk-MIX3MCIF.js} +96 -96
  15. package/bundle/{chunk-BKISQ5CJ.js → chunk-NLDROUCR.js} +56 -34
  16. package/bundle/{chunk-2DIEL4WG.js → chunk-OUM6SEVD.js} +2 -2
  17. package/bundle/{chunk-XIA5GSEU.js → chunk-Q4VH72JI.js} +2 -2
  18. package/bundle/{chunk-D32H53HM.js → chunk-R3NH5XAL.js} +1 -1
  19. package/bundle/{chunk-CGWNA6EJ.js → chunk-R5XS4CVE.js} +98 -29
  20. package/bundle/{chunk-V7SZMS6W.js → chunk-RHMU7SXN.js} +2 -2
  21. package/bundle/{chunk-4ZQBZDF3.js → chunk-SG3NCWZW.js} +86 -20
  22. package/bundle/{chunk-KXW62VBU.js → chunk-SWGB2P5J.js} +1 -1
  23. package/bundle/{chunk-6CG2VAG4.js → chunk-TRN65L4F.js} +1 -1
  24. package/bundle/{chunk-GDR2ILWY.js → chunk-TXC7WIPL.js} +51 -22
  25. package/bundle/{chunk-IYT7X46U.js → chunk-UNLGCAC4.js} +5 -5
  26. package/bundle/{chunk-PYKBTBY6.js → chunk-URKQZHVH.js} +9 -9
  27. package/bundle/{chunk-W6HIYD2Z.js → chunk-UUW7P6KJ.js} +1 -1
  28. package/bundle/{chunk-CYKNHFXB.js → chunk-VEEUXJDO.js} +1 -1
  29. package/bundle/{chunk-JQTHG2ID.js → chunk-WMGQNIP7.js} +75 -32
  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 +2 -2
  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
@@ -6561,6 +6561,9 @@ var REX_EXIT_UNREACHABLE = 4;
6561
6561
  function isRexLocalMachine(machine) {
6562
6562
  return machine?.provider === "rex" && !("target" in machine);
6563
6563
  }
6564
+ function editsLocalDisk(machine) {
6565
+ return machine !== void 0 && !("target" in machine);
6566
+ }
6564
6567
  var REX_BUNDLE_BIN = "Library/Application Support/com.superlogical.rex/RexServer/Versions/Current/Rex Server.app/Contents/MacOS/rex";
6565
6568
  var REX_CALL_TIMEOUT_MS = 15e3;
6566
6569
  var REX_MAX_OUTPUT = 1024 * 1024;
@@ -6604,9 +6607,12 @@ function resolveRexLocalPlacement(input) {
6604
6607
  if (result.status === REX_EXIT_UNREACHABLE) throw new Error("Machine 'local' needs the Rex server, but it is unreachable.");
6605
6608
  if (result.status !== 0) throw new Error(`rex session inspect exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
6606
6609
  if (!sessionConfirmed(result.stdout, session)) throw new Error(`The Rex server did not confirm session ${session}.`);
6607
- const stepCwd = input.stepCwd?.trim();
6608
- const home = stepCwd === "~" || stepCwd?.startsWith("~/") ? path12.join(os4.homedir(), stepCwd.slice(1)) : void 0;
6609
- const requested = home ?? (stepCwd ? path12.resolve(input.cwd, stepCwd) : input.cwd);
6610
+ return { provider: "rex", id: REX_LOCAL_MACHINE, session, cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd), ...server ? { server } : {} };
6611
+ }
6612
+ function resolveLocalLaunchCwd(parentCwd, stepCwd) {
6613
+ const step = stepCwd?.trim();
6614
+ const home = step === "~" || step?.startsWith("~/") ? path12.join(os4.homedir(), step.slice(1)) : void 0;
6615
+ const requested = home ?? (step ? path12.resolve(parentCwd, step) : parentCwd);
6610
6616
  let cwd;
6611
6617
  try {
6612
6618
  cwd = fs12.realpathSync(requested);
@@ -6614,9 +6620,7 @@ function resolveRexLocalPlacement(input) {
6614
6620
  throw new Error(`Machine 'local' cwd does not exist: ${requested}.`, { cause: error });
6615
6621
  }
6616
6622
  if (!fs12.statSync(cwd).isDirectory()) throw new Error(`Machine 'local' cwd is not a directory: ${requested}.`);
6617
- const machine = { provider: "rex", id: REX_LOCAL_MACHINE, session, cwd };
6618
- if (server) machine.server = server;
6619
- return machine;
6623
+ return cwd;
6620
6624
  }
6621
6625
 
6622
6626
  // src/runs/shared/single-output.ts
@@ -6701,7 +6705,7 @@ function outputPathMappingFromTask(task, savedPath) {
6701
6705
  }
6702
6706
  function injectSingleOutputInstruction(task, outputPath, capabilities, machine) {
6703
6707
  if (!outputPath) return task;
6704
- const remote = machine !== void 0 && !isRexLocalMachine(machine);
6708
+ const remote = machine !== void 0 && !editsLocalDisk(machine);
6705
6709
  const delivery = !remote && (!capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools)) ? `Write your findings to exactly this path: ${outputPath}` : [
6706
6710
  "Return the complete artifact in your final response.",
6707
6711
  `The runtime will persist it to exactly this path: ${outputPath}`,
@@ -7660,6 +7664,13 @@ function resolveChildCwd(baseCwd, childCwd) {
7660
7664
  function isNotFoundError(error) {
7661
7665
  return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
7662
7666
  }
7667
+ function isStatusAccessError(error, asyncDir) {
7668
+ const code = error?.cause?.code;
7669
+ if (code !== "EACCES" && code !== "EPERM") return false;
7670
+ const message = error instanceof Error ? error.message : "";
7671
+ const quotedPath = `'${path16.join(asyncDir, "status.json")}':`;
7672
+ return message.startsWith(`Failed to inspect async status file ${quotedPath}`) || message.startsWith(`Failed to read async status file ${quotedPath}`);
7673
+ }
7663
7674
  function readStatus(asyncDir) {
7664
7675
  if (Buffer.byteLength(path16.basename(asyncDir), "utf-8") > 255) {
7665
7676
  return null;
@@ -8629,6 +8640,7 @@ export {
8629
8640
  REX_EXIT_GONE,
8630
8641
  REX_EXIT_UNREACHABLE,
8631
8642
  isRexLocalMachine,
8643
+ editsLocalDisk,
8632
8644
  REX_BUNDLE_BIN,
8633
8645
  REX_CALL_TIMEOUT_MS,
8634
8646
  REX_MAX_OUTPUT,
@@ -8636,6 +8648,7 @@ export {
8636
8648
  resolveRexBinary,
8637
8649
  rexCommandEnv,
8638
8650
  resolveRexLocalPlacement,
8651
+ resolveLocalLaunchCwd,
8639
8652
  extractChildWrittenOutput,
8640
8653
  normalizeSingleOutputOverride,
8641
8654
  resolveSingleOutputPath,
@@ -8714,6 +8727,7 @@ export {
8714
8727
  getProjectConfigDir,
8715
8728
  getAgentDir,
8716
8729
  resolveChildCwd,
8730
+ isStatusAccessError,
8717
8731
  readStatus,
8718
8732
  findLatestSessionFile,
8719
8733
  assistantMessageError,
@@ -1,19 +1,23 @@
1
1
  import {
2
2
  PLACED_RESTORE_UNSUPPORTED,
3
+ SocketRpcClient,
3
4
  connectHerdrMachine,
4
- remoteShellCommand,
5
+ herdrLocalEnv,
6
+ parseHerdrEndpoint,
5
7
  runBoundedCommand,
8
+ shellScriptCommand,
6
9
  sshMachineAccess
7
- } from "./chunk-GDR2ILWY.js";
10
+ } from "./chunk-TXC7WIPL.js";
8
11
  import {
9
12
  package_default
10
- } from "./chunk-6CG2VAG4.js";
13
+ } from "./chunk-TRN65L4F.js";
11
14
  import {
12
15
  ensureSupervisorChannelDir
13
- } from "./chunk-CYKNHFXB.js";
16
+ } from "./chunk-VEEUXJDO.js";
14
17
  import "./chunk-HXRB42AF.js";
15
18
  import "./chunk-NIXWDZZV.js";
16
19
  import {
20
+ HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES,
17
21
  HERDR_PI_MODE_ENV,
18
22
  HERDR_PI_PROTOCOL,
19
23
  HERDR_PI_RUNTIME_DIR_ENV,
@@ -21,20 +25,21 @@ import {
21
25
  HerdrPiFrameDecoder,
22
26
  encodeHerdrPiFrame,
23
27
  validateHerdrPiRunId
24
- } from "./chunk-4QFZZV3O.js";
28
+ } from "./chunk-4AL6LDBY.js";
25
29
  import {
26
30
  REX_BUNDLE_BIN,
27
31
  REX_CALL_TIMEOUT_MS,
28
32
  REX_EXIT_GONE,
29
33
  REX_EXIT_UNREACHABLE,
30
34
  REX_MAX_OUTPUT,
35
+ editsLocalDisk,
31
36
  getAgentDir,
32
37
  getPiSpawnCommand,
33
38
  isRexLocalMachine,
34
39
  resolveRexBinary,
35
40
  rexCommandEnv,
36
41
  rexGlobalArgs
37
- } from "./chunk-4MVDMA5C.js";
42
+ } from "./chunk-LWH7IGI3.js";
38
43
  import "./chunk-JEZOSEWG.js";
39
44
  import "./chunk-YFCK7H2S.js";
40
45
  import "./chunk-QXASAHIA.js";
@@ -46,14 +51,48 @@ import * as net from "node:net";
46
51
  import * as path5 from "node:path";
47
52
 
48
53
  // src/runs/shared/herdr-pane-host.ts
49
- import { createHash as createHash2 } from "node:crypto";
54
+ import { createHash as createHash3 } from "node:crypto";
55
+
56
+ // src/runs/shared/local-machine-access.ts
57
+ import { spawnSync } from "node:child_process";
58
+ import * as path from "node:path";
59
+ var DEFAULT_TIMEOUT_MS = 15e3;
60
+ var DEFAULT_MAX_BUFFER = 256 * 1024;
61
+ function localSockets() {
62
+ return {
63
+ async forwardRemoteSocket(socketPath) {
64
+ if (!path.isAbsolute(socketPath)) throw new Error("Local socket path must be absolute.");
65
+ return { socketPath, async close() {
66
+ } };
67
+ },
68
+ async close() {
69
+ }
70
+ };
71
+ }
72
+ function localMachineAccess(options = {}) {
73
+ const env = options.env ?? process.env;
74
+ return {
75
+ shellCommand: shellScriptCommand,
76
+ run(command, limits = {}) {
77
+ const spawned = spawnSync("/bin/sh", ["-c", command], { encoding: "utf8", env, timeout: limits.timeout ?? DEFAULT_TIMEOUT_MS, maxBuffer: limits.maxBuffer ?? DEFAULT_MAX_BUFFER, windowsHide: true });
78
+ const result = { status: spawned.status, stdout: spawned.stdout ?? "", stderr: spawned.stderr ?? "" };
79
+ if (spawned.error) result.error = spawned.error;
80
+ return result;
81
+ },
82
+ runAsync: (command, limits = {}) => runBoundedCommand("/bin/sh", ["-c", command], { env, ...limits }),
83
+ openSockets: localSockets
84
+ };
85
+ }
50
86
 
51
87
  // src/runs/shared/placed-run-owner.ts
88
+ import { createHash } from "node:crypto";
52
89
  import * as fs from "node:fs";
53
- import * as path from "node:path";
90
+ import * as path2 from "node:path";
54
91
  var PLACED_MANIFEST_READ_SCRIPT = 'p="$1/manifest.json"; test -f "$p" && test ! -L "$p" && cat "$p"';
55
- async function discoverPlacedBridgeManifest(access, runId, runtimeDir, missing = "The placed Pi's pi-subagents bridge manifest is not in its runtime directory; the Pi may have exited.") {
56
- for (let attempt = 0; attempt < 100; attempt++) {
92
+ var PLACED_MANIFEST_DEADLINE_MS = 3e4;
93
+ async function discoverPlacedBridgeManifest(access, runId, runtimeDir, missing = "The placed Pi's pi-subagents bridge manifest is not in its runtime directory; the Pi may have exited.", deadlineMs = PLACED_MANIFEST_DEADLINE_MS) {
94
+ const deadline = Date.now() + deadlineMs;
95
+ for (; ; ) {
57
96
  const result = await access.runAsync(access.shellCommand(PLACED_MANIFEST_READ_SCRIPT, [runtimeDir]), { timeout: 5e3, maxBuffer: 64 * 1024 });
58
97
  if (result.error) throw new Error(`Remote bridge manifest discovery failed: ${result.error.message}`, { cause: result.error });
59
98
  if (result.status === 0 && result.stdout.trim()) {
@@ -64,22 +103,25 @@ async function discoverPlacedBridgeManifest(access, runId, runtimeDir, missing =
64
103
  throw new Error("Remote bridge manifest is malformed.");
65
104
  }
66
105
  const p = value;
67
- if (p.runId !== runId || typeof p.socketPath !== "string" || path.posix.dirname(p.socketPath) !== runtimeDir || typeof p.nativeSessionId !== "string" || typeof p.packageVersion !== "string" || typeof p.protocol !== "number") throw new Error("Remote bridge manifest identity is incomplete or outside its owned runtime directory.");
106
+ if (p.runId !== runId || typeof p.socketPath !== "string" || path2.posix.dirname(p.socketPath) !== runtimeDir || typeof p.nativeSessionId !== "string" || typeof p.packageVersion !== "string" || typeof p.protocol !== "number") throw new Error("Remote bridge manifest identity is incomplete or outside its owned runtime directory.");
68
107
  return { socketPath: p.socketPath, nativeSessionId: p.nativeSessionId, packageVersion: p.packageVersion, protocol: p.protocol };
69
108
  }
109
+ if (Date.now() >= deadline) throw new Error(missing);
70
110
  await new Promise((resolve) => setTimeout(resolve, 50));
71
111
  }
72
- throw new Error(missing);
112
+ }
113
+ function hashedRuntimeDirName(runId) {
114
+ return createHash("sha256").update(runId).digest("hex").slice(0, 12);
73
115
  }
74
116
  async function createPlacedRuntimeDir(access, runId) {
75
117
  const result = await access.runAsync(access.shellCommand('umask 077; mktemp -d "${TMPDIR:-/tmp}/pi-subagents-herdr-$1-XXXXXXXX"', [runId]), { timeout: 1e4, maxBuffer: 4096 });
76
118
  if (result.error) throw new Error(`Could not provision a run-private remote bridge runtime directory: ${result.error.message}`, { cause: result.error });
77
119
  const value = result.stdout.trim();
78
- if (result.status !== 0 || !path.posix.isAbsolute(value) || value.includes("\n")) throw new Error("Could not provision a run-private remote bridge runtime directory.");
120
+ if (result.status !== 0 || !path2.posix.isAbsolute(value) || value.includes("\n")) throw new Error("Could not provision a run-private remote bridge runtime directory.");
79
121
  return value;
80
122
  }
81
123
  function removePlacedRuntimeDir(access, runtimeDir) {
82
- const result = access.run(access.shellCommand('p=$1; case "${p##*/}" in pi-subagents-herdr-*) test -d "$p" && test ! -L "$p" && rm -rf -- "$p";; *) exit 64;; esac', [runtimeDir]), { timeout: 1e4, maxBuffer: 4096 });
124
+ const result = access.run(access.shellCommand('p=$1; case "${p##*/}" in pi-subagents-herdr-*) if test -d "$p" && test ! -L "$p"; then rm -rf -- "$p"; fi; test ! -e "$p" && test ! -L "$p";; *) exit 64;; esac', [runtimeDir]), { timeout: 1e4, maxBuffer: 4096 });
83
125
  if (result.status !== 0 || result.stdout) throw new Error(`Could not remove the exact owned remote runtime directory: ${String(result.stderr).slice(0, 512)}`);
84
126
  }
85
127
  var PlacedRunOwner = class {
@@ -98,13 +140,11 @@ var PlacedRunOwner = class {
98
140
  };
99
141
  #snapshot = { connection: "connected", state: "ready", revision: 0 };
100
142
  #cleanupPromise;
101
- #removeRuntime;
102
- constructor(machine, runId, runtimeDir, connection, host, access, removeRuntime = () => removePlacedRuntimeDir(access, runtimeDir)) {
143
+ constructor(machine, runId, runtimeDir, connection, host, access) {
103
144
  this.machine = machine;
104
145
  this.runId = runId;
105
146
  this.runtimeDir = runtimeDir;
106
147
  this.connection = connection;
107
- this.#removeRuntime = removeRuntime;
108
148
  this.host = host;
109
149
  this.access = access;
110
150
  }
@@ -153,9 +193,9 @@ var PlacedRunOwner = class {
153
193
  journal(identity) {
154
194
  this.identity = identity;
155
195
  this.#snapshot = { ...this.#snapshot, identity };
156
- const journalDir = path.join(getAgentDir(), "pi-subagents", "herdr-run-journal");
196
+ const journalDir = path2.join(getAgentDir(), "pi-subagents", "herdr-run-journal");
157
197
  fs.mkdirSync(journalDir, { recursive: true, mode: 448 });
158
- fs.writeFileSync(path.join(journalDir, `${this.runId}.json`), JSON.stringify({ version: 1, identity, state: "ready", updatedAt: Date.now() }), { mode: 384, flag: "wx" });
198
+ fs.writeFileSync(path2.join(journalDir, `${this.runId}.json`), JSON.stringify({ version: 1, identity, state: "ready", updatedAt: Date.now() }), { mode: 384, flag: "wx" });
159
199
  }
160
200
  get snapshot() {
161
201
  return this.#snapshot;
@@ -185,7 +225,7 @@ var PlacedRunOwner = class {
185
225
  try {
186
226
  this.#unsubscribe();
187
227
  await this.connection.close();
188
- this.#removeRuntime();
228
+ removePlacedRuntimeDir(this.access, this.runtimeDir);
189
229
  } catch (error) {
190
230
  failure ??= error;
191
231
  }
@@ -195,9 +235,9 @@ var PlacedRunOwner = class {
195
235
  };
196
236
 
197
237
  // src/runs/shared/placement-host.ts
198
- import { createHash, randomBytes } from "node:crypto";
238
+ import { createHash as createHash2, randomBytes } from "node:crypto";
199
239
  import * as fs2 from "node:fs";
200
- import * as path2 from "node:path";
240
+ import * as path3 from "node:path";
201
241
  var HERDR_ALLOCATION_LOCK_TIMEOUT_MS = 1e4;
202
242
  var HERDR_ALLOCATION_LOCK_POLL_MS = 25;
203
243
  function herdrPaneAllocationKey(target, session, cwd) {
@@ -208,7 +248,7 @@ function assertPrivateDir(directory) {
208
248
  if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 511) !== 448 || typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("Herdr allocation path is not a mode-0700 agent-private owned directory.");
209
249
  }
210
250
  function ensurePrivateChild(parent, name) {
211
- const directory = path2.join(parent, name);
251
+ const directory = path3.join(parent, name);
212
252
  try {
213
253
  fs2.mkdirSync(directory, { mode: 448 });
214
254
  } catch (error) {
@@ -248,7 +288,7 @@ function sameOwner(left, right) {
248
288
  return left.token === right.token && left.dev === right.dev && left.ino === right.ino;
249
289
  }
250
290
  async function withHerdrPaneAllocationLock(key, action, options = {}) {
251
- const root = allocationLockRoot(), digest = createHash("sha256").update(key).digest("hex"), lockPath = path2.join(root, `${digest}.lock`), recoveryPath = path2.join(root, `${digest}.recovery`), token = randomBytes(16).toString("hex"), tempPath = path2.join(root, `.${digest}.${token}.tmp`), deadline = Date.now() + (options.timeoutMs ?? HERDR_ALLOCATION_LOCK_TIMEOUT_MS);
291
+ const root = allocationLockRoot(), digest = createHash2("sha256").update(key).digest("hex"), lockPath = path3.join(root, `${digest}.lock`), recoveryPath = path3.join(root, `${digest}.recovery`), token = randomBytes(16).toString("hex"), tempPath = path3.join(root, `.${digest}.${token}.tmp`), deadline = Date.now() + (options.timeoutMs ?? HERDR_ALLOCATION_LOCK_TIMEOUT_MS);
252
292
  let published;
253
293
  try {
254
294
  fs2.writeFileSync(tempPath, JSON.stringify({ pid: process.pid, token, createdAt: Date.now() }), { mode: 384, flag: "wx" });
@@ -394,7 +434,7 @@ async function provisionHerdrPane(client, cwd, runId, runtimeDir, environment, a
394
434
  return withHerdrPaneAllocationLock(allocationKey, async () => {
395
435
  const snapshot = parseHerdrSessionSnapshot(await client.call("session.snapshot"));
396
436
  const panes = list(snapshot, "panes").filter((item) => Boolean(item && typeof item === "object")), workspaces = list(snapshot, "workspaces").filter((item) => Boolean(item && typeof item === "object"));
397
- const ownedLabel = `pi-subagents-${createHash2("sha256").update(cwd).digest("hex").slice(0, 10)}`, owned = workspaces.filter((item) => item.label === ownedLabel);
437
+ const ownedLabel = `pi-subagents-${createHash3("sha256").update(cwd).digest("hex").slice(0, 10)}`, owned = workspaces.filter((item) => item.label === ownedLabel);
398
438
  if (owned.length > 1) throw new Error("Herdr deterministic owned workspace identity is ambiguous.");
399
439
  const cwdWorkspaceIds = new Set(panes.filter((item) => item.cwd === cwd || item.foreground_cwd === cwd).map((item) => item.workspace_id).filter((id) => typeof id === "string")), cwdWorkspaces = workspaces.filter((item) => typeof item.workspace_id === "string" && cwdWorkspaceIds.has(item.workspace_id));
400
440
  const selected = owned[0] ?? (cwdWorkspaces.length === 1 ? cwdWorkspaces[0] : void 0), selectedId = selected ? idOf(selected, "workspace_id") : void 0, actual = selectedId ? panes.filter((pane) => pane.workspace_id === selectedId).length : 0;
@@ -409,12 +449,23 @@ async function provisionHerdrPane(client, cwd, runId, runtimeDir, environment, a
409
449
  });
410
450
  }
411
451
  function provisionHerdrOwnedPane(connection, machine, runId, runtimeDir, environment) {
412
- return provisionHerdrPane(connection.client, machine.cwd, runId, runtimeDir, environment, herdrPaneAllocationKey(machine.target, connection.endpoint.session, machine.cwd));
452
+ return provisionHerdrPane(connection.client, machine.cwd, runId, runtimeDir, environment, "target" in machine ? herdrPaneAllocationKey(machine.target, connection.endpoint.session, machine.cwd) : JSON.stringify(["local", machine.socket, connection.endpoint.session, machine.cwd]));
413
453
  }
414
454
  function asHerdrMachine(machine) {
415
- if (machine.provider !== "herdr") throw new Error("The Herdr pane host only places runs on Herdr saved machines.");
455
+ if (machine.provider !== "herdr") throw new Error("The Herdr pane host only places runs on Herdr machines.");
416
456
  return machine;
417
457
  }
458
+ async function connectLocalHerdrMachine(machine) {
459
+ const result = await runBoundedCommand(process.env.HERDR_BIN ?? "herdr", ["status", "server", "--json"], { env: herdrLocalEnv(machine.socket, machine.session, process.env), timeout: 15e3 });
460
+ if (result.error) throw new Error(`Local Herdr discovery failed: ${result.error.message}`, { cause: result.error });
461
+ if (result.status !== 0) throw new Error(`Local Herdr discovery failed with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
462
+ const endpoint = parseHerdrEndpoint(result.stdout, machine.session);
463
+ if (endpoint.socket !== machine.socket) throw new Error(`Local Herdr server identity mismatch: expected socket ${machine.socket}, received ${endpoint.socket}.`);
464
+ return { endpoint, socketPath: machine.socket, client: new SocketRpcClient(machine.socket), ...localMachineAccess().openSockets() };
465
+ }
466
+ function herdrAccess(machine) {
467
+ return "target" in machine ? sshMachineAccess(machine) : localMachineAccess({ env: { ...process.env, TMPDIR: "/tmp" } });
468
+ }
418
469
  async function startHerdrAgent(connection, owned, kind, name, args, options = {}) {
419
470
  const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5e3), pollMs = options.pollMs ?? 50;
420
471
  let response;
@@ -453,7 +504,8 @@ async function closeOwnedHerdrPane(connection, owned, terminalId, agentName) {
453
504
  }
454
505
  var herdrPaneHost = {
455
506
  connect(machine) {
456
- return connectHerdrMachine(asHerdrMachine(machine));
507
+ const herdr = asHerdrMachine(machine);
508
+ return "target" in herdr ? connectHerdrMachine(herdr) : connectLocalHerdrMachine(herdr);
457
509
  },
458
510
  sessionOf(connection) {
459
511
  return connection.endpoint.session;
@@ -490,22 +542,16 @@ var herdrPaneHost = {
490
542
  reconcile: reconcileHerdrPlacedRun,
491
543
  closeOwnedPane: closeOwnedHerdrPane
492
544
  };
493
- function createRemoteRuntimeDir(machine, runId, options = {}) {
494
- return createPlacedRuntimeDir(sshMachineAccess(machine, options), runId);
495
- }
496
- function removeRemoteRuntimeDir(machine, runtimeDir, options = {}) {
497
- removePlacedRuntimeDir(sshMachineAccess(machine, options), runtimeDir);
498
- }
499
545
  var HerdrPlacedRunOwner = class _HerdrPlacedRunOwner extends PlacedRunOwner {
500
- constructor(machine, runId, runtimeDir, connection, removeRuntime) {
501
- super(machine, runId, runtimeDir, connection, herdrPaneHost, sshMachineAccess(machine), removeRuntime);
546
+ constructor(machine, runId, runtimeDir, connection, access) {
547
+ super(machine, runId, runtimeDir, connection, herdrPaneHost, access);
502
548
  }
503
549
  static async create(machine, runId, beforePane) {
504
- const runtimeDir = await createRemoteRuntimeDir(machine, runId);
550
+ const access = herdrAccess(machine), runtimeDir = await createPlacedRuntimeDir(access, "target" in machine ? runId : hashedRuntimeDirName(runId));
505
551
  let connection;
506
552
  try {
507
553
  connection = await herdrPaneHost.connect(machine);
508
- const owner = new _HerdrPlacedRunOwner(machine, runId, runtimeDir, connection);
554
+ const owner = new _HerdrPlacedRunOwner(machine, runId, runtimeDir, connection, access);
509
555
  await beforePane?.(owner);
510
556
  return owner;
511
557
  } catch (error) {
@@ -516,7 +562,7 @@ var HerdrPlacedRunOwner = class _HerdrPlacedRunOwner extends PlacedRunOwner {
516
562
  cleanupErrors.push(cleanupError);
517
563
  }
518
564
  try {
519
- removeRemoteRuntimeDir(machine, runtimeDir);
565
+ removePlacedRuntimeDir(access, runtimeDir);
520
566
  } catch (cleanupError) {
521
567
  cleanupErrors.push(cleanupError);
522
568
  }
@@ -539,43 +585,9 @@ var HerdrPlacedRunOwner = class _HerdrPlacedRunOwner extends PlacedRunOwner {
539
585
  };
540
586
 
541
587
  // src/runs/shared/rex-pane-host.ts
542
- import { createHash as createHash3 } from "node:crypto";
543
588
  import * as path4 from "node:path";
544
589
  import { Type } from "typebox";
545
590
  import { Compile } from "typebox/compile";
546
-
547
- // src/runs/shared/local-machine-access.ts
548
- import { spawnSync } from "node:child_process";
549
- import * as path3 from "node:path";
550
- var DEFAULT_TIMEOUT_MS = 15e3;
551
- var DEFAULT_MAX_BUFFER = 256 * 1024;
552
- function localSockets() {
553
- return {
554
- async forwardRemoteSocket(socketPath) {
555
- if (!path3.isAbsolute(socketPath)) throw new Error("Local socket path must be absolute.");
556
- return { socketPath, async close() {
557
- } };
558
- },
559
- async close() {
560
- }
561
- };
562
- }
563
- function localMachineAccess(options = {}) {
564
- const env = options.env ?? process.env;
565
- return {
566
- shellCommand: remoteShellCommand,
567
- run(command, limits = {}) {
568
- const spawned = spawnSync("/bin/sh", ["-c", command], { encoding: "utf8", env, timeout: limits.timeout ?? DEFAULT_TIMEOUT_MS, maxBuffer: limits.maxBuffer ?? DEFAULT_MAX_BUFFER, windowsHide: true });
569
- const result = { status: spawned.status, stdout: spawned.stdout ?? "", stderr: spawned.stderr ?? "" };
570
- if (spawned.error) result.error = spawned.error;
571
- return result;
572
- },
573
- runAsync: (command, limits = {}) => runBoundedCommand("/bin/sh", ["-c", command], { env, ...limits }),
574
- openSockets: localSockets
575
- };
576
- }
577
-
578
- // src/runs/shared/rex-pane-host.ts
579
591
  var REX_CLOSE_POLLS = 20;
580
592
  var REX_CLOSE_POLL_MS = 50;
581
593
  var REX_SSH_SESSION_LABEL = "subagents";
@@ -589,7 +601,7 @@ function rexAccess() {
589
601
  return localMachineAccess({ env: { ...rexCommandEnv(), TMPDIR: "/tmp" } });
590
602
  }
591
603
  function rexSshAccess(machine, access = sshMachineAccess(machine)) {
592
- return { ...access, shellCommand: (script, args) => remoteShellCommand(`TMPDIR=/tmp; export TMPDIR; ${script}`, args) };
604
+ return { ...access, shellCommand: (script, args) => access.shellCommand(`TMPDIR=/tmp; export TMPDIR; ${script}`, args) };
593
605
  }
594
606
  function asRexMachine(machine) {
595
607
  if (machine.provider !== "rex") throw new Error("The Rex pane host only places runs on Rex machines.");
@@ -775,33 +787,20 @@ var rexPaneHost = {
775
787
  reconcile: reconcileRexPlacedRun,
776
788
  closeOwnedPane: closeOwnedRexPane
777
789
  };
778
- function runtimeDirPresent(access, runtimeDir) {
779
- const result = access.run(access.shellCommand('test -e "$1" || test -L "$1"', [runtimeDir]), { timeout: 1e4, maxBuffer: 4096 });
780
- if (result.error) throw new Error(`Could not check the owned runtime directory: ${result.error.message}`, { cause: result.error });
781
- return result.status === 0;
782
- }
783
- function removeRexRuntimeDir(access, runtimeDir) {
784
- if (!runtimeDirPresent(access, runtimeDir)) return;
785
- try {
786
- removePlacedRuntimeDir(access, runtimeDir);
787
- } catch (error) {
788
- if (runtimeDirPresent(access, runtimeDir)) throw error;
789
- }
790
- }
791
790
  var RexPlacedRunOwner = class _RexPlacedRunOwner extends PlacedRunOwner {
792
791
  constructor(machine, runId, runtimeDir, connection, access, host) {
793
- super(machine, runId, runtimeDir, connection, host, access, () => removeRexRuntimeDir(access, runtimeDir));
792
+ super(machine, runId, runtimeDir, connection, host, access);
794
793
  }
795
794
  /** A Rex SSH owner's machine carries the resolved remote cwd, and its host reconnects only to the session recorded here. */
796
795
  static async create(machine, runId, options = {}) {
797
- const hash = createHash3("sha256").update(runId).digest("hex").slice(0, 12);
796
+ const hash = hashedRuntimeDirName(runId);
798
797
  if (isRexLocalMachine(machine)) {
799
798
  const access2 = rexAccess(), runtimeDir2 = await createPlacedRuntimeDir(access2, hash);
800
799
  try {
801
800
  return new _RexPlacedRunOwner(machine, runId, runtimeDir2, await connectRex(machine, { access: access2 }), access2, rexPaneHost);
802
801
  } catch (error) {
803
802
  try {
804
- removeRexRuntimeDir(access2, runtimeDir2);
803
+ removePlacedRuntimeDir(access2, runtimeDir2);
805
804
  } catch (cleanupError) {
806
805
  throw new AggregateError([error, cleanupError], "Rex owner creation failed and runtime cleanup also failed.", { cause: error });
807
806
  }
@@ -817,7 +816,7 @@ var RexPlacedRunOwner = class _RexPlacedRunOwner extends PlacedRunOwner {
817
816
  return new _RexPlacedRunOwner(placed, runId, runtimeDir, await host.connect(placed), access, host);
818
817
  } catch (error) {
819
818
  try {
820
- removeRexRuntimeDir(access, runtimeDir);
819
+ removePlacedRuntimeDir(access, runtimeDir);
821
820
  } catch (cleanupError) {
822
821
  throw new AggregateError([error, cleanupError], "Rex owner creation failed and runtime cleanup also failed.", { cause: error });
823
822
  }
@@ -860,14 +859,15 @@ function serializeHerdrPiLaunch(launch) {
860
859
  if (launch.extensionPaths.length || launch.requiredExtensions?.length) throw new Error("Pane-native remote Pi cannot transfer local extension paths; install/configure pi-subagents on the remote machine.");
861
860
  if (launch.processEnv && Object.values(launch.processEnv).some((value) => value !== void 0 && value !== "__none__")) throw new Error("Pane-native remote Pi cannot transfer local bindings, MCP selections, or process environment.");
862
861
  if (launch.runtime.nestedRoute || launch.runtime.fanoutChild || launch.runtime.depth > 1) throw new Error("Nested delegation from a pane-native remote Pi is not supported.");
863
- if (launch.excludeTools?.length || launch.runtime.permissions || launch.runtime.toolBudget || launch.runtime.requiredExtensions || launch.runtime.mcpDirectTools?.length) throw new Error("Pane-native remote Pi cannot yet represent exclusions, permission rules, tool budgets, MCP direct tools, or required-extension contracts; remove machine placement.");
862
+ if (launch.excludeTools?.length || launch.runtime.permissions || launch.runtime.toolBudget || launch.runtime.requiredExtensions || launch.runtime.mcpDirectTools?.length || launch.runtime.structuredOutput) throw new Error("Pane-native remote Pi cannot yet represent exclusions, permission rules, tool budgets, MCP direct tools, required-extension contracts, or outputSchema; remove machine placement.");
864
863
  const resources = launch.remoteResources;
865
864
  if (!resources || !/^[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 && resources.reads.some((read) => typeof read !== "string" || Buffer.byteLength(read) > 4096)) throw new Error("Pane-native remote resources require bounded logical agent, skill, tool, and read names.");
865
+ if (resources.acceptancePrompt !== void 0 && Buffer.byteLength(resources.acceptancePrompt) > HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES) throw new Error(`A placed Pi child's acceptance instructions exceed ${HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES} bytes; shorten the acceptance criteria or remove machine placement.`);
866
866
  const args = [];
867
867
  if (launch.noSkills) args.push("--no-skills", "--no-prompt-templates");
868
868
  if (launch.noContextFiles) args.push("--no-context-files");
869
869
  if (launch.model) args.push("--model", launch.model);
870
- return { args, resources: { agent: resources.agent, ...resources.skills ? { skills: [...resources.skills] } : {}, ...resources.toolCeiling ? { toolCeiling: [...resources.toolCeiling] } : {}, ...resources.reads !== void 0 ? { reads: resources.reads === false ? false : [...resources.reads] } : {} } };
870
+ return { args, resources: { agent: resources.agent, ...resources.skills ? { skills: [...resources.skills] } : {}, ...resources.toolCeiling ? { toolCeiling: [...resources.toolCeiling] } : {}, ...resources.reads !== void 0 ? { reads: resources.reads === false ? false : [...resources.reads] } : {}, ...resources.acceptancePrompt ? { acceptancePrompt: resources.acceptancePrompt } : {} } };
871
871
  }
872
872
  var BridgeChannel = class {
873
873
  socket;
@@ -1259,8 +1259,8 @@ async function reconnectHerdrPiSession(session, launch, dependencies = {}) {
1259
1259
  await session.replaceTransport({ ...validated, paneId: result.paneId, cursor: result.cursor, state: result.state });
1260
1260
  }
1261
1261
  async function createHerdrPiSession(launch) {
1262
- if (!launch.machine) throw new Error("Pane-native Pi launch requires a saved machine.");
1263
- if (launch.machine.provider !== "herdr") throw new Error("Herdr pane-native Pi launch requires a Herdr saved machine.");
1262
+ if (!launch.machine) throw new Error("Pane-native Pi launch requires a machine.");
1263
+ if (launch.machine.provider !== "herdr") throw new Error("Herdr pane-native Pi launch requires a Herdr machine.");
1264
1264
  const policy = serializeHerdrPiLaunch(launch);
1265
1265
  const runId = safeRunId(launch.runtime.runId);
1266
1266
  return startPlacedPiSession(launch, await HerdrPlacedRunOwner.create(launch.machine, runId), policy);
@@ -1290,7 +1290,7 @@ async function startPlacedPiSession(launch, owner, policy) {
1290
1290
  const missingRequired = (launch.runtime.requiredTools ?? []).filter((tool) => !configured.tools.includes(tool));
1291
1291
  if (missingRequired.length) throw new Error(`Remote Pi agent '${policy.resources.agent}' did not activate required tools: ${missingRequired.join(", ")}.`);
1292
1292
  if (launch.model && configured.model !== launch.model.split(":")[0]) throw new Error(`Remote Pi model '${launch.model}' did not resolve to the requested provider/model.`);
1293
- const identity = { runId, machineId: machine.id, target: isRexLocalMachine(machine) ? machine.id : machine.target, session: owner.host.sessionOf(connection), workspaceId: owned.workspaceId, tabId: owned.tabId, paneId: owned.paneId, terminalId, agentName, nativeSessionId: manifest.nativeSessionId, cwd: machine.cwd, runtimeDir };
1293
+ const identity = { runId, machineId: machine.id, target: editsLocalDisk(machine) ? machine.id : machine.target, session: owner.host.sessionOf(connection), workspaceId: owned.workspaceId, tabId: owned.tabId, paneId: owned.paneId, terminalId, agentName, nativeSessionId: manifest.nativeSessionId, cwd: machine.cwd, runtimeDir };
1294
1294
  owner.journal(identity);
1295
1295
  const session = new HerdrPiSession(owner, bridgeForward, bridge, configured.tools, typeof ready.model === "string" ? ready.model : void 0, launch.runtime, ready.initialGit);
1296
1296
  reconnectSession = session;