@xzzpig/pi-subagents 0.8.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 +443 -0
- package/README.md +2 -2
- 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 +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- 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-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- 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 +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -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 +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- 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 +39 -16
- 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 +84 -17
- 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 +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- 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 +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- 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 +138 -36
- 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 +32 -6
- 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 +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- 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 +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- 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 +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- 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 +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- 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 +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- 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 +8 -1
- 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 +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- 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 +217 -82
- 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 +1429 -163
- 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/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 +988 -59
- 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 -935
- 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,76 +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
|
-
}
|
|
29
|
-
|
|
30
|
-
const UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION = "unsupported-continuation: detached workflow child settled, but JavaScript workflow continuation was not persisted. Resume the workflow explicitly instead of treating the completed child as top-level workflow completion.";
|
|
31
|
-
const INTERRUPTED_DETACHED_CHILD = "Interrupted. Waiting for explicit next action.";
|
|
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";
|
|
32
32
|
|
|
33
33
|
export function applyDetachedChildToPausedWorkflow(
|
|
34
34
|
status: AsyncStatus,
|
|
35
|
-
input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "sessionFile">; workflowKey?: string },
|
|
35
|
+
input: { childRunId: string; result: Pick<SingleResult, "exitCode" | "error" | "interrupted" | "sessionFile" | "sessionName" | "stopped">; workflowKey?: string },
|
|
36
36
|
): AsyncStatus | undefined {
|
|
37
|
-
|
|
38
|
-
const next = cloneWorkflowStatus(status);
|
|
39
|
-
const step = next.steps?.find((candidate) => candidate.runId === input.childRunId)
|
|
40
|
-
?? (input.workflowKey ? next.steps?.find((candidate) => candidate.workflowKey === input.workflowKey) : undefined);
|
|
41
|
-
if (!step) return undefined;
|
|
42
|
-
const succeeded = childSucceeded(input.result);
|
|
43
|
-
const failedSiblingError = next.steps?.find((candidate) => candidate !== step && candidate.status === "failed" && candidate.error)?.error;
|
|
44
|
-
const updatedAt = Date.now();
|
|
45
|
-
step.status = succeeded ? "completed" : "failed";
|
|
46
|
-
step.endedAt = updatedAt;
|
|
47
|
-
delete step.activityState;
|
|
48
|
-
delete step.currentTool;
|
|
49
|
-
delete step.currentToolStartedAt;
|
|
50
|
-
if (input.result.sessionFile) step.sessionFile = input.result.sessionFile;
|
|
51
|
-
if (succeeded) delete step.error;
|
|
52
|
-
else if (input.result.interrupted) step.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
|
|
53
|
-
else if (input.result.error) step.error = input.result.error;
|
|
54
|
-
next.lastUpdate = updatedAt;
|
|
55
|
-
const promoted = promotePausedWorkflowIfSettled(next);
|
|
56
|
-
if (promoted?.state === "failed" && input.result.interrupted && !failedSiblingError) promoted.error = input.result.error ?? INTERRUPTED_DETACHED_CHILD;
|
|
57
|
-
else if (promoted?.state === "failed" && input.result.error) promoted.error = input.result.error;
|
|
58
|
-
return promoted ?? next;
|
|
37
|
+
return applyDetachedChildSettlement(status, input);
|
|
59
38
|
}
|
|
60
39
|
|
|
61
40
|
export function promotePausedWorkflowIfSettled(status: AsyncStatus): AsyncStatus | undefined {
|
|
62
|
-
|
|
63
|
-
const next = cloneWorkflowStatus(status);
|
|
64
|
-
const stillOpen = next.steps?.some((candidate) =>
|
|
65
|
-
candidate.status === "running"
|
|
66
|
-
|| (candidate.status === "paused" && candidate.activityState === "needs_attention")
|
|
67
|
-
) === true;
|
|
68
|
-
if (stillOpen || !next.steps?.length) return undefined;
|
|
69
|
-
const failed = next.steps.some((candidate) => candidate.status === "failed");
|
|
70
|
-
const updatedAt = Date.now();
|
|
71
|
-
next.lastUpdate = updatedAt;
|
|
72
|
-
next.state = "failed";
|
|
73
|
-
next.endedAt = updatedAt;
|
|
74
|
-
delete next.activityState;
|
|
75
|
-
if (failed) return next;
|
|
76
|
-
next.error = UNSUPPORTED_DETACHED_WORKFLOW_CONTINUATION;
|
|
77
|
-
return next;
|
|
41
|
+
return promoteSettledPausedWorkflow(status);
|
|
78
42
|
}
|
|
79
43
|
|
|
80
|
-
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 {
|
|
81
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);
|
|
82
56
|
if (Array.isArray(existingResults)) {
|
|
83
57
|
return existingResults.map((entry) => {
|
|
84
58
|
if (!entry || typeof entry !== "object" || Array.isArray(entry)) return entry;
|
|
@@ -86,61 +60,45 @@ function workflowResultChildren(status: AsyncStatus, childRunId: string, result:
|
|
|
86
60
|
if (child.runId !== childRunId) return child;
|
|
87
61
|
return {
|
|
88
62
|
...child,
|
|
89
|
-
success:
|
|
63
|
+
success: result.exitCode === 0 && !result.error && !result.interrupted,
|
|
90
64
|
output,
|
|
91
65
|
outputState: output.trim() ? "present" : "absent",
|
|
92
66
|
detached: undefined,
|
|
93
|
-
...(
|
|
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 } : {}),
|
|
94
75
|
...(result.error ? { error: result.error } : {}),
|
|
95
76
|
};
|
|
96
77
|
});
|
|
97
78
|
}
|
|
98
|
-
return status.steps?.map((step) => ({
|
|
79
|
+
return status.steps?.map((step: WorkflowStatusStep) => ({
|
|
99
80
|
workflowKey: step.workflowKey,
|
|
100
81
|
agent: step.agent,
|
|
82
|
+
...(step.sessionName ? { sessionName: step.sessionName } : {}),
|
|
101
83
|
runId: step.runId,
|
|
102
84
|
success: step.status === "completed" || step.status === "complete",
|
|
103
85
|
output: step.runId === childRunId ? output : "",
|
|
104
86
|
outputState: step.runId === childRunId && output.trim() ? "present" : "absent",
|
|
105
|
-
...(step.runId === childRunId
|
|
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 } : {}),
|
|
106
93
|
...(step.error ? { error: step.error } : {}),
|
|
107
94
|
}));
|
|
108
95
|
}
|
|
109
96
|
|
|
110
|
-
function
|
|
111
|
-
const
|
|
112
|
-
const
|
|
113
|
-
? `Workflow completed after detached child ${childRunId} finished.`
|
|
114
|
-
: status.error ?? (typeof existing?.summary === "string" ? existing.summary : undefined);
|
|
115
|
-
return {
|
|
116
|
-
...(existing ?? {}),
|
|
117
|
-
id: status.runId,
|
|
118
|
-
runId: status.runId,
|
|
119
|
-
toolCallId: status.toolCallId,
|
|
120
|
-
agent: "workflow",
|
|
121
|
-
mode: "workflow",
|
|
122
|
-
success: status.state === "complete",
|
|
123
|
-
state: status.state,
|
|
124
|
-
summary,
|
|
125
|
-
error: status.error,
|
|
126
|
-
activityState: status.activityState,
|
|
127
|
-
endedAt: status.endedAt,
|
|
128
|
-
timestamp: Date.now(),
|
|
129
|
-
results: workflowResultChildren(status, childRunId, result, existing?.results),
|
|
130
|
-
workflow: status.workflow,
|
|
131
|
-
reconciledFromDetachedChild: childRunId,
|
|
132
|
-
...(receipt ? { workflowReceipt: { path: path.join(asyncDir, "workflow-receipt.json"), receipt } } : {}),
|
|
133
|
-
asyncDir,
|
|
134
|
-
cwd: status.cwd,
|
|
135
|
-
sessionId,
|
|
136
|
-
completionOwnerId: status.completionOwnerId,
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, result: SingleResult, asyncDir: string): WorkflowReceipt | undefined {
|
|
141
|
-
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);
|
|
142
100
|
if (!fs.existsSync(receiptPath)) return undefined;
|
|
143
|
-
const receipt = readWorkflowReceipt(
|
|
101
|
+
const receipt = readWorkflowReceipt(receiptRoot, status.runId);
|
|
144
102
|
const step = status.steps?.find((candidate) => candidate.runId === childRunId);
|
|
145
103
|
const key = step?.workflowKey;
|
|
146
104
|
if (!key) throw new Error(`Workflow receipt '${status.runId}' cannot identify detached child '${childRunId}' by stable key.`);
|
|
@@ -154,6 +112,13 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
154
112
|
resumability = { state: "not-resumable", reason: error instanceof Error ? error.message : String(error) };
|
|
155
113
|
}
|
|
156
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 };
|
|
157
122
|
const updatedEntry: WorkflowReceipt["entries"][string] = resumability.state === "resumable"
|
|
158
123
|
? {
|
|
159
124
|
...entry,
|
|
@@ -162,6 +127,8 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
162
127
|
latestRunId: entry.latestRunId ?? childRunId,
|
|
163
128
|
resumability,
|
|
164
129
|
...(outputReference ? { outputReference } : {}),
|
|
130
|
+
...(childTerminalOutcome ? { terminalOutcome: childTerminalOutcome } : {}),
|
|
131
|
+
...(externalAdapter ? { externalAdapter } : {}),
|
|
165
132
|
}
|
|
166
133
|
: {
|
|
167
134
|
...entry,
|
|
@@ -169,6 +136,8 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
169
136
|
...(step.context ? { resolvedContext: step.context } : {}),
|
|
170
137
|
resumability,
|
|
171
138
|
...(outputReference ? { outputReference } : {}),
|
|
139
|
+
...(childTerminalOutcome ? { terminalOutcome: childTerminalOutcome } : {}),
|
|
140
|
+
...(externalAdapter ? { externalAdapter } : {}),
|
|
172
141
|
};
|
|
173
142
|
const next: WorkflowReceipt = {
|
|
174
143
|
...receipt,
|
|
@@ -177,7 +146,15 @@ function reconcileWorkflowReceipt(status: AsyncStatus, childRunId: string, resul
|
|
|
177
146
|
...receipt.entries,
|
|
178
147
|
[key]: updatedEntry,
|
|
179
148
|
},
|
|
149
|
+
workflowChildren: status.workflowChildren,
|
|
150
|
+
...(receipt.terminalOutcome ? { terminalOutcome: receipt.terminalOutcome } : {}),
|
|
151
|
+
...(resolution ? { workflowResolution: resolution } : {}),
|
|
180
152
|
};
|
|
153
|
+
if (resolution) next.recovery = workflowRecoveryActions(next);
|
|
154
|
+
else {
|
|
155
|
+
delete next.workflowResolution;
|
|
156
|
+
delete next.recovery;
|
|
157
|
+
}
|
|
181
158
|
writeWorkflowReceipt(asyncDir, next);
|
|
182
159
|
return next;
|
|
183
160
|
}
|
|
@@ -203,21 +180,26 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
203
180
|
const asyncDir = job?.asyncDir ?? path.join(DIRS.async, input.workflowRunId);
|
|
204
181
|
const status = readStatus(asyncDir);
|
|
205
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
|
+
}
|
|
206
193
|
const next = applyDetachedChildToPausedWorkflow(status, {
|
|
207
194
|
childRunId: input.childRunId,
|
|
208
195
|
result: input.result,
|
|
209
196
|
workflowKey: input.workflowKey,
|
|
210
197
|
});
|
|
211
198
|
if (!next) return false;
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
job.updatedAt = next.lastUpdate;
|
|
217
|
-
job.activityState = next.activityState;
|
|
218
|
-
job.steps = next.steps?.map((step, index) => ({ ...step, index }));
|
|
219
|
-
job.workflow = next.workflow;
|
|
220
|
-
}
|
|
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;
|
|
221
203
|
const resultPath = resultFilePath(DIRS.results, input.workflowRunId);
|
|
222
204
|
let existing: Record<string, unknown> | undefined;
|
|
223
205
|
try {
|
|
@@ -228,13 +210,55 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
228
210
|
}
|
|
229
211
|
let receipt: WorkflowReceipt | undefined;
|
|
230
212
|
let receiptError: string | undefined;
|
|
213
|
+
const resolution = classifyWorkflowSettlement(next, input.result.interrupted);
|
|
231
214
|
try {
|
|
232
|
-
receipt = reconcileWorkflowReceipt(next, input.childRunId, input.result, asyncDir);
|
|
215
|
+
receipt = reconcileWorkflowReceipt(next, input.childRunId, input.result, asyncDir, resolution);
|
|
233
216
|
} catch (error) {
|
|
234
217
|
receiptError = `Failed to reconcile async workflow receipt: ${error instanceof Error ? error.message : String(error)}`;
|
|
235
218
|
}
|
|
236
|
-
const
|
|
237
|
-
|
|
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);
|
|
238
262
|
if (receiptError) {
|
|
239
263
|
appendDetachedWorkflowEvent(asyncDir, {
|
|
240
264
|
ts: Date.now(),
|
|
@@ -244,14 +268,12 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
244
268
|
reconciledFromDetachedChild: input.childRunId,
|
|
245
269
|
});
|
|
246
270
|
}
|
|
247
|
-
if (
|
|
271
|
+
if (plan.completionEvent) {
|
|
248
272
|
appendDetachedWorkflowEvent(asyncDir, {
|
|
249
273
|
ts: Date.now(),
|
|
250
274
|
runId: input.workflowRunId,
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
...(next.error ? { error: next.error } : {}),
|
|
254
|
-
reconciledFromDetachedChild: input.childRunId,
|
|
275
|
+
...plan.completionEvent,
|
|
276
|
+
recovery: plan.recovery,
|
|
255
277
|
});
|
|
256
278
|
input.events?.emit(SUBAGENT_ASYNC_COMPLETE_EVENT, {
|
|
257
279
|
id: input.workflowRunId,
|
|
@@ -259,13 +281,16 @@ export function reconcileDetachedWorkflowChildCompletion(input: {
|
|
|
259
281
|
source: "async",
|
|
260
282
|
mode: "workflow",
|
|
261
283
|
agent: "workflow",
|
|
262
|
-
success:
|
|
263
|
-
state:
|
|
264
|
-
|
|
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,
|
|
265
290
|
reconciledFromDetachedChild: input.childRunId,
|
|
266
|
-
|
|
267
|
-
sessionId:
|
|
268
|
-
completionOwnerId:
|
|
291
|
+
results,
|
|
292
|
+
sessionId: plan.status.sessionId,
|
|
293
|
+
completionOwnerId: plan.status.completionOwnerId,
|
|
269
294
|
timestamp: Date.now(),
|
|
270
295
|
triggerTurn: true,
|
|
271
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
|
+
}
|