@vicary/pi-subagents 0.88.0 → 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 (106) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-6EUQPQY7.js → chunk-443LPCRI.js} +5 -5
  5. package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
  6. package/bundle/{chunk-CKLZ5FGU.js → chunk-4ALRHKGE.js} +1 -1
  7. package/bundle/{chunk-SVIXQDIV.js → chunk-6JD4XCA4.js} +77 -19
  8. package/bundle/{chunk-XZXYPZUT.js → chunk-7JLNWAMO.js} +54 -36
  9. package/bundle/{chunk-RHYVKQQL.js → chunk-7W2IQFP4.js} +4 -4
  10. package/bundle/{chunk-W6HIYD2Z.js → chunk-A3INCQ6Z.js} +1 -1
  11. package/bundle/{chunk-JYHTDTOZ.js → chunk-CFIYO2IV.js} +5 -5
  12. package/bundle/{chunk-CYKNHFXB.js → chunk-EPMRDKQT.js} +1 -1
  13. package/bundle/{chunk-6PR44R7E.js → chunk-ETDE2VYK.js} +2 -2
  14. package/bundle/{chunk-4MVDMA5C.js → chunk-GHJ6BH5U.js} +13 -7
  15. package/bundle/{chunk-IZEKQEY4.js → chunk-HSHLPYCQ.js} +27 -10
  16. package/bundle/{chunk-3MFYKBKI.js → chunk-HZDLR73C.js} +4 -4
  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-TDJKY2NE.js → chunk-LEPIY76E.js} +34 -5
  21. package/bundle/{chunk-BW5JLKIU.js → chunk-MJHQIUU7.js} +68 -41
  22. package/bundle/{chunk-47ZN7NKR.js → chunk-NONHDYXE.js} +1 -1
  23. package/bundle/{chunk-PJSOS2Q4.js → chunk-NQ26PJSQ.js} +96 -96
  24. package/bundle/{chunk-AOSILI5R.js → chunk-OVBUEVOT.js} +95 -49
  25. package/bundle/{chunk-NVGQE2H2.js → chunk-PFZZMVD5.js} +75 -32
  26. package/bundle/{chunk-YDZ7BZD5.js → chunk-S77ZKDLS.js} +1 -1
  27. package/bundle/{chunk-3DT5X2QC.js → chunk-SLLZJ5EC.js} +50 -18
  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-YZPVALSQ.js → chunk-WW6GQBBS.js} +4 -4
  31. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  32. package/bundle/{chunk-GDR2ILWY.js → chunk-ZSCIHMUI.js} +50 -22
  33. package/bundle/control-channel.js +2 -2
  34. package/bundle/index.js +2 -2
  35. package/bundle/intercom-bridge.js +2 -2
  36. package/bundle/preflight.js +9 -9
  37. package/bundle/project-panes.js +3 -3
  38. package/bundle/required-child-extensions.js +1 -1
  39. package/docs/agents.md +14 -6
  40. package/docs/configuration.md +2 -0
  41. package/docs/extension-api.md +1 -1
  42. package/docs/tool-reference.md +1 -1
  43. package/docs/workflows.md +8 -4
  44. package/package.json +2 -2
  45. package/src/extension/herdr-pi-bridge.js +78 -22
  46. package/src/extension/index.d.ts +1 -1
  47. package/src/extension/index.js +43 -20
  48. package/src/extension/schemas.js +1 -1
  49. package/src/extension/subagent-launch-tool.d.ts +6 -2
  50. package/src/extension/subagent-launch-tool.js +13 -9
  51. package/src/extension/subagent-options.js +5 -0
  52. package/src/intercom/result-intercom.js +3 -2
  53. package/src/runs/background/notify.d.ts +3 -0
  54. package/src/runs/background/notify.js +7 -2
  55. package/src/runs/background/run-status.js +3 -2
  56. package/src/runs/background/runner-child-launch.js +1 -0
  57. package/src/runs/background/stale-run-reconciler.js +17 -8
  58. package/src/runs/background/subagent-runner.js +11 -8
  59. package/src/runs/foreground/execution.js +8 -7
  60. package/src/runs/foreground/subagent-executor.js +42 -11
  61. package/src/runs/shared/child-launch.d.ts +2 -0
  62. package/src/runs/shared/child-launch.js +7 -4
  63. package/src/runs/shared/child-session.d.ts +3 -2
  64. package/src/runs/shared/child-session.js +3 -27
  65. package/src/runs/shared/herdr-connection.d.ts +6 -0
  66. package/src/runs/shared/herdr-connection.js +11 -1
  67. package/src/runs/shared/herdr-machine.d.ts +2 -2
  68. package/src/runs/shared/herdr-machine.js +47 -22
  69. package/src/runs/shared/herdr-pane-host.d.ts +7 -19
  70. package/src/runs/shared/herdr-pane-host.js +48 -33
  71. package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
  72. package/src/runs/shared/herdr-pi-protocol.js +3 -2
  73. package/src/runs/shared/herdr-placed-run.d.ts +2 -12
  74. package/src/runs/shared/herdr-placed-run.js +10 -8
  75. package/src/runs/shared/kept-branch-text.d.ts +8 -0
  76. package/src/runs/shared/kept-branch-text.js +24 -0
  77. package/src/runs/shared/local-machine-access.d.ts +4 -1
  78. package/src/runs/shared/local-machine-access.js +6 -3
  79. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -3
  80. package/src/runs/shared/mcp-direct-tool-allowlist.js +5 -4
  81. package/src/runs/shared/mutation-evidence.d.ts +7 -1
  82. package/src/runs/shared/mutation-evidence.js +18 -2
  83. package/src/runs/shared/parallel-handoff.js +19 -7
  84. package/src/runs/shared/placed-run-owner.d.ts +4 -2
  85. package/src/runs/shared/placed-run-owner.js +15 -7
  86. package/src/runs/shared/rex-machine.d.ts +7 -3
  87. package/src/runs/shared/rex-machine.js +12 -9
  88. package/src/runs/shared/rex-pane-host.js +7 -27
  89. package/src/runs/shared/single-output.js +2 -2
  90. package/src/runs/shared/subagent-prompt-runtime.js +33 -0
  91. package/src/runs/shared/tool-availability.d.ts +4 -0
  92. package/src/runs/shared/tool-availability.js +7 -0
  93. package/src/runs/shared/worktree-cleanup-plan.js +2 -2
  94. package/src/runs/shared/worktree.d.ts +4 -14
  95. package/src/runs/shared/worktree.js +38 -8
  96. package/src/shared/compaction-interruption.d.ts +9 -0
  97. package/src/shared/compaction-interruption.js +47 -0
  98. package/src/shared/parent-wake.d.ts +3 -2
  99. package/src/shared/parent-wake.js +14 -3
  100. package/src/shared/required-child-extensions.d.ts +2 -0
  101. package/src/shared/required-child-extensions.js +27 -0
  102. package/src/shared/types.d.ts +26 -2
  103. package/src/tui/fleet.d.ts +7 -2
  104. package/src/tui/fleet.js +22 -0
  105. package/src/workflows/workflow-child-summary.d.ts +2 -1
  106. package/src/workflows/workflow-child-summary.js +14 -6
@@ -450,8 +450,23 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
450
450
  const existingResultPath = effectiveStatus.sessionId
451
451
  ? resultPayloadPathForSessionRun(resultsDir, effectiveStatus.sessionId, runId) ?? (regularFileExists(resultPath) ? resultPath : undefined)
452
452
  : regularFileExists(resultPath) ? resultPath : undefined;
453
+ const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
454
+ const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
455
+ const observedScope = options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope();
456
+ const runnerLiveness = (pid) => checkRecordedPidLiveness({ pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
457
+ kill: options.kill,
458
+ observedScope,
459
+ observedBootId: options.bootId ? options.bootId() : currentBootId(),
460
+ });
453
461
  if (existingResultPath) {
454
- const terminalStatus = effectiveStatus.state === "running" || effectiveStatus.state === "queued"
462
+ // A live runner writes its result before its final status; repairing in that window would replace
463
+ // its pending exit proof with a placeholder. Only a confirmed-alive pid defers: a result is better
464
+ // evidence than an unprobeable pid, and a pid from another pid namespace can be alive here as an unrelated
465
+ // process. A workflow's pid is its host Pi process, which outlives the workflow.
466
+ const runnerStillFinishing = effectiveStatus.state === "running" && effectiveStatus.mode !== "workflow" && typeof effectiveStatus.pid === "number"
467
+ && effectiveStatus.pidNamespaceScope === observedScope
468
+ && now - lastUpdate <= staleAfterMs && runnerLiveness(effectiveStatus.pid) === "alive";
469
+ const terminalStatus = (effectiveStatus.state === "running" || effectiveStatus.state === "queued") && !runnerStillFinishing
455
470
  ? terminalStatusFromResult(effectiveStatus, existingResultPath, now)
456
471
  : undefined;
457
472
  if (terminalStatus) {
@@ -491,14 +506,8 @@ export function reconcileAsyncRun(asyncDir, options = {}, observeStatus) {
491
506
  return { status: null, repaired: false, resultPath };
492
507
  }
493
508
  }
494
- const liveness = checkRecordedPidLiveness({ pid: effectiveStatus.pid, pidNamespaceScope: effectiveStatus.pidNamespaceScope, bootId: effectiveStatus.bootId }, {
495
- kill: options.kill,
496
- observedScope: options.pidNamespaceScope ? options.pidNamespaceScope() : currentPidNamespaceScope(),
497
- observedBootId: options.bootId ? options.bootId() : currentBootId(),
498
- });
509
+ const liveness = runnerLiveness(effectiveStatus.pid);
499
510
  if (liveness !== "dead") {
500
- const staleAfterMs = options.staleAlivePidMs ?? 24 * 60 * 60 * 1000;
501
- const lastUpdate = effectiveStatus.lastUpdate ?? effectiveStatus.startedAt;
502
511
  if (now - lastUpdate <= staleAfterMs)
503
512
  return { status: status ?? null, repaired: false, resultPath };
504
513
  const probe = liveness === "alive" ? "is still live" : "cannot be probed from this process";
@@ -44,7 +44,7 @@ import { outputEntryFromAsyncResult, resolveOutputReferences } from "../shared/c
44
44
  import { clearStructuredOutputCaptures, createStructuredOutputFileCapture, createStructuredOutputRuntime, formatStructuredOutputRejectionError, MISSING_STRUCTURED_OUTPUT_CALL_ERROR, readStructuredOutput, readStructuredOutputAcceptanceReport } from "../shared/structured-output.js";
45
45
  import { formatMidToolExitError, isOrdinaryToolForMidToolExit, isUnexplainedProcessSignal } from "../shared/process-signal.js";
46
46
  import { formatChildToolDiagnostic } from "../shared/tool-availability.js";
47
- import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
47
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, remoteMutationEvidence, remoteMutationSnapshot, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
48
48
  import { collectDynamicResults, DynamicFanoutError, materializeDynamicParallelStep, validateDynamicCollection } from "../shared/dynamic-fanout.js";
49
49
  import { claimRunFanoutBatch, getRunFanoutBudgetSnapshot } from "../shared/run-fanout-budget.js";
50
50
  import { nestedSummaryFromAsyncStatus, projectNestedEvents, resolveNestedAsyncDir, writeNestedEvent } from "../shared/nested-events.js";
@@ -79,7 +79,7 @@ import { resolveCodexExecLaunch } from "../shared/codex-exec-adapter.js";
79
79
  import { resolveCursorAgentLaunch } from "../shared/cursor-agent-adapter.js";
80
80
  import { resolveExternalCliRunnerStatus } from "../shared/external-cli-contract.js";
81
81
  import { formatHerdrMachineHint, prepareHerdrMachineExternalCliRun } from "../shared/herdr-machine.js";
82
- import { isRexLocalMachine } from "../shared/rex-machine.js";
82
+ import { editsLocalDisk } from "../shared/rex-machine.js";
83
83
  import { HerdrExternalNeedsAttentionError, createHerdrExternalAdapter, prepareInternalHerdrExternalAdapter } from "../shared/herdr-external-adapters.js";
84
84
  import { runExternalJob } from "../shared/external-job-runner.js";
85
85
  import { createOrcaProgressTab } from "../shared/orca-progress-tabs.js";
@@ -606,6 +606,8 @@ export async function runSingleStepInner(step, ctx) {
606
606
  if (step.machine) {
607
607
  if (step.machine.provider !== "herdr")
608
608
  throw new Error("Rex supports native Pi children only.");
609
+ if (!("target" in step.machine))
610
+ throw new Error("Machine 'local' runs native Pi children only.");
609
611
  const runner = resolveExternalCliRunnerStatus({ ...step.runner, machine: step.machine });
610
612
  const outputSnapshot = captureSingleOutputSnapshot(step.outputPath);
611
613
  const placedRunId = `${ctx.id}-${ctx.flatIndex}`;
@@ -762,7 +764,7 @@ export async function runSingleStepInner(step, ctx) {
762
764
  }
763
765
  const effectiveCwd = step.cwd ?? ctx.cwd;
764
766
  // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
765
- const cwdError = step.machine && !isRexLocalMachine(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
767
+ const cwdError = step.machine && !editsLocalDisk(step.machine) ? undefined : preflightLaunchCwd(step.requestedCwd ?? effectiveCwd, effectiveCwd);
766
768
  if (cwdError)
767
769
  return { agent: step.agent, output: cwdError, error: cwdError, exitCode: 1, context: step.context };
768
770
  if (step.context === "fork" && step.sessionFile && fs.existsSync(step.sessionFile)) {
@@ -781,7 +783,7 @@ export async function runSingleStepInner(step, ctx) {
781
783
  let toolBudgetBlocked = false;
782
784
  let actualLaunchContractDigest = step.launchContractDigest;
783
785
  // A machine 'local' child edits this disk, so its local Git evidence is authoritative, as for an unplaced run.
784
- const mutationSnapshot = step.machine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, cwd: step.cwd ?? ctx.cwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
786
+ const mutationSnapshot = step.machine && !editsLocalDisk(step.machine) ? remoteMutationSnapshot(step.cwd ?? ctx.cwd) : snapshotTrackedMutations(step.cwd ?? ctx.cwd);
785
787
  let finalMutationEvidence = await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
786
788
  let contextOverflow = false;
787
789
  let launchWarningsEmitted = false;
@@ -944,7 +946,9 @@ export async function runSingleStepInner(step, ctx) {
944
946
  // A parked run still owes output diagnostics when it actually finishes.
945
947
  // Stopped/timedOut runs already have terminal failures, so terminal output diagnostics are deferred.
946
948
  const terminalDiagnosticsEligible = !run.interrupted && !run.stopped && !run.timedOut;
947
- const toolDiagnostic = run.exitCode === 0 && !run.error ? launch.capture.toolDiagnostic() : undefined;
949
+ const recordedToolDiagnostic = launch.capture.toolDiagnostic();
950
+ // An undeclared allowlisted tool aborts the child itself, so its diagnostic explains that abort's error.
951
+ const toolDiagnostic = (run.exitCode === 0 && !run.error) || recordedToolDiagnostic?.undeclared ? recordedToolDiagnostic : undefined;
948
952
  const toolAvailabilityError = toolDiagnostic ? formatChildToolDiagnostic(toolDiagnostic) : undefined;
949
953
  const runtimeAcknowledgedExtensions = launch.capture.runtimeAcknowledgedExtensions();
950
954
  const midToolExitError = run.currentTool
@@ -1007,8 +1011,7 @@ export async function runSingleStepInner(step, ctx) {
1007
1011
  const truncatedResponseError = hiddenError && !hiddenError.hasError && !validatedStructuredOutput && getTerminalAssistantStopReason(run.messages) === "length"
1008
1012
  ? TRUNCATED_RESPONSE_ERROR
1009
1013
  : undefined;
1010
- const remoteGitChanged = run.nativeMachine?.initialGit && run.nativeMachine.finalGit ? run.nativeMachine.initialGit.head !== run.nativeMachine.finalGit.head || run.nativeMachine.initialGit.dirty !== run.nativeMachine.finalGit.dirty : undefined;
1011
- const mutationEvidence = run.nativeMachine && !isRexLocalMachine(step.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1014
+ const mutationEvidence = run.nativeMachine && !editsLocalDisk(step.machine) ? remoteMutationEvidence(run.nativeMachine) : await collectTrackedMutationEvidence(mutationSnapshot, step.cwd ?? ctx.cwd);
1012
1015
  finalMutationEvidence = mutationEvidence;
1013
1016
  const mutationAttemptObserved = run.observedMutationAttempt === true || mutationEvidence.attemptedMutation === true;
1014
1017
  // Validated structured output is persistable file content even when the final text is only
@@ -1289,7 +1292,7 @@ async function runSingleStep(step, ctx) {
1289
1292
  }
1290
1293
  function externalRunnerStatus(runner, machine) {
1291
1294
  if (runner?.type === "external-cli") {
1292
- return resolveExternalCliRunnerStatus(machine?.provider === "herdr" ? { ...runner, machine } : runner);
1295
+ return resolveExternalCliRunnerStatus(machine?.provider === "herdr" && "target" in machine ? { ...runner, machine } : runner);
1293
1296
  }
1294
1297
  if (runner?.type === "external-job") {
1295
1298
  return {
@@ -27,7 +27,7 @@ import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/
27
27
  import { formatChildToolDiagnostic } from "../shared/tool-availability.js";
28
28
  import { formatChildModelResolutionDiagnostic, formatInheritedProviderDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.js";
29
29
  import { planAbortRecovery } from "../shared/abort-recovery.js";
30
- import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
30
+ import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, remoteMutationEvidence, remoteMutationSnapshot, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
31
31
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, isSettlementFatalOutputError, resolveSingleOutput, validateFileOnlyOutputMode } from "../shared/single-output.js";
32
32
  import { formatSubagentModelVerificationError, isContextOverflow, resolveModelSelection, } from "../shared/model-resolution.js";
33
33
  import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
@@ -44,7 +44,7 @@ import { buildInProcessChildLaunch, createReportedChildSessionInput } from "../s
44
44
  import { childSessionFactory, childSessionHasQueuedMessages, projectChildSessionEventForJson } from "../shared/child-session.js";
45
45
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.js";
46
46
  import { clearProviderRetry, observeProviderDiagnostics, snapshotProviderDiagnostics } from "../../shared/provider-diagnostics.js";
47
- import { isRexLocalMachine } from "../shared/rex-machine.js";
47
+ import { editsLocalDisk } from "../shared/rex-machine.js";
48
48
  import { pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
49
49
  const artifactOutputByResult = new WeakMap();
50
50
  const acceptanceOutputByResult = new WeakMap();
@@ -278,6 +278,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
278
278
  machine: options.machine,
279
279
  remoteSkillNames: options.skills ?? agent.skills,
280
280
  remoteReads: options.remoteReads,
281
+ acceptancePrompt: shared.acceptancePrompt,
281
282
  extensionBindings: options.extensionBindings,
282
283
  requiredExtensions: options.requiredExtensions,
283
284
  sessionEnabled: shared.sessionEnabled,
@@ -399,6 +400,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
399
400
  index: options.index ?? 0,
400
401
  agent: agent.name,
401
402
  ...(childSessionName ? { sessionName: childSessionName } : {}),
403
+ ...(options.sessionFile ? { sessionFile: options.sessionFile } : {}),
402
404
  status: "running",
403
405
  task,
404
406
  skills: shared.resolvedSkillNames,
@@ -447,8 +449,8 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
447
449
  return result;
448
450
  }
449
451
  // A machine 'local' child edits this disk, so its local Git evidence is authoritative, as for an unplaced run.
450
- const mutationCwd = isRexLocalMachine(options.machine) ? options.machine.cwd : options.cwd ?? runtimeCwd;
451
- const mutationSnapshot = options.machine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, cwd: mutationCwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(mutationCwd);
452
+ const mutationCwd = editsLocalDisk(options.machine) ? options.machine.cwd : options.cwd ?? runtimeCwd;
453
+ const mutationSnapshot = options.machine && !editsLocalDisk(options.machine) ? remoteMutationSnapshot(mutationCwd) : snapshotTrackedMutations(mutationCwd);
452
454
  let structuredOutputToolInvoked = false;
453
455
  let structuredOutputMessageStartIndex;
454
456
  let toolAvailabilityError;
@@ -1574,8 +1576,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1574
1576
  tokens: progress.tokens,
1575
1577
  durationMs: progress.durationMs,
1576
1578
  };
1577
- const remoteGitChanged = result.nativeMachine?.initialGit && result.nativeMachine.finalGit ? result.nativeMachine.initialGit.head !== result.nativeMachine.finalGit.head || result.nativeMachine.initialGit.dirty !== result.nativeMachine.finalGit.dirty : undefined;
1578
- const mutationEvidence = result.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1579
+ const mutationEvidence = result.nativeMachine && !editsLocalDisk(options.machine) ? remoteMutationEvidence(result.nativeMachine) : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1579
1580
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1580
1581
  const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1581
1582
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1678,7 +1679,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
1678
1679
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
1679
1680
  const effectiveCwd = options.cwd ?? runtimeCwd;
1680
1681
  // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
1681
- const cwdError = options.machine && !isRexLocalMachine(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1682
+ const cwdError = options.machine && !editsLocalDisk(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1682
1683
  if (cwdError) {
1683
1684
  return redactResultPrompt(withRunContext({
1684
1685
  index: options.index ?? 0,
@@ -3360,6 +3360,21 @@ function writeWorkflowAggregateOutput(outputPath, text, producedChildOutputPaths
3360
3360
  return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3361
3361
  }
3362
3362
  }
3363
+ /**
3364
+ * Runs once as the script starts, never at the end: another run sharing the path may publish its report meanwhile,
3365
+ * and a failing run must not delete it.
3366
+ */
3367
+ function removeEarlierWorkflowOutput(outputPath) {
3368
+ if (!outputPath)
3369
+ return undefined;
3370
+ try {
3371
+ fs.rmSync(outputPath, { force: true });
3372
+ return undefined;
3373
+ }
3374
+ catch (error) {
3375
+ return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
3376
+ }
3377
+ }
3363
3378
  function appendWorkflowOutputWarning(text, warning) {
3364
3379
  return warning ? `${text}\n\n${warning}` : text;
3365
3380
  }
@@ -5775,6 +5790,8 @@ export function createSubagentExecutor(deps) {
5775
5790
  step.async = runId !== undefined && path.basename(runId) === runId && fs.existsSync(path.join(path.dirname(asyncDir), runId));
5776
5791
  persist({ tolerateStatusWriteFailure: true });
5777
5792
  };
5793
+ // A relaunch never deletes: a child of the interrupted run, settled or still finishing when Pi exited, may have saved its report there, and a stale file is better than a lost one.
5794
+ const earlierOutputWarning = workflowReuseSource ? undefined : removeEarlierWorkflowOutput(workflowAggregateOutputPath);
5778
5795
  try {
5779
5796
  const workflow = await runWorkflowScript({
5780
5797
  script: workflowScript,
@@ -5951,9 +5968,12 @@ export function createSubagentExecutor(deps) {
5951
5968
  const result = await runMissionWorkflowChild(missionBinding, workflowRunId, key, childPhase, async () => {
5952
5969
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
5953
5970
  preparedChildParams = childRequest;
5954
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5955
- if (launchRefusal)
5956
- return buildRequestedModeError(childRequest, launchRefusal);
5971
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
5972
+ if ("refusal" in approval)
5973
+ return buildRequestedModeError(childRequest, approval.refusal);
5974
+ // Assigned in place: the WeakMaps below are keyed on this object. A resume's task is its message, which stays as sent.
5975
+ if (approval.task !== undefined && childRequest.action !== "resume")
5976
+ childRequest.task = approval.task;
5957
5977
  if (workflowUsageBudget.budget)
5958
5978
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
5959
5979
  if (workflowRequiredExtensions)
@@ -6124,7 +6144,10 @@ export function createSubagentExecutor(deps) {
6124
6144
  const terminalSummary = `${status.state === "complete"
6125
6145
  ? "Workflow completed after detached child finished."
6126
6146
  : errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
6127
- const outputWarning = writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths);
6147
+ // Only completion writes the declared file, so its existence never reads as a delivered report.
6148
+ const outputWarning = status.state === "complete"
6149
+ ? writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths)
6150
+ : earlierOutputWarning;
6128
6151
  const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
6129
6152
  const receiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
6130
6153
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
@@ -6212,6 +6235,7 @@ export function createSubagentExecutor(deps) {
6212
6235
  const liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "running", inventoryComplete: false, trace: liveWorkflow.trace, progress: childProgress, launches: childLaunches });
6213
6236
  onUpdate?.(workflowProgressUpdate(foregroundWorkflowRunId, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight));
6214
6237
  };
6238
+ const earlierOutputWarning = removeEarlierWorkflowOutput(workflowAggregateOutputPath);
6215
6239
  try {
6216
6240
  const workflow = await runWorkflowScript({
6217
6241
  script: requestParams.workflowScript,
@@ -6282,9 +6306,11 @@ export function createSubagentExecutor(deps) {
6282
6306
  const result = await runMissionWorkflowChild(missionBinding, foregroundWorkflowRunId, key, childPhase, async () => {
6283
6307
  const childRequest = bindMissionWorkflowChildAsyncLaunch({ ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted }, missionBinding, deps.asyncByDefault, undefined, inheritedNestedRoute(deps)?.rootRunId);
6284
6308
  preparedChildParams = childRequest;
6285
- const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6286
- if (launchRefusal)
6287
- return buildRequestedModeError(childRequest, launchRefusal);
6309
+ const approval = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
6310
+ if ("refusal" in approval)
6311
+ return buildRequestedModeError(childRequest, approval.refusal);
6312
+ if (approval.task !== undefined && childRequest.action !== "resume")
6313
+ childRequest.task = approval.task;
6288
6314
  if (workflowUsageBudget.budget)
6289
6315
  workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
6290
6316
  if (workflowRequiredExtensions)
@@ -6305,7 +6331,11 @@ export function createSubagentExecutor(deps) {
6305
6331
  (deps.state.blockingWorkflowChildren ??= new Set()).add(launch.runId);
6306
6332
  blockingWorkflowChildren.add(launch.runId);
6307
6333
  }
6308
- childLaunches.set(key, { agent: launch.agent, ...(launch.runId ? { runId: launch.runId } : {}) });
6334
+ childLaunches.set(key, {
6335
+ agent: launch.agent,
6336
+ ...(launch.runId ? { runId: launch.runId } : {}),
6337
+ ...(launch.sessionFile ? { sessionFile: launch.sessionFile } : {}),
6338
+ });
6309
6339
  // Telemetry must not decide the child's outcome, as with onTrace in scripted-workflow.
6310
6340
  try {
6311
6341
  sendWorkflowProgress();
@@ -6406,7 +6436,7 @@ export function createSubagentExecutor(deps) {
6406
6436
  const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
6407
6437
  const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
6408
6438
  const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
6409
- const displayText = formatWorkflowResultText({
6439
+ const displayText = appendWorkflowOutputWarning(formatWorkflowResultText({
6410
6440
  head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
6411
6441
  script: [
6412
6442
  `Workflow failed: ${text}`,
@@ -6419,10 +6449,11 @@ export function createSubagentExecutor(deps) {
6419
6449
  ...(outputMappings ? [outputMappings] : []),
6420
6450
  ],
6421
6451
  maxOutput: requestParams.maxOutput,
6422
- aggregateOutputPath: workflowAggregateOutputPath,
6452
+ // A failed workflow's text never goes to the declared output file; truncated text goes to the full-result file.
6453
+ aggregateOutputPath: undefined,
6423
6454
  fullResultPath: workflowFullResultPath,
6424
6455
  producedChildOutputPaths,
6425
- });
6456
+ }), earlierOutputWarning);
6426
6457
  const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
6427
6458
  const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
6428
6459
  const receipt = terminalWorkflowReceipt(foregroundWorkflowRunId, "failed", partial.children, workflowChildren, terminalOutcome, [...workflowHostSteps.values()], workflowResource?.provenance, workflowArgsDigest);
@@ -26,6 +26,8 @@ export interface BuildInProcessChildLaunchInput {
26
26
  machine?: PlacementMachineReference;
27
27
  remoteSkillNames?: string[];
28
28
  remoteReads?: string[] | false;
29
+ /** Acceptance instructions already folded into `systemPrompt`; a placed child gets only these, since it builds the rest from its own agent file. */
30
+ acceptancePrompt?: string;
29
31
  parentSessionId?: string;
30
32
  /** The launching session's file; a new child session records it as its parent. */
31
33
  parentSessionFile?: string;
@@ -13,7 +13,7 @@ import { encodeExtensionBindings, PI_SUBAGENT_EXTENSION_BINDINGS_ENV } from "./e
13
13
  import { intersectSubagentCapabilityCeilings } from "./capability-ceiling.js";
14
14
  import { isSubagentRuntimeExtensionPath, projectLaunchResolvedChildExtensions, resolvePiLaunchToolPlan, supervisorChannelDir, } from "./child-tool-plan.js";
15
15
  import { createCapturedChildHooks, withChildSessionErrorReporting } from "./child-hooks.js";
16
- import { resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
16
+ import { createRequiredChildExtensionIdentity, resolveRequiredChildExtensions } from "../../shared/required-child-extensions.js";
17
17
  import { DEFAULT_WAIT_TOOL_NAME, waitToolName } from "../../shared/wait-tool-name.js";
18
18
  /** Environment variable pi-mcp-adapter reads for the tools a child may expose. */
19
19
  export const MCP_DIRECT_TOOLS_ENV = "MCP_DIRECT_TOOLS";
@@ -57,6 +57,8 @@ function childProcessEnv(input, toolPlan) {
57
57
  else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
58
58
  env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
59
59
  }
60
+ else if (input.tools === undefined && !toolPlan.capabilityCeiling)
61
+ env[MCP_DIRECT_TOOLS_ENV] = undefined;
60
62
  else
61
63
  env[MCP_DIRECT_TOOLS_ENV] = "__none__";
62
64
  return env;
@@ -106,10 +108,11 @@ export function buildInProcessChildLaunch(input) {
106
108
  permissionRules: input.permissionRules,
107
109
  runtimeSnapshotHost: input.runtimeSnapshotHost,
108
110
  });
109
- // Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
111
+ // Foreground children load no ambient extensions, so only their required extensions' registerMcpServer() runs in them.
110
112
  if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
113
+ const requiredExtensionIdentity = createRequiredChildExtensionIdentity(toolPlan.requiredExtensions.map(({ path }) => path));
111
114
  // Pi treats a session without a trust decision as trusted.
112
- const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
115
+ const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false, (extensionPath) => requiredExtensionIdentity(extensionPath) !== undefined);
113
116
  if (servers.length)
114
117
  throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
115
118
  }
@@ -215,7 +218,7 @@ export function buildInProcessChildLaunch(input) {
215
218
  cwd: input.cwd,
216
219
  ...(input.machine ? { machine: input.machine } : {}),
217
220
  ...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
218
- ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
221
+ ...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}), ...(input.acceptancePrompt ? { acceptancePrompt: input.acceptancePrompt } : {}) } } : {}),
219
222
  storage: childStorage(input),
220
223
  ...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
221
224
  ...(input.model ? { model: input.model } : {}),
@@ -1,7 +1,7 @@
1
1
  import type { AgentMessage } from "@earendil-works/pi-agent-core";
2
2
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
3
3
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
4
- import type { RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
4
+ import { type RequiredChildExtensionSnapshot } from "../../shared/required-child-extensions.ts";
5
5
  import type { PlacementMachineReference, HerdrRemoteGitStatus } from "../../shared/types.ts";
6
6
  export interface ChildSessionEvent {
7
7
  type: string;
@@ -37,12 +37,13 @@ export interface ChildSessionLaunch {
37
37
  projectTrusted?: boolean;
38
38
  /** Process-local provider source owned by the invoking foreground parent. */
39
39
  parentProviderRegistry?: ParentProviderRegistry;
40
- /** Logical names resolved only by the remote ambient package. */
40
+ /** Logical names resolved only by the remote ambient package, plus the parent's acceptance instructions, which no remote file holds. */
41
41
  remoteResources?: {
42
42
  agent: string;
43
43
  skills?: string[];
44
44
  toolCeiling?: string[];
45
45
  reads?: string[] | false;
46
+ acceptancePrompt?: string;
46
47
  };
47
48
  storage: ChildSessionStorage;
48
49
  /** The launching session's file, recorded as the new child session's `parentSession` header like Pi's forks. */
@@ -26,6 +26,7 @@ import { parseAcceptanceReport } from "./acceptance.js";
26
26
  import { getAgentDir, PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.js";
27
27
  import { resolvePackageSubpath } from "../background/runner-aliases.js";
28
28
  import { PI_CODING_AGENT_PACKAGE, resolveHostPiPackageRoot } from "./pi-spawn.js";
29
+ import { createRequiredChildExtensionIdentity } from "../../shared/required-child-extensions.js";
29
30
  /** Mirror pi's JSON event projection: `message_update` drops the partial message. */
30
31
  export function projectChildSessionEventForJson(event) {
31
32
  if (event.type !== "message_update")
@@ -80,32 +81,6 @@ const CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime
80
81
  const CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
81
82
  /** Same class as UNICODE_SPACES in pi-coding-agent dist/utils/paths.js, which resolvePath(..., { normalizeUnicodeSpaces: true }) replaces with a space. */
82
83
  const PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
83
- function childExtensionFileIdentity(extensionPath) {
84
- if (!path.isAbsolute(extensionPath))
85
- return undefined;
86
- try {
87
- const stat = fs.statSync(extensionPath, { bigint: true });
88
- return stat.isFile() ? `${stat.dev}:${stat.ino}` : undefined;
89
- }
90
- catch {
91
- return undefined;
92
- }
93
- }
94
- function createRequiredChildExtensionIdentity(requiredPaths) {
95
- const aliases = new Map([...requiredPaths].map((extensionPath) => [extensionPath, childExtensionFileIdentity(extensionPath) ?? extensionPath]));
96
- const identities = new Set(aliases.values());
97
- return (extensionPath) => {
98
- const known = aliases.get(extensionPath);
99
- if (known !== undefined)
100
- return known;
101
- const identity = childExtensionFileIdentity(extensionPath);
102
- if (identity === undefined || !identities.has(identity))
103
- return undefined;
104
- // Retain the alias even if the extension removes its file before reporting a failure.
105
- aliases.set(extensionPath, identity);
106
- return identity;
107
- };
108
- }
109
84
  /** The prompt runtime filters parent-only context before ambient extensions inspect
110
85
  * the child prompt, and the boundary hook appends the child boundary after every
111
86
  * extension has added its prompt sections. Every other extension keeps its order. */
@@ -591,7 +566,8 @@ export function createDefaultChildSessionFactory(options = {}) {
591
566
  await session.bindExtensions({
592
567
  mode: "print",
593
568
  onError: (error) => {
594
- if (binding && isRequiredSource(error.extensionPath))
569
+ // Pi's unconnected-MCP-server report means the server's tools are outside this child's tool contract, which the child can run without.
570
+ if (binding && error.event !== "register_mcp_server" && isRequiredSource(error.extensionPath))
595
571
  requiredStartupErrors.push(`${error.extensionPath} (${error.event}): ${error.error}`);
596
572
  launch.onExtensionError?.({ extensionPath: error.extensionPath, event: error.event, error: error.error });
597
573
  },
@@ -37,7 +37,13 @@ export interface HerdrForwardedConnection {
37
37
  type SshTarget = Pick<HerdrMachineReference, "target">;
38
38
  export declare function decodeHerdrJsonLine(line: Buffer): unknown;
39
39
  export declare function shellQuoteRemote(value: string): string;
40
+ export declare function shellScriptCommand(script: string, args?: string[]): string;
40
41
  export declare function remoteShellCommand(script: string, args?: string[]): string;
42
+ /**
43
+ * Points herdr at a recorded local server only: the calling process's own pane selectors (a background runner started from
44
+ * another pane) never choose it. A named session's server reports its name only when HERDR_SESSION says it (herdr 0.9.5).
45
+ */
46
+ export declare function herdrLocalEnv(socket: string, session: string | null | undefined, source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
41
47
  export declare function runHerdrRemoteCommand(machine: SshTarget, command: string, options?: {
42
48
  sshBin?: string;
43
49
  env?: NodeJS.ProcessEnv;
@@ -25,8 +25,18 @@ catch {
25
25
  throw new Error("Herdr emitted malformed JSON or UTF-8.");
26
26
  } }
27
27
  export function shellQuoteRemote(value) { return `'${value.replaceAll("'", "'\\''")}'`; }
28
- export function remoteShellCommand(script, args = []) { return `sh -c ${shellQuoteRemote(`PATH="${HERDR_REMOTE_PATH}"; export PATH; ${script}`)} sh${args.map((arg) => ` ${shellQuoteRemote(arg)}`).join("")}`; }
28
+ export function shellScriptCommand(script, args = []) { return `sh -c ${shellQuoteRemote(script)} sh${args.map((arg) => ` ${shellQuoteRemote(arg)}`).join("")}`; }
29
+ export function remoteShellCommand(script, args = []) { return shellScriptCommand(`PATH="${HERDR_REMOTE_PATH}"; export PATH; ${script}`, args); }
29
30
  function canonicalHerdrSession(session) { return session && session !== "default" ? session : null; }
31
+ /**
32
+ * Points herdr at a recorded local server only: the calling process's own pane selectors (a background runner started from
33
+ * another pane) never choose it. A named session's server reports its name only when HERDR_SESSION says it (herdr 0.9.5).
34
+ */
35
+ export function herdrLocalEnv(socket, session, source) {
36
+ const { HERDR_SESSION: _session, HERDR_CLIENT_SOCKET_PATH: _client, HERDR_PANE_ID: _pane, HERDR_ENV: _env, HERDR_SOCKET_PATH: _socket, ...env } = source;
37
+ const selected = canonicalHerdrSession(session);
38
+ return { ...env, HERDR_SOCKET_PATH: socket, ...(selected ? { HERDR_SESSION: selected } : {}) };
39
+ }
30
40
  function sshEnvCommand(session, command) { const selected = canonicalHerdrSession(session), assignment = selected ? ` HERDR_SESSION=${shellQuoteRemote(selected)}` : ""; return `/usr/bin/env -u HERDR_SOCKET_PATH -u HERDR_SESSION${assignment} ${remoteShellCommand(command)}`; }
31
41
  export function runHerdrRemoteCommand(machine, command, options = {}) { return spawnSync(options.sshBin ?? "ssh", [...herdrSshArgs(options.env), machine.target, command], { encoding: "utf8", env: hardenedSshEnv(options.env), timeout: options.timeout ?? 15_000, maxBuffer: options.maxBuffer ?? MAX_DISCOVERY_BYTES, windowsHide: true }); }
32
42
  export function runHerdrRemoteCommandAsync(machine, command, options = {}) {
@@ -29,7 +29,7 @@ export interface ResolveHerdrMachinePlacementInput {
29
29
  export interface HerdrMachinePlacement extends MachinePlacement {
30
30
  machine: HerdrMachineReference;
31
31
  }
32
- /** A resolved `machine` value: a Herdr saved machine, or the reserved `local` (a Rex pane on this machine). */
32
+ /** A resolved `machine` value: a Herdr saved machine, a Rex SSH host, or the reserved `local` (a new tab of the Herdr or Rex session this Pi runs in). */
33
33
  export interface MachinePlacement {
34
34
  machine: PlacementMachineReference;
35
35
  /** Opt-in `subagents.machines.<name>.env`, exported in front of the remote command. */
@@ -40,7 +40,7 @@ export interface PreparedHerdrMachineExternalCliRun {
40
40
  decorateProcess(process: ExternalProcessStatus): ExternalProcessStatus;
41
41
  }
42
42
  export declare function resolveHerdrMachinePlacement(input: ResolveHerdrMachinePlacementInput): HerdrMachinePlacement;
43
- /** `local` resolves to a Rex pane on this machine; a name with a `rex` entry in user settings to a Rex pane on that SSH host; any other value to a Herdr saved machine. */
43
+ /** `local` resolves to a new tab of the terminal this Pi runs in (Herdr, else Rex); a name with a `rex` entry in user settings to a Rex pane on that SSH host; any other value to a Herdr saved machine. */
44
44
  export declare function resolveMachinePlacement(input: ResolveHerdrMachinePlacementInput): MachinePlacement;
45
45
  /** A placed Pi keeps its transcript on the pane's machine, so it can't start from a local one. */
46
46
  export declare const PLACED_RESTORE_UNSUPPORTED = "Pane-native remote Pi does not support fork, resume, or revival; use fresh context.";
@@ -3,7 +3,8 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { getAgentDir, getProjectConfigDir } from "../../shared/utils.js";
5
5
  import { CODE_OWNED_EXTERNAL_CLI_ADAPTER_IDS } from "./external-cli-contract.js";
6
- import { REX_LOCAL_MACHINE, resolveRexLocalPlacement } from "./rex-machine.js";
6
+ import { herdrLocalEnv, parseHerdrEndpoint } from "./herdr-connection.js";
7
+ import { REX_LOCAL_MACHINE, resolveLocalLaunchCwd, resolveRexLocalPlacement } from "./rex-machine.js";
7
8
  export { shellQuoteRemote as shellQuote } from "./herdr-connection.js";
8
9
  /**
9
10
  * Herdr saved-machine placement for external CLI children.
@@ -75,22 +76,15 @@ function parseMachineCatalog(json) {
75
76
  });
76
77
  }
77
78
  function readHerdrMachineCatalog(env, herdrBin) {
78
- const result = spawnSync(herdrBin, ["machine", "list", "--json"], {
79
- env,
80
- encoding: "utf-8",
81
- maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES,
82
- timeout: HERDR_MACHINE_LIST_TIMEOUT_MS,
83
- windowsHide: true,
84
- });
85
- if (result.error) {
86
- const code = result.error.code;
87
- if (code === "ENOENT")
88
- throw new Error(`Herdr CLI '${herdrBin}' was not found on PATH. Saved-machine placement needs Herdr installed locally.`);
89
- throw new Error(`Failed to run herdr machine list --json: ${result.error.message}`);
90
- }
79
+ return parseMachineCatalog(runLocalHerdr(herdrBin, ["machine", "list", "--json"], env, `Herdr CLI '${herdrBin}' was not found on PATH. Saved-machine placement needs Herdr installed locally.`));
80
+ }
81
+ function runLocalHerdr(bin, args, env, notFound) {
82
+ const result = spawnSync(bin, args, { env, encoding: "utf-8", maxBuffer: MAX_HERDR_MACHINE_LIST_BYTES, timeout: HERDR_MACHINE_LIST_TIMEOUT_MS, windowsHide: true });
83
+ if (result.error)
84
+ throw new Error(result.error.code === "ENOENT" ? notFound : `Failed to run herdr ${args.join(" ")}: ${result.error.message}`, { cause: result.error });
91
85
  if (result.status !== 0)
92
- throw new Error(`herdr machine list --json exited with code ${result.status}: ${(result.stderr || result.stdout).trim()}`);
93
- return parseMachineCatalog(result.stdout);
86
+ throw new Error(`herdr ${args.join(" ")} exited with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
87
+ return result.stdout;
94
88
  }
95
89
  /** Mirrors Herdr's own selector rules: profile id first, then a unique case-sensitive label; disabled fails closed. */
96
90
  function selectMachine(catalog, requested) {
@@ -220,14 +214,44 @@ export function resolveHerdrMachinePlacement(input) {
220
214
  ...(settings?.env ? { env: settings.env } : {}),
221
215
  };
222
216
  }
223
- /** `local` resolves to a Rex pane on this machine; a name with a `rex` entry in user settings to a Rex pane on that SSH host; any other value to a Herdr saved machine. */
217
+ /** Resolves `machine: "local"` inside a Herdr pane: records the server drawing this Pi (confirmed to know this pane) and the real launch directory. */
218
+ function resolveHerdrLocalPlacement(input) {
219
+ if (process.platform === "win32")
220
+ throw new Error("Machine 'local' runs the child in a Herdr pane, which is not supported on Windows.");
221
+ 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.`;
222
+ let endpoint;
223
+ try {
224
+ endpoint = parseHerdrEndpoint(runLocalHerdr(bin, ["status", "server", "--json"], env, notFound), env.HERDR_SESSION);
225
+ }
226
+ catch (error) {
227
+ throw new Error(`Machine 'local' could not confirm this pane's Herdr server: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
228
+ }
229
+ let pane;
230
+ try {
231
+ pane = JSON.parse(runLocalHerdr(bin, ["pane", "get", paneId], herdrLocalEnv(endpoint.socket, endpoint.session, env), notFound));
232
+ }
233
+ catch (error) {
234
+ 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 });
235
+ }
236
+ const result = pane?.result;
237
+ if (result?.type !== "pane_info" || result.pane?.pane_id !== paneId)
238
+ throw new Error(`The Herdr server at ${endpoint.socket} did not confirm pane ${paneId}.`);
239
+ return { provider: "herdr", id: REX_LOCAL_MACHINE, socket: endpoint.socket, ...(endpoint.session ? { session: endpoint.session } : {}), cwd: resolveLocalLaunchCwd(input.cwd, input.stepCwd) };
240
+ }
241
+ /** `local` resolves to a new tab of the terminal this Pi runs in (Herdr, else Rex); a name with a `rex` entry in user settings to a Rex pane on that SSH host; any other value to a Herdr saved machine. */
224
242
  export function resolveMachinePlacement(input) {
225
243
  const requested = validateMachineName(input.machine);
226
244
  const settings = input.settings ?? readMachineSettings(input.cwd, [requested]);
227
245
  if (requested === REX_LOCAL_MACHINE) {
228
246
  if (settings?.rex)
229
- 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.");
230
- return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env: input.env }) };
247
+ 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.");
248
+ const env = input.env ?? process.env;
249
+ // A Herdr pane sets both; when Herdr runs inside a Rex tab its panes also inherit REX_SESSION, and the Herdr pane is where this Pi is drawn.
250
+ if (env.HERDR_ENV === "1" && env.HERDR_PANE_ID?.trim())
251
+ return { machine: resolveHerdrLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env, herdrBin: input.herdrBin }) };
252
+ if (env.REX_SESSION?.trim())
253
+ return { machine: resolveRexLocalPlacement({ cwd: input.cwd, stepCwd: input.stepCwd, env }) };
254
+ 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).");
231
255
  }
232
256
  if (settings?.rex)
233
257
  return { machine: { provider: "rex", id: requested, target: settings.rex.ssh, cwd: validateRemoteCwd(remoteMachineCwd(input.stepCwd, settings.cwd, requested), requested) } };
@@ -239,20 +263,21 @@ export function formatHerdrMachineRunnerUnsupported(input) {
239
263
  if (input.machine === undefined)
240
264
  return undefined;
241
265
  const name = input.machine.trim();
266
+ const local = name === REX_LOCAL_MACHINE;
242
267
  let rex;
243
268
  try {
244
- rex = name === REX_LOCAL_MACHINE || userRexMachine(name);
269
+ rex = local || userRexMachine(name);
245
270
  }
246
271
  catch (error) {
247
272
  return error instanceof Error ? error.message : String(error);
248
273
  }
249
274
  if (rex) {
250
275
  if (input.runnerType !== undefined && input.runnerType !== "pi")
251
- return `Agent '${input.agentName}' requested machine '${name}', but Rex supports native Pi children only. Remove the machine or use a native Pi agent.`;
276
+ 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.`;
252
277
  if (input.worktree === true)
253
278
  return `Agent '${input.agentName}' requested machine '${name}', but managed worktrees cannot be combined with machine placement.`;
254
279
  if (process.platform === "win32")
255
- return `Machine '${name}' runs the child in a Rex pane, which is not supported on Windows.`;
280
+ return `Machine '${name}' runs the child in ${local ? "a Herdr or Rex pane" : "a Rex pane"}, which is not supported on Windows.`;
256
281
  return undefined;
257
282
  }
258
283
  if (input.runnerType !== undefined && input.runnerType !== "pi" && input.runnerType !== "external-cli") {