@xzzpig/pi-subagents 0.13.0 → 0.15.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 +243 -0
- package/README.md +6 -5
- package/agents/evidence-auditor.md +34 -0
- package/agents/researcher.md +23 -13
- package/agents/reviewer.md +3 -2
- package/docs/agents.md +56 -15
- package/docs/configuration.md +93 -15
- package/docs/extension-api.md +132 -19
- package/docs/missions.md +10 -2
- package/docs/models.md +11 -22
- package/docs/observability.md +67 -11
- package/docs/standalone-background.md +59 -0
- package/docs/tool-reference.md +42 -23
- package/docs/watchdog.md +39 -10
- package/docs/workflows.md +58 -19
- package/index.ts +5 -2
- package/inspector-runner.mjs +2 -2
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
- package/node_modules/@xzzpig/pi-components/README.md +28 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
- package/node_modules/@xzzpig/pi-components/package.json +1 -1
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
- package/package.json +10 -5
- package/prompts/parallel-review.md +1 -1
- package/runner-peer-loader.mjs +24 -0
- package/runner-peer-preload.mjs +36 -0
- package/skills/pi-subagents/SKILL.md +34 -22
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
- package/skills/pi-subagents/references/execution-controls.md +27 -8
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
- package/skills/pi-subagents/references/review-and-validation.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +94 -0
- package/src/agents/agent-management.ts +71 -59
- package/src/agents/agent-serializer.ts +6 -3
- package/src/agents/agents.ts +198 -72
- package/src/agents/builtin-names.ts +1 -0
- package/src/agents/chain-serializer.ts +5 -0
- package/src/agents/runtime-agent-registry.ts +7 -6
- package/src/api/delegation.ts +4 -0
- package/src/api/preflight.ts +110 -71
- package/src/api/required-child-extensions.ts +6 -0
- package/src/api/shared-types.ts +3 -1
- package/src/api/workflow-resources.ts +6 -0
- package/src/extension/config.ts +14 -37
- package/src/extension/fanout-child.ts +68 -5
- package/src/extension/herdr-pi-bridge.ts +164 -0
- package/src/extension/index.ts +141 -51
- package/src/extension/public-execution.ts +7 -6
- package/src/extension/rpc.ts +8 -21
- package/src/extension/schemas.ts +86 -84
- package/src/extension/tool-description.ts +32 -79
- package/src/inspectors/actions.ts +148 -0
- package/src/inspectors/ghostty/actions.ts +74 -0
- package/src/inspectors/ghostty/plugin.ts +17 -0
- package/src/inspectors/herdr/actions.ts +99 -179
- package/src/inspectors/herdr/plugin.ts +20 -0
- package/src/inspectors/herdr/project-panes.ts +4 -1
- package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
- package/src/inspectors/plugins.ts +8 -0
- package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
- package/src/inspectors/types.ts +51 -0
- package/src/integrations/pi-web-session-liveness.ts +73 -0
- package/src/intercom/intercom-bridge.ts +50 -8
- package/src/intercom/native-supervisor-channel.ts +142 -115
- package/src/intercom/supervisor-ui.ts +3 -2
- package/src/missions/workflow-state.ts +37 -16
- package/src/policy/authority.ts +4 -0
- package/src/profiles/profiles.ts +12 -6
- package/src/runs/background/active-async-capacity.ts +22 -18
- package/src/runs/background/active-run-index.ts +17 -1
- package/src/runs/background/async-execution.ts +359 -176
- package/src/runs/background/async-job-tracker.ts +41 -7
- package/src/runs/background/async-resume.ts +19 -12
- package/src/runs/background/async-retention.ts +20 -0
- package/src/runs/background/async-status-snapshot.ts +10 -12
- package/src/runs/background/async-status.ts +32 -13
- package/src/runs/background/auto-drain.ts +59 -35
- package/src/runs/background/binary-bootstrap.ts +38 -0
- package/src/runs/background/chain-append.ts +1 -1
- package/src/runs/background/chain-root-attachment.ts +22 -33
- package/src/runs/background/control-channel.ts +78 -44
- package/src/runs/background/fleet-view.ts +30 -2
- package/src/runs/background/notify.ts +193 -19
- package/src/runs/background/owned-process-tree.ts +35 -8
- package/src/runs/background/process-terminal.ts +23 -23
- package/src/runs/background/result-files.ts +8 -4
- package/src/runs/background/result-watcher.ts +19 -2
- package/src/runs/background/retained-nested-route-tracker.ts +96 -0
- package/src/runs/background/run-child-session.ts +118 -41
- package/src/runs/background/run-status.ts +78 -5
- package/src/runs/background/runner-aliases.ts +22 -5
- package/src/runs/background/runner-child-launch.ts +93 -0
- package/src/runs/background/runner-child-sessions.ts +5 -4
- package/src/runs/background/runner-http-dispatcher.ts +119 -0
- package/src/runs/background/scheduled-runs.ts +51 -18
- package/src/runs/background/stale-run-reconciler.ts +38 -12
- package/src/runs/background/steering.ts +20 -2
- package/src/runs/background/subagent-runner.ts +766 -432
- package/src/runs/background/subagent-wait.ts +179 -28
- package/src/runs/background/wait-completions.ts +79 -27
- package/src/runs/background/wait-subscriptions.ts +9 -3
- package/src/runs/background/wait-tool.ts +5 -3
- package/src/runs/foreground/async-steering-action.ts +37 -7
- package/src/runs/foreground/async-stop-action.ts +93 -3
- package/src/runs/foreground/execution.ts +174 -194
- package/src/runs/foreground/foreground-history.ts +5 -2
- package/src/runs/foreground/prompt-audit.ts +12 -6
- package/src/runs/foreground/subagent-executor.ts +896 -397
- package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
- package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
- package/src/runs/shared/acceptance.ts +54 -14
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +172 -78
- package/src/runs/shared/capability-ceiling.ts +2 -0
- package/src/runs/shared/child-hooks.ts +167 -3
- package/src/runs/shared/child-launch-plan.ts +15 -3
- package/src/runs/shared/child-launch.ts +44 -16
- package/src/runs/shared/child-lifecycle.ts +6 -3
- package/src/runs/shared/child-runtime-config.ts +8 -1
- package/src/runs/shared/child-session.ts +130 -24
- package/src/runs/shared/child-tool-plan.ts +145 -14
- package/src/runs/shared/completion-evidence.ts +2 -2
- package/src/runs/shared/completion-guard.ts +6 -3
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/effective-system-prompt.ts +33 -0
- package/src/runs/shared/external-cli-contract.ts +11 -1
- package/src/runs/shared/external-cli-preflight.ts +6 -2
- package/src/runs/shared/external-cli-runner.ts +9 -7
- package/src/runs/shared/herdr-connection.ts +134 -0
- package/src/runs/shared/herdr-external-adapters.ts +169 -0
- package/src/runs/shared/herdr-machine.ts +279 -0
- package/src/runs/shared/herdr-pi-protocol.ts +59 -0
- package/src/runs/shared/herdr-placed-run.ts +263 -0
- package/src/runs/shared/host-step-status.ts +11 -11
- package/src/runs/shared/llm-intent-arbiter.ts +40 -21
- package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
- package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
- package/src/runs/shared/model-scope.ts +1 -1
- package/src/runs/shared/nested-events.ts +19 -10
- package/src/runs/shared/orca-progress-tabs.ts +7 -1
- package/src/runs/shared/parallel-handoff.ts +57 -12
- package/src/runs/shared/parallel-utils.ts +10 -4
- package/src/runs/shared/pi-spawn.ts +10 -0
- package/src/runs/shared/readonly-drain-observation.ts +42 -0
- package/src/runs/shared/run-fanout-budget.ts +8 -8
- package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
- package/src/runs/shared/task-intent.ts +46 -13
- package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
- package/src/runs/shared/worktree-setup-command.ts +213 -0
- package/src/runs/shared/worktree.ts +437 -214
- package/src/shared/child-cache-retention.ts +43 -0
- package/src/shared/fork-context.ts +15 -72
- package/src/shared/launch-contract.ts +70 -8
- package/src/shared/model-response-aliases.ts +13 -0
- package/src/shared/opencode-session-headers.ts +30 -0
- package/src/shared/pruned-fork.ts +1 -1
- package/src/shared/required-child-extensions.ts +81 -0
- package/src/shared/settings.ts +5 -2
- package/src/shared/shortcuts.ts +0 -4
- package/src/shared/types.ts +164 -90
- package/src/shared/utils.ts +10 -2
- package/src/shared/watch-strategy.ts +2 -0
- package/src/shared/workflow-child-permit.ts +18 -13
- package/src/slash/delegation-adapters.ts +3 -1
- package/src/slash/delegation-request.ts +14 -0
- package/src/slash/slash-commands.ts +2 -7
- package/src/slash/subagents-admin.ts +31 -14
- package/src/tui/fleet-native-transcript.ts +50 -6
- package/src/tui/fleet-status.ts +165 -20
- package/src/tui/fleet.ts +52 -21
- package/src/tui/render.ts +210 -50
- package/src/watchdog/child-status.ts +28 -28
- package/src/watchdog/lsp-diagnostics.ts +1 -1
- package/src/watchdog/model-selection.ts +21 -1
- package/src/watchdog/permission-arbiter.ts +5 -2
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/register-main.ts +39 -35
- package/src/watchdog/render.ts +1 -1
- package/src/watchdog/review.ts +122 -74
- package/src/watchdog/rules.ts +1 -1
- package/src/watchdog/runtime.ts +100 -27
- package/src/watchdog/scope.ts +1 -1
- package/src/watchdog/settings.ts +3 -0
- package/src/watchdog/tool-actions.ts +13 -12
- package/src/watchdog/turn-delta.ts +23 -0
- package/src/watchdog/types.ts +5 -3
- package/src/watchdog/warning-format.ts +1 -1
- package/src/workflows/chat-progress.ts +3 -3
- package/src/workflows/scripted-workflow.ts +349 -26
- package/src/workflows/workflow-checklist.ts +17 -20
- package/src/workflows/workflow-child-summary.ts +57 -8
- package/src/workflows/workflow-preflight.ts +19 -19
- package/src/workflows/workflow-receipt.ts +24 -6
- package/src/workflows/workflow-resources.ts +108 -22
- package/src/workflows/workflow-settlement.ts +3 -0
- package/src/runs/shared/model-exclusions.ts +0 -373
- /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
|
@@ -4,10 +4,10 @@ import { writeAtomicJson, writePrivateAtomicJson } from "../../shared/atomic-jso
|
|
|
4
4
|
import {
|
|
5
5
|
SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
6
6
|
type AsyncStatus,
|
|
7
|
-
type
|
|
8
|
-
type
|
|
7
|
+
type CanonicalSessionTerminal,
|
|
8
|
+
type ProcessInstanceExit,
|
|
9
9
|
type ProcessTerminalReason,
|
|
10
|
-
type
|
|
10
|
+
type ProcessTerminal,
|
|
11
11
|
} from "../../shared/types.ts";
|
|
12
12
|
import { canonicalSessionId, inspectSessionLease } from "../shared/session-lease.ts";
|
|
13
13
|
import { releaseActiveRunIndex } from "./active-run-index.ts";
|
|
@@ -16,7 +16,7 @@ export interface ProcessTerminalCandidate {
|
|
|
16
16
|
version: 1;
|
|
17
17
|
runId: string;
|
|
18
18
|
runnerProcessInstanceId: string;
|
|
19
|
-
writers: Record<string,
|
|
19
|
+
writers: Record<string, ProcessInstanceExit[]>;
|
|
20
20
|
expectedWriters?: Record<string, number>;
|
|
21
21
|
sessionFile?: string;
|
|
22
22
|
revivalLeaseToken?: string;
|
|
@@ -34,7 +34,7 @@ function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
34
34
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
-
function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is
|
|
37
|
+
function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExit {
|
|
38
38
|
if (!isRecord(value)) return false;
|
|
39
39
|
if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
|
|
40
40
|
if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
|
|
@@ -56,7 +56,7 @@ function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): va
|
|
|
56
56
|
&& (value.processTree.diagnostic === undefined || typeof value.processTree.diagnostic === "string");
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
function validInstance(value: unknown): value is
|
|
59
|
+
function validInstance(value: unknown): value is ProcessInstanceExit {
|
|
60
60
|
return validProcessInstance(value, "pi-writer");
|
|
61
61
|
}
|
|
62
62
|
|
|
@@ -78,7 +78,7 @@ export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalC
|
|
|
78
78
|
if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
|
|
79
79
|
throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
|
|
80
80
|
}
|
|
81
|
-
const writers: Record<string,
|
|
81
|
+
const writers: Record<string, ProcessInstanceExit[]> = {};
|
|
82
82
|
for (const [index, entries] of Object.entries(raw.writers)) {
|
|
83
83
|
if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
|
|
84
84
|
writers[index] = entries;
|
|
@@ -137,7 +137,7 @@ export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token
|
|
|
137
137
|
writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
|
|
138
138
|
}
|
|
139
139
|
|
|
140
|
-
function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string):
|
|
140
|
+
function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string): ProcessTerminal {
|
|
141
141
|
return { version: 1, state: "unknown", runId, runnerProcessInstanceId, reason, ...(diagnostic ? { diagnostic } : {}) };
|
|
142
142
|
}
|
|
143
143
|
|
|
@@ -147,7 +147,7 @@ function resumeDisposition(state: string | undefined, sessionFile: string | unde
|
|
|
147
147
|
return sessionFile && fs.existsSync(sessionFile) ? "resumable" : "unavailable";
|
|
148
148
|
}
|
|
149
149
|
|
|
150
|
-
function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnType<typeof inspectSessionLease>):
|
|
150
|
+
function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnType<typeof inspectSessionLease>): CanonicalSessionTerminal | undefined {
|
|
151
151
|
if (!candidate.sessionFile || lease.state !== "free") return undefined;
|
|
152
152
|
if (candidate.revivalLeaseToken && candidate.revivalLeaseReleaseAcknowledged !== true) return undefined;
|
|
153
153
|
return {
|
|
@@ -158,7 +158,7 @@ function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnTyp
|
|
|
158
158
|
};
|
|
159
159
|
}
|
|
160
160
|
|
|
161
|
-
function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): raw is
|
|
161
|
+
function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): raw is ProcessTerminal {
|
|
162
162
|
if (!isRecord(raw) || raw.version !== 1 || !["pending", "observed", "unknown", "not-started"].includes(String(raw.state)) || typeof raw.runId !== "string" || !raw.runId || typeof raw.runnerProcessInstanceId !== "string" || !raw.runnerProcessInstanceId) {
|
|
163
163
|
throw new Error(`Invalid process-terminal proof in '${asyncDir}'.`);
|
|
164
164
|
}
|
|
@@ -177,21 +177,21 @@ function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: stri
|
|
|
177
177
|
return true;
|
|
178
178
|
}
|
|
179
179
|
|
|
180
|
-
export function sanitizeProcessTerminal(value: unknown, fallback: { runId?: string; runnerProcessInstanceId?: string }, label = "status"):
|
|
180
|
+
export function sanitizeProcessTerminal(value: unknown, fallback: { runId?: string; runnerProcessInstanceId?: string }, label = "status"): ProcessTerminal | undefined {
|
|
181
181
|
if (value === undefined) return undefined;
|
|
182
182
|
try {
|
|
183
183
|
validateProof(value, label, fallback);
|
|
184
|
-
return value as
|
|
184
|
+
return value as ProcessTerminal;
|
|
185
185
|
} catch (error) {
|
|
186
186
|
return unknownProof(fallback.runId ?? label, fallback.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
187
187
|
}
|
|
188
188
|
}
|
|
189
189
|
|
|
190
|
-
export function readProcessTerminal(asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }):
|
|
190
|
+
export function readProcessTerminal(asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): ProcessTerminal | undefined {
|
|
191
191
|
try {
|
|
192
192
|
const raw = JSON.parse(fs.readFileSync(processTerminalPath(asyncDir), "utf-8")) as unknown;
|
|
193
193
|
validateProof(raw, asyncDir, fallback);
|
|
194
|
-
return raw as
|
|
194
|
+
return raw as ProcessTerminal;
|
|
195
195
|
} catch (error) {
|
|
196
196
|
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
197
197
|
return unknownProof(fallback?.runId ?? path.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
@@ -199,12 +199,12 @@ export function readProcessTerminal(asyncDir: string, fallback?: { runId?: strin
|
|
|
199
199
|
}
|
|
200
200
|
|
|
201
201
|
function stepProcessTerminalProof(
|
|
202
|
-
proof:
|
|
202
|
+
proof: ProcessTerminal,
|
|
203
203
|
childIndex: number,
|
|
204
|
-
state:
|
|
205
|
-
records:
|
|
206
|
-
resumeDispositionValue:
|
|
207
|
-
):
|
|
204
|
+
state: ProcessTerminal["state"],
|
|
205
|
+
records: ProcessInstanceExit[],
|
|
206
|
+
resumeDispositionValue: ProcessTerminal["resumeDisposition"],
|
|
207
|
+
): ProcessTerminal {
|
|
208
208
|
const base = {
|
|
209
209
|
version: 1 as const,
|
|
210
210
|
runId: proof.runId,
|
|
@@ -221,7 +221,7 @@ function stepProcessTerminalProof(
|
|
|
221
221
|
return { ...base, state };
|
|
222
222
|
}
|
|
223
223
|
|
|
224
|
-
function overlayStatus(asyncDir: string, proof:
|
|
224
|
+
function overlayStatus(asyncDir: string, proof: ProcessTerminal, candidate?: ProcessTerminalCandidate): void {
|
|
225
225
|
const statusPath = path.join(asyncDir, "status.json");
|
|
226
226
|
try {
|
|
227
227
|
const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as AsyncStatus;
|
|
@@ -244,13 +244,13 @@ export function finalizeProcessTerminal(
|
|
|
244
244
|
asyncDir: string,
|
|
245
245
|
runId: string,
|
|
246
246
|
runnerClose: RunnerCloseObservation,
|
|
247
|
-
):
|
|
247
|
+
): ProcessTerminal {
|
|
248
248
|
const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
|
|
249
249
|
if (existing && fs.existsSync(processTerminalPath(asyncDir))) {
|
|
250
250
|
if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
|
|
251
251
|
if (existing.state === "unknown") return existing;
|
|
252
252
|
}
|
|
253
|
-
let proof:
|
|
253
|
+
let proof: ProcessTerminal;
|
|
254
254
|
let candidateForOverlay: ProcessTerminalCandidate | undefined;
|
|
255
255
|
try {
|
|
256
256
|
const candidate = readProcessTerminalCandidate(asyncDir);
|
|
@@ -279,7 +279,7 @@ export function finalizeProcessTerminal(
|
|
|
279
279
|
} else if (allWriters.some((writer) => writer.kind === "pi-writer" && writer.processTree.state !== "observed")) {
|
|
280
280
|
proof = unknownProof(runId, runnerClose.processInstanceId, "process-tree-unverified");
|
|
281
281
|
} else {
|
|
282
|
-
const runner:
|
|
282
|
+
const runner: ProcessInstanceExit = { kind: "runner", ...runnerClose };
|
|
283
283
|
const canonicalSession = session && sessionProjection(candidate, session);
|
|
284
284
|
proof = {
|
|
285
285
|
version: 1,
|
|
@@ -241,10 +241,15 @@ function pendingResultExists(resultsDir: string, sessionId: string, runId: strin
|
|
|
241
241
|
return firstExistingResultFile(resultPendingPaths(resultsDir, sessionId, runId)) !== undefined;
|
|
242
242
|
}
|
|
243
243
|
|
|
244
|
+
export function resultPayloadMatchesSessionRun(data: unknown, sessionId: string, runId: string): boolean {
|
|
245
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return false;
|
|
246
|
+
const record = data as Record<string, unknown>;
|
|
247
|
+
return (nonEmptyString(record.runId) ?? nonEmptyString(record.id)) === runId && nonEmptyString(record.sessionId) === sessionId;
|
|
248
|
+
}
|
|
249
|
+
|
|
244
250
|
function pendingResultPayloadMatches(filePath: string, sessionId: string, runId: string): boolean {
|
|
245
251
|
try {
|
|
246
|
-
|
|
247
|
-
return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
|
|
252
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
248
253
|
} catch (error) {
|
|
249
254
|
if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
|
|
250
255
|
return false;
|
|
@@ -252,8 +257,7 @@ function pendingResultPayloadMatches(filePath: string, sessionId: string, runId:
|
|
|
252
257
|
}
|
|
253
258
|
|
|
254
259
|
function assertPendingResultPayloadMatches(filePath: string, sessionId: string, runId: string): boolean {
|
|
255
|
-
|
|
256
|
-
return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
|
|
260
|
+
return resultPayloadMatchesSessionRun(JSON.parse(fs.readFileSync(filePath, "utf-8")), sessionId, runId);
|
|
257
261
|
}
|
|
258
262
|
|
|
259
263
|
export function promotePendingResultFile(resultsDir: string, sessionId: string, runId: string, file = resultFileName(runId), options: { logFailure?: boolean } = {}): "none" | "promoted" | "pending" {
|
|
@@ -70,6 +70,7 @@ type ResultFileChild = {
|
|
|
70
70
|
sessionName?: string;
|
|
71
71
|
output?: string;
|
|
72
72
|
structuredOutput?: unknown;
|
|
73
|
+
structuredOutputPath?: string;
|
|
73
74
|
outputState?: SubagentOutputState;
|
|
74
75
|
error?: string;
|
|
75
76
|
success?: boolean;
|
|
@@ -81,6 +82,8 @@ type ResultFileChild = {
|
|
|
81
82
|
processSignal?: string | null;
|
|
82
83
|
sessionFile?: string;
|
|
83
84
|
artifactPaths?: { outputPath?: string };
|
|
85
|
+
outputSaveError?: string;
|
|
86
|
+
artifactOutputSaveFailed?: true;
|
|
84
87
|
intercomTarget?: string;
|
|
85
88
|
children?: unknown;
|
|
86
89
|
};
|
|
@@ -408,7 +411,9 @@ export function createResultWatcher(
|
|
|
408
411
|
if (typeof data.sessionId !== "string" || !data.sessionId) return;
|
|
409
412
|
const sessionId = data.sessionId;
|
|
410
413
|
const completionOwnerId = data.completionOwnerId;
|
|
411
|
-
const runId = data.runId
|
|
414
|
+
const runId = typeof data.runId === "string" && data.runId
|
|
415
|
+
? data.runId
|
|
416
|
+
: typeof data.id === "string" && data.id ? data.id : file.replace(/\.json$/i, "");
|
|
412
417
|
const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId : undefined;
|
|
413
418
|
let observerSucceeded = true;
|
|
414
419
|
try {
|
|
@@ -428,7 +433,7 @@ export function createResultWatcher(
|
|
|
428
433
|
if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
|
|
429
434
|
// Recorded before dedupe and before the unlink below so bg_wait can
|
|
430
435
|
// use the in-memory record or its bounded durable replay after cleanup.
|
|
431
|
-
recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
|
|
436
|
+
const completionPersisted = recordWaitCompletion(state, runId, data, Date.now(), completionTtlMs, {
|
|
432
437
|
resultsDir,
|
|
433
438
|
sessionId,
|
|
434
439
|
});
|
|
@@ -456,6 +461,10 @@ export function createResultWatcher(
|
|
|
456
461
|
}
|
|
457
462
|
if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
|
|
458
463
|
if (markReplacedPayload()) return;
|
|
464
|
+
if (!completionPersisted) {
|
|
465
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
459
468
|
if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
460
469
|
return;
|
|
461
470
|
}
|
|
@@ -513,6 +522,10 @@ export function createResultWatcher(
|
|
|
513
522
|
}
|
|
514
523
|
if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
|
|
515
524
|
if (markReplacedPayload()) return;
|
|
525
|
+
if (!completionPersisted) {
|
|
526
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
516
529
|
if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
517
530
|
return;
|
|
518
531
|
}
|
|
@@ -600,6 +613,10 @@ export function createResultWatcher(
|
|
|
600
613
|
return;
|
|
601
614
|
}
|
|
602
615
|
if (!ownsCompletion(sessionId, completionOwnerId, epoch)) return;
|
|
616
|
+
if (!completionPersisted) {
|
|
617
|
+
scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
618
|
+
return;
|
|
619
|
+
}
|
|
603
620
|
if (!removeDeliveredResult(file, sessionId, runId, toolCallId)) scheduleResult(file, triggerTurn, RETRY_DELAY_MS);
|
|
604
621
|
} catch (error) {
|
|
605
622
|
if (isAccessDenied(error)) {
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import type { SubagentState } from "../../shared/types.ts";
|
|
3
|
+
import { shouldUseNativeFsWatch } from "../../shared/watch-strategy.ts";
|
|
4
|
+
import { hasLiveNestedDescendants, projectNestedEvents } from "../shared/nested-events.ts";
|
|
5
|
+
|
|
6
|
+
interface RetainedNestedRouteTrackerOptions {
|
|
7
|
+
pollIntervalMs?: number;
|
|
8
|
+
platform?: NodeJS.Platform;
|
|
9
|
+
watch?: typeof fs.watch;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
const DEFAULT_POLL_INTERVAL_MS = 5000;
|
|
13
|
+
const REFRESH_DEBOUNCE_MS = 25;
|
|
14
|
+
|
|
15
|
+
export function createRetainedNestedRouteTracker(
|
|
16
|
+
state: Pick<SubagentState, "retainedForegroundNestedRoutes">,
|
|
17
|
+
options: RetainedNestedRouteTrackerOptions = {},
|
|
18
|
+
): { track: (rootRunId: string) => void; clear: () => void } {
|
|
19
|
+
const pollIntervalMs = options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS;
|
|
20
|
+
const watch = options.watch ?? fs.watch;
|
|
21
|
+
const watchers = new Map<string, fs.FSWatcher>();
|
|
22
|
+
const refreshTimers = new Map<string, ReturnType<typeof setTimeout>>();
|
|
23
|
+
let poller: ReturnType<typeof setInterval> | undefined;
|
|
24
|
+
|
|
25
|
+
const close = (rootRunId: string): void => {
|
|
26
|
+
watchers.get(rootRunId)?.close();
|
|
27
|
+
watchers.delete(rootRunId);
|
|
28
|
+
const timer = refreshTimers.get(rootRunId);
|
|
29
|
+
if (timer) clearTimeout(timer);
|
|
30
|
+
refreshTimers.delete(rootRunId);
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const refresh = (rootRunId: string): void => {
|
|
34
|
+
const retained = state.retainedForegroundNestedRoutes?.get(rootRunId);
|
|
35
|
+
if (!retained) {
|
|
36
|
+
close(rootRunId);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
if (hasLiveNestedDescendants(projectNestedEvents(retained).children)) return;
|
|
41
|
+
state.retainedForegroundNestedRoutes?.delete(rootRunId);
|
|
42
|
+
close(rootRunId);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
console.error(`Failed to refresh retained nested descendants for foreground run '${rootRunId}':`, error);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const scheduleRefresh = (rootRunId: string): void => {
|
|
49
|
+
if (refreshTimers.has(rootRunId)) return;
|
|
50
|
+
const timer = setTimeout(() => {
|
|
51
|
+
refreshTimers.delete(rootRunId);
|
|
52
|
+
refresh(rootRunId);
|
|
53
|
+
}, REFRESH_DEBOUNCE_MS);
|
|
54
|
+
timer.unref?.();
|
|
55
|
+
refreshTimers.set(rootRunId, timer);
|
|
56
|
+
};
|
|
57
|
+
|
|
58
|
+
const ensurePoller = (): void => {
|
|
59
|
+
if (poller || (state.retainedForegroundNestedRoutes?.size ?? 0) === 0) return;
|
|
60
|
+
poller = setInterval(() => {
|
|
61
|
+
for (const rootRunId of state.retainedForegroundNestedRoutes?.keys() ?? []) refresh(rootRunId);
|
|
62
|
+
if ((state.retainedForegroundNestedRoutes?.size ?? 0) > 0) return;
|
|
63
|
+
if (poller) clearInterval(poller);
|
|
64
|
+
poller = undefined;
|
|
65
|
+
}, pollIntervalMs);
|
|
66
|
+
poller.unref?.();
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
const track = (rootRunId: string): void => {
|
|
70
|
+
const retained = state.retainedForegroundNestedRoutes?.get(rootRunId);
|
|
71
|
+
if (!retained) return;
|
|
72
|
+
if (shouldUseNativeFsWatch("retained-nested-route-tracker", options.platform) && !watchers.has(rootRunId)) {
|
|
73
|
+
try {
|
|
74
|
+
const watcher = watch(retained.eventSink, () => scheduleRefresh(rootRunId));
|
|
75
|
+
watcher.on("error", () => close(rootRunId));
|
|
76
|
+
watcher.unref?.();
|
|
77
|
+
watchers.set(rootRunId, watcher);
|
|
78
|
+
} catch {
|
|
79
|
+
// The bounded safety poll below covers unsupported or failed watchers.
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
scheduleRefresh(rootRunId);
|
|
83
|
+
ensurePoller();
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
const clear = (): void => {
|
|
87
|
+
if (poller) clearInterval(poller);
|
|
88
|
+
poller = undefined;
|
|
89
|
+
for (const rootRunId of watchers.keys()) close(rootRunId);
|
|
90
|
+
for (const timer of refreshTimers.values()) clearTimeout(timer);
|
|
91
|
+
refreshTimers.clear();
|
|
92
|
+
state.retainedForegroundNestedRoutes?.clear();
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
return { track, clear };
|
|
96
|
+
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import type { Message } from "@earendil-works/pi-ai";
|
|
9
9
|
import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
|
|
10
10
|
import { extractTextFromContent, extractToolArgsPreview, getFinalOutput, hasEmptyTerminalAssistantResponse } from "../../shared/utils.ts";
|
|
11
|
-
import type { EffectsProjection,
|
|
11
|
+
import type { EffectsProjection, RuntimeAcknowledgedChildExtensions, SubagentOutputState, ToolBudgetState, Usage } from "../../shared/types.ts";
|
|
12
12
|
import {
|
|
13
13
|
acceptChildWatchdogEvent,
|
|
14
14
|
applyChildWatchdogMessage,
|
|
@@ -19,13 +19,15 @@ import {
|
|
|
19
19
|
type ChildWatchdogStatusEvent,
|
|
20
20
|
} from "../../watchdog/child-status.ts";
|
|
21
21
|
import { projectChildLifecycle, type ChildLifecycleAction, type ChildLifecycleState } from "../shared/child-lifecycle.ts";
|
|
22
|
-
import { formatSubagentModelVerificationError } from "../shared/model-
|
|
22
|
+
import { formatSubagentModelVerificationError } from "../shared/model-resolution.ts";
|
|
23
|
+
import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
|
|
23
24
|
import { isMutatingTool, resolveCurrentPath } from "../shared/long-running-guard.ts";
|
|
24
25
|
import { effectiveToolTimeoutMs, formatToolTimeoutMessage, toolTimeoutCallKey } from "../shared/tool-timeout.ts";
|
|
25
|
-
import type
|
|
26
|
-
import { projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
|
|
26
|
+
import { createReportedChildSessionInput, type InProcessChildLaunch } from "../shared/child-launch.ts";
|
|
27
|
+
import { childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent, type ChildSessionFactory } from "../shared/child-session.ts";
|
|
27
28
|
import { formatSteerMessage } from "../shared/subagent-prompt-runtime.ts";
|
|
28
29
|
import type { SteerDeliveryStatus, SteerRequest } from "./control-channel.ts";
|
|
30
|
+
import { takeMatchingAcceptedSteer, unconsumedSteerReason } from "./steering.ts";
|
|
29
31
|
|
|
30
32
|
export interface ChildEventContext {
|
|
31
33
|
runId: string;
|
|
@@ -83,6 +85,8 @@ export interface RunChildSessionInput {
|
|
|
83
85
|
registerTimeout?: (interrupt: (() => void) | undefined) => void;
|
|
84
86
|
registerStop?: (stop: (() => void) | undefined) => void;
|
|
85
87
|
registerSteer?: (steer: StepSteerHandler | undefined) => void;
|
|
88
|
+
/** Consumption (or unconsumed settlement) after the child accepted a steer or follow-up. */
|
|
89
|
+
onSteerOutcome?: (request: SteerRequest, delivery: SteerDelivery) => void;
|
|
86
90
|
/** Receives the sink the child's watchdog hook reports status through; the launch's `watchdogStatus` must forward to it. */
|
|
87
91
|
registerWatchdogStatus?: (sink: ((event: ChildWatchdogStatusEvent) => void) | undefined) => void;
|
|
88
92
|
timeoutMessage?: string;
|
|
@@ -93,6 +97,7 @@ export interface RunChildSessionInput {
|
|
|
93
97
|
runDeadlineAt?: number;
|
|
94
98
|
expectedModelForVerification?: string;
|
|
95
99
|
modelVerificationRegistry?: Array<{ provider: string; id: string; fullId: string }>;
|
|
100
|
+
modelResponseAliases?: Record<string, string[]>;
|
|
96
101
|
mutationTools?: readonly string[];
|
|
97
102
|
}
|
|
98
103
|
|
|
@@ -103,6 +108,7 @@ export interface RunChildSessionResult {
|
|
|
103
108
|
toolCount: number;
|
|
104
109
|
durationMs: number;
|
|
105
110
|
model?: string;
|
|
111
|
+
nativeMachine?: { provider: "herdr"; machineId: string; initialGit?: import("../../shared/types.ts").HerdrRemoteGitStatus; finalGit?: import("../../shared/types.ts").HerdrRemoteGitStatus };
|
|
106
112
|
error?: string;
|
|
107
113
|
finalOutput: string;
|
|
108
114
|
outputState: SubagentOutputState;
|
|
@@ -118,12 +124,12 @@ export interface RunChildSessionResult {
|
|
|
118
124
|
currentToolArgs?: string;
|
|
119
125
|
currentPath?: string;
|
|
120
126
|
afterCompactionSettlement?: boolean;
|
|
127
|
+
abortRecoveryDiagnostic?: string;
|
|
121
128
|
/** Set by the runner while it finalizes the attempt. */
|
|
122
129
|
toolBudget?: ToolBudgetState;
|
|
123
130
|
toolBudgetBlocked?: boolean;
|
|
124
131
|
structuredOutput?: unknown;
|
|
125
|
-
runtimeAcknowledgedExtensions?:
|
|
126
|
-
abortRecoveryDiagnostic?: string;
|
|
132
|
+
runtimeAcknowledgedExtensions?: RuntimeAcknowledgedChildExtensions;
|
|
127
133
|
effects?: EffectsProjection;
|
|
128
134
|
}
|
|
129
135
|
|
|
@@ -175,12 +181,14 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
175
181
|
let currentPath: string | undefined;
|
|
176
182
|
let toolCount = 0;
|
|
177
183
|
let session: ChildSession | undefined;
|
|
184
|
+
const acceptedSteers: Array<{ request: SteerRequest; text: string }> = [];
|
|
178
185
|
let unsubscribe: (() => void) | undefined;
|
|
179
186
|
let settled = false;
|
|
180
187
|
let promptSettled = false;
|
|
181
188
|
let forcedTermination = false;
|
|
182
189
|
let cleanTerminalAssistantStopReceived = false;
|
|
183
190
|
let agentSettledReceived = false;
|
|
191
|
+
let queuedDrainHold = false;
|
|
184
192
|
let compactionStartedReceived = false;
|
|
185
193
|
let afterCompactionSettlement = false;
|
|
186
194
|
let finalDrainTimer: NodeJS.Timeout | undefined;
|
|
@@ -299,14 +307,28 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
299
307
|
}
|
|
300
308
|
// If the child emits its terminal event but its run never settles (a hook
|
|
301
309
|
// is stuck), abort it after a short grace period and then finish without it.
|
|
310
|
+
const observeQueuedDrainHold = (): boolean => {
|
|
311
|
+
if (childSessionHasQueuedMessages(session)) queuedDrainHold = true;
|
|
312
|
+
return queuedDrainHold;
|
|
313
|
+
};
|
|
302
314
|
function startFinalDrain(): void {
|
|
303
315
|
if (childWatchdogIsActive(childWatchdogState)) {
|
|
304
316
|
armWatchdogTail();
|
|
305
317
|
return;
|
|
306
318
|
}
|
|
319
|
+
if (promptSettled || finalDrainTimer || settled) return;
|
|
320
|
+
if (observeQueuedDrainHold()) return;
|
|
321
|
+
armFinalDrainTimer();
|
|
322
|
+
}
|
|
323
|
+
function armFinalDrainTimer(): void {
|
|
307
324
|
if (promptSettled || finalDrainTimer || settled) return;
|
|
308
325
|
finalDrainTimer = setTimeout(() => {
|
|
309
326
|
if (settled || promptSettled) return;
|
|
327
|
+
if (input.launch.capture.finalDrainHeld() || observeQueuedDrainHold()) {
|
|
328
|
+
finalDrainTimer = undefined;
|
|
329
|
+
armFinalDrainTimer();
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
310
332
|
forcedTermination = true;
|
|
311
333
|
if (!cleanTerminalAssistantStopReceived && !agentSettledReceived && !error && !assistantError) {
|
|
312
334
|
error = `Subagent session did not settle within ${FINAL_STOP_GRACE_MS}ms after its terminal event. Aborting it.`;
|
|
@@ -322,6 +344,8 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
322
344
|
}
|
|
323
345
|
const applyChildLifecycle = (action: ChildLifecycleAction): void => {
|
|
324
346
|
if (action === "cancel-drain") {
|
|
347
|
+
cleanTerminalAssistantStopReceived = false;
|
|
348
|
+
agentSettledReceived = false;
|
|
325
349
|
clearFinalDrainTimers();
|
|
326
350
|
clearWatchdogTailTimer();
|
|
327
351
|
return;
|
|
@@ -389,6 +413,9 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
389
413
|
compactionStartedReceived = false;
|
|
390
414
|
afterCompactionSettlement = false;
|
|
391
415
|
}
|
|
416
|
+
if (event.type === "turn_start" || event.type === "agent_start" || event.type === "auto_retry_start") {
|
|
417
|
+
queuedDrainHold = false;
|
|
418
|
+
}
|
|
392
419
|
if (event.type === "agent_start" || event.type === "auto_retry_start") {
|
|
393
420
|
compactionStartedReceived = false;
|
|
394
421
|
afterCompactionSettlement = false;
|
|
@@ -458,6 +485,16 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
458
485
|
messages.push(event.message);
|
|
459
486
|
const text = extractTextFromContent(event.message.content);
|
|
460
487
|
if (text) writeOutputText(text);
|
|
488
|
+
if (event.type === "message_end" && event.message.role === "user" && text) {
|
|
489
|
+
const matched = takeMatchingAcceptedSteer(acceptedSteers, text);
|
|
490
|
+
if (matched) {
|
|
491
|
+
input.onSteerOutcome?.(matched.request, {
|
|
492
|
+
state: "delivered",
|
|
493
|
+
deliveryStatus: "delivered",
|
|
494
|
+
message: "Child consumed the steering input.",
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
}
|
|
461
498
|
|
|
462
499
|
if (input.childWatchdog && event.type === "message_end") {
|
|
463
500
|
const next = applyChildWatchdogMessage(childWatchdogState, event.message);
|
|
@@ -468,11 +505,15 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
468
505
|
if (event.message.model) {
|
|
469
506
|
model = event.message.model;
|
|
470
507
|
if (input.expectedModelForVerification && !hasToolCall) {
|
|
471
|
-
const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry);
|
|
508
|
+
const modelVerificationError = formatSubagentModelVerificationError(input.expectedModelForVerification, event.message.model, input.modelVerificationRegistry, input.modelResponseAliases);
|
|
472
509
|
if (modelVerificationError && !error) error = modelVerificationError;
|
|
473
510
|
}
|
|
474
511
|
}
|
|
475
512
|
if (event.message.errorMessage) assistantError = event.message.errorMessage;
|
|
513
|
+
else if (hasToolCall && event.message.stopReason === "toolUse") {
|
|
514
|
+
// A recovered request can finish via a terminating tool, without a text stop.
|
|
515
|
+
assistantError = undefined;
|
|
516
|
+
}
|
|
476
517
|
const eventUsage = event.message.usage;
|
|
477
518
|
if (eventUsage) {
|
|
478
519
|
usage.turns++;
|
|
@@ -513,14 +554,33 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
513
554
|
};
|
|
514
555
|
|
|
515
556
|
/** The child run ended (or was forced to end); fold in the outcome once the child's shutdown work is done. */
|
|
557
|
+
const failUnconsumedSteers = (): void => {
|
|
558
|
+
for (const entry of acceptedSteers.splice(0)) {
|
|
559
|
+
input.onSteerOutcome?.(entry.request, { state: "failed", message: unconsumedSteerReason(entry.request.mode) });
|
|
560
|
+
}
|
|
561
|
+
};
|
|
516
562
|
const settle = (promptError: unknown, forced = false): void => {
|
|
517
563
|
if (settled) return;
|
|
518
564
|
settled = true;
|
|
565
|
+
failUnconsumedSteers();
|
|
519
566
|
const closed = finish();
|
|
520
567
|
const finalOutput = getFinalOutput(messages);
|
|
521
568
|
let finalError = error ?? assistantError;
|
|
522
|
-
|
|
523
|
-
|
|
569
|
+
const promptErrorMessage = promptError === undefined ? undefined : promptError instanceof Error ? promptError.message : String(promptError);
|
|
570
|
+
if (!finalError && promptErrorMessage !== undefined) {
|
|
571
|
+
finalError = promptErrorMessage;
|
|
572
|
+
}
|
|
573
|
+
// A child launched without the ambient extensions resolves a provider
|
|
574
|
+
// extension's model as "not found". Annotate only a creation/prompt failure
|
|
575
|
+
// that produced no turn; keep the core error and add the rule and the
|
|
576
|
+
// remedies that load the extension for this child.
|
|
577
|
+
if (promptErrorMessage !== undefined
|
|
578
|
+
&& finalError === promptErrorMessage
|
|
579
|
+
&& isChildModelResolutionFailure(promptErrorMessage)
|
|
580
|
+
&& messages.length === 0
|
|
581
|
+
&& usage.turns === 0
|
|
582
|
+
&& !input.launch.session.ambientExtensions) {
|
|
583
|
+
finalError = `${promptErrorMessage}\n\n${formatChildModelResolutionDiagnostic({ agent: input.launch.config.agent, model: input.launch.session.model, host: "runner", capabilityCeiling: input.launch.toolPlan.capabilityCeiling })}`;
|
|
524
584
|
}
|
|
525
585
|
const forcedDrainAfterFinalSuccess = (forced || forcedTermination) && (cleanTerminalAssistantStopReceived || agentSettledReceived) && !finalError;
|
|
526
586
|
const forcedDrainAfterEmptyTerminal = forcedDrainAfterFinalSuccess && hasEmptyTerminalAssistantResponse(messages);
|
|
@@ -532,29 +592,33 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
532
592
|
: interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal)
|
|
533
593
|
? 0
|
|
534
594
|
: finalError || promptError !== undefined ? 1 : 0;
|
|
535
|
-
void closed.then(() =>
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
595
|
+
void closed.then(() => {
|
|
596
|
+
const result: RunChildSessionResult = omitUndefined({
|
|
597
|
+
exitCode,
|
|
598
|
+
messages,
|
|
599
|
+
usage,
|
|
600
|
+
toolCount,
|
|
601
|
+
durationMs: Date.now() - startedAt,
|
|
602
|
+
model,
|
|
603
|
+
nativeMachine: session?.machineEvidence ? { provider: "herdr", machineId: session.machineEvidence.machineId, ...(session.machineEvidence.initial ? { initialGit: session.machineEvidence.initial } : {}), ...(session.machineEvidence.final ? { finalGit: session.machineEvidence.final } : {}) } : undefined,
|
|
604
|
+
error: stopped ? stopMessage() : timedOut ? (error ?? timeoutMessage()) : interrupted || (forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal) ? undefined : finalError,
|
|
605
|
+
finalOutput: (timedOut || stopped) && !finalOutput.trim() ? (stopped ? stopMessage() : error ?? timeoutMessage()) : finalOutput,
|
|
606
|
+
outputState: finalOutput.trim() ? "present" : "absent",
|
|
607
|
+
interrupted: interrupted || undefined,
|
|
608
|
+
timedOut: timedOut || undefined,
|
|
609
|
+
stopped: stopped || undefined,
|
|
610
|
+
observedMutationAttempt,
|
|
611
|
+
structuredOutputToolInvoked,
|
|
612
|
+
structuredOutputMessageStartIndex,
|
|
613
|
+
watchdog: childWatchdogState,
|
|
614
|
+
sessionFile: session?.sessionFile,
|
|
615
|
+
currentTool,
|
|
616
|
+
currentToolArgs,
|
|
617
|
+
currentPath,
|
|
618
|
+
afterCompactionSettlement: afterCompactionSettlement || undefined,
|
|
619
|
+
});
|
|
620
|
+
resolve(result);
|
|
621
|
+
});
|
|
558
622
|
};
|
|
559
623
|
|
|
560
624
|
input.registerInterrupt?.(() => {
|
|
@@ -574,31 +638,44 @@ export function runChildSession(input: RunChildSessionInput): Promise<RunChildSe
|
|
|
574
638
|
|
|
575
639
|
void (async () => {
|
|
576
640
|
try {
|
|
577
|
-
const
|
|
578
|
-
|
|
579
|
-
onExtensionError: (extensionError) => {
|
|
580
|
-
input.transcriptWriter?.writeStderrLine(`Extension error (${extensionError.extensionPath}, ${extensionError.event}): ${extensionError.error instanceof Error ? extensionError.error.message : String(extensionError.error)}`);
|
|
581
|
-
},
|
|
582
|
-
});
|
|
641
|
+
const createInput = createReportedChildSessionInput(input.launch, input.transcriptWriter);
|
|
642
|
+
const created = await input.factory.create(createInput);
|
|
583
643
|
if (settled) {
|
|
584
644
|
void created.dispose();
|
|
585
645
|
return;
|
|
586
646
|
}
|
|
587
647
|
session = created;
|
|
648
|
+
const steer = created.steer.bind(created);
|
|
649
|
+
const followUp = created.followUp.bind(created);
|
|
650
|
+
created.steer = async (text) => {
|
|
651
|
+
if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
|
|
652
|
+
return steer(text);
|
|
653
|
+
};
|
|
654
|
+
created.followUp = async (text) => {
|
|
655
|
+
if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
|
|
656
|
+
return followUp(text);
|
|
657
|
+
};
|
|
588
658
|
unsubscribe = created.subscribe(processEvent);
|
|
589
659
|
input.registerWatchdogStatus?.((event) => processEvent(event as unknown as ChildSessionEvent));
|
|
590
660
|
input.registerSteer?.(async (request) => {
|
|
591
661
|
const text = formatSteerMessage(request);
|
|
592
662
|
const followUp = request.mode === "follow_up";
|
|
663
|
+
const accepted = { request, text };
|
|
664
|
+
acceptedSteers.push(accepted);
|
|
665
|
+
const queued: SteerDelivery = {
|
|
666
|
+
state: "queued",
|
|
667
|
+
deliveryStatus: "queued",
|
|
668
|
+
message: followUp ? "Pi queued the follow-up input." : "Pi accepted the steering input.",
|
|
669
|
+
};
|
|
593
670
|
try {
|
|
594
671
|
if (followUp) await created.followUp(text);
|
|
595
672
|
else await created.steer(text);
|
|
596
673
|
} catch (steerError) {
|
|
674
|
+
const index = acceptedSteers.indexOf(accepted);
|
|
675
|
+
if (index >= 0) acceptedSteers.splice(index, 1);
|
|
597
676
|
return { state: "failed", message: steerError instanceof Error ? steerError.message : String(steerError) };
|
|
598
677
|
}
|
|
599
|
-
return
|
|
600
|
-
? { state: "queued", deliveryStatus: "queued", message: "Pi queued the follow-up input." }
|
|
601
|
-
: { state: "delivered", deliveryStatus: "delivered", message: "Pi accepted the steering input." };
|
|
678
|
+
return queued;
|
|
602
679
|
});
|
|
603
680
|
if (interrupted || timedOut || stopped) abortChild();
|
|
604
681
|
await created.prompt(input.prompt);
|