@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
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
import type { WorkflowPreflightLaneV1, WorkflowPreflightV1 } from "../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
export const WORKFLOW_PREFLIGHT_VERSION = 1 as const;
|
|
4
|
+
export const WORKFLOW_PREFLIGHT_MAX_LANES = 64;
|
|
5
|
+
export const WORKFLOW_PREFLIGHT_MAX_STRING_LENGTH = 256;
|
|
6
|
+
export const WORKFLOW_PREFLIGHT_MAX_CLAIMS = 16;
|
|
7
|
+
export const WORKFLOW_PREFLIGHT_MAX_DEPTH = 3;
|
|
8
|
+
export const WORKFLOW_PREFLIGHT_MAX_BYTES = 16 * 1024;
|
|
9
|
+
export const WORKFLOW_PREFLIGHT_MAX_WARNINGS = 16;
|
|
10
|
+
|
|
11
|
+
const WORKFLOW_KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
12
|
+
const PREFLIGHT_FIELDS = new Set(["version", "coverage", "lanes"]);
|
|
13
|
+
const LANE_FIELDS = new Set(["key", "mode", "decision", "claims", "expectedOutput", "independence"]);
|
|
14
|
+
const PREFLIGHT_MODES = new Set<WorkflowPreflightLaneV1["mode"]>(["mutation", "review", "scout", "gate"]);
|
|
15
|
+
|
|
16
|
+
type WorkflowTraceLike = {
|
|
17
|
+
operation: string;
|
|
18
|
+
key: string;
|
|
19
|
+
phase?: string;
|
|
20
|
+
generatedLaneKey?: string;
|
|
21
|
+
warning?: string;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export interface WorkflowPreflightValidationResult {
|
|
25
|
+
ok: boolean;
|
|
26
|
+
preflight?: WorkflowPreflightV1;
|
|
27
|
+
error?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
31
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
32
|
+
const prototype = Object.getPrototypeOf(value);
|
|
33
|
+
return prototype === Object.prototype || prototype === null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function assertPlainObject(value: unknown, path: string): asserts value is Record<string, unknown> {
|
|
37
|
+
if (!isPlainObject(value)) throw new Error(`${path} must be a plain JSON object.`);
|
|
38
|
+
if (Object.getOwnPropertySymbols(value).length > 0) throw new Error(`${path} must not contain symbol keys.`);
|
|
39
|
+
for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
|
|
40
|
+
if (!descriptor.enumerable || !("value" in descriptor)) throw new Error(`${path}.${key} must be an enumerable data property.`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function assertKnownFields(value: Record<string, unknown>, allowed: ReadonlySet<string>, path: string): void {
|
|
45
|
+
for (const key of Object.keys(value)) {
|
|
46
|
+
if (!allowed.has(key)) throw new Error(`${path} contains unsupported field '${key}'.`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function normalizeDisplayString(value: unknown, path: string): string {
|
|
51
|
+
if (typeof value !== "string") throw new Error(`${path} must be a string.`);
|
|
52
|
+
const normalized = value
|
|
53
|
+
.replace(/[\u0000-\u001f\u007f]/g, " ")
|
|
54
|
+
.replace(/\s+/g, " ")
|
|
55
|
+
.trim();
|
|
56
|
+
if (!normalized) throw new Error(`${path} must be a non-empty string.`);
|
|
57
|
+
if (normalized.length > WORKFLOW_PREFLIGHT_MAX_STRING_LENGTH) {
|
|
58
|
+
throw new Error(`${path} exceeds the maximum length of ${WORKFLOW_PREFLIGHT_MAX_STRING_LENGTH}.`);
|
|
59
|
+
}
|
|
60
|
+
return normalized;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function normalizeLane(value: unknown, index: number): WorkflowPreflightLaneV1 {
|
|
64
|
+
const path = `preflight.lanes[${index}]`;
|
|
65
|
+
assertPlainObject(value, path);
|
|
66
|
+
assertKnownFields(value, LANE_FIELDS, path);
|
|
67
|
+
const key = normalizeDisplayString(value.key, `${path}.key`);
|
|
68
|
+
if (!WORKFLOW_KEY_PATTERN.test(key)) throw new Error(`${path}.key must be 1-128 characters using letters, numbers, '.', '_' or '-', and start with a letter or number.`);
|
|
69
|
+
let mode: WorkflowPreflightLaneV1["mode"];
|
|
70
|
+
if (value.mode !== undefined) {
|
|
71
|
+
if (typeof value.mode !== "string" || !PREFLIGHT_MODES.has(value.mode as WorkflowPreflightLaneV1["mode"])) {
|
|
72
|
+
throw new Error(`${path}.mode must be one of: mutation, review, scout, gate.`);
|
|
73
|
+
}
|
|
74
|
+
mode = value.mode as WorkflowPreflightLaneV1["mode"];
|
|
75
|
+
}
|
|
76
|
+
let claims: string[] | undefined;
|
|
77
|
+
if (value.claims !== undefined) {
|
|
78
|
+
if (!Array.isArray(value.claims)) throw new Error(`${path}.claims must be an array of strings.`);
|
|
79
|
+
if (value.claims.length > WORKFLOW_PREFLIGHT_MAX_CLAIMS) throw new Error(`${path}.claims supports at most ${WORKFLOW_PREFLIGHT_MAX_CLAIMS} entries.`);
|
|
80
|
+
claims = value.claims.map((claim, claimIndex) => normalizeDisplayString(claim, `${path}.claims[${claimIndex}]`));
|
|
81
|
+
for (let claimIndex = 0; claimIndex < value.claims.length; claimIndex += 1) {
|
|
82
|
+
if (!Object.prototype.hasOwnProperty.call(value.claims, claimIndex)) throw new Error(`${path}.claims must not contain sparse arrays.`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
key,
|
|
87
|
+
...(mode ? { mode } : {}),
|
|
88
|
+
...(value.decision !== undefined ? { decision: normalizeDisplayString(value.decision, `${path}.decision`) } : {}),
|
|
89
|
+
...(claims ? { claims } : {}),
|
|
90
|
+
...(value.expectedOutput !== undefined ? { expectedOutput: normalizeDisplayString(value.expectedOutput, `${path}.expectedOutput`) } : {}),
|
|
91
|
+
...(value.independence !== undefined ? { independence: normalizeDisplayString(value.independence, `${path}.independence`) } : {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Validate and canonicalize the explicit preflight input. This is intentionally
|
|
97
|
+
* independent of workflowScript parsing: callers may describe dynamic fanout
|
|
98
|
+
* without making the metadata a second execution graph.
|
|
99
|
+
*/
|
|
100
|
+
export function normalizeWorkflowPreflight(input: unknown): WorkflowPreflightV1 | undefined {
|
|
101
|
+
if (input === undefined) return undefined;
|
|
102
|
+
assertPlainObject(input, "preflight");
|
|
103
|
+
assertKnownFields(input, PREFLIGHT_FIELDS, "preflight");
|
|
104
|
+
if (input.version !== WORKFLOW_PREFLIGHT_VERSION) throw new Error(`preflight.version must be ${WORKFLOW_PREFLIGHT_VERSION}.`);
|
|
105
|
+
const coverage = input.coverage === undefined ? "partial" : input.coverage;
|
|
106
|
+
if (coverage !== "complete" && coverage !== "partial") throw new Error("preflight.coverage must be 'complete' or 'partial'.");
|
|
107
|
+
if (!Array.isArray(input.lanes)) throw new Error("preflight.lanes must be an array.");
|
|
108
|
+
if (input.lanes.length > WORKFLOW_PREFLIGHT_MAX_LANES) throw new Error(`preflight.lanes supports at most ${WORKFLOW_PREFLIGHT_MAX_LANES} lanes.`);
|
|
109
|
+
for (let index = 0; index < input.lanes.length; index += 1) {
|
|
110
|
+
if (!Object.prototype.hasOwnProperty.call(input.lanes, index)) throw new Error("preflight.lanes must not contain sparse arrays.");
|
|
111
|
+
}
|
|
112
|
+
const lanes = input.lanes.map(normalizeLane);
|
|
113
|
+
const seenKeys = new Set<string>();
|
|
114
|
+
for (const lane of lanes) {
|
|
115
|
+
if (seenKeys.has(lane.key)) throw new Error(`preflight.lanes contains duplicate key '${lane.key}'.`);
|
|
116
|
+
seenKeys.add(lane.key);
|
|
117
|
+
}
|
|
118
|
+
const normalized = { version: WORKFLOW_PREFLIGHT_VERSION, coverage, lanes } satisfies WorkflowPreflightV1;
|
|
119
|
+
const depth = 1 + (lanes.length > 0 ? 1 : 0) + (lanes.some((lane) => lane.claims !== undefined) ? 1 : 0);
|
|
120
|
+
if (depth > WORKFLOW_PREFLIGHT_MAX_DEPTH) throw new Error(`preflight exceeds the maximum nesting depth of ${WORKFLOW_PREFLIGHT_MAX_DEPTH}.`);
|
|
121
|
+
const bytes = Buffer.byteLength(JSON.stringify(normalized), "utf8");
|
|
122
|
+
if (bytes > WORKFLOW_PREFLIGHT_MAX_BYTES) throw new Error(`preflight canonical JSON is ${bytes} bytes; maximum is ${WORKFLOW_PREFLIGHT_MAX_BYTES}.`);
|
|
123
|
+
return normalized;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function validateWorkflowPreflight(input: unknown): WorkflowPreflightValidationResult {
|
|
127
|
+
try {
|
|
128
|
+
const preflight = normalizeWorkflowPreflight(input);
|
|
129
|
+
return { ok: true, ...(preflight ? { preflight } : {}) };
|
|
130
|
+
} catch (error) {
|
|
131
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function warningLimit(messages: string[]): string[] {
|
|
136
|
+
if (messages.length <= WORKFLOW_PREFLIGHT_MAX_WARNINGS) return messages;
|
|
137
|
+
const omitted = messages.length - WORKFLOW_PREFLIGHT_MAX_WARNINGS + 1;
|
|
138
|
+
return [...messages.slice(0, WORKFLOW_PREFLIGHT_MAX_WARNINGS - 1), `Preflight advisory: ${omitted} additional mismatch warning(s) omitted.`];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function declaredKeys(preflight: WorkflowPreflightV1): Set<string> {
|
|
142
|
+
return new Set(preflight.lanes.map((lane) => lane.key));
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Treat declared lane keys as plan roots: `lane` is the lane itself and
|
|
147
|
+
* `lane.stage` is a stage by convention, even without generated provenance.
|
|
148
|
+
*/
|
|
149
|
+
export function workflowKeyMatchesPreflightLane(key: string, laneKey: string, generatedLaneKey?: string): boolean {
|
|
150
|
+
return generatedLaneKey === laneKey || key === laneKey || key.startsWith(`${laneKey}.`);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Select the most specific advisory lane without allowing declaration order to override an exact runtime key. */
|
|
154
|
+
export function workflowPreflightLaneForRuntimeKey(
|
|
155
|
+
preflight: WorkflowPreflightV1 | undefined,
|
|
156
|
+
key: string,
|
|
157
|
+
preferredKeys: readonly (string | undefined)[] = [],
|
|
158
|
+
): WorkflowPreflightLaneV1 | undefined {
|
|
159
|
+
const lanes = preflight?.lanes;
|
|
160
|
+
if (!lanes) return undefined;
|
|
161
|
+
const exact = lanes.find((lane) => lane.key === key);
|
|
162
|
+
if (exact) return exact;
|
|
163
|
+
let closestRoot: WorkflowPreflightLaneV1 | undefined;
|
|
164
|
+
for (const lane of lanes) {
|
|
165
|
+
if (key.startsWith(`${lane.key}.`) && (!closestRoot || lane.key.length > closestRoot.key.length)) closestRoot = lane;
|
|
166
|
+
}
|
|
167
|
+
if (closestRoot) return closestRoot;
|
|
168
|
+
for (const preferredKey of preferredKeys) {
|
|
169
|
+
if (!preferredKey) continue;
|
|
170
|
+
const preferred = lanes.find((lane) => lane.key === preferredKey);
|
|
171
|
+
if (preferred) return preferred;
|
|
172
|
+
}
|
|
173
|
+
return undefined;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function declaredLaneCoversWorkflowKey(entry: WorkflowTraceLike, laneKey: string): boolean {
|
|
177
|
+
return workflowKeyMatchesPreflightLane(entry.key, laneKey, entry.generatedLaneKey);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function keyCoveredByDeclaredLane(entry: WorkflowTraceLike, declared: ReadonlySet<string>): boolean {
|
|
181
|
+
for (const laneKey of declared) if (declaredLaneCoversWorkflowKey(entry, laneKey)) return true;
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function launchedEntries(trace: readonly WorkflowTraceLike[]): WorkflowTraceLike[] {
|
|
186
|
+
const entries: WorkflowTraceLike[] = [];
|
|
187
|
+
const seen = new Set<string>();
|
|
188
|
+
for (const entry of trace) {
|
|
189
|
+
if (entry.operation !== "run" || entry.phase === "auto-resume" || seen.has(entry.key)) continue;
|
|
190
|
+
seen.add(entry.key);
|
|
191
|
+
entries.push(entry);
|
|
192
|
+
}
|
|
193
|
+
return entries;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function undeclaredWarning(key: string): string {
|
|
197
|
+
return `Preflight advisory: workflow key '${key}' launched without a declared lane.`;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function unlaunchedWarning(key: string): string {
|
|
201
|
+
return `Preflight advisory: declared lane '${key}' was not launched.`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Return bounded advisory mismatch warnings; these never reject a child launch. */
|
|
205
|
+
export function workflowPreflightWarnings(
|
|
206
|
+
preflight: WorkflowPreflightV1 | undefined,
|
|
207
|
+
trace: readonly WorkflowTraceLike[],
|
|
208
|
+
options: { settled?: boolean } = {},
|
|
209
|
+
): string[] {
|
|
210
|
+
if (!preflight) return [];
|
|
211
|
+
const declared = declaredKeys(preflight);
|
|
212
|
+
const launched = launchedEntries(trace);
|
|
213
|
+
const messages = launched.filter((entry) => !keyCoveredByDeclaredLane(entry, declared)).map((entry) => undeclaredWarning(entry.key));
|
|
214
|
+
if (options.settled === true) {
|
|
215
|
+
for (const lane of preflight.lanes) if (!launched.some((entry) => declaredLaneCoversWorkflowKey(entry, lane.key))) messages.push(unlaunchedWarning(lane.key));
|
|
216
|
+
}
|
|
217
|
+
return warningLimit(messages);
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Attach the first undeclared-key warning to its first trace row for status/debug views. */
|
|
221
|
+
export function annotateWorkflowPreflightTrace<T extends WorkflowTraceLike>(trace: readonly T[], preflight: WorkflowPreflightV1 | undefined): T[] {
|
|
222
|
+
if (!preflight) return [...trace];
|
|
223
|
+
const declared = declaredKeys(preflight);
|
|
224
|
+
const warned = new Set<string>();
|
|
225
|
+
return trace.map((entry) => {
|
|
226
|
+
if (entry.operation !== "run" || entry.phase === "auto-resume" || keyCoveredByDeclaredLane(entry, declared) || warned.has(entry.key)) return entry;
|
|
227
|
+
warned.add(entry.key);
|
|
228
|
+
return { ...entry, warning: entry.warning ?? undeclaredWarning(entry.key) };
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function laneCell(value: string | undefined): string {
|
|
233
|
+
return value ?? "—";
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const WORKFLOW_PREFLIGHT_PLAN_LABEL_LENGTH = 96;
|
|
237
|
+
|
|
238
|
+
function planLaneLabel(lane: WorkflowPreflightLaneV1): string {
|
|
239
|
+
const value = lane.decision?.trim() || lane.key;
|
|
240
|
+
if (value.length <= WORKFLOW_PREFLIGHT_PLAN_LABEL_LENGTH) return value;
|
|
241
|
+
return `${value.slice(0, WORKFLOW_PREFLIGHT_PLAN_LABEL_LENGTH - 1).trimEnd()}…`;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Render the detailed bounded table reserved for tool output and expanded/debug views. */
|
|
245
|
+
export function formatWorkflowPreflight(preflight: WorkflowPreflightV1 | undefined, options: { indent?: string } = {}): string {
|
|
246
|
+
if (!preflight) return "";
|
|
247
|
+
const indent = options.indent ?? "";
|
|
248
|
+
const count = preflight.lanes.length;
|
|
249
|
+
const lines = [
|
|
250
|
+
`${indent}Preflight: v${preflight.version} · ${preflight.coverage} · ${count} lane${count === 1 ? "" : "s"}`,
|
|
251
|
+
`${indent} key | mode | decision | claims | expected output | independence`,
|
|
252
|
+
];
|
|
253
|
+
for (const lane of preflight.lanes) {
|
|
254
|
+
lines.push(`${indent} ${[
|
|
255
|
+
lane.key,
|
|
256
|
+
laneCell(lane.mode),
|
|
257
|
+
laneCell(lane.decision),
|
|
258
|
+
lane.claims?.join(", ") ?? "—",
|
|
259
|
+
laneCell(lane.expectedOutput),
|
|
260
|
+
laneCell(lane.independence),
|
|
261
|
+
].join(" | ")}`);
|
|
262
|
+
}
|
|
263
|
+
return lines.join("\n");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export function formatWorkflowPreflightSummary(preflight: WorkflowPreflightV1 | undefined): string {
|
|
267
|
+
if (!preflight) return "";
|
|
268
|
+
const keys = preflight.lanes.slice(0, 4).map((lane) => lane.key).join(", ");
|
|
269
|
+
const remainder = preflight.lanes.length > 4 ? `, +${preflight.lanes.length - 4}` : "";
|
|
270
|
+
return `preflight · ${preflight.coverage} · ${preflight.lanes.length} lane${preflight.lanes.length === 1 ? "" : "s"}${keys ? `: ${keys}${remainder}` : ""}`;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/** Render the operator-facing one-line plan shown in routine status views. */
|
|
274
|
+
export function formatWorkflowPreflightPlanSummary(preflight: WorkflowPreflightV1 | undefined, options: { indent?: string } = {}): string {
|
|
275
|
+
if (!preflight) return "";
|
|
276
|
+
const indent = options.indent ?? "";
|
|
277
|
+
const count = preflight.lanes.length;
|
|
278
|
+
const labels = count === 1
|
|
279
|
+
? planLaneLabel(preflight.lanes[0]!)
|
|
280
|
+
: preflight.lanes.slice(0, 4).map((lane) => lane.key).join(", ") + (count > 4 ? `, +${count - 4}` : "");
|
|
281
|
+
return `${indent}Plan: ${count} lane${count === 1 ? "" : "s"}${labels ? ` · ${labels}` : ""}`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Render a bounded, non-alarming warning for routine status views. */
|
|
285
|
+
export function formatWorkflowPreflightWarningSummary(warnings: readonly string[] | undefined, options: { indent?: string; hint?: string } = {}): string {
|
|
286
|
+
if (!warnings?.length) return "";
|
|
287
|
+
const indent = options.indent ?? "";
|
|
288
|
+
const hint = options.hint ?? "details available for debug";
|
|
289
|
+
const count = warnings.length;
|
|
290
|
+
return `${indent}Plan note: ${count} preflight mismatch${count === 1 ? "" : "es"} · ${hint}.`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function formatWorkflowPreflightWarnings(warnings: readonly string[] | undefined, options: { indent?: string } = {}): string {
|
|
294
|
+
if (!warnings?.length) return "";
|
|
295
|
+
const indent = options.indent ?? "";
|
|
296
|
+
return [`${indent}Preflight warnings:`, ...warnings.map((warning) => `${indent} - ${warning.replace(/\s+/g, " ").trim()}`)].join("\n");
|
|
297
|
+
}
|
|
@@ -1,15 +1,20 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import { writePrivateAtomicJson } from "../shared/atomic-json.ts";
|
|
4
|
-
import type { WorkflowReceipt, WorkflowReceiptEntry, WorkflowReceiptState } from "../shared/types.ts";
|
|
4
|
+
import type { AcceptanceRecoveryMetadata, ExternalCliReceiptMetadata, WorkflowReceipt, WorkflowReceiptEntry, WorkflowReceiptState, WorkflowRecoveryAction, WorkflowResourceProvenanceV1, WorkflowTerminalOutcome, WorkflowTerminalResolution } from "../shared/types.ts";
|
|
5
5
|
import type { WorkflowReceiptResumeReference, WorkflowScriptChildResult } from "./scripted-workflow.ts";
|
|
6
|
+
import { parseWorkflowChildSummary } from "./workflow-child-summary.ts";
|
|
7
|
+
import { HOST_STEP_MAX_COUNT, assertUniqueHostStepIds, parseHostStepNode } from "../runs/shared/host-step-status.ts";
|
|
8
|
+
import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "../runs/shared/lane-metadata.ts";
|
|
6
9
|
|
|
7
10
|
export type { WorkflowReceipt, WorkflowReceiptEntry, WorkflowReceiptState } from "../shared/types.ts";
|
|
8
11
|
|
|
9
12
|
export const WORKFLOW_RECEIPT_VERSION = 1;
|
|
10
13
|
export const WORKFLOW_RECEIPT_FILE = "workflow-receipt.json";
|
|
14
|
+
const MAX_WORKFLOW_RECEIPT_BYTES = 2 * 1024 * 1024;
|
|
11
15
|
|
|
12
16
|
const KEY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
17
|
+
const RESOURCE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
13
18
|
|
|
14
19
|
function assertSafeRunId(value: string, label: string): string {
|
|
15
20
|
const normalized = value.trim();
|
|
@@ -32,30 +37,45 @@ export function buildWorkflowReceipt(input: {
|
|
|
32
37
|
workflowRunId: string;
|
|
33
38
|
state: WorkflowReceiptState;
|
|
34
39
|
children: WorkflowScriptChildResult[];
|
|
40
|
+
hostSteps?: WorkflowReceipt["hostSteps"];
|
|
41
|
+
workflowChildren?: WorkflowReceipt["workflowChildren"];
|
|
42
|
+
resource?: WorkflowResourceProvenanceV1;
|
|
43
|
+
terminalOutcome?: WorkflowTerminalOutcome;
|
|
35
44
|
createdAt?: number;
|
|
36
45
|
}): WorkflowReceipt {
|
|
37
46
|
const workflowRunId = assertSafeRunId(input.workflowRunId, "workflowRunId");
|
|
47
|
+
if (input.workflowChildren?.workflowRunId !== undefined && input.workflowChildren.workflowRunId !== workflowRunId) throw new Error("workflowChildren workflowRunId does not match its receipt.");
|
|
38
48
|
const entries: Record<string, WorkflowReceiptEntry> = Object.create(null) as Record<string, WorkflowReceiptEntry>;
|
|
39
49
|
for (const child of input.children) {
|
|
40
50
|
const key = assertKey(child.key, "workflow receipt child key");
|
|
41
51
|
if (entries[key]) throw new Error(`Workflow receipt has duplicate child key '${key}'.`);
|
|
52
|
+
const lane = normalizeWorkflowLaneMetadata(child.lane, `workflow receipt child '${key}'.lane`);
|
|
53
|
+
assertWorkflowLaneKey(lane, key, `workflow receipt child '${key}'.lane`);
|
|
42
54
|
const runIds = [...new Set((child.continuation?.runIds ?? (child.runId ? [child.runId] : [])).filter((runId) => typeof runId === "string" && runId.trim()).map((runId) => runId.trim()))];
|
|
43
55
|
const latestRunId = runIds.at(-1);
|
|
44
56
|
const resumability = child.resumability ?? { state: "not-resumable", reason: child.runId ? "resumability was not recorded" : "child produced no run id" };
|
|
45
57
|
if (resumability.state === "resumable" && !latestRunId) throw new Error(`Workflow receipt child '${key}' is resumable but has no retained run id.`);
|
|
46
58
|
const base = {
|
|
47
59
|
key,
|
|
60
|
+
...(lane ? { lane } : {}),
|
|
61
|
+
...(child.terminalOutcome ? { terminalOutcome: child.terminalOutcome } : {}),
|
|
48
62
|
...(child.agent ? { agent: child.agent } : {}),
|
|
49
63
|
...(child.requestedContext ? { requestedContext: child.requestedContext } : {}),
|
|
50
64
|
...(child.resolvedContext ? { resolvedContext: child.resolvedContext } : {}),
|
|
51
65
|
...(child.outputReference ? { outputReference: child.outputReference } : {}),
|
|
66
|
+
...(child.recovery ? { acceptanceRecovery: child.recovery } : {}),
|
|
67
|
+
...(child.externalAdapter ? { externalAdapter: child.externalAdapter } : {}),
|
|
52
68
|
continuation: { runIds },
|
|
53
69
|
};
|
|
54
70
|
entries[key] = resumability.state === "resumable"
|
|
55
71
|
? { ...base, latestRunId: latestRunId!, resumability }
|
|
56
72
|
: { ...base, ...(latestRunId ? { latestRunId } : {}), resumability };
|
|
57
73
|
}
|
|
58
|
-
|
|
74
|
+
if (input.hostSteps && input.hostSteps.length > HOST_STEP_MAX_COUNT) throw new Error(`Workflow receipt has more than ${HOST_STEP_MAX_COUNT} host steps.`);
|
|
75
|
+
const hostSteps = input.hostSteps?.map((hostStep, index) => parseHostStepNode(hostStep, `workflow receipt hostSteps[${index}]`));
|
|
76
|
+
if (hostSteps) assertUniqueHostStepIds(hostSteps, "workflow receipt");
|
|
77
|
+
const resource = parseWorkflowResource(input.resource, "workflow receipt");
|
|
78
|
+
return { version: WORKFLOW_RECEIPT_VERSION, workflowRunId, state: input.state, createdAt: input.createdAt ?? Date.now(), entries, ...(resource ? { resource } : {}), ...(hostSteps?.length ? { hostSteps } : {}), ...(input.workflowChildren ? { workflowChildren: input.workflowChildren } : {}), ...(input.terminalOutcome ? { terminalOutcome: input.terminalOutcome } : {}) };
|
|
59
79
|
}
|
|
60
80
|
|
|
61
81
|
export function writeWorkflowReceipt(asyncDir: string, receipt: WorkflowReceipt): string {
|
|
@@ -64,6 +84,150 @@ export function writeWorkflowReceipt(asyncDir: string, receipt: WorkflowReceipt)
|
|
|
64
84
|
return receiptPath;
|
|
65
85
|
}
|
|
66
86
|
|
|
87
|
+
function readWorkflowReceiptFile(receiptPath: string): unknown {
|
|
88
|
+
let fd: number | undefined;
|
|
89
|
+
try {
|
|
90
|
+
fd = fs.openSync(receiptPath, "r");
|
|
91
|
+
const stat = fs.fstatSync(fd);
|
|
92
|
+
if (!stat.isFile()) throw new Error("workflow receipt is not a regular file.");
|
|
93
|
+
if (stat.size > MAX_WORKFLOW_RECEIPT_BYTES) throw new Error(`workflow receipt exceeds the ${MAX_WORKFLOW_RECEIPT_BYTES}-byte limit.`);
|
|
94
|
+
const buffer = Buffer.allocUnsafe(stat.size);
|
|
95
|
+
let offset = 0;
|
|
96
|
+
while (offset < buffer.length) {
|
|
97
|
+
const bytesRead = fs.readSync(fd, buffer, offset, buffer.length - offset, null);
|
|
98
|
+
if (bytesRead <= 0) throw new Error("workflow receipt ended before its declared size.");
|
|
99
|
+
offset += bytesRead;
|
|
100
|
+
}
|
|
101
|
+
return JSON.parse(buffer.toString("utf-8")) as unknown;
|
|
102
|
+
} finally {
|
|
103
|
+
if (fd !== undefined) fs.closeSync(fd);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const EXTERNAL_CLI_CAPABILITIES = {
|
|
108
|
+
stop: true,
|
|
109
|
+
steer: false,
|
|
110
|
+
resume: false,
|
|
111
|
+
structuredOutput: false,
|
|
112
|
+
toolEvents: false,
|
|
113
|
+
supervisor: "unsupported",
|
|
114
|
+
forkContext: false,
|
|
115
|
+
extensionBindings: false,
|
|
116
|
+
} as const;
|
|
117
|
+
|
|
118
|
+
function parseExternalCliReceiptMetadata(value: unknown, key: string, source: string): ExternalCliReceiptMetadata | undefined {
|
|
119
|
+
if (value === undefined) return undefined;
|
|
120
|
+
const label = `Invalid workflow receipt '${source}': entry '${key}' externalAdapter`;
|
|
121
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
122
|
+
const metadata = value as Record<string, unknown>;
|
|
123
|
+
const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "safety", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
|
|
124
|
+
if (unknownMetadata.length > 0) throw new Error(`${label} has unsupported fields: ${unknownMetadata.join(", ")}.`);
|
|
125
|
+
const adapter = metadata.adapter;
|
|
126
|
+
if (!adapter || typeof adapter !== "object" || Array.isArray(adapter)) throw new Error(`${label}.adapter must be an object.`);
|
|
127
|
+
const adapterRecord = adapter as Record<string, unknown>;
|
|
128
|
+
const unknownAdapter = Object.keys(adapterRecord).filter((field) => !["id", "version", "executionMode"].includes(field));
|
|
129
|
+
if (unknownAdapter.length > 0) throw new Error(`${label}.adapter has unsupported fields: ${unknownAdapter.join(", ")}.`);
|
|
130
|
+
if ((adapterRecord.id !== "external-cli" && adapterRecord.id !== "codex-exec" && adapterRecord.id !== "codex-exec-writer" && adapterRecord.id !== "claude-code" && adapterRecord.id !== "claude-code-writer" && adapterRecord.id !== "cursor-agent" && adapterRecord.id !== "cursor-agent-writer" && adapterRecord.id !== "grok-build") || adapterRecord.version !== 1 || adapterRecord.executionMode !== (adapterRecord.id === "cursor-agent" || adapterRecord.id === "cursor-agent-writer" || adapterRecord.id === "grok-build" ? "one-shot-prompt-file" : "one-shot-stdin")) throw new Error(`${label}.adapter is invalid.`);
|
|
131
|
+
const capabilities = metadata.capabilities;
|
|
132
|
+
if (!capabilities || typeof capabilities !== "object" || Array.isArray(capabilities)) throw new Error(`${label}.capabilities must be an object.`);
|
|
133
|
+
const capabilityRecord = capabilities as Record<string, unknown>;
|
|
134
|
+
const unknownCapabilities = Object.keys(capabilityRecord).filter((field) => !(field in EXTERNAL_CLI_CAPABILITIES));
|
|
135
|
+
if (unknownCapabilities.length > 0) throw new Error(`${label}.capabilities has unsupported fields: ${unknownCapabilities.join(", ")}.`);
|
|
136
|
+
for (const [capability, expected] of Object.entries(EXTERNAL_CLI_CAPABILITIES)) {
|
|
137
|
+
if (capabilityRecord[capability] !== expected) throw new Error(`${label}.capabilities.${capability} is invalid.`);
|
|
138
|
+
}
|
|
139
|
+
const safety = metadata.safety;
|
|
140
|
+
if (adapterRecord.id === "codex-exec") {
|
|
141
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
142
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
143
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["sandbox", "approvalPolicy", "ephemeral"].includes(field));
|
|
144
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
145
|
+
if (safetyRecord.sandbox !== "read-only" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
|
|
146
|
+
} else if (adapterRecord.id === "codex-exec-writer") {
|
|
147
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
148
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
149
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "sandbox", "approvalPolicy", "ephemeral"].includes(field));
|
|
150
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
151
|
+
if (safetyRecord.access !== "workspace-write" || safetyRecord.sandbox !== "workspace-write" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
|
|
152
|
+
} else if (adapterRecord.id === "claude-code") {
|
|
153
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
154
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
155
|
+
const legacy = safetyRecord.authentication === undefined;
|
|
156
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !(legacy
|
|
157
|
+
? ["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"]
|
|
158
|
+
: ["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"]).includes(field));
|
|
159
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
160
|
+
if (legacy) {
|
|
161
|
+
if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
162
|
+
} else if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
163
|
+
} else if (adapterRecord.id === "claude-code-writer") {
|
|
164
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
165
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
166
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"].includes(field));
|
|
167
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
168
|
+
if (safetyRecord.access !== "workspace-write" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "acceptEdits" || safetyRecord.tools !== "Read,Write,Edit,Glob,Grep" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
169
|
+
} else if (adapterRecord.id === "cursor-agent" || adapterRecord.id === "cursor-agent-writer") {
|
|
170
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
171
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
172
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "mode", "sandbox", "workspaceTrust", "sessionReuse"].includes(field));
|
|
173
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
174
|
+
const writer = adapterRecord.id === "cursor-agent-writer";
|
|
175
|
+
if (safetyRecord.access !== (writer ? "workspace-write" : "read-only") || safetyRecord.authentication !== "cursor-api-key-or-existing-login" || safetyRecord.mode !== (writer ? "print" : "ask") || safetyRecord.sandbox !== "enabled" || safetyRecord.workspaceTrust !== "existing-required" || safetyRecord.sessionReuse !== false) throw new Error(`${label}.safety is invalid.`);
|
|
176
|
+
} else if (adapterRecord.id === "grok-build") {
|
|
177
|
+
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
178
|
+
const safetyRecord = safety as Record<string, unknown>;
|
|
179
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "deniedTools", "sandbox", "webSearch", "subagents", "config", "updates", "sessionPersistence"].includes(field));
|
|
180
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
181
|
+
if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "xai-api-key-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "read_file,grep,list_dir" || safetyRecord.deniedTools !== "run_terminal_cmd,search_replace,Agent,Bash,Edit,Write,MCPTool" || safetyRecord.sandbox !== "read-only" || safetyRecord.webSearch !== false || safetyRecord.subagents !== false || safetyRecord.config !== "temporary-home" || safetyRecord.updates !== "disabled" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
182
|
+
} else if (safety !== undefined) throw new Error(`${label}.safety is invalid for the generic adapter.`);
|
|
183
|
+
const handoff = metadata.handoff;
|
|
184
|
+
if (!handoff || typeof handoff !== "object" || Array.isArray(handoff)) throw new Error(`${label}.handoff must be an object.`);
|
|
185
|
+
const handoffRecord = handoff as Record<string, unknown>;
|
|
186
|
+
const unknownHandoff = Object.keys(handoffRecord).filter((field) => field !== "mode");
|
|
187
|
+
if (unknownHandoff.length > 0) throw new Error(`${label}.handoff has unsupported fields: ${unknownHandoff.join(", ")}.`);
|
|
188
|
+
if (handoffRecord.mode !== "fresh") throw new Error(`${label}.handoff is invalid.`);
|
|
189
|
+
const supervisor = metadata.supervisor;
|
|
190
|
+
if (!supervisor || typeof supervisor !== "object" || Array.isArray(supervisor)) throw new Error(`${label}.supervisor must be an object.`);
|
|
191
|
+
const supervisorRecord = supervisor as Record<string, unknown>;
|
|
192
|
+
const unknownSupervisor = Object.keys(supervisorRecord).filter((field) => !["mode", "reason"].includes(field));
|
|
193
|
+
if (unknownSupervisor.length > 0) throw new Error(`${label}.supervisor has unsupported fields: ${unknownSupervisor.join(", ")}.`);
|
|
194
|
+
if (supervisorRecord.mode !== "unsupported" || typeof supervisorRecord.reason !== "string" || !supervisorRecord.reason.trim()) throw new Error(`${label}.supervisor is invalid.`);
|
|
195
|
+
if (typeof metadata.nonResumableReason !== "string" || !metadata.nonResumableReason.trim()) throw new Error(`${label}.nonResumableReason is missing.`);
|
|
196
|
+
const outputArtifacts = metadata.outputArtifacts;
|
|
197
|
+
if (outputArtifacts !== undefined) {
|
|
198
|
+
if (!outputArtifacts || typeof outputArtifacts !== "object" || Array.isArray(outputArtifacts)) throw new Error(`${label}.outputArtifacts must be an object.`);
|
|
199
|
+
const unknownArtifacts = Object.keys(outputArtifacts).filter((field) => !["stdoutPath", "stderrPath", "finalOutputPath"].includes(field));
|
|
200
|
+
if (unknownArtifacts.length > 0) throw new Error(`${label}.outputArtifacts has unsupported fields: ${unknownArtifacts.join(", ")}.`);
|
|
201
|
+
for (const field of ["stdoutPath", "stderrPath", "finalOutputPath"] as const) {
|
|
202
|
+
const artifactPath = (outputArtifacts as Record<string, unknown>)[field];
|
|
203
|
+
if (artifactPath !== undefined && (typeof artifactPath !== "string" || !artifactPath.trim())) throw new Error(`${label}.outputArtifacts.${field} must be a non-empty string.`);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return value as ExternalCliReceiptMetadata;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function parseTerminalOutcome(value: unknown, label: string): WorkflowTerminalOutcome | undefined {
|
|
210
|
+
if (value === undefined) return undefined;
|
|
211
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
212
|
+
const outcome = value as Record<string, unknown>;
|
|
213
|
+
if (outcome.state !== "partial" || (outcome.reason !== "budget_exhausted" && outcome.reason !== "timeout")) throw new Error(`${label} is invalid.`);
|
|
214
|
+
return { state: "partial", reason: outcome.reason };
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function parseAcceptanceRecoveryMetadata(value: unknown, label: string): AcceptanceRecoveryMetadata | undefined {
|
|
218
|
+
if (value === undefined) return undefined;
|
|
219
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
220
|
+
const recovery = value as Record<string, unknown>;
|
|
221
|
+
if (recovery.status !== "available-for-review" || recovery.reason !== "acceptance-metadata-rejected") throw new Error(`${label} is invalid.`);
|
|
222
|
+
if (typeof recovery.reportPath !== "string" || !recovery.reportPath.trim() || typeof recovery.reportHash !== "string" || !/^[a-f0-9]{64}$/u.test(recovery.reportHash)) throw new Error(`${label} is invalid.`);
|
|
223
|
+
return {
|
|
224
|
+
status: "available-for-review",
|
|
225
|
+
reason: "acceptance-metadata-rejected",
|
|
226
|
+
reportPath: recovery.reportPath,
|
|
227
|
+
reportHash: recovery.reportHash,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
67
231
|
function parseEntry(value: unknown, key: string, source: string): WorkflowReceiptEntry {
|
|
68
232
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid workflow receipt '${source}': entry '${key}' must be an object.`);
|
|
69
233
|
const entry = value as Record<string, unknown>;
|
|
@@ -84,16 +248,65 @@ function parseEntry(value: unknown, key: string, source: string): WorkflowReceip
|
|
|
84
248
|
const reason = (resumability as Record<string, unknown>).reason;
|
|
85
249
|
if (state === "resumable" && latestRunId === undefined) throw new Error(`Invalid workflow receipt '${source}': entry '${key}' resumable entry has no retained run id.`);
|
|
86
250
|
if (state === "not-resumable" && (typeof reason !== "string" || !reason.trim())) throw new Error(`Invalid workflow receipt '${source}': entry '${key}' non-resumable reason is missing.`);
|
|
87
|
-
|
|
251
|
+
const terminalOutcome = parseTerminalOutcome(entry.terminalOutcome, `Invalid workflow receipt '${source}': entry '${key}' terminalOutcome`);
|
|
252
|
+
const acceptanceRecovery = parseAcceptanceRecoveryMetadata(entry.acceptanceRecovery, `Invalid workflow receipt '${source}': entry '${key}' acceptanceRecovery`);
|
|
253
|
+
parseExternalCliReceiptMetadata(entry.externalAdapter, key, source);
|
|
254
|
+
const lane = normalizeWorkflowLaneMetadata(entry.lane, `Invalid workflow receipt '${source}': entry '${key}'.lane`);
|
|
255
|
+
assertWorkflowLaneKey(lane, key, `Invalid workflow receipt '${source}': entry '${key}'.lane`);
|
|
256
|
+
return { ...(value as WorkflowReceiptEntry), ...(lane ? { lane } : {}), ...(terminalOutcome ? { terminalOutcome } : {}), ...(acceptanceRecovery ? { acceptanceRecovery } : {}) };
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function parseWorkflowResolution(value: unknown, source: string): WorkflowTerminalResolution | undefined {
|
|
260
|
+
if (value === undefined) return undefined;
|
|
261
|
+
if (value !== "settled-awaiting-resume" && value !== "failed-child" && value !== "interrupted-child") throw new Error(`Invalid workflow receipt '${source}': workflowResolution is invalid.`);
|
|
262
|
+
return value;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function parseWorkflowResource(value: unknown, source: string): WorkflowResourceProvenanceV1 | undefined {
|
|
266
|
+
if (value === undefined) return undefined;
|
|
267
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid workflow receipt '${source}': resource must be an object.`);
|
|
268
|
+
const resource = value as Record<string, unknown>;
|
|
269
|
+
if (resource.kind !== "workflow" || typeof resource.name !== "string" || !KEY_PATTERN.test(resource.name) || !Number.isInteger(resource.version) || (resource.version as number) < 1 || (resource.version as number) > 1_000_000 || resource.invocation !== "named" || resource.expansion !== "resolved" || typeof resource.id !== "string" || !RESOURCE_ID_PATTERN.test(resource.id)) {
|
|
270
|
+
throw new Error(`Invalid workflow receipt '${source}': resource is invalid.`);
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
kind: "workflow",
|
|
274
|
+
name: resource.name,
|
|
275
|
+
version: resource.version as number,
|
|
276
|
+
invocation: "named",
|
|
277
|
+
expansion: "resolved",
|
|
278
|
+
id: resource.id,
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function parseRecovery(value: unknown, workflowRunId: string, entries: Record<string, WorkflowReceiptEntry>, source: string): WorkflowRecoveryAction[] | undefined {
|
|
283
|
+
if (value === undefined) return undefined;
|
|
284
|
+
if (!Array.isArray(value)) throw new Error(`Invalid workflow receipt '${source}': recovery must be an array.`);
|
|
285
|
+
return value.map((item, index) => {
|
|
286
|
+
if (!item || typeof item !== "object" || Array.isArray(item)) throw new Error(`Invalid workflow receipt '${source}': recovery[${index}] must be an object.`);
|
|
287
|
+
const action = item as Record<string, unknown>;
|
|
288
|
+
const key = action.key;
|
|
289
|
+
const resume = action.resume;
|
|
290
|
+
if (typeof key !== "string" || !entries[key] || action.call !== "runs.run" || action.taskRequired !== true || !resume || typeof resume !== "object" || Array.isArray(resume)) throw new Error(`Invalid workflow receipt '${source}': recovery[${index}] is invalid.`);
|
|
291
|
+
const reference = resume as Record<string, unknown>;
|
|
292
|
+
if (reference.workflowRunId !== workflowRunId || reference.key !== key || reference.latest !== true || entries[key].resumability.state !== "resumable") throw new Error(`Invalid workflow receipt '${source}': recovery[${index}] does not identify a resumable entry.`);
|
|
293
|
+
return { key, call: "runs.run", resume: { workflowRunId, key, latest: true }, taskRequired: true };
|
|
294
|
+
});
|
|
88
295
|
}
|
|
89
296
|
|
|
90
297
|
export function readWorkflowReceipt(asyncDirRoot: string, workflowRunId: string): WorkflowReceipt {
|
|
91
298
|
const receiptPath = workflowReceiptPath(asyncDirRoot, workflowRunId);
|
|
92
299
|
let value: unknown;
|
|
93
300
|
try {
|
|
94
|
-
value =
|
|
301
|
+
value = readWorkflowReceiptFile(receiptPath);
|
|
95
302
|
} catch (error) {
|
|
96
|
-
if ((error as NodeJS.ErrnoException).code === "ENOENT")
|
|
303
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") {
|
|
304
|
+
const workflowDir = path.dirname(receiptPath);
|
|
305
|
+
if (fs.existsSync(path.join(workflowDir, "status.json")) || fs.existsSync(path.join(workflowDir, "events.jsonl"))) {
|
|
306
|
+
throw new Error(`Workflow receipt '${workflowRunId}' is not available because the workflow may still be active or terminal receipt writing failed. Use direct child run IDs from status/events for direct resume after the normal retained-child checks.`);
|
|
307
|
+
}
|
|
308
|
+
throw new Error(`Workflow receipt '${workflowRunId}' was not found.`);
|
|
309
|
+
}
|
|
97
310
|
throw new Error(`Workflow receipt '${workflowRunId}' could not be read: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : undefined });
|
|
98
311
|
}
|
|
99
312
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`Invalid workflow receipt '${receiptPath}': expected an object.`);
|
|
@@ -107,7 +320,20 @@ export function readWorkflowReceipt(asyncDirRoot: string, workflowRunId: string)
|
|
|
107
320
|
if (!receipt.entries || typeof receipt.entries !== "object" || Array.isArray(receipt.entries)) throw new Error(`Invalid workflow receipt '${receiptPath}': entries must be an object.`);
|
|
108
321
|
const entries: Record<string, WorkflowReceiptEntry> = Object.create(null) as Record<string, WorkflowReceiptEntry>;
|
|
109
322
|
for (const [key, entry] of Object.entries(receipt.entries as Record<string, unknown>)) entries[assertKey(key, "workflow receipt key")] = parseEntry(entry, key, receiptPath);
|
|
110
|
-
|
|
323
|
+
const workflowChildren = parseWorkflowChildSummary(receipt.workflowChildren);
|
|
324
|
+
if (workflowChildren && workflowChildren.workflowRunId !== workflowRunId) throw new Error(`Workflow receipt '${receiptPath}' is stale: workflowChildren.workflowRunId does not match.`);
|
|
325
|
+
let hostSteps: NonNullable<WorkflowReceipt["hostSteps"]> | undefined;
|
|
326
|
+
if (receipt.hostSteps !== undefined) {
|
|
327
|
+
if (!Array.isArray(receipt.hostSteps)) throw new Error(`Invalid workflow receipt '${receiptPath}': hostSteps must be an array.`);
|
|
328
|
+
if (receipt.hostSteps.length > HOST_STEP_MAX_COUNT) throw new Error(`Invalid workflow receipt '${receiptPath}': hostSteps exceeds ${HOST_STEP_MAX_COUNT} entries.`);
|
|
329
|
+
hostSteps = receipt.hostSteps.map((hostStep, index) => parseHostStepNode(hostStep, `${receiptPath} hostSteps[${index}]`));
|
|
330
|
+
assertUniqueHostStepIds(hostSteps, receiptPath);
|
|
331
|
+
}
|
|
332
|
+
const workflowResolution = parseWorkflowResolution(receipt.workflowResolution, receiptPath);
|
|
333
|
+
const resource = parseWorkflowResource(receipt.resource, receiptPath);
|
|
334
|
+
const terminalOutcome = parseTerminalOutcome(receipt.terminalOutcome, `Invalid workflow receipt '${receiptPath}': terminalOutcome`);
|
|
335
|
+
const recovery = parseRecovery(receipt.recovery, workflowRunId, entries, receiptPath);
|
|
336
|
+
return { version: 1, workflowRunId, state: receipt.state, createdAt: receipt.createdAt, entries, ...(resource ? { resource } : {}), ...(hostSteps?.length ? { hostSteps } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(workflowResolution ? { workflowResolution } : {}), ...(terminalOutcome ? { terminalOutcome } : {}), ...(recovery ? { recovery } : {}) };
|
|
111
337
|
}
|
|
112
338
|
|
|
113
339
|
export function resolveWorkflowReceiptResumeEntry(input: {
|