pi-subagents 0.88.1 → 0.89.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -1
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/{chunk-VTUUOLM4.js → chunk-2I6YN6ET.js} +34 -5
- package/bundle/{chunk-7OX6O7DQ.js → chunk-443LPCRI.js} +5 -5
- package/bundle/{chunk-4QFZZV3O.js → chunk-4AL6LDBY.js} +3 -1
- package/bundle/{chunk-6CG2VAG4.js → chunk-4ALRHKGE.js} +1 -1
- package/bundle/{chunk-4ZQBZDF3.js → chunk-6JD4XCA4.js} +76 -18
- package/bundle/{chunk-LV3CPYXJ.js → chunk-7W2IQFP4.js} +4 -4
- package/bundle/{chunk-W6HIYD2Z.js → chunk-A3INCQ6Z.js} +1 -1
- package/bundle/{chunk-FLNDHNPE.js → chunk-AZW4HXNU.js} +21 -21
- package/bundle/{chunk-ZJ2BT5TI.js → chunk-CHEABMO2.js} +56 -34
- package/bundle/{chunk-CYKNHFXB.js → chunk-EPMRDKQT.js} +1 -1
- package/bundle/{chunk-RMZAAXIR.js → chunk-ETDE2VYK.js} +2 -2
- package/bundle/{chunk-4MVDMA5C.js → chunk-GHJ6BH5U.js} +13 -7
- package/bundle/{chunk-PYKBTBY6.js → chunk-HSHLPYCQ.js} +9 -9
- package/bundle/{chunk-D32H53HM.js → chunk-HZDLR73C.js} +1 -1
- package/bundle/{chunk-2DIEL4WG.js → chunk-JFACGAJT.js} +2 -2
- package/bundle/{chunk-L4YY2TOE.js → chunk-JRO2CU4D.js} +1 -1
- package/bundle/{chunk-KXW62VBU.js → chunk-KOLLMZ2X.js} +1 -1
- package/bundle/{chunk-47ZN7NKR.js → chunk-NONHDYXE.js} +1 -1
- package/bundle/{chunk-DSHQWGHO.js → chunk-NQ26PJSQ.js} +96 -96
- package/bundle/{chunk-6OWNDN7R.js → chunk-PPPAEFRA.js} +2 -2
- package/bundle/{chunk-YDZ7BZD5.js → chunk-S77ZKDLS.js} +1 -1
- package/bundle/{chunk-CPSUJHZE.js → chunk-SLLZJ5EC.js} +39 -10
- package/bundle/{chunk-N6TAAIB3.js → chunk-TGABNSG5.js} +5 -5
- package/bundle/{chunk-XIA5GSEU.js → chunk-UQT2EQ4U.js} +2 -2
- package/bundle/{chunk-5EMPFFO4.js → chunk-WW6GQBBS.js} +4 -4
- package/bundle/{chunk-PCZEQQAQ.js → chunk-X5ZOTDHO.js} +26 -15
- package/bundle/{chunk-YQSTGPEU.js → chunk-YX7R55CR.js} +74 -31
- package/bundle/{chunk-GDR2ILWY.js → chunk-ZSCIHMUI.js} +50 -22
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +2 -2
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +8 -8
- package/bundle/project-panes.js +3 -3
- package/docs/agents.md +10 -4
- package/docs/configuration.md +2 -0
- package/docs/extension-api.md +1 -1
- package/docs/tool-reference.md +1 -1
- package/docs/workflows.md +5 -3
- package/package.json +1 -1
- package/src/extension/herdr-pi-bridge.js +78 -22
- package/src/extension/schemas.js +1 -1
- package/src/extension/subagent-options.js +5 -0
- package/src/intercom/result-intercom.js +3 -2
- package/src/runs/background/notify.d.ts +3 -0
- package/src/runs/background/notify.js +7 -2
- package/src/runs/background/run-status.js +3 -2
- package/src/runs/background/runner-child-launch.js +1 -0
- package/src/runs/background/subagent-runner.js +11 -8
- package/src/runs/foreground/execution.js +8 -7
- package/src/runs/foreground/subagent-executor.js +31 -5
- package/src/runs/shared/child-launch.d.ts +2 -0
- package/src/runs/shared/child-launch.js +1 -1
- package/src/runs/shared/child-session.d.ts +2 -1
- package/src/runs/shared/herdr-connection.d.ts +6 -0
- package/src/runs/shared/herdr-connection.js +11 -1
- package/src/runs/shared/herdr-machine.d.ts +2 -2
- package/src/runs/shared/herdr-machine.js +47 -22
- package/src/runs/shared/herdr-pane-host.d.ts +7 -19
- package/src/runs/shared/herdr-pane-host.js +48 -33
- package/src/runs/shared/herdr-pi-protocol.d.ts +1 -0
- package/src/runs/shared/herdr-pi-protocol.js +3 -2
- package/src/runs/shared/herdr-placed-run.d.ts +2 -12
- package/src/runs/shared/herdr-placed-run.js +10 -8
- package/src/runs/shared/kept-branch-text.d.ts +8 -0
- package/src/runs/shared/kept-branch-text.js +24 -0
- package/src/runs/shared/local-machine-access.d.ts +4 -1
- package/src/runs/shared/local-machine-access.js +6 -3
- package/src/runs/shared/mutation-evidence.d.ts +7 -1
- package/src/runs/shared/mutation-evidence.js +18 -2
- package/src/runs/shared/parallel-handoff.js +19 -7
- package/src/runs/shared/placed-run-owner.d.ts +4 -2
- package/src/runs/shared/placed-run-owner.js +15 -7
- package/src/runs/shared/rex-machine.d.ts +7 -3
- package/src/runs/shared/rex-machine.js +12 -9
- package/src/runs/shared/rex-pane-host.js +7 -27
- package/src/runs/shared/single-output.js +2 -2
- package/src/runs/shared/subagent-prompt-runtime.js +33 -0
- package/src/runs/shared/tool-availability.d.ts +4 -0
- package/src/runs/shared/tool-availability.js +7 -0
- package/src/runs/shared/worktree-cleanup-plan.js +2 -2
- package/src/runs/shared/worktree.d.ts +4 -14
- package/src/runs/shared/worktree.js +38 -8
- package/src/shared/types.d.ts +26 -2
- package/src/workflows/workflow-child-summary.d.ts +2 -1
- package/src/workflows/workflow-child-summary.js +14 -6
|
@@ -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 {
|
|
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 =
|
|
451
|
-
const mutationSnapshot = options.machine && !
|
|
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
|
|
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 && !
|
|
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,
|
|
@@ -3372,6 +3372,21 @@ function writeWorkflowAggregateOutput(outputPath, text, producedChildOutputPaths
|
|
|
3372
3372
|
return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
|
|
3373
3373
|
}
|
|
3374
3374
|
}
|
|
3375
|
+
/**
|
|
3376
|
+
* Runs once as the script starts, never at the end: another run sharing the path may publish its report meanwhile,
|
|
3377
|
+
* and a failing run must not delete it.
|
|
3378
|
+
*/
|
|
3379
|
+
function removeEarlierWorkflowOutput(outputPath) {
|
|
3380
|
+
if (!outputPath)
|
|
3381
|
+
return undefined;
|
|
3382
|
+
try {
|
|
3383
|
+
fs.rmSync(outputPath, { force: true });
|
|
3384
|
+
return undefined;
|
|
3385
|
+
}
|
|
3386
|
+
catch (error) {
|
|
3387
|
+
return `Output file error: ${outputPath}\n${error instanceof Error ? error.message : String(error)}`;
|
|
3388
|
+
}
|
|
3389
|
+
}
|
|
3375
3390
|
function appendWorkflowOutputWarning(text, warning) {
|
|
3376
3391
|
return warning ? `${text}\n\n${warning}` : text;
|
|
3377
3392
|
}
|
|
@@ -5787,6 +5802,8 @@ export function createSubagentExecutor(deps) {
|
|
|
5787
5802
|
step.async = runId !== undefined && path.basename(runId) === runId && fs.existsSync(path.join(path.dirname(asyncDir), runId));
|
|
5788
5803
|
persist({ tolerateStatusWriteFailure: true });
|
|
5789
5804
|
};
|
|
5805
|
+
// 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.
|
|
5806
|
+
const earlierOutputWarning = workflowReuseSource ? undefined : removeEarlierWorkflowOutput(workflowAggregateOutputPath);
|
|
5790
5807
|
try {
|
|
5791
5808
|
const workflow = await runWorkflowScript({
|
|
5792
5809
|
script: workflowScript,
|
|
@@ -6139,7 +6156,10 @@ export function createSubagentExecutor(deps) {
|
|
|
6139
6156
|
const terminalSummary = `${status.state === "complete"
|
|
6140
6157
|
? "Workflow completed after detached child finished."
|
|
6141
6158
|
: errorPreview ?? (pauseForDetached ? "Workflow paused." : "Workflow failed.")}${stopCause ? ` ${WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE}` : ""}${workflowOutputPathMappingSummary(partial.children)}${finalPreflightWarnings.length ? ` ${finalPreflightWarnings.join(" ")}` : ""}`;
|
|
6142
|
-
|
|
6159
|
+
// Only completion writes the declared file, so its existence never reads as a delivered report.
|
|
6160
|
+
const outputWarning = status.state === "complete"
|
|
6161
|
+
? writeWorkflowAggregateOutput(workflowAggregateOutputPath, terminalSummary, producedChildOutputPaths)
|
|
6162
|
+
: earlierOutputWarning;
|
|
6143
6163
|
const resultSummary = appendWorkflowOutputWarning(terminalSummary, outputWarning);
|
|
6144
6164
|
const receiptState = status.state === "complete" ? "complete" : status.state === "paused" ? "paused" : status.state === "stopped" ? "stopped" : "failed";
|
|
6145
6165
|
const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
|
|
@@ -6227,6 +6247,7 @@ export function createSubagentExecutor(deps) {
|
|
|
6227
6247
|
const liveWorkflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "running", inventoryComplete: false, trace: liveWorkflow.trace, progress: childProgress, launches: childLaunches });
|
|
6228
6248
|
onUpdate?.(workflowProgressUpdate(foregroundWorkflowRunId, chatProgress, liveWorkflow, liveWorkflowChildren, workflowPreflight));
|
|
6229
6249
|
};
|
|
6250
|
+
const earlierOutputWarning = removeEarlierWorkflowOutput(workflowAggregateOutputPath);
|
|
6230
6251
|
try {
|
|
6231
6252
|
const workflow = await runWorkflowScript({
|
|
6232
6253
|
script: requestParams.workflowScript,
|
|
@@ -6322,7 +6343,11 @@ export function createSubagentExecutor(deps) {
|
|
|
6322
6343
|
(deps.state.blockingWorkflowChildren ??= new Set()).add(launch.runId);
|
|
6323
6344
|
blockingWorkflowChildren.add(launch.runId);
|
|
6324
6345
|
}
|
|
6325
|
-
childLaunches.set(key, {
|
|
6346
|
+
childLaunches.set(key, {
|
|
6347
|
+
agent: launch.agent,
|
|
6348
|
+
...(launch.runId ? { runId: launch.runId } : {}),
|
|
6349
|
+
...(launch.sessionFile ? { sessionFile: launch.sessionFile } : {}),
|
|
6350
|
+
});
|
|
6326
6351
|
// Telemetry must not decide the child's outcome, as with onTrace in scripted-workflow.
|
|
6327
6352
|
try {
|
|
6328
6353
|
sendWorkflowProgress();
|
|
@@ -6423,7 +6448,7 @@ export function createSubagentExecutor(deps) {
|
|
|
6423
6448
|
const finalPreflightTrace = annotateWorkflowPreflightTrace(partial.trace, workflowPreflight);
|
|
6424
6449
|
const trace = finalPreflightTrace.map((entry) => ({ line: `- ${entry.operation} ${entry.key}: ${entry.state}${entry.runId ? ` (${entry.runId})` : ""}${entry.warning ? ` — ${entry.warning}` : ""}`, error: entry.error }));
|
|
6425
6450
|
const outputMappings = workflowOutputPathMappingSummary(partial.children).trim();
|
|
6426
|
-
const displayText = formatWorkflowResultText({
|
|
6451
|
+
const displayText = appendWorkflowOutputWarning(formatWorkflowResultText({
|
|
6427
6452
|
head: workflowPreflight ? [formatWorkflowPreflight(workflowPreflight)] : [],
|
|
6428
6453
|
script: [
|
|
6429
6454
|
`Workflow failed: ${text}`,
|
|
@@ -6436,10 +6461,11 @@ export function createSubagentExecutor(deps) {
|
|
|
6436
6461
|
...(outputMappings ? [outputMappings] : []),
|
|
6437
6462
|
],
|
|
6438
6463
|
maxOutput: requestParams.maxOutput,
|
|
6439
|
-
|
|
6464
|
+
// A failed workflow's text never goes to the declared output file; truncated text goes to the full-result file.
|
|
6465
|
+
aggregateOutputPath: undefined,
|
|
6440
6466
|
fullResultPath: workflowFullResultPath,
|
|
6441
6467
|
producedChildOutputPaths,
|
|
6442
|
-
});
|
|
6468
|
+
}), earlierOutputWarning);
|
|
6443
6469
|
const workflowChildren = workflowChildSummary({ parentToolCallId: _id, workflowRunId: foregroundWorkflowRunId, workflowState: "failed", inventoryComplete: true, trace: partial.trace, children: partial.children });
|
|
6444
6470
|
const terminalOutcome = workflowFailureTerminalOutcome(error, partial.children, usageBudgetState(workflowUsageBudget.budget, sumResultsCost(workflowResults)));
|
|
6445
6471
|
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;
|
|
@@ -218,7 +218,7 @@ export function buildInProcessChildLaunch(input) {
|
|
|
218
218
|
cwd: input.cwd,
|
|
219
219
|
...(input.machine ? { machine: input.machine } : {}),
|
|
220
220
|
...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
|
|
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] } : {}) } } : {}),
|
|
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 } : {}) } } : {}),
|
|
222
222
|
storage: childStorage(input),
|
|
223
223
|
...(input.parentSessionFile ? { parentSessionFile: input.parentSessionFile } : {}),
|
|
224
224
|
...(input.model ? { model: input.model } : {}),
|
|
@@ -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. */
|
|
@@ -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
|
|
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
|
|
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
|
|
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 {
|
|
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
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
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
|
|
93
|
-
return
|
|
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`
|
|
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
|
|
230
|
-
|
|
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 =
|
|
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") {
|
|
@@ -1,8 +1,9 @@
|
|
|
1
|
-
import type { HerdrMachineReference, PlacementMachineReference } from "../../shared/types.ts";
|
|
1
|
+
import type { HerdrLocalMachineReference, HerdrMachineReference, PlacementMachineReference } from "../../shared/types.ts";
|
|
2
2
|
import { type HerdrForwardedConnection, type HerdrRpcClient } from "./herdr-connection.ts";
|
|
3
3
|
import type { HerdrRunIdentity } from "./herdr-placed-run.ts";
|
|
4
|
-
import { PlacedRunOwner
|
|
4
|
+
import { PlacedRunOwner } from "./placed-run-owner.ts";
|
|
5
5
|
import { type PlacementAgentKind, type PlacementBridgeIdentity, type PlacementEvidenceProof, type PlacementOwnedPane, type PlacementPromptOptions, type PlacementReconnectCheck, type PlacementRunState, type PlacementStartOptions } from "./placement-host.ts";
|
|
6
|
+
type HerdrPlacementMachine = HerdrMachineReference | HerdrLocalMachineReference;
|
|
6
7
|
export interface HerdrPaneCandidate {
|
|
7
8
|
endpoint: {
|
|
8
9
|
session: string | null;
|
|
@@ -35,7 +36,7 @@ export declare function provisionHerdrPane(client: HerdrRpcClient, cwd: string,
|
|
|
35
36
|
paneId: string;
|
|
36
37
|
}>;
|
|
37
38
|
declare function closeOwnedHerdrPane(connection: HerdrForwardedConnection, owned: PlacementOwnedPane, terminalId: string | undefined, agentName: string | undefined): Promise<void>;
|
|
38
|
-
/** Herdr pane host: Herdr RPC over the SSH-forwarded
|
|
39
|
+
/** Herdr pane host: Herdr RPC over the Herdr socket, SSH-forwarded for a saved machine and direct for `local`. Ownership is the Herdr terminal_id/pane_id pair; run state comes from agent_status. */
|
|
39
40
|
export declare const herdrPaneHost: {
|
|
40
41
|
connect(machine: PlacementMachineReference): Promise<HerdrForwardedConnection>;
|
|
41
42
|
sessionOf(connection: HerdrForwardedConnection): string | null;
|
|
@@ -61,23 +62,10 @@ export declare const herdrPaneHost: {
|
|
|
61
62
|
reconcile: typeof reconcileHerdrPlacedRun;
|
|
62
63
|
closeOwnedPane: typeof closeOwnedHerdrPane;
|
|
63
64
|
};
|
|
64
|
-
/** SSH
|
|
65
|
-
export declare
|
|
66
|
-
sshBin?: string;
|
|
67
|
-
env?: NodeJS.ProcessEnv;
|
|
68
|
-
}): Promise<PlacedBridgeManifest>;
|
|
69
|
-
export declare function createRemoteRuntimeDir(machine: HerdrMachineReference, runId: string, options?: {
|
|
70
|
-
sshBin?: string;
|
|
71
|
-
env?: NodeJS.ProcessEnv;
|
|
72
|
-
}): Promise<string>;
|
|
73
|
-
export declare function removeRemoteRuntimeDir(machine: HerdrMachineReference, runtimeDir: string, options?: {
|
|
74
|
-
sshBin?: string;
|
|
75
|
-
env?: NodeJS.ProcessEnv;
|
|
76
|
-
}): void;
|
|
77
|
-
/** The placed-run owner bound to Herdr and SSH access, plus the separate provision and start steps the external CLI adapters use. */
|
|
78
|
-
export declare class HerdrPlacedRunOwner extends PlacedRunOwner<HerdrForwardedConnection, HerdrMachineReference> {
|
|
65
|
+
/** The placed-run owner bound to Herdr and its machine access (SSH, or this machine for `local`), plus the separate provision and start steps the external CLI adapters use. */
|
|
66
|
+
export declare class HerdrPlacedRunOwner<M extends HerdrPlacementMachine = HerdrMachineReference> extends PlacedRunOwner<HerdrForwardedConnection, M> {
|
|
79
67
|
private constructor();
|
|
80
|
-
static create(machine:
|
|
68
|
+
static create<M extends HerdrPlacementMachine>(machine: M, runId: string, beforePane?: (owner: HerdrPlacedRunOwner<M>) => void | Promise<void>): Promise<HerdrPlacedRunOwner<M>>;
|
|
81
69
|
provision(environment?: Record<string, string>): Promise<PlacementOwnedPane>;
|
|
82
70
|
start(kind: PlacementAgentKind, name: string, args: string[], options?: PlacementStartOptions): Promise<{
|
|
83
71
|
terminalId: string;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { connectHerdrMachine, sshMachineAccess } from "./herdr-connection.js";
|
|
2
|
+
import { connectHerdrMachine, herdrLocalEnv, parseHerdrEndpoint, runBoundedCommand, SocketRpcClient, sshMachineAccess } from "./herdr-connection.js";
|
|
3
3
|
import { HERDR_PI_MODE_ENV, HERDR_PI_RUN_ENV, HERDR_PI_RUNTIME_DIR_ENV } from "./herdr-pi-protocol.js";
|
|
4
|
-
import {
|
|
4
|
+
import { localMachineAccess } from "./local-machine-access.js";
|
|
5
|
+
import { createPlacedRuntimeDir, hashedRuntimeDirName, PlacedRunOwner, removePlacedRuntimeDir } from "./placed-run-owner.js";
|
|
5
6
|
import { herdrPaneAllocationKey, withHerdrPaneAllocationLock } from "./placement-host.js";
|
|
6
7
|
function herdrRunState(status, fallback = "unknown") {
|
|
7
8
|
return status === "working" ? "working" : status === "blocked" ? "blocked" : status === "idle" || status === "done" ? "settled" : status === "unknown" ? "unknown" : fallback;
|
|
@@ -53,9 +54,23 @@ export async function provisionHerdrPane(client, cwd, runId, runtimeDir, environ
|
|
|
53
54
|
return { workspaceId: workspace.workspaceId, tabId: workspace.tabId, paneId: workspace.paneId };
|
|
54
55
|
});
|
|
55
56
|
}
|
|
56
|
-
function provisionHerdrOwnedPane(connection, machine, runId, runtimeDir, environment) { return provisionHerdrPane(connection.client, machine.cwd, runId, runtimeDir, environment, herdrPaneAllocationKey(machine.target, connection.endpoint.session, machine.cwd)); }
|
|
57
|
+
function provisionHerdrOwnedPane(connection, machine, runId, runtimeDir, environment) { 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])); }
|
|
57
58
|
function asHerdrMachine(machine) { if (machine.provider !== "herdr")
|
|
58
|
-
throw new Error("The Herdr pane host only places runs on Herdr
|
|
59
|
+
throw new Error("The Herdr pane host only places runs on Herdr machines."); return machine; }
|
|
60
|
+
/** `machine: "local"` in Herdr: the recorded server on this machine, confirmed by socket and session, reached without SSH. */
|
|
61
|
+
async function connectLocalHerdrMachine(machine) {
|
|
62
|
+
const result = await runBoundedCommand(process.env.HERDR_BIN ?? "herdr", ["status", "server", "--json"], { env: herdrLocalEnv(machine.socket, machine.session, process.env), timeout: 15_000 });
|
|
63
|
+
if (result.error)
|
|
64
|
+
throw new Error(`Local Herdr discovery failed: ${result.error.message}`, { cause: result.error });
|
|
65
|
+
if (result.status !== 0)
|
|
66
|
+
throw new Error(`Local Herdr discovery failed with code ${result.status}: ${(result.stderr || result.stdout).trim().slice(0, 512)}`);
|
|
67
|
+
const endpoint = parseHerdrEndpoint(result.stdout, machine.session);
|
|
68
|
+
if (endpoint.socket !== machine.socket)
|
|
69
|
+
throw new Error(`Local Herdr server identity mismatch: expected socket ${machine.socket}, received ${endpoint.socket}.`);
|
|
70
|
+
return { endpoint, socketPath: machine.socket, client: new SocketRpcClient(machine.socket), ...localMachineAccess().openSockets() };
|
|
71
|
+
}
|
|
72
|
+
/** Local runtime directories go under /tmp: the bridge socket path inside a macOS TMPDIR exceeds the unix socket path limit. */
|
|
73
|
+
function herdrAccess(machine) { return "target" in machine ? sshMachineAccess(machine) : localMachineAccess({ env: { ...process.env, TMPDIR: "/tmp" } }); }
|
|
59
74
|
async function startHerdrAgent(connection, owned, kind, name, args, options = {}) {
|
|
60
75
|
const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5_000), pollMs = options.pollMs ?? 50;
|
|
61
76
|
let response;
|
|
@@ -99,9 +114,9 @@ async function closeOwnedHerdrPane(connection, owned, terminalId, agentName) {
|
|
|
99
114
|
await connection.client.call("pane.close", { pane_id: owned.paneId });
|
|
100
115
|
}
|
|
101
116
|
}
|
|
102
|
-
/** Herdr pane host: Herdr RPC over the SSH-forwarded
|
|
117
|
+
/** Herdr pane host: Herdr RPC over the Herdr socket, SSH-forwarded for a saved machine and direct for `local`. Ownership is the Herdr terminal_id/pane_id pair; run state comes from agent_status. */
|
|
103
118
|
export const herdrPaneHost = {
|
|
104
|
-
connect(machine) { return connectHerdrMachine(
|
|
119
|
+
connect(machine) { const herdr = asHerdrMachine(machine); return "target" in herdr ? connectHerdrMachine(herdr) : connectLocalHerdrMachine(herdr); },
|
|
105
120
|
sessionOf(connection) { return connection.endpoint.session; },
|
|
106
121
|
async launch(connection, machine, runId, runtimeDir, request, onPane, options) { const owned = await provisionHerdrOwnedPane(connection, asHerdrMachine(machine), runId, runtimeDir, request.environment); await onPane(owned); const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options); return { owned, terminalId }; },
|
|
107
122
|
async prompt(connection, identity, text, options = {}) {
|
|
@@ -127,37 +142,37 @@ export const herdrPaneHost = {
|
|
|
127
142
|
reconcile: reconcileHerdrPlacedRun,
|
|
128
143
|
closeOwnedPane: closeOwnedHerdrPane,
|
|
129
144
|
};
|
|
130
|
-
/** SSH
|
|
131
|
-
export function discoverBridgeManifest(machine, runId, runtimeDir, options = {}) { return discoverPlacedBridgeManifest(sshMachineAccess(machine, options), runId, runtimeDir); }
|
|
132
|
-
export function createRemoteRuntimeDir(machine, runId, options = {}) { return createPlacedRuntimeDir(sshMachineAccess(machine, options), runId); }
|
|
133
|
-
export function removeRemoteRuntimeDir(machine, runtimeDir, options = {}) { removePlacedRuntimeDir(sshMachineAccess(machine, options), runtimeDir); }
|
|
134
|
-
/** The placed-run owner bound to Herdr and SSH access, plus the separate provision and start steps the external CLI adapters use. */
|
|
145
|
+
/** The placed-run owner bound to Herdr and its machine access (SSH, or this machine for `local`), plus the separate provision and start steps the external CLI adapters use. */
|
|
135
146
|
export class HerdrPlacedRunOwner extends PlacedRunOwner {
|
|
136
|
-
constructor(machine, runId, runtimeDir, connection,
|
|
137
|
-
static async create(machine, runId, beforePane) {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
await beforePane?.(owner);
|
|
141
|
-
return owner;
|
|
142
|
-
}
|
|
143
|
-
catch (error) {
|
|
144
|
-
const cleanupErrors = [];
|
|
147
|
+
constructor(machine, runId, runtimeDir, connection, access) { super(machine, runId, runtimeDir, connection, herdrPaneHost, access); }
|
|
148
|
+
static async create(machine, runId, beforePane) {
|
|
149
|
+
const access = herdrAccess(machine), runtimeDir = await createPlacedRuntimeDir(access, "target" in machine ? runId : hashedRuntimeDirName(runId));
|
|
150
|
+
let connection;
|
|
145
151
|
try {
|
|
146
|
-
await
|
|
152
|
+
connection = await herdrPaneHost.connect(machine);
|
|
153
|
+
const owner = new HerdrPlacedRunOwner(machine, runId, runtimeDir, connection, access);
|
|
154
|
+
await beforePane?.(owner);
|
|
155
|
+
return owner;
|
|
147
156
|
}
|
|
148
|
-
catch (
|
|
149
|
-
cleanupErrors
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
157
|
+
catch (error) {
|
|
158
|
+
const cleanupErrors = [];
|
|
159
|
+
try {
|
|
160
|
+
await connection?.close();
|
|
161
|
+
}
|
|
162
|
+
catch (cleanupError) {
|
|
163
|
+
cleanupErrors.push(cleanupError);
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
removePlacedRuntimeDir(access, runtimeDir);
|
|
167
|
+
}
|
|
168
|
+
catch (cleanupError) {
|
|
169
|
+
cleanupErrors.push(cleanupError);
|
|
170
|
+
}
|
|
171
|
+
if (cleanupErrors.length)
|
|
172
|
+
throw new AggregateError([error, ...cleanupErrors], "Herdr owner creation failed and cleanup also failed.", { cause: error });
|
|
173
|
+
throw error;
|
|
156
174
|
}
|
|
157
|
-
|
|
158
|
-
throw new AggregateError([error, ...cleanupErrors], "Herdr owner creation failed and cleanup also failed.", { cause: error });
|
|
159
|
-
throw error;
|
|
160
|
-
} }
|
|
175
|
+
}
|
|
161
176
|
async provision(environment) { this.owned = await provisionHerdrOwnedPane(this.connection, this.machine, this.runId, this.runtimeDir, environment); return this.owned; }
|
|
162
177
|
async start(kind, name, args, options = {}) {
|
|
163
178
|
if (!this.owned)
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export declare const HERDR_PI_PROTOCOL = 1;
|
|
2
2
|
export declare const HERDR_PI_MAX_FRAME_BYTES: number;
|
|
3
|
+
export declare const HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES: number;
|
|
3
4
|
export declare const HERDR_PI_MODE_ENV = "PI_SUBAGENTS_HERDR_BRIDGE";
|
|
4
5
|
export declare const HERDR_PI_RUN_ENV = "PI_SUBAGENTS_HERDR_RUN_ID";
|
|
5
6
|
export declare const HERDR_PI_RUNTIME_DIR_ENV = "PI_SUBAGENTS_HERDR_RUNTIME_DIR";
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import * as path from "node:path";
|
|
2
2
|
export const HERDR_PI_PROTOCOL = 1;
|
|
3
3
|
export const HERDR_PI_MAX_FRAME_BYTES = 1024 * 1024;
|
|
4
|
+
export const HERDR_PI_MAX_ACCEPTANCE_PROMPT_BYTES = 256 * 1024;
|
|
4
5
|
export const HERDR_PI_MODE_ENV = "PI_SUBAGENTS_HERDR_BRIDGE";
|
|
5
6
|
export const HERDR_PI_RUN_ENV = "PI_SUBAGENTS_HERDR_RUN_ID";
|
|
6
7
|
export const HERDR_PI_RUNTIME_DIR_ENV = "PI_SUBAGENTS_HERDR_RUNTIME_DIR";
|
|
@@ -26,11 +27,11 @@ export class HerdrPiFrameDecoder {
|
|
|
26
27
|
#buffer = Buffer.alloc(0);
|
|
27
28
|
push(chunk) {
|
|
28
29
|
this.#buffer = Buffer.concat([this.#buffer, chunk]);
|
|
29
|
-
if (this.#buffer.byteLength > HERDR_PI_MAX_FRAME_BYTES)
|
|
30
|
-
throw new Error(`Herdr Pi frame exceeds ${HERDR_PI_MAX_FRAME_BYTES} bytes.`);
|
|
31
30
|
const frames = [];
|
|
32
31
|
for (;;) {
|
|
33
32
|
const newline = this.#buffer.indexOf(10);
|
|
33
|
+
if ((newline < 0 ? this.#buffer.byteLength : newline) >= HERDR_PI_MAX_FRAME_BYTES)
|
|
34
|
+
throw new Error(`Herdr Pi frame exceeds ${HERDR_PI_MAX_FRAME_BYTES} bytes.`);
|
|
34
35
|
if (newline < 0)
|
|
35
36
|
break;
|
|
36
37
|
const line = this.#buffer.subarray(0, newline);
|
|
@@ -48,12 +48,7 @@ export declare function boundedHerdrReconnect(identity: HerdrRunIdentity, lastEv
|
|
|
48
48
|
}>;
|
|
49
49
|
export declare function serializeHerdrPiLaunch(launch: ChildSessionLaunch): {
|
|
50
50
|
args: string[];
|
|
51
|
-
resources:
|
|
52
|
-
agent: string;
|
|
53
|
-
skills?: string[];
|
|
54
|
-
toolCeiling?: string[];
|
|
55
|
-
reads?: string[] | false;
|
|
56
|
-
};
|
|
51
|
+
resources: NonNullable<ChildSessionLaunch["remoteResources"]>;
|
|
57
52
|
};
|
|
58
53
|
export declare class BridgeChannel {
|
|
59
54
|
#private;
|
|
@@ -72,12 +67,7 @@ export declare class BridgeChannel {
|
|
|
72
67
|
get failed(): boolean;
|
|
73
68
|
adopt(listener: (frame: HerdrPiFrame) => void): HerdrPiFrame[];
|
|
74
69
|
wait(type: string, requestId: string): Promise<HerdrPiFrame>;
|
|
75
|
-
configure(resources:
|
|
76
|
-
agent: string;
|
|
77
|
-
skills?: string[];
|
|
78
|
-
toolCeiling?: string[];
|
|
79
|
-
reads?: string[] | false;
|
|
80
|
-
}): Promise<HerdrPiFrame>;
|
|
70
|
+
configure(resources: ReturnType<typeof serializeHerdrPiLaunch>["resources"]): Promise<HerdrPiFrame>;
|
|
81
71
|
supervisorDelivered(requestId: string): void;
|
|
82
72
|
prepare(requestId: string, operation: string, text?: string, supervisorId?: string, supervisorError?: string): Promise<HerdrPiFrame>;
|
|
83
73
|
close(): void;
|