@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -9,69 +9,50 @@ import {
|
|
|
9
9
|
type IntercomEventBus,
|
|
10
10
|
type SingleResult,
|
|
11
11
|
type SubagentState,
|
|
12
|
+
type WorkflowTerminalResolution,
|
|
12
13
|
} from "../../shared/types.ts";
|
|
13
14
|
import { updateActiveRunIndex } from "../background/active-run-index.ts";
|
|
14
15
|
import { resultFilePath, writeAsyncResultFile } from "../background/result-files.ts";
|
|
15
16
|
import { resolveAsyncResumeTarget } from "../background/async-resume.ts";
|
|
17
|
+
import { externalCliReceiptMetadata, normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
|
|
18
|
+
import { outputPathMappingFromTask } from "../shared/single-output.ts";
|
|
16
19
|
import { readWorkflowReceipt, workflowReceiptPath, writeWorkflowReceipt, type WorkflowReceipt } from "../../workflows/workflow-receipt.ts";
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
}
|
|
20
|
+
import {
|
|
21
|
+
applyDetachedChildSettlement,
|
|
22
|
+
classifyWorkflowSettlement,
|
|
23
|
+
findWorkflowSettlementStep,
|
|
24
|
+
planWorkflowSettlement,
|
|
25
|
+
promoteSettledPausedWorkflow,
|
|
26
|
+
workflowOutputPathMappingSummary,
|
|
27
|
+
workflowRecoveryActions,
|
|
28
|
+
workflowTerminalOutcomeForResult,
|
|
29
|
+
type WorkflowPublicChild,
|
|
30
|
+
type WorkflowStatusStep,
|
|
31
|
+
} from "../../workflows/workflow-settlement.ts";
|
|
29
32
|
|
|
30
33
|
export function applyDetachedChildToPausedWorkflow(
|
|
31
34
|
status: AsyncStatus,
|
|
32
|
-
input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "sessionFile">; workflowKey?: string },
|
|
35
|
+
input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "sessionFile" | "sessionName" | "stopped">; workflowKey?: string },
|
|
33
36
|
): AsyncStatus | undefined {
|
|
34
|
-
|
|
35
|
-
const next = cloneWorkflowStatus(status);
|
|
36
|
-
const step = next.steps?.find((candidate) => candidate.runId === input.childRunId)
|
|
37
|
-
?? (input.workflowKey ? next.steps?.find((candidate) => candidate.workflowKey === input.workflowKey) : undefined);
|
|
38
|
-
if (!step) return undefined;
|
|
39
|
-
const succeeded = childSucceeded(input.result);
|
|
40
|
-
const updatedAt = Date.now();
|
|
41
|
-
step.status = succeeded ? "completed" : "failed";
|
|
42
|
-
step.endedAt = updatedAt;
|
|
43
|
-
delete step.activityState;
|
|
44
|
-
delete step.currentTool;
|
|
45
|
-
delete step.currentToolStartedAt;
|
|
46
|
-
if (input.result.sessionFile) step.sessionFile = input.result.sessionFile;
|
|
47
|
-
if (succeeded) delete step.error;
|
|
48
|
-
else if (input.result.error) step.error = input.result.error;
|
|
49
|
-
next.lastUpdate = updatedAt;
|
|
50
|
-
const promoted = promotePausedWorkflowIfSettled(next);
|
|
51
|
-
if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
|
|
52
|
-
return promoted ?? next;
|
|
37
|
+
return applyDetachedChildSettlement(status, input);
|
|
53
38
|
}
|
|
54
39
|
|
|
55
40
|
export function promotePausedWorkflowIfSettled(status: AsyncStatus): AsyncStatus | undefined {
|
|
56
|
-
|
|
57
|
-
const next = cloneWorkflowStatus(status);
|
|
58
|
-
const stillOpen = next.steps?.some((candidate) =>
|
|
59
|
-
candidate.status === "running"
|
|
60
|
-
|| (candidate.status === "paused" && candidate.activityState === "needs_attention")
|
|
61
|
-
) === true;
|
|
62
|
-
if (stillOpen || !next.steps?.length) return undefined;
|
|
63
|
-
const failed = next.steps.some((candidate) => candidate.status === "failed");
|
|
64
|
-
const updatedAt = Date.now();
|
|
65
|
-
next.lastUpdate = updatedAt;
|
|
66
|
-
next.state = failed ? "failed" : "complete";
|
|
67
|
-
next.endedAt = updatedAt;
|
|
68
|
-
delete next.activityState;
|
|
69
|
-
if (!failed) delete next.error;
|
|
70
|
-
return next;
|
|
41
|
+
return promoteSettledPausedWorkflow(status);
|
|
71
42
|
}
|
|
72
43
|
|
|
73
|
-
function
|
|
44
|
+
function usageWithValue(usage: SingleResult["usage"] | undefined): SingleResult["usage"] | undefined {
|
|
45
|
+
return usage && (usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0)
|
|
46
|
+
? usage
|
|
47
|
+
: undefined;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function workflowResultChildren(status: AsyncStatus, childRunId: string, result: SingleResult, existingResults: unknown, receipt?: WorkflowReceipt): unknown {
|
|
74
51
|
const output = getSingleResultOutput(result);
|
|
52
|
+
const outputReference = result.savedOutputPath ?? result.outputReference?.path;
|
|
53
|
+
const outputPathMapping = outputPathMappingFromTask(result.task, outputReference);
|
|
54
|
+
const terminalOutcome = workflowTerminalOutcomeForResult(result);
|
|
55
|
+
const usage = usageWithValue(result.usage);
|
|
75
56
|
if (Array.isArray(existingResults)) {
|
|
76
57
|
return existingResults.map((entry) => {
|
|
77
58
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
|
|
@@ -79,58 +60,45 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
|
|
|
79
60
|
if (child.runId !== childRunId) return child;
|
|
80
61
|
return {
|
|
81
62
|
...child,
|
|
82
|
-
success:
|
|
63
|
+
success: result.exitCode === 0 && !result.error && !result.interrupted,
|
|
83
64
|
output,
|
|
84
65
|
outputState: output.trim() ? "present" : "absent",
|
|
85
66
|
detached: undefined,
|
|
67
|
+
...(usage ? { usage } : {}),
|
|
68
|
+
...(outputReference ? { outputReference } : {}),
|
|
69
|
+
...(outputPathMapping ? { outputPathMapping } : {}),
|
|
70
|
+
...(result.interrupted || result.stopped ? { interrupted: true } : {}),
|
|
71
|
+
...(result.stopped ? { stopped: true } : {}),
|
|
72
|
+
...(terminalOutcome ? { terminalOutcome } : {}),
|
|
73
|
+
...(result.sessionName ? { sessionName: result.sessionName } : {}),
|
|
74
|
+
...(result.sessionFile ? { sessionFile: result.sessionFile } : {}),
|
|
86
75
|
...(result.error ? { error: result.error } : {}),
|
|
87
76
|
};
|
|
88
77
|
});
|
|
89
78
|
}
|
|
90
|
-
return status.steps?.map((step) => ({
|
|
79
|
+
return status.steps?.map((step: WorkflowStatusStep) => ({
|
|
91
80
|
workflowKey: step.workflowKey,
|
|
92
81
|
agent: step.agent,
|
|
82
|
+
...(step.sessionName ? { sessionName: step.sessionName } : {}),
|
|
93
83
|
runId: step.runId,
|
|
94
84
|
success: step.status === "completed" || step.status === "complete",
|
|
95
85
|
output: step.runId === childRunId ? output : "",
|
|
96
86
|
outputState: step.runId === childRunId && output.trim() ? "present" : "absent",
|
|
87
|
+
...(step.runId === childRunId ? { ...(usage ? { usage } : {}), ...(result.sessionFile ? { sessionFile: result.sessionFile } : {}) } : {}),
|
|
88
|
+
...(step.runId === childRunId && outputReference ? { outputReference } : step.workflowKey && receipt?.entries[step.workflowKey]?.outputReference ? { outputReference: receipt.entries[step.workflowKey]!.outputReference } : {}),
|
|
89
|
+
...(step.runId === childRunId && outputPathMapping ? { outputPathMapping } : step.outputPathMapping ? { outputPathMapping: step.outputPathMapping } : {}),
|
|
90
|
+
...(step.interrupted ? { interrupted: true } : {}),
|
|
91
|
+
...(step.runId === childRunId && terminalOutcome ? { terminalOutcome } : step.workflowKey && receipt?.entries[step.workflowKey]?.terminalOutcome ? { terminalOutcome: receipt.entries[step.workflowKey]!.terminalOutcome } : {}),
|
|
92
|
+
...(step.stopped ? { stopped: true } : {}),
|
|
97
93
|
...(step.error ? { error: step.error } : {}),
|
|
98
94
|
}));
|
|
99
95
|
}
|
|
100
96
|
|
|
101
|
-
function
|
|
102
|
-
const
|
|
103
|
-
const
|
|
104
|
-
? `Workflow completed after detached child ${childRunId} finished.`
|
|
105
|
-
: status.error ?? (typeof existing?.summary === "string" ? existing.summary : undefined);
|
|
106
|
-
return {
|
|
107
|
-
...(existing ?? {}),
|
|
108
|
-
id: status.runId,
|
|
109
|
-
runId: status.runId,
|
|
110
|
-
toolCallId: status.toolCallId,
|
|
111
|
-
agent: "workflow",
|
|
112
|
-
mode: "workflow",
|
|
113
|
-
success: status.state === "complete",
|
|
114
|
-
state: status.state,
|
|
115
|
-
summary,
|
|
116
|
-
error: status.error,
|
|
117
|
-
activityState: status.activityState,
|
|
118
|
-
endedAt: status.endedAt,
|
|
119
|
-
timestamp: Date.now(),
|
|
120
|
-
results: workflowResultChildren(status, childRunId, result, existing?.results),
|
|
121
|
-
workflow: status.workflow,
|
|
122
|
-
...(receipt ? { workflowReceipt: { path: path.join(asyncDir, "workflow-receipt.json"), receipt } } : {}),
|
|
123
|
-
asyncDir,
|
|
124
|
-
cwd: status.cwd,
|
|
125
|
-
sessionId,
|
|
126
|
-
completionOwnerId: status.completionOwnerId,
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, result: SingleResult, asyncDir: string): WorkflowReceipt | undefined {
|
|
131
|
-
const receiptPath = workflowReceiptPath(DIRS.async, status.runId);
|
|
97
|
+
function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, result: SingleResult, asyncDir: string, resolution: WorkflowTerminalResolution | undefined): WorkflowReceipt | undefined {
|
|
98
|
+
const receiptRoot = path.dirname(asyncDir);
|
|
99
|
+
const receiptPath = workflowReceiptPath(receiptRoot, status.runId);
|
|
132
100
|
if (!fs.existsSync(receiptPath)) return undefined;
|
|
133
|
-
const receipt = readWorkflowReceipt(
|
|
101
|
+
const receipt = readWorkflowReceipt(receiptRoot, status.runId);
|
|
134
102
|
const step = status.steps?.find((candidate) => candidate.runId === childRunId);
|
|
135
103
|
const key = step?.workflowKey;
|
|
136
104
|
if (!key) throw new Error(`Workflow receipt '${status.runId}' cannot identify detached child '${childRunId}' by stable key.`);
|
|
@@ -144,6 +112,13 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
144
112
|
resumability = { state: "not-resumable", reason: error instanceof Error ? error.message : String(error) };
|
|
145
113
|
}
|
|
146
114
|
const outputReference = result.savedOutputPath ?? result.outputReference?.path ?? entry.outputReference;
|
|
115
|
+
const childStatus = readStatus(path.join(DIRS.async, childRunId));
|
|
116
|
+
const externalStep = childStatus?.steps?.length === 1 && childStatus.steps[0]?.runner?.type === "external-cli" ? childStatus.steps[0] : undefined;
|
|
117
|
+
const externalRunner = normalizeExternalCliRunnerStatus(result.runner?.type === "external-cli" ? result.runner : externalStep?.runner);
|
|
118
|
+
const externalProcess = result.externalProcess ?? externalStep?.externalProcess;
|
|
119
|
+
const externalAdapter = externalRunner ? externalCliReceiptMetadata({ runner: externalRunner, externalProcess, outputReference }) : entry.externalAdapter;
|
|
120
|
+
const childTerminalOutcome = workflowTerminalOutcomeForResult(result) ?? entry.terminalOutcome;
|
|
121
|
+
if (externalAdapter) resumability = { state: "not-resumable", reason: externalAdapter.nonResumableReason };
|
|
147
122
|
const updatedEntry: WorkflowReceipt["entries"][string] = resumability.state === "resumable"
|
|
148
123
|
? {
|
|
149
124
|
...entry,
|
|
@@ -152,6 +127,8 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
152
127
|
latestRunId: entry.latestRunId ?? childRunId,
|
|
153
128
|
resumability,
|
|
154
129
|
...(outputReference ? { outputReference } : {}),
|
|
130
|
+
...(childTerminalOutcome ? { terminalOutcome: childTerminalOutcome } : {}),
|
|
131
|
+
...(externalAdapter ? { externalAdapter } : {}),
|
|
155
132
|
}
|
|
156
133
|
: {
|
|
157
134
|
...entry,
|
|
@@ -159,6 +136,8 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
159
136
|
...(step.context ? { resolvedContext: step.context } : {}),
|
|
160
137
|
resumability,
|
|
161
138
|
...(outputReference ? { outputReference } : {}),
|
|
139
|
+
...(childTerminalOutcome ? { terminalOutcome: childTerminalOutcome } : {}),
|
|
140
|
+
...(externalAdapter ? { externalAdapter } : {}),
|
|
162
141
|
};
|
|
163
142
|
const next: WorkflowReceipt = {
|
|
164
143
|
...receipt,
|
|
@@ -167,7 +146,15 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
167
146
|
...receipt.entries,
|
|
168
147
|
[key]: updatedEntry,
|
|
169
148
|
},
|
|
149
|
+
workflowChildren: status.workflowChildren,
|
|
150
|
+
...(receipt.terminalOutcome ? { terminalOutcome: receipt.terminalOutcome } : {}),
|
|
151
|
+
...(resolution ? { workflowResolution: resolution } : {}),
|
|
170
152
|
};
|
|
153
|
+
if (resolution) next.recovery = workflowRecoveryActions(next);
|
|
154
|
+
else {
|
|
155
|
+
delete next.workflowResolution;
|
|
156
|
+
delete next.recovery;
|
|
157
|
+
}
|
|
171
158
|
writeWorkflowReceipt(asyncDir, next);
|
|
172
159
|
return next;
|
|
173
160
|
}
|
|
@@ -193,21 +180,26 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
193
180
|
const asyncDir = job?.asyncDir ?? path.join(DIRS.async, input.workflowRunId);
|
|
194
181
|
const status = readStatus(asyncDir);
|
|
195
182
|
if (!status) return false;
|
|
183
|
+
const matchingControls = input.workflowKey === undefined ? [] : [...(input.state.foregroundControls?.values() ?? [])].filter((control) =>
|
|
184
|
+
control.parentWorkflowRunId === input.workflowRunId && control.workflowKey === input.workflowKey
|
|
185
|
+
);
|
|
186
|
+
const confirmedLiveIdentity = matchingControls.length === 1 && matchingControls[0]?.runId === input.childRunId;
|
|
187
|
+
if (confirmedLiveIdentity) {
|
|
188
|
+
const candidates = status.steps?.filter((candidate) => candidate.workflowKey === input.workflowKey) ?? [];
|
|
189
|
+
const candidate = candidates.length === 1 ? candidates[0] : undefined;
|
|
190
|
+
if (candidate && candidate.runId === undefined && candidate.sessionFile === undefined
|
|
191
|
+
&& candidate.status === "paused" && candidate.activityState === "needs_attention") candidate.runId = input.childRunId;
|
|
192
|
+
}
|
|
196
193
|
const next = applyDetachedChildToPausedWorkflow(status, {
|
|
197
194
|
childRunId: input.childRunId,
|
|
198
195
|
result: input.result,
|
|
199
196
|
workflowKey: input.workflowKey,
|
|
200
197
|
});
|
|
201
198
|
if (!next) return false;
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
job.updatedAt = next.lastUpdate;
|
|
207
|
-
job.activityState = next.activityState;
|
|
208
|
-
job.steps = next.steps?.map((step, index) => ({ ...step, index }));
|
|
209
|
-
job.workflow = next.workflow;
|
|
210
|
-
}
|
|
199
|
+
const outputReference = input.result.savedOutputPath ?? input.result.outputReference?.path;
|
|
200
|
+
const outputPathMapping = outputPathMappingFromTask(input.result.task, outputReference);
|
|
201
|
+
const settledStep = findWorkflowSettlementStep(next, input.childRunId);
|
|
202
|
+
if (settledStep && outputPathMapping) settledStep.outputPathMapping = outputPathMapping;
|
|
211
203
|
const resultPath = resultFilePath(DIRS.results, input.workflowRunId);
|
|
212
204
|
let existing: Record<string, unknown> | undefined;
|
|
213
205
|
try {
|
|
@@ -218,13 +210,55 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
218
210
|
}
|
|
219
211
|
let receipt: WorkflowReceipt | undefined;
|
|
220
212
|
let receiptError: string | undefined;
|
|
213
|
+
const resolution = classifyWorkflowSettlement(next, input.result.interrupted);
|
|
221
214
|
try {
|
|
222
|
-
receipt = reconcileWorkflowReceipt(next, input.childRunId, input.result, asyncDir);
|
|
215
|
+
receipt = reconcileWorkflowReceipt(next, input.childRunId, input.result, asyncDir, resolution);
|
|
223
216
|
} catch (error) {
|
|
224
217
|
receiptError = `Failed to reconcile async workflow receipt: ${error instanceof Error ? error.message : String(error)}`;
|
|
225
218
|
}
|
|
226
|
-
const
|
|
227
|
-
|
|
219
|
+
const results = workflowResultChildren(next, input.childRunId, input.result, existing?.results, receipt) as WorkflowPublicChild[];
|
|
220
|
+
const recovery = workflowRecoveryActions(receipt);
|
|
221
|
+
const summary = `${resolution === "settled-awaiting-resume"
|
|
222
|
+
? `Workflow lanes settled after detached child ${input.childRunId} finished. JavaScript workflow continuation was not persisted.${recovery.length ? " Use the listed keyed recovery action to continue a child." : " No retained child is resumable."}`
|
|
223
|
+
: next.state === "complete"
|
|
224
|
+
? `Workflow completed after detached child ${input.childRunId} finished.`
|
|
225
|
+
: next.error ?? (typeof existing?.summary === "string" ? existing.summary : "Workflow failed.")}${workflowOutputPathMappingSummary(results)}`;
|
|
226
|
+
const plan = planWorkflowSettlement({
|
|
227
|
+
status: next,
|
|
228
|
+
summary,
|
|
229
|
+
children: results,
|
|
230
|
+
baseResult: {
|
|
231
|
+
...(existing ?? {}),
|
|
232
|
+
id: next.runId,
|
|
233
|
+
runId: next.runId,
|
|
234
|
+
toolCallId: next.toolCallId,
|
|
235
|
+
agent: "workflow",
|
|
236
|
+
mode: "workflow",
|
|
237
|
+
endedAt: next.endedAt,
|
|
238
|
+
workflow: next.workflow,
|
|
239
|
+
reconciledFromDetachedChild: input.childRunId,
|
|
240
|
+
asyncDir,
|
|
241
|
+
cwd: next.cwd,
|
|
242
|
+
sessionId: next.sessionId ?? (typeof existing?.sessionId === "string" ? existing.sessionId : undefined),
|
|
243
|
+
completionOwnerId: next.completionOwnerId,
|
|
244
|
+
},
|
|
245
|
+
receipt,
|
|
246
|
+
receiptPath: path.join(asyncDir, "workflow-receipt.json"),
|
|
247
|
+
receiptPersistenceError: receiptError,
|
|
248
|
+
resolution,
|
|
249
|
+
terminalOutcome: receipt?.terminalOutcome,
|
|
250
|
+
eventMetadata: { reconciledFromDetachedChild: input.childRunId },
|
|
251
|
+
});
|
|
252
|
+
writeAtomicJson(path.join(asyncDir, "status.json"), plan.status);
|
|
253
|
+
updateActiveRunIndex(asyncDir, plan.status.state, plan.status.toolCallId);
|
|
254
|
+
if (job) {
|
|
255
|
+
job.status = plan.status.state;
|
|
256
|
+
job.updatedAt = plan.status.lastUpdate;
|
|
257
|
+
job.activityState = plan.status.activityState;
|
|
258
|
+
job.steps = plan.status.steps?.map((step, index) => ({ ...step, index }));
|
|
259
|
+
job.workflow = plan.status.workflow;
|
|
260
|
+
}
|
|
261
|
+
writeAsyncResultFile(resultPath, plan.publicResult);
|
|
228
262
|
if (receiptError) {
|
|
229
263
|
appendDetachedWorkflowEvent(asyncDir, {
|
|
230
264
|
ts: Date.now(),
|
|
@@ -234,14 +268,12 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
234
268
|
reconciledFromDetachedChild: input.childRunId,
|
|
235
269
|
});
|
|
236
270
|
}
|
|
237
|
-
if (
|
|
271
|
+
if (plan.completionEvent) {
|
|
238
272
|
appendDetachedWorkflowEvent(asyncDir, {
|
|
239
273
|
ts: Date.now(),
|
|
240
274
|
runId: input.workflowRunId,
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
...(next.error ? { error: next.error } : {}),
|
|
244
|
-
reconciledFromDetachedChild: input.childRunId,
|
|
275
|
+
...plan.completionEvent,
|
|
276
|
+
recovery: plan.recovery,
|
|
245
277
|
});
|
|
246
278
|
input.events?.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
|
|
247
279
|
id: input.workflowRunId,
|
|
@@ -249,11 +281,16 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
249
281
|
source: "async",
|
|
250
282
|
mode: "workflow",
|
|
251
283
|
agent: "workflow",
|
|
252
|
-
success:
|
|
253
|
-
state:
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
284
|
+
success: plan.status.state === "complete",
|
|
285
|
+
state: plan.status.state,
|
|
286
|
+
...(resolution ? { workflowResolution: resolution } : {}),
|
|
287
|
+
...(plan.receipt?.terminalOutcome ? { terminalOutcome: plan.receipt.terminalOutcome } : {}),
|
|
288
|
+
recovery: plan.recovery,
|
|
289
|
+
summary: typeof plan.publicResult.summary === "string" ? plan.publicResult.summary : plan.status.error,
|
|
290
|
+
reconciledFromDetachedChild: input.childRunId,
|
|
291
|
+
results,
|
|
292
|
+
sessionId: plan.status.sessionId,
|
|
293
|
+
completionOwnerId: plan.status.completionOwnerId,
|
|
257
294
|
timestamp: Date.now(),
|
|
258
295
|
triggerTurn: true,
|
|
259
296
|
});
|
|
@@ -1,20 +1,10 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import * as fs from "node:fs";
|
|
3
2
|
import * as path from "node:path";
|
|
4
3
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
4
|
import type { Details, ForegroundRunControl, SubagentState } from "../../shared/types.ts";
|
|
6
5
|
import { readStatus } from "../../shared/utils.ts";
|
|
7
6
|
import { steeringReceipt } from "../background/steering.ts";
|
|
8
|
-
import {
|
|
9
|
-
consumeSteerAckFromDir,
|
|
10
|
-
readSteerCapability,
|
|
11
|
-
steerAcksDir,
|
|
12
|
-
steerCapabilityPath,
|
|
13
|
-
stepSteerInboxDir,
|
|
14
|
-
writeSteerRequestToExistingDir,
|
|
15
|
-
type SteerDeliveryMode,
|
|
16
|
-
type SteerRequest,
|
|
17
|
-
} from "../background/control-channel.ts";
|
|
7
|
+
import type { SteerDeliveryMode } from "../background/control-channel.ts";
|
|
18
8
|
|
|
19
9
|
export interface WorkflowForegroundSteeringTarget {
|
|
20
10
|
control: ForegroundRunControl;
|
|
@@ -40,7 +30,6 @@ function activeWorkflowError(state: SubagentState, workflowRunId: string, asyncD
|
|
|
40
30
|
function controlIsLiveInWorkflow(control: ForegroundRunControl, workflowRunId: string, sessionId: string): boolean {
|
|
41
31
|
return control.parentWorkflowRunId === workflowRunId
|
|
42
32
|
&& control.sessionId === sessionId
|
|
43
|
-
&& Boolean(control.workflowSteeringDir)
|
|
44
33
|
&& (control.activeChildren?.size ?? 0) > 0;
|
|
45
34
|
}
|
|
46
35
|
|
|
@@ -77,17 +66,18 @@ function managementError(message: string): AgentToolResult<Details> {
|
|
|
77
66
|
return { content: [{ type: "text", text: message }], isError: true, details: { mode: "management", results: [] } };
|
|
78
67
|
}
|
|
79
68
|
|
|
69
|
+
/**
|
|
70
|
+
* Steer a live workflow-owned foreground child through its in-process session.
|
|
71
|
+
* `steer` (and `auto`) interrupt the child at its next safe point; `follow_up`
|
|
72
|
+
* queues the message until the current run settles.
|
|
73
|
+
*/
|
|
80
74
|
export async function steerWorkflowForegroundTarget(input: {
|
|
81
75
|
target: WorkflowForegroundSteeringTarget;
|
|
82
76
|
message: string;
|
|
83
77
|
mode?: SteerDeliveryMode;
|
|
84
78
|
index?: number;
|
|
85
|
-
signal?: AbortSignal;
|
|
86
|
-
ackTimeoutMs?: number;
|
|
87
79
|
}): Promise<AgentToolResult<Details>> {
|
|
88
80
|
const { control, sourceRunId } = input.target;
|
|
89
|
-
const routeDir = control.workflowSteeringDir;
|
|
90
|
-
if (!routeDir || !fs.existsSync(routeDir)) return managementError(`Foreground run '${control.runId}' has no live workflow steering route.`);
|
|
91
81
|
const activeIndexes = [...(control.activeChildren?.keys() ?? [])].sort((left, right) => left - right);
|
|
92
82
|
const index = input.index ?? (activeIndexes.length === 1 ? activeIndexes[0] : undefined);
|
|
93
83
|
if (index === undefined) {
|
|
@@ -95,94 +85,30 @@ export async function steerWorkflowForegroundTarget(input: {
|
|
|
95
85
|
? `Foreground run '${control.runId}' has no live child session.`
|
|
96
86
|
: `Foreground run '${control.runId}' has ${activeIndexes.length} live child sessions; provide index.`);
|
|
97
87
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (
|
|
88
|
+
const child = control.activeChildren?.get(index);
|
|
89
|
+
if (!child) return managementError(`Foreground run '${control.runId}' child ${index} is not live.`);
|
|
90
|
+
if (!child.steer) return managementError(`Foreground run '${control.runId}' child ${index} does not support steering.`);
|
|
101
91
|
|
|
102
|
-
const
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
targetIndex: index,
|
|
109
|
-
source: "steer-action",
|
|
110
|
-
};
|
|
111
|
-
try {
|
|
112
|
-
writeSteerRequestToExistingDir(stepSteerInboxDir(routeDir, index), request);
|
|
113
|
-
} catch (error) {
|
|
114
|
-
if (typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
115
|
-
return managementError(`Foreground run '${control.runId}' has no live workflow steering route.`);
|
|
116
|
-
}
|
|
117
|
-
return managementError(`Failed to queue steering for foreground run ${control.runId}: ${error instanceof Error ? error.message : String(error)}`);
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
const deadline = Date.now() + (input.ackTimeoutMs ?? 3_000);
|
|
121
|
-
let ack;
|
|
122
|
-
let routeRemoved = false;
|
|
123
|
-
while (Date.now() <= deadline) {
|
|
124
|
-
ack = consumeSteerAckFromDir(steerAcksDir(routeDir, index), request.id);
|
|
125
|
-
if (ack || input.signal?.aborted) break;
|
|
126
|
-
if (!fs.existsSync(routeDir)) {
|
|
127
|
-
routeRemoved = true;
|
|
128
|
-
break;
|
|
129
|
-
}
|
|
130
|
-
await new Promise<void>((resolve) => setTimeout(resolve, Math.min(50, Math.max(1, deadline - Date.now()))));
|
|
131
|
-
}
|
|
132
|
-
if (routeRemoved || (!ack && !input.signal?.aborted && !fs.existsSync(routeDir))) {
|
|
133
|
-
return managementError(`Foreground run '${control.runId}' has no live child session.`);
|
|
134
|
-
}
|
|
135
|
-
const target = ack?.state === "delivered"
|
|
136
|
-
? { index, state: "delivered" as const, deliveredAt: ack.ts }
|
|
137
|
-
: ack?.state === "queued"
|
|
92
|
+
const message = input.message.trim();
|
|
93
|
+
const requestId = randomUUID();
|
|
94
|
+
const outcome = await child.steer({ message, ...(input.mode && input.mode !== "steer" ? { mode: input.mode } : {}) });
|
|
95
|
+
const target = outcome.state === "delivered"
|
|
96
|
+
? { index, state: "delivered" as const, deliveredAt: Date.now() }
|
|
97
|
+
: outcome.state === "queued"
|
|
138
98
|
? { index, state: "queued" as const }
|
|
139
|
-
:
|
|
140
|
-
? { index, state: "failed" as const, reason: ack.message }
|
|
141
|
-
: { index, state: "pending" as const };
|
|
99
|
+
: { index, state: "failed" as const, reason: outcome.reason };
|
|
142
100
|
const steering = {
|
|
143
|
-
requestId
|
|
144
|
-
state:
|
|
145
|
-
deliveryStatus:
|
|
101
|
+
requestId,
|
|
102
|
+
state: outcome.state === "delivered" ? "delivered" as const : outcome.state === "failed" ? "failed" as const : "pending" as const,
|
|
103
|
+
deliveryStatus: outcome.state === "delivered" ? "delivered" as const : "queued" as const,
|
|
146
104
|
sourceRunId,
|
|
147
105
|
targets: [target],
|
|
148
106
|
};
|
|
149
|
-
if (
|
|
150
|
-
return { content: [{ type: "text", text: steeringReceipt(
|
|
151
|
-
}
|
|
152
|
-
if (ack?.state === "delivered") {
|
|
153
|
-
return { content: [{ type: "text", text: steeringReceipt(request.message, `Steering delivered for foreground run ${control.runId} (request ${request.id}).`) }], details: { mode: "management", results: [], steering } };
|
|
154
|
-
}
|
|
155
|
-
if (ack?.state === "queued") {
|
|
156
|
-
return { content: [{ type: "text", text: steeringReceipt(request.message, `Steering queued for foreground run ${control.runId} (request ${request.id}).`) }], details: { mode: "management", results: [], steering } };
|
|
107
|
+
if (outcome.state === "delivered") {
|
|
108
|
+
return { content: [{ type: "text", text: steeringReceipt(message, `Steering delivered for foreground run ${control.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering } };
|
|
157
109
|
}
|
|
158
|
-
if (
|
|
159
|
-
return { content: [{ type: "text", text: steeringReceipt(
|
|
110
|
+
if (outcome.state === "queued") {
|
|
111
|
+
return { content: [{ type: "text", text: steeringReceipt(message, `Steering queued for foreground run ${control.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering } };
|
|
160
112
|
}
|
|
161
|
-
return { content: [{ type: "text", text: steeringReceipt(
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
export function workflowForegroundSteeringDir(asyncDirRoot: string, workflowRunId: string, childRunId: string): string {
|
|
165
|
-
return path.join(asyncDirRoot, workflowRunId, "control", "workflow-foreground", childRunId);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
export function removeWorkflowForegroundSteeringRoute(control: ForegroundRunControl): void {
|
|
169
|
-
if (!control.workflowSteeringDir) return;
|
|
170
|
-
try {
|
|
171
|
-
fs.rmSync(control.workflowSteeringDir, { recursive: true, force: true });
|
|
172
|
-
} catch (error) {
|
|
173
|
-
console.warn(`[pi-subagents] Failed to remove workflow foreground steering route '${control.workflowSteeringDir}': ${error instanceof Error ? error.message : String(error)}`);
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
export function workflowForegroundSteeringLaunchOptions(control: ForegroundRunControl | undefined, index: number): Pick<import("../../shared/types.ts").RunSyncOptions, "steerInboxDir" | "steerCapabilityPath" | "steerAckDir"> {
|
|
178
|
-
if (!control?.workflowSteeringDir) return {};
|
|
179
|
-
const steerInboxDir = stepSteerInboxDir(control.workflowSteeringDir, index);
|
|
180
|
-
const steerAckDir = steerAcksDir(control.workflowSteeringDir, index);
|
|
181
|
-
fs.mkdirSync(steerInboxDir, { recursive: true });
|
|
182
|
-
fs.mkdirSync(steerAckDir, { recursive: true });
|
|
183
|
-
return {
|
|
184
|
-
steerInboxDir,
|
|
185
|
-
steerCapabilityPath: steerCapabilityPath(control.workflowSteeringDir, index),
|
|
186
|
-
steerAckDir,
|
|
187
|
-
};
|
|
113
|
+
return { content: [{ type: "text", text: steeringReceipt(message, `Steering failed for foreground run ${control.runId} (request ${requestId}): ${outcome.reason ?? "unknown error"}`) }], isError: true, details: { mode: "management", results: [], steering } };
|
|
188
114
|
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
2
|
+
|
|
3
|
+
export const ABORT_RECOVERY_PROMPT = "The prior run ended from a provider/transport abort after useful progress. Continue from the current files and transcript. Do not restart. Fix any validation failure or write the required report. Finish with final output.";
|
|
4
|
+
|
|
5
|
+
export type AbortRecoveryPlan =
|
|
6
|
+
| { action: "resume"; prompt: typeof ABORT_RECOVERY_PROMPT }
|
|
7
|
+
| { action: "settle"; reason: string; diagnostic?: string };
|
|
8
|
+
|
|
9
|
+
const PROVIDER_ABORT_PATTERN = /(?:provider|transport|connection|stream|socket|request).*(?:abort|closed|reset|ended|terminated|error|fail)|(?:abort|closed|reset|ended|terminated|error|fail).*(?:provider|transport|connection|stream|socket|request)/i;
|
|
10
|
+
const ABORT_ERROR_PATTERN = /\b(?:operation|request|response|stream|connection|transport|provider)?\s*(?:was\s+)?aborted\b/i;
|
|
11
|
+
const TOOL_FAILURE_PREFIX = /^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i;
|
|
12
|
+
|
|
13
|
+
function isProviderAbortError(error: string): boolean {
|
|
14
|
+
return !TOOL_FAILURE_PREFIX.test(error.trim()) && (PROVIDER_ABORT_PATTERN.test(error) || ABORT_ERROR_PATTERN.test(error));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function record(value: unknown): Record<string, unknown> | undefined {
|
|
18
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
19
|
+
? value as Record<string, unknown>
|
|
20
|
+
: undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function contentParts(message: Record<string, unknown>): unknown[] {
|
|
24
|
+
return Array.isArray(message.content) ? message.content : [];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function terminalAssistant(messages: readonly Message[]): { message?: Record<string, unknown>; index: number } {
|
|
28
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
29
|
+
const message = record(messages[index]);
|
|
30
|
+
if (message?.role === "assistant") return { message, index };
|
|
31
|
+
}
|
|
32
|
+
return { index: messages.length };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function zeroOutputUsage(message: Record<string, unknown>): boolean {
|
|
36
|
+
const usage = record(message.usage);
|
|
37
|
+
return usage !== undefined && (usage.output ?? usage.outputTokens ?? 0) === 0;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function hasUsefulProgress(messages: readonly Message[], terminalIndex: number): boolean {
|
|
41
|
+
for (let index = 0; index < terminalIndex; index++) {
|
|
42
|
+
const message = record(messages[index]);
|
|
43
|
+
if (!message) continue;
|
|
44
|
+
if (message.role === "assistant" && contentParts(message).length > 0) return true;
|
|
45
|
+
if (message.role === "toolResult" && message.isError !== true) return true;
|
|
46
|
+
}
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function hasUnresolvedToolCall(messages: readonly Message[]): boolean {
|
|
51
|
+
const pending = new Set<string>();
|
|
52
|
+
for (const rawMessage of messages) {
|
|
53
|
+
const message = record(rawMessage);
|
|
54
|
+
if (!message) continue;
|
|
55
|
+
if (message.role === "assistant") {
|
|
56
|
+
for (const rawPart of contentParts(message)) {
|
|
57
|
+
const part = record(rawPart);
|
|
58
|
+
if (part?.type === "toolCall" && typeof part.id === "string" && part.id) pending.add(part.id);
|
|
59
|
+
}
|
|
60
|
+
} else if (message.role === "toolResult" && typeof message.toolCallId === "string") {
|
|
61
|
+
pending.delete(message.toolCallId);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return pending.size > 0;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function planAbortRecovery(input: {
|
|
68
|
+
messages: readonly Message[];
|
|
69
|
+
error?: string;
|
|
70
|
+
processSignal?: string | null;
|
|
71
|
+
sessionAvailable: boolean;
|
|
72
|
+
alreadyResumed: boolean;
|
|
73
|
+
stopped?: boolean;
|
|
74
|
+
interrupted?: boolean;
|
|
75
|
+
timedOut?: boolean;
|
|
76
|
+
toolBudgetExhausted?: boolean;
|
|
77
|
+
usageBudgetExhausted?: boolean;
|
|
78
|
+
structuredOutputFailed?: boolean;
|
|
79
|
+
acceptanceFailed?: boolean;
|
|
80
|
+
currentTool?: string;
|
|
81
|
+
afterCompactionSettlement?: boolean;
|
|
82
|
+
}): AbortRecoveryPlan {
|
|
83
|
+
const terminal = terminalAssistant(input.messages);
|
|
84
|
+
const message = terminal.message;
|
|
85
|
+
const terminalError = typeof message?.errorMessage === "string" ? message.errorMessage : undefined;
|
|
86
|
+
const emptyZeroUsageTerminal = message !== undefined
|
|
87
|
+
&& contentParts(message).length === 0
|
|
88
|
+
&& zeroOutputUsage(message);
|
|
89
|
+
const terminalAssistantAbort = message?.stopReason === "aborted"
|
|
90
|
+
|| (message?.stopReason === "error" && terminalError !== undefined && isProviderAbortError(terminalError));
|
|
91
|
+
const abortCandidate = emptyZeroUsageTerminal && terminalAssistantAbort;
|
|
92
|
+
const compactionAbortCandidate = input.afterCompactionSettlement === true && abortCandidate;
|
|
93
|
+
const settle = (reason: string): AbortRecoveryPlan => ({
|
|
94
|
+
action: "settle",
|
|
95
|
+
reason,
|
|
96
|
+
...(compactionAbortCandidate
|
|
97
|
+
? { diagnostic: `Compaction-induced child abort could not be resumed safely: ${reason}.` }
|
|
98
|
+
: {}),
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
if (input.alreadyResumed) return settle("resume already attempted");
|
|
102
|
+
if (!input.sessionAvailable) return settle("retained session unavailable");
|
|
103
|
+
if (input.stopped || input.interrupted) return settle("explicit stop or interrupt");
|
|
104
|
+
// An external-job runner reports a process signal when its terminal drain
|
|
105
|
+
// ends a child left open by a compaction abort. The compaction + settlement
|
|
106
|
+
// markers make that cleanup signal non-authoritative; explicit stop/interrupt still wins.
|
|
107
|
+
if (input.processSignal && !compactionAbortCandidate) return settle("process terminated by signal");
|
|
108
|
+
if (input.timedOut) return settle("elapsed timeout");
|
|
109
|
+
if (input.toolBudgetExhausted || input.usageBudgetExhausted) return settle("budget exhausted");
|
|
110
|
+
if (input.structuredOutputFailed) return settle("structured output failure");
|
|
111
|
+
if (input.acceptanceFailed) return settle("acceptance failure");
|
|
112
|
+
if (input.currentTool) return settle(`active tool '${input.currentTool.slice(0, 128)}' remains in flight`);
|
|
113
|
+
if (hasUnresolvedToolCall(input.messages)) return settle("unresolved tool call remains in transcript");
|
|
114
|
+
if (!input.afterCompactionSettlement) return settle("compaction settlement not verified");
|
|
115
|
+
if (!abortCandidate) return settle("terminal assistant abort evidence not verified");
|
|
116
|
+
const progressLimit = emptyZeroUsageTerminal ? terminal.index : input.messages.length;
|
|
117
|
+
if (!hasUsefulProgress(input.messages, progressLimit)) return settle("no useful prior progress");
|
|
118
|
+
return { action: "resume", prompt: ABORT_RECOVERY_PROMPT };
|
|
119
|
+
}
|