@xzzpig/pi-subagents 0.16.0 → 0.19.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 +233 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +34 -21
- package/docs/configuration.md +82 -7
- package/docs/extension-api.md +75 -8
- package/docs/missions.md +13 -13
- package/docs/models.md +7 -5
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +5 -5
- package/docs/tool-reference.md +98 -100
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +214 -162
- package/inspector-runner.mjs +1 -1
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +15 -9
- package/prompts/council.md +6 -3
- package/prompts/review-loop.md +1 -1
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +13 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
- package/skills/pi-subagents/references/execution-controls.md +72 -69
- package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
- package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +63 -54
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +132 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +7 -2
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +10 -4
- package/src/extension/fanout-child.ts +20 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +168 -206
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +39 -11
- package/src/extension/schemas.ts +47 -138
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +146 -0
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +26 -16
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +60 -95
- package/src/runs/background/async-job-tracker.ts +91 -56
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +98 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +20 -6
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +16 -4
- package/src/runs/background/runner-aliases.ts +54 -16
- package/src/runs/background/runner-child-launch.ts +4 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +111 -288
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +111 -139
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +715 -258
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +37 -16
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +144 -8
- package/src/runs/shared/child-tool-plan.ts +38 -116
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +5 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +35 -10
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +12 -0
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +4 -1
- package/src/runs/shared/pi-spawn.ts +1 -3
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +36 -9
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/model-info.ts +9 -0
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +73 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +18 -3
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +17 -246
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +4 -5
- package/src/tui/fleet-status.ts +38 -8
- package/src/tui/fleet.ts +21 -6
- package/src/tui/render.ts +166 -71
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +47 -12
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +13 -5
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +16 -16
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +12 -6
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +225 -59
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -12,6 +12,7 @@ export function registerWaitTool(
|
|
|
12
12
|
subscriptions?: Pick<WaitSubscriptionManager, "arm">,
|
|
13
13
|
defaultTimeoutMs?: number,
|
|
14
14
|
child?: { nestedRootRunId?: string },
|
|
15
|
+
hasPendingSupervisorRequest?: () => boolean,
|
|
15
16
|
): void {
|
|
16
17
|
const description = `Wait for background, provider, or detached work that has no native completion notification, then return.
|
|
17
18
|
|
|
@@ -30,6 +31,7 @@ Non-blocking subscriptions are visible in subagent status and differ from disabl
|
|
|
30
31
|
nestedRootRunId: child?.nestedRootRunId,
|
|
31
32
|
events: pi.events,
|
|
32
33
|
enabled,
|
|
34
|
+
hasPendingSupervisorRequest,
|
|
33
35
|
...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs } : {}),
|
|
34
36
|
onUpdate,
|
|
35
37
|
...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { AsyncStatus, ProcessTerminal, WorkflowChildSummary, WorkflowTerminalProof } from "../../shared/types.ts";
|
|
4
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
5
|
+
import { readProcessTerminal } from "./process-terminal.ts";
|
|
6
|
+
|
|
7
|
+
const TERMINAL_WORKFLOW_STATES = new Set<WorkflowChildSummary["workflowState"]>(["completed", "failed", "stopped"]);
|
|
8
|
+
|
|
9
|
+
export function isTerminalAsyncState(state: AsyncStatus["state"]): boolean {
|
|
10
|
+
return state !== "queued" && state !== "running" && state !== "paused";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export type WorkflowChildProcessEvidence =
|
|
14
|
+
| { state: "observed"; children: ProcessTerminal[] }
|
|
15
|
+
| { state: "pending" | "unknown"; reason: string };
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Process evidence for a workflow's async children. Status proofs and capacity
|
|
19
|
+
* release both use this so they cannot disagree about the same workflow.
|
|
20
|
+
* Synchronous children run inside the workflow host and have no process of their own.
|
|
21
|
+
*/
|
|
22
|
+
export function readWorkflowChildProcessEvidence(workflowAsyncDir: string, steps: AsyncStatus["steps"]): WorkflowChildProcessEvidence {
|
|
23
|
+
if (!steps) return { state: "unknown", reason: "workflow child roster is missing" };
|
|
24
|
+
const children: ProcessTerminal[] = [];
|
|
25
|
+
for (const step of steps) {
|
|
26
|
+
const label = step.workflowKey ?? step.agent;
|
|
27
|
+
if (typeof step.async !== "boolean") return { state: "unknown", reason: `workflow child ${label} is missing async classification` };
|
|
28
|
+
if (!step.async) continue;
|
|
29
|
+
if (!step.runId || path.basename(step.runId) !== step.runId) return { state: "unknown", reason: `async workflow child ${label} is missing run id` };
|
|
30
|
+
const childDir = path.join(path.dirname(workflowAsyncDir), step.runId);
|
|
31
|
+
if (!fs.existsSync(childDir)) return { state: "unknown", reason: `async workflow child ${label} directory is missing` };
|
|
32
|
+
const childStatus = readStatus(childDir);
|
|
33
|
+
if (!childStatus) return { state: "unknown", reason: `async workflow child ${label} status is missing or unreadable` };
|
|
34
|
+
if (!isTerminalAsyncState(childStatus.state)) return { state: "pending", reason: `async workflow child ${label} is still ${childStatus.state}` };
|
|
35
|
+
const recorded = childStatus.processTerminal;
|
|
36
|
+
if (!recorded?.runnerProcessInstanceId) return { state: "unknown", reason: `async workflow child ${label} has no runner process identity` };
|
|
37
|
+
// A runner startup failure records `not-started` in status and never writes a process-terminal sidecar.
|
|
38
|
+
if (recorded.state === "not-started" && recorded.runId === step.runId && typeof childStatus.error === "string" && childStatus.error) {
|
|
39
|
+
children.push(recorded);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const proof = readProcessTerminal(childDir, { runId: step.runId, runnerProcessInstanceId: recorded.runnerProcessInstanceId });
|
|
43
|
+
if (proof?.state !== "observed" || proof.runId !== step.runId) {
|
|
44
|
+
return { state: !proof || proof.state === "pending" ? "pending" : "unknown", reason: `async workflow child ${label} process-terminal proof is ${proof?.state ?? "missing"}` };
|
|
45
|
+
}
|
|
46
|
+
children.push(proof);
|
|
47
|
+
}
|
|
48
|
+
return { state: "observed", children };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function unresolved(runId: string, state: "pending" | "unknown", dispatchClosed: boolean, reason: string): WorkflowTerminalProof {
|
|
52
|
+
return { version: 1, kind: "workflow", runId, state, dispatchClosed, reason };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** A persistent workflow host is terminal only after dispatch closes and every async child has process evidence. */
|
|
56
|
+
export function readWorkflowTerminalProof(asyncDir: string, steps: AsyncStatus["steps"], summary: WorkflowChildSummary, hostCommandCount: number, closedAt: number): WorkflowTerminalProof {
|
|
57
|
+
const runId = summary.workflowRunId;
|
|
58
|
+
if (!summary.inventoryComplete || !TERMINAL_WORKFLOW_STATES.has(summary.workflowState)) {
|
|
59
|
+
return unresolved(runId, "pending", false, "Workflow dispatch is still open.");
|
|
60
|
+
}
|
|
61
|
+
if (hostCommandCount > 0) {
|
|
62
|
+
return unresolved(runId, "unknown", true, "Workflow host commands have no process-terminal proof.");
|
|
63
|
+
}
|
|
64
|
+
const evidence = readWorkflowChildProcessEvidence(asyncDir, steps);
|
|
65
|
+
if (evidence.state !== "observed") return unresolved(runId, evidence.state, true, evidence.reason);
|
|
66
|
+
const observedAt = Math.max(closedAt, ...evidence.children.map((child) => child.state === "observed" ? child.observedAt : 0));
|
|
67
|
+
return { version: 1, kind: "workflow", runId, state: "observed", dispatchClosed: true, observedAt, children: evidence.children };
|
|
68
|
+
}
|
|
@@ -4,11 +4,12 @@ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
|
4
4
|
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
5
5
|
import { DIRS, type AsyncStatus, type Details, type SubagentState } from "../../shared/types.ts";
|
|
6
6
|
import { updateActiveRunIndex } from "../background/active-run-index.ts";
|
|
7
|
-
import { deliverStopRequest } from "../background/control-channel.ts";
|
|
7
|
+
import { deliverStopRequest, stopInboxClosedPath } from "../background/control-channel.ts";
|
|
8
8
|
import { readProcessTerminal } from "../background/process-terminal.ts";
|
|
9
9
|
import { resultFilePath, resultPayloadPathForSessionRun, writeAsyncResultFile } from "../background/result-files.ts";
|
|
10
10
|
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
11
|
-
import {
|
|
11
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
12
|
+
import { isStoppableAsyncStatusStep, resolveAsyncStatusChild, stopStoppableAsyncStatusChildren, type ResolvedAsyncStatusChild } from "../shared/child-identity.ts";
|
|
12
13
|
|
|
13
14
|
function getAsyncStopTarget(
|
|
14
15
|
state: SubagentState,
|
|
@@ -108,6 +109,18 @@ export function stopAsyncRun(
|
|
|
108
109
|
childId?: string,
|
|
109
110
|
): AgentToolResult<Details> | null {
|
|
110
111
|
const target = getAsyncStopTarget(state, runId, location);
|
|
112
|
+
// An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
|
|
113
|
+
const workflowRunId = target?.asyncId ?? runId;
|
|
114
|
+
const workflowController = childId === undefined && workflowRunId ? state.workflowControllers?.get(workflowRunId) : undefined;
|
|
115
|
+
const workflowAsyncDir = workflowController && workflowRunId ? target?.asyncDir ?? state.asyncJobs.get(workflowRunId)?.asyncDir : undefined;
|
|
116
|
+
const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
|
|
117
|
+
// Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
|
|
118
|
+
const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
|
|
119
|
+
if (workflowController && workflowRunId && !foreignWorkflow) {
|
|
120
|
+
if (workflowStatus) stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
|
|
121
|
+
workflowController.abort(new Error("Workflow stopped."));
|
|
122
|
+
return { content: [{ type: "text", text: `Stop requested for async workflow ${workflowRunId}.` }], details: { mode: "management", results: [] } };
|
|
123
|
+
}
|
|
111
124
|
if (!target) return null;
|
|
112
125
|
const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
|
|
113
126
|
if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
|
|
@@ -145,7 +158,8 @@ export function stopAsyncRun(
|
|
|
145
158
|
}
|
|
146
159
|
}
|
|
147
160
|
try {
|
|
148
|
-
|
|
161
|
+
// A paused run whose runner closed its inbox can only be sealed from exact exit proof below.
|
|
162
|
+
if (!(pausedWholeRun && fs.existsSync(stopInboxClosedPath(target.asyncDir)))) deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action", targetIndex: child?.index, childId: child?.id ?? childId });
|
|
149
163
|
if (pausedWholeRun) {
|
|
150
164
|
const failure = sealPausedRun(target.asyncDir, status);
|
|
151
165
|
if (failure) {
|
|
@@ -53,9 +53,6 @@ import {
|
|
|
53
53
|
} from "../../shared/utils.ts";
|
|
54
54
|
import { resolveSkillsWithFallback } from "../../agents/skills.ts";
|
|
55
55
|
import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.ts";
|
|
56
|
-
import { evaluateCompletionMutationGuard, expectsImplementationMutation, hasMutationToolCapability, validateImplementationToolContract } from "../shared/completion-guard.ts";
|
|
57
|
-
import { planCompletionEvidence } from "../shared/completion-evidence.ts";
|
|
58
|
-
import { arbitrateCompletionGuardRescue } from "../shared/llm-intent-arbiter.ts";
|
|
59
56
|
import { preflightLaunchCwd } from "../shared/launch-cwd.ts";
|
|
60
57
|
import { createJsonlWriter } from "../../shared/jsonl-writer.ts";
|
|
61
58
|
import { createOrcaProgressTab, type OrcaProgressTab } from "../shared/orca-progress-tabs.ts";
|
|
@@ -66,7 +63,7 @@ import { deriveChildSessionName } from "../../shared/child-session-name.ts";
|
|
|
66
63
|
import { assertAgentAllowedByCapabilityCeiling, intersectSubagentCapabilityCeilings, resolveCurrentSubagentCapabilityCeiling } from "../shared/capability-ceiling.ts";
|
|
67
64
|
import { resolveEffectiveThinking } from "../../shared/model-info.ts";
|
|
68
65
|
import { assertThinkingWithinCeiling, intersectThinkingCeilings } from "../../shared/thinking-ceiling.ts";
|
|
69
|
-
import { MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
|
|
66
|
+
import { formatStructuredOutputRejectionError, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, MISSING_STRUCTURED_OUTPUT_CALL_ERROR } from "../shared/structured-output.ts";
|
|
70
67
|
import { formatMidToolExitError, isOrdinaryToolForMidToolExit } from "../shared/process-signal.ts";
|
|
71
68
|
import { formatChildToolDiagnostic } from "../shared/tool-availability.ts";
|
|
72
69
|
import { formatChildModelResolutionDiagnostic, isChildModelResolutionFailure } from "../shared/model-resolution-diagnostic.ts";
|
|
@@ -89,10 +86,10 @@ import {
|
|
|
89
86
|
shouldEscalateMutatingFailures,
|
|
90
87
|
summarizeRecentMutatingFailures,
|
|
91
88
|
} from "../shared/long-running-guard.ts";
|
|
92
|
-
import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput } from "../shared/acceptance.ts";
|
|
89
|
+
import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, captureStagedIndexBaseline, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput, typedVerifyOutput } from "../shared/acceptance.ts";
|
|
93
90
|
import { PROMPT_REDACTED } from "../../shared/utils.ts";
|
|
94
91
|
import { attachContractProjections, isAgentContract } from "../shared/agent-contract.ts";
|
|
95
|
-
import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.ts";
|
|
92
|
+
import { initialToolBudgetState, isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.ts";
|
|
96
93
|
import { resolveWatchdogConfig } from "../../watchdog/settings.ts";
|
|
97
94
|
import { resolveLaunchBinding } from "../../shared/launch-contract.ts";
|
|
98
95
|
import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.ts";
|
|
@@ -108,6 +105,7 @@ import {
|
|
|
108
105
|
} from "../../watchdog/child-status.ts";
|
|
109
106
|
import { buildInProcessChildLaunch, createReportedChildSessionInput } from "../shared/child-launch.ts";
|
|
110
107
|
import { childSessionFactory, childSessionHasQueuedMessages, projectChildSessionEventForJson, type ChildSession, type ChildSessionEvent } from "../shared/child-session.ts";
|
|
108
|
+
import { reconcileAttemptUsage } from "../shared/usage-reconciliation.ts";
|
|
111
109
|
|
|
112
110
|
const artifactOutputByResult = new WeakMap<SingleResult, string>();
|
|
113
111
|
const acceptanceOutputByResult = new WeakMap<SingleResult, string>();
|
|
@@ -288,6 +286,7 @@ interface StructuredDelegationProgressState {
|
|
|
288
286
|
model?: string;
|
|
289
287
|
toolCount: number;
|
|
290
288
|
tokens: number;
|
|
289
|
+
turnCount?: number;
|
|
291
290
|
}
|
|
292
291
|
|
|
293
292
|
function captureStructuredDelegationProgressState(progress: AgentProgress, result: SingleResult): StructuredDelegationProgressState {
|
|
@@ -300,6 +299,7 @@ function captureStructuredDelegationProgressState(progress: AgentProgress, resul
|
|
|
300
299
|
model: progress.model ?? result.model,
|
|
301
300
|
toolCount: progress.toolCount,
|
|
302
301
|
tokens: progress.tokens,
|
|
302
|
+
turnCount: progress.turnCount,
|
|
303
303
|
};
|
|
304
304
|
}
|
|
305
305
|
|
|
@@ -314,6 +314,7 @@ function structuredDelegationProgressChanged(
|
|
|
314
314
|
|| previous.model !== (progress.model ?? result.model)
|
|
315
315
|
|| previous.toolCount !== progress.toolCount
|
|
316
316
|
|| previous.tokens !== progress.tokens
|
|
317
|
+
|| previous.turnCount !== progress.turnCount
|
|
317
318
|
|| previous.recentOutput.length !== progress.recentOutput.length) return true;
|
|
318
319
|
for (let index = 0; index < progress.recentOutput.length; index++) {
|
|
319
320
|
if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
|
|
@@ -328,6 +329,9 @@ function structuredDelegationProgressChanged(
|
|
|
328
329
|
return false;
|
|
329
330
|
}
|
|
330
331
|
|
|
332
|
+
function isCompleteUsageCounter(value: unknown): value is number {
|
|
333
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
334
|
+
}
|
|
331
335
|
|
|
332
336
|
const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
|
|
333
337
|
const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
|
|
@@ -400,6 +404,7 @@ async function runSingleAttempt(
|
|
|
400
404
|
tools: agent.tools,
|
|
401
405
|
excludeTools: agent.excludeTools,
|
|
402
406
|
allowNestedSubagents: agent.allowNestedSubagents,
|
|
407
|
+
descendantAllowedAgents: agent.allowedAgents,
|
|
403
408
|
extensions: agent.extensions,
|
|
404
409
|
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
405
410
|
// Exact terminal protocol belongs to session resources, not compactable history.
|
|
@@ -434,7 +439,6 @@ async function runSingleAttempt(
|
|
|
434
439
|
thinkingCeiling: options.thinkingCeiling,
|
|
435
440
|
maxSubagentDepth: options.maxSubagentDepth,
|
|
436
441
|
runtimeSnapshotHost: options.runtimeSnapshotHost,
|
|
437
|
-
hostAvailableBuiltins: options.hostAvailableBuiltins,
|
|
438
442
|
inherited: options.childRuntime,
|
|
439
443
|
host: "parent",
|
|
440
444
|
});
|
|
@@ -446,34 +450,6 @@ async function runSingleAttempt(
|
|
|
446
450
|
}
|
|
447
451
|
|
|
448
452
|
const effectiveSystemPrompt = shared.systemPrompt;
|
|
449
|
-
const contractTools = toolPlan.explicitToolAllowlist ? toolPlan.effectiveToolAllowlist : undefined;
|
|
450
|
-
const contractError = validateImplementationToolContract({
|
|
451
|
-
agent: agent.name,
|
|
452
|
-
task: shared.originalTask ?? task,
|
|
453
|
-
tools: contractTools,
|
|
454
|
-
mcpDirectTools: toolPlan.effectiveMcpTools,
|
|
455
|
-
configuredExtensions: toolPlan.configuredExtensions,
|
|
456
|
-
requestedTools: toolPlan.requestedBuiltinTools,
|
|
457
|
-
acceptanceRole: agent.acceptanceRole,
|
|
458
|
-
completionGuard: agent.completionGuard,
|
|
459
|
-
});
|
|
460
|
-
if (contractError) {
|
|
461
|
-
return {
|
|
462
|
-
index: options.index ?? 0,
|
|
463
|
-
agent: agent.name,
|
|
464
|
-
task,
|
|
465
|
-
...(childSessionName ? { sessionName: childSessionName } : {}),
|
|
466
|
-
messages: [],
|
|
467
|
-
finalOutput: "",
|
|
468
|
-
exitCode: 1,
|
|
469
|
-
error: contractError,
|
|
470
|
-
usage: emptyUsage(),
|
|
471
|
-
model: modelArg,
|
|
472
|
-
progressSummary: { status: "failed", toolCount: 0, tokens: 0, durationMs: 0 },
|
|
473
|
-
...(toolPlan.capabilityCeiling ? { capabilityCeiling: toolPlan.capabilityCeiling } : {}),
|
|
474
|
-
...(toolPlan.capabilityAudit ? { capabilityAudit: toolPlan.capabilityAudit } : {}),
|
|
475
|
-
};
|
|
476
|
-
}
|
|
477
453
|
const fast = options.fast ?? agent.fast;
|
|
478
454
|
const { launchContractDigest } = resolveLaunchBinding({
|
|
479
455
|
agent,
|
|
@@ -532,6 +508,10 @@ async function runSingleAttempt(
|
|
|
532
508
|
pendingControlEvents.push(event);
|
|
533
509
|
options.onControlEvent?.(event);
|
|
534
510
|
};
|
|
511
|
+
let inputUsageComplete = true;
|
|
512
|
+
let outputUsageComplete = true;
|
|
513
|
+
let cacheReadUsageComplete = true;
|
|
514
|
+
let cacheWriteUsageComplete = true;
|
|
535
515
|
|
|
536
516
|
const progress: AgentProgress = {
|
|
537
517
|
index: options.index ?? 0,
|
|
@@ -546,12 +526,20 @@ async function runSingleAttempt(
|
|
|
546
526
|
tokens: 0,
|
|
547
527
|
...(modelArg ? { model: modelArg } : {}),
|
|
548
528
|
...(resolvedThinking ? { thinking: resolvedThinking } : {}),
|
|
549
|
-
inputTokens: 0,
|
|
550
|
-
outputTokens: 0,
|
|
551
529
|
durationMs: 0,
|
|
552
530
|
lastActivityAt: startTime,
|
|
553
531
|
};
|
|
554
532
|
result.progress = progress;
|
|
533
|
+
const projectCompleteUsage = () => {
|
|
534
|
+
if (inputUsageComplete) progress.inputTokens = result.usage.input;
|
|
535
|
+
else delete progress.inputTokens;
|
|
536
|
+
if (outputUsageComplete) progress.outputTokens = result.usage.output;
|
|
537
|
+
else delete progress.outputTokens;
|
|
538
|
+
if (cacheReadUsageComplete) progress.cacheRead = result.usage.cacheRead;
|
|
539
|
+
else delete progress.cacheRead;
|
|
540
|
+
if (cacheWriteUsageComplete) progress.cacheWrite = result.usage.cacheWrite;
|
|
541
|
+
else delete progress.cacheWrite;
|
|
542
|
+
};
|
|
555
543
|
const attemptTimeout = resolveAttemptTimeout(options);
|
|
556
544
|
if (attemptTimeout?.remainingMs === 0) {
|
|
557
545
|
result.exitCode = 1;
|
|
@@ -568,7 +556,6 @@ async function runSingleAttempt(
|
|
|
568
556
|
return result;
|
|
569
557
|
}
|
|
570
558
|
const mutationSnapshot = options.machine ? { source: "tracked-files" as const, trackedOnly: true as const, cwd: options.cwd ?? runtimeCwd, dirtyFiles: [], fingerprints: {}, unavailable: "Local Git evidence is not authoritative for a pane-native remote run." } : snapshotTrackedMutations(options.cwd ?? runtimeCwd);
|
|
571
|
-
let observedMutationAttempt = false;
|
|
572
559
|
let structuredOutputToolInvoked = false;
|
|
573
560
|
let structuredOutputMessageStartIndex: number | undefined;
|
|
574
561
|
let toolAvailabilityError: string | undefined;
|
|
@@ -597,6 +584,7 @@ async function runSingleAttempt(
|
|
|
597
584
|
const exitCode = await new Promise<number>((resolve) => {
|
|
598
585
|
const jsonlWriter = createJsonlWriter(shared.jsonlPath, { pause() {}, resume() {} });
|
|
599
586
|
let session: ChildSession | undefined;
|
|
587
|
+
let messageBaseline: number | undefined;
|
|
600
588
|
let unsubscribe: (() => void) | undefined;
|
|
601
589
|
let sessionSettled = false;
|
|
602
590
|
let lifecycleFinished = false;
|
|
@@ -999,7 +987,7 @@ async function runSingleAttempt(
|
|
|
999
987
|
// deliver the same result either as a tool_result_end event or as a
|
|
1000
988
|
// message_end whose message role is toolResult; both funnel through here
|
|
1001
989
|
// so one result updates budget, output, and mutating-failure state once.
|
|
1002
|
-
const handleToolResult = (message: Message, completion: { toolCallId?: unknown }, now: number): void => {
|
|
990
|
+
const handleToolResult = (message: Message, completion: { toolCallId?: unknown; toolName?: unknown }, now: number): void => {
|
|
1003
991
|
const rawCallId = completion.toolCallId ?? (message as { toolCallId?: unknown }).toolCallId;
|
|
1004
992
|
const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
|
|
1005
993
|
if (callId) {
|
|
@@ -1012,9 +1000,18 @@ async function runSingleAttempt(
|
|
|
1012
1000
|
}
|
|
1013
1001
|
result.messages!.push(message);
|
|
1014
1002
|
const resultText = extractTextFromContent(message.content);
|
|
1015
|
-
|
|
1003
|
+
// The result event's own tool name is authoritative; the single pending slot can
|
|
1004
|
+
// describe a different, overlapping call and serves only as a fallback.
|
|
1005
|
+
const blockedTool = (typeof completion.toolName === "string" && completion.toolName.length > 0
|
|
1006
|
+
? completion.toolName
|
|
1007
|
+
: undefined) ?? pendingToolResult?.tool;
|
|
1008
|
+
if (options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool)) {
|
|
1016
1009
|
result.toolBudgetBlocked = true;
|
|
1017
|
-
result.toolBudget = toolBudgetState(
|
|
1010
|
+
result.toolBudget = toolBudgetState(
|
|
1011
|
+
options.toolBudget,
|
|
1012
|
+
Math.max(progress.toolCount, options.toolBudget.hard + 1),
|
|
1013
|
+
blockedTool,
|
|
1014
|
+
);
|
|
1018
1015
|
}
|
|
1019
1016
|
appendRecentOutput(progress, resultText.split("\n").slice(-10));
|
|
1020
1017
|
const toolSnapshot = pendingToolResult;
|
|
@@ -1047,7 +1044,10 @@ async function runSingleAttempt(
|
|
|
1047
1044
|
jsonlWriter.writeLine(JSON.stringify(projectChildSessionEventForJson(evt)));
|
|
1048
1045
|
shared.transcriptWriter?.writeChildEvent(evt);
|
|
1049
1046
|
shared.orcaProgressTab?.event(evt);
|
|
1050
|
-
if (evt.type === "compaction_start")
|
|
1047
|
+
if (evt.type === "compaction_start") {
|
|
1048
|
+
compactionStartedReceived = true;
|
|
1049
|
+
if (agentSettledReceived) afterCompactionSettlement = true;
|
|
1050
|
+
}
|
|
1051
1051
|
if (evt.type === "compaction_end" && evt.willRetry === true) {
|
|
1052
1052
|
compactionStartedReceived = false;
|
|
1053
1053
|
afterCompactionSettlement = false;
|
|
@@ -1125,7 +1125,6 @@ async function runSingleAttempt(
|
|
|
1125
1125
|
result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount);
|
|
1126
1126
|
}
|
|
1127
1127
|
const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
|
|
1128
|
-
observedMutationAttempt = observedMutationAttempt || mutates;
|
|
1129
1128
|
pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
|
|
1130
1129
|
fireUpdate();
|
|
1131
1130
|
}
|
|
@@ -1150,33 +1149,36 @@ async function runSingleAttempt(
|
|
|
1150
1149
|
// tool_result_end reach the same deduplicated completion path.
|
|
1151
1150
|
handleToolResult(evt.message, evt, now);
|
|
1152
1151
|
} else {
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1152
|
+
result.messages!.push(evt.message);
|
|
1153
|
+
if (childWatchdog) {
|
|
1154
|
+
const next = applyChildWatchdogMessage(childWatchdogState, evt.message);
|
|
1155
|
+
if (next) updateChildWatchdogState(next);
|
|
1156
|
+
}
|
|
1157
|
+
if (evt.message.role === "assistant") {
|
|
1158
|
+
result.usage.turns++;
|
|
1159
|
+
progress.turnCount = result.usage.turns;
|
|
1160
|
+
const toolCalls = Array.isArray(evt.message.content)
|
|
1161
|
+
? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
|
|
1162
|
+
: [];
|
|
1163
|
+
const hasToolCall = toolCalls.length > 0;
|
|
1164
|
+
const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
|
|
1165
|
+
const u = evt.message.usage;
|
|
1166
|
+
inputUsageComplete &&= isCompleteUsageCounter(u?.input);
|
|
1167
|
+
outputUsageComplete &&= isCompleteUsageCounter(u?.output);
|
|
1168
|
+
cacheReadUsageComplete &&= isCompleteUsageCounter(u?.cacheRead);
|
|
1169
|
+
cacheWriteUsageComplete &&= isCompleteUsageCounter(u?.cacheWrite);
|
|
1170
|
+
if (u) {
|
|
1171
|
+
const window = (u.input || 0) + (u.cacheRead || 0);
|
|
1172
|
+
result.usage.input += u.input || 0;
|
|
1173
|
+
result.usage.output += u.output || 0;
|
|
1174
|
+
result.usage.cacheRead += u.cacheRead || 0;
|
|
1175
|
+
result.usage.cacheWrite += u.cacheWrite || 0;
|
|
1176
|
+
result.usage.cost += u.cost?.total || 0;
|
|
1177
|
+
progress.tokens = result.usage.input + result.usage.output;
|
|
1178
|
+
progress.window = window;
|
|
1179
|
+
progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
|
|
1157
1180
|
}
|
|
1158
|
-
|
|
1159
|
-
result.usage.turns++;
|
|
1160
|
-
progress.turnCount = result.usage.turns;
|
|
1161
|
-
const toolCalls = Array.isArray(evt.message.content)
|
|
1162
|
-
? evt.message.content.filter((part) => (part as { type?: string }).type === "toolCall")
|
|
1163
|
-
: [];
|
|
1164
|
-
const hasToolCall = toolCalls.length > 0;
|
|
1165
|
-
const terminalAssistantStop = (evt.message as { stopReason?: string }).stopReason === "stop" && !hasToolCall;
|
|
1166
|
-
const u = evt.message.usage;
|
|
1167
|
-
if (u) {
|
|
1168
|
-
const window = (u.input || 0) + (u.cacheRead || 0);
|
|
1169
|
-
result.usage.input += u.input || 0;
|
|
1170
|
-
result.usage.output += u.output || 0;
|
|
1171
|
-
result.usage.cacheRead += u.cacheRead || 0;
|
|
1172
|
-
result.usage.cacheWrite += u.cacheWrite || 0;
|
|
1173
|
-
result.usage.cost += u.cost?.total || 0;
|
|
1174
|
-
progress.tokens = result.usage.input + result.usage.output;
|
|
1175
|
-
progress.inputTokens = result.usage.input;
|
|
1176
|
-
progress.outputTokens = result.usage.output;
|
|
1177
|
-
progress.window = window;
|
|
1178
|
-
progress.windowPeak = Math.max(progress.windowPeak ?? 0, window);
|
|
1179
|
-
}
|
|
1181
|
+
projectCompleteUsage();
|
|
1180
1182
|
if (evt.message.model) {
|
|
1181
1183
|
progress.model = evt.message.model;
|
|
1182
1184
|
if (!result.model) result.model = evt.message.model;
|
|
@@ -1365,11 +1367,19 @@ async function runSingleAttempt(
|
|
|
1365
1367
|
if (!closeError && (abortedBySignal || session?.shutDown) && !result.interrupted && !result.timedOut) {
|
|
1366
1368
|
closeError = session?.shutDown ? "Subagent stopped because the parent session shut down." : STOPPED_BEFORE_COMPLETION_ERROR;
|
|
1367
1369
|
}
|
|
1370
|
+
// A workflow child ended by the workflow's abort signal was stopped, not failed.
|
|
1371
|
+
if (options.abortedAsStopped && abortedBySignal && !session?.shutDown && !result.interrupted && !result.timedOut) result.stopped = true;
|
|
1368
1372
|
if (!closeError && forced && !forcedDrainAfterFinalSuccess) {
|
|
1369
1373
|
closeError = "Subagent session did not settle after it was aborted.";
|
|
1370
1374
|
}
|
|
1371
1375
|
const finalCode = forcedDrainAfterFinalSuccess && !forcedDrainAfterEmptyTerminal ? 0 : closeError || promptError !== undefined ? 1 : 0;
|
|
1372
1376
|
if (!result.error && closeError) result.error = closeError;
|
|
1377
|
+
if (session && messageBaseline !== undefined) {
|
|
1378
|
+
result.usage = reconcileAttemptUsage(result.usage, session.messages, messageBaseline);
|
|
1379
|
+
progress.tokens = result.usage.input + result.usage.output;
|
|
1380
|
+
projectCompleteUsage();
|
|
1381
|
+
progress.turnCount = result.usage.turns;
|
|
1382
|
+
}
|
|
1373
1383
|
finish(finalCode);
|
|
1374
1384
|
};
|
|
1375
1385
|
|
|
@@ -1453,6 +1463,7 @@ async function runSingleAttempt(
|
|
|
1453
1463
|
abortChild();
|
|
1454
1464
|
}
|
|
1455
1465
|
options.onChildSession?.({ steer: (text) => created.steer(text), followUp: (text) => created.followUp(text) });
|
|
1466
|
+
messageBaseline = created.messages.length;
|
|
1456
1467
|
await created.prompt(`Task: ${task}`);
|
|
1457
1468
|
settle(undefined);
|
|
1458
1469
|
} catch (error) {
|
|
@@ -1492,15 +1503,11 @@ async function runSingleAttempt(
|
|
|
1492
1503
|
result.exitCode = 1;
|
|
1493
1504
|
}
|
|
1494
1505
|
let validatedStructuredOutput = false;
|
|
1495
|
-
if (options.structuredOutput
|
|
1506
|
+
if (options.structuredOutput) {
|
|
1496
1507
|
result.structuredOutputSchemaPath = options.structuredOutput.schemaPath;
|
|
1497
1508
|
result.structuredOutputPath = options.structuredOutput.outputPath;
|
|
1498
1509
|
const structured = capture.structuredOutput();
|
|
1499
|
-
if (
|
|
1500
|
-
result.exitCode = 1;
|
|
1501
|
-
result.error = MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
|
|
1502
|
-
result.structuredOutputFailed = true;
|
|
1503
|
-
} else {
|
|
1510
|
+
if (structuredOutputToolInvoked && structured.called) {
|
|
1504
1511
|
result.structuredOutput = structured.value;
|
|
1505
1512
|
const acceptanceMode = options.structuredOutput.acceptanceReportPath
|
|
1506
1513
|
? options.structuredOutput.acceptanceReportRequired ? "required" : "optional"
|
|
@@ -1512,6 +1519,12 @@ async function runSingleAttempt(
|
|
|
1512
1519
|
(result as SingleResult & { structuredAcceptanceReport?: unknown; structuredAcceptanceReportError?: string }).structuredAcceptanceReportError = acceptanceReportError;
|
|
1513
1520
|
writeStructuredOutputArtifacts(options.structuredOutput, structured.value, acceptanceMode ? structured.acceptanceReport : undefined);
|
|
1514
1521
|
validatedStructuredOutput = true;
|
|
1522
|
+
} else if (result.exitCode === 0 && !result.error) {
|
|
1523
|
+
result.exitCode = 1;
|
|
1524
|
+
result.error = structuredOutputToolInvoked
|
|
1525
|
+
? formatStructuredOutputRejectionError(result.messages ?? [])
|
|
1526
|
+
: MISSING_STRUCTURED_OUTPUT_CALL_ERROR;
|
|
1527
|
+
result.structuredOutputFailed = true;
|
|
1515
1528
|
}
|
|
1516
1529
|
}
|
|
1517
1530
|
if (result.exitCode === 0 && !result.error) {
|
|
@@ -1590,70 +1603,6 @@ async function runSingleAttempt(
|
|
|
1590
1603
|
fullOutput = fullOutput.trim()
|
|
1591
1604
|
? `${timeoutMessage}\n\n${result.timeoutRecovery.message}\n\nPartial output before timeout:\n${fullOutput}`
|
|
1592
1605
|
: `${timeoutMessage}\n\n${result.timeoutRecovery.message}`;
|
|
1593
|
-
}
|
|
1594
|
-
const completionGuardEnabled = isAgentContract(options.agentContract) ? agent.completionGuard === true : agent.completionGuard !== false;
|
|
1595
|
-
const completionGuard = ((result.exitCode === 0 && !result.error) || toolAvailabilityError) && completionGuardEnabled
|
|
1596
|
-
? evaluateCompletionMutationGuard({
|
|
1597
|
-
agent: agent.name,
|
|
1598
|
-
task: shared.originalTask ?? task,
|
|
1599
|
-
messages: result.messages ?? [],
|
|
1600
|
-
tools: contractTools,
|
|
1601
|
-
mcpDirectTools: toolPlan.effectiveMcpTools,
|
|
1602
|
-
mutationTools: agent.mutationTools,
|
|
1603
|
-
toolAvailabilityError,
|
|
1604
|
-
mutationEvidence,
|
|
1605
|
-
})
|
|
1606
|
-
: undefined;
|
|
1607
|
-
const mutationAttemptObserved = observedMutationAttempt || mutationEvidence.attemptedMutation;
|
|
1608
|
-
let completionGuardTriggered = completionGuard?.triggered === true && !mutationAttemptObserved;
|
|
1609
|
-
// The classifier is deliberately narrow, so a read-only review task can
|
|
1610
|
-
// still be misread as implementation. Arbitrate BEFORE any failure side
|
|
1611
|
-
// effect is published (effects, exit code, progress, notifications,
|
|
1612
|
-
// acceptance, output persistence): only a confident read-only verdict
|
|
1613
|
-
// rescues, and the task text alone is evidence — never the child's own
|
|
1614
|
-
// final message.
|
|
1615
|
-
let arbiterRescued = false;
|
|
1616
|
-
if (completionGuardTriggered) {
|
|
1617
|
-
const arbitration = await arbitrateCompletionGuardRescue({
|
|
1618
|
-
guardTriggered: true,
|
|
1619
|
-
task: shared.originalTask ?? task,
|
|
1620
|
-
arbiter: options.llmIntentArbiter,
|
|
1621
|
-
});
|
|
1622
|
-
completionGuardTriggered = arbitration.triggered;
|
|
1623
|
-
arbiterRescued = arbitration.rescued;
|
|
1624
|
-
}
|
|
1625
|
-
const completionEvidence = planCompletionEvidence({
|
|
1626
|
-
guard: completionGuard,
|
|
1627
|
-
guardTriggered: completionGuardTriggered,
|
|
1628
|
-
completionGuardEnabled,
|
|
1629
|
-
mutationCapable: hasMutationToolCapability(contractTools, toolPlan.effectiveMcpTools),
|
|
1630
|
-
implementationMutationExpected: expectsImplementationMutation(agent.name, shared.originalTask ?? task),
|
|
1631
|
-
mutationAttemptObserved,
|
|
1632
|
-
mutationEvidence,
|
|
1633
|
-
arbiterRescued,
|
|
1634
|
-
agentContractEnabled: isAgentContract(options.agentContract),
|
|
1635
|
-
});
|
|
1636
|
-
if (completionEvidence.fileMutation) {
|
|
1637
|
-
result.effects = {
|
|
1638
|
-
...(result.effects ?? {}),
|
|
1639
|
-
fileMutation: completionEvidence.fileMutation,
|
|
1640
|
-
};
|
|
1641
|
-
}
|
|
1642
|
-
if (completionEvidence.legacyFailureError) {
|
|
1643
|
-
result.exitCode = 1;
|
|
1644
|
-
result.error = completionEvidence.legacyFailureError;
|
|
1645
|
-
progress.status = "failed";
|
|
1646
|
-
progress.error = result.error;
|
|
1647
|
-
emitControlEvent(buildControlEvent({
|
|
1648
|
-
from: progress.activityState,
|
|
1649
|
-
to: "needs_attention",
|
|
1650
|
-
runId: options.runId ?? agent.name,
|
|
1651
|
-
agent: agent.name,
|
|
1652
|
-
index: options.index,
|
|
1653
|
-
ts: Date.now(),
|
|
1654
|
-
message: `${agent.name} completed without making edits for an implementation task`,
|
|
1655
|
-
reason: "completion_guard",
|
|
1656
|
-
}));
|
|
1657
1606
|
}
|
|
1658
1607
|
if (options.outputPath && result.exitCode === 0) {
|
|
1659
1608
|
const resolvedOutput = resolveSingleOutput(options.outputPath, fullOutput, shared.outputSnapshot, options.outputClaimPath);
|
|
@@ -1953,6 +1902,22 @@ async function runSyncCompletionInner(
|
|
|
1953
1902
|
const verifyModel = Boolean(candidate) && !options.modelOverrideFromParent;
|
|
1954
1903
|
let lastResult: SingleResult | undefined;
|
|
1955
1904
|
let recoveryPrompt = task;
|
|
1905
|
+
let stagedIndexBaseline: string | undefined;
|
|
1906
|
+
if (effectiveAcceptance.preserveStagedIndex) {
|
|
1907
|
+
try {
|
|
1908
|
+
stagedIndexBaseline = captureStagedIndexBaseline(options.cwd ?? runtimeCwd);
|
|
1909
|
+
} catch (error) {
|
|
1910
|
+
return redactResultPrompt(withRunContext({
|
|
1911
|
+
index: options.index ?? 0,
|
|
1912
|
+
agent: agentName,
|
|
1913
|
+
task,
|
|
1914
|
+
exitCode: 1,
|
|
1915
|
+
messages: [],
|
|
1916
|
+
usage: emptyUsage(),
|
|
1917
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1918
|
+
}, options.context));
|
|
1919
|
+
}
|
|
1920
|
+
}
|
|
1956
1921
|
for (let attemptIndex = 0; attemptIndex < 2; attemptIndex++) {
|
|
1957
1922
|
const outputSnapshot = captureSingleOutputSnapshot(options.outputPath);
|
|
1958
1923
|
const attemptResult = await runSingleAttempt(runtimeCwd, agent, recoveryPrompt, candidate, attemptOptions, {
|
|
@@ -2083,6 +2048,7 @@ async function runSyncCompletionInner(
|
|
|
2083
2048
|
? { content: childWrittenOutput, path: options.outputPath, authoritative: options.outputMode === "file-only", durable: result.savedOutputPath !== undefined }
|
|
2084
2049
|
: undefined,
|
|
2085
2050
|
cwd: options.cwd ?? runtimeCwd,
|
|
2051
|
+
stagedIndexBaseline,
|
|
2086
2052
|
reportOptional: isAgentContract(options.agentContract),
|
|
2087
2053
|
artifactsDir: options.artifactsDir,
|
|
2088
2054
|
runId: options.runId,
|
|
@@ -2095,6 +2061,12 @@ async function runSyncCompletionInner(
|
|
|
2095
2061
|
}
|
|
2096
2062
|
const acceptanceFailure = acceptanceFailureMessage(result.acceptance);
|
|
2097
2063
|
stripAcceptanceReportsFromMessages(result.messages);
|
|
2064
|
+
// A passing typed gate supplies the structured output for runs that have no
|
|
2065
|
+
// outputSchema of their own; preflight rejects the combination.
|
|
2066
|
+
const typedGate = typedVerifyOutput(result.acceptance);
|
|
2067
|
+
if (typedGate && result.structuredOutput === undefined && !acceptanceFailure && result.exitCode === 0) {
|
|
2068
|
+
result.structuredOutput = typedGate.value;
|
|
2069
|
+
}
|
|
2098
2070
|
if (acceptanceFailure && result.acceptance.explicit && result.exitCode === 0 && !result.interrupted && !result.timedOut && !isAgentContract(options.agentContract)) {
|
|
2099
2071
|
result.exitCode = 1;
|
|
2100
2072
|
if (result.savedOutputPath) {
|
|
@@ -64,20 +64,14 @@ export async function rewritePromptWithGuidance(input: {
|
|
|
64
64
|
}): Promise<string> {
|
|
65
65
|
const model = input.ctx.model;
|
|
66
66
|
if (!model) throw new Error("Prompt redo needs the current session model to rewrite the authored task.");
|
|
67
|
-
const [{ Agent }, { convertToLlm }
|
|
67
|
+
const [{ Agent }, { convertToLlm }] = await Promise.all([
|
|
68
68
|
import("@earendil-works/pi-agent-core"),
|
|
69
69
|
import("@earendil-works/pi-coding-agent"),
|
|
70
|
-
import("@earendil-works/pi-ai/compat"),
|
|
71
70
|
]);
|
|
72
71
|
const auth = await resolveRewriteAuth(input.ctx, model);
|
|
73
|
-
const
|
|
74
|
-
getRegisteredProviderConfig?: (provider: string) => { api?: string; streamSimple?: StreamFn } | undefined;
|
|
75
|
-
}).getRegisteredProviderConfig?.(model.provider);
|
|
76
|
-
const baseStreamFn = input.streamFn ?? (registeredProvider?.streamSimple && registeredProvider.api === model.api
|
|
77
|
-
? registeredProvider.streamSimple
|
|
78
|
-
: streamSimple);
|
|
72
|
+
const baseStreamFn: StreamFn = (input.streamFn ?? ((nextModel, context, streamOptions) => input.ctx.modelRegistry.streamSimple(nextModel, context, streamOptions))) as StreamFn;
|
|
79
73
|
const sessionId = input.ctx.sessionManager.getSessionId();
|
|
80
|
-
const streamFn: StreamFn = (nextModel, context, streamOptions) => baseStreamFn(nextModel, context, {
|
|
74
|
+
const streamFn: StreamFn = (nextModel, context, streamOptions) => (baseStreamFn as StreamFn)(nextModel, context, {
|
|
81
75
|
...streamOptions,
|
|
82
76
|
...(auth.apiKey ? { apiKey: auth.apiKey } : {}),
|
|
83
77
|
env: auth.env || streamOptions?.env ? { ...(auth.env ?? {}), ...(streamOptions?.env ?? {}) } : undefined,
|