@nathanstephenson/flow 0.1.9 → 0.1.10-beta.2
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/README.md +9 -0
- package/build/backend-worker-chunks/chunk-LO7O6NAM.mjs +133 -0
- package/build/backend-worker-chunks/{claude-GTW5KHY5.mjs → claude-COCNALN2.mjs} +76 -8
- package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-HJKTV2TH.mjs} +84 -6
- package/build/backend-worker.mjs +16 -5
- package/dist/backend/claude/index.js +54 -7
- package/dist/backend/claude/session-tools.js +14 -0
- package/dist/backend/fake/index.js +16 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/index.js +41 -4
- package/dist/backend/pi/session-tools.js +21 -0
- package/dist/backend/pi/state.js +16 -1
- package/dist/backend/session-tools.js +27 -0
- package/dist/backend/worker/claude-state.js +22 -0
- package/dist/backend/worker/entry.js +14 -2
- package/dist/backend/worker/index.js +34 -6
- package/dist/backend/worker/protocol.js +1 -1
- package/dist/backend/workflow-tools.js +9 -6
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/client/reduce.js +20 -0
- package/dist/daemon/host.js +218 -12
- package/dist/daemon/runtime.js +8 -0
- package/dist/daemon/session-tool-views.js +22 -0
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder.js +36 -11
- package/dist/daemon/workflow-execution-routes.js +14 -5
- package/dist/daemon/workflow-executions.js +214 -79
- package/dist/daemon/workflow-routes.js +39 -0
- package/dist/protocol/events.js +2 -0
- package/dist/workflows/calls.js +50 -0
- package/dist/workflows/graph.js +78 -4
- package/dist/workflows/invocations.js +20 -0
- package/dist/workflows/records.js +142 -8
- package/dist/workflows/recovery.js +87 -2
- package/dist/workflows/scheduler.js +348 -80
- package/dist/workflows/schema.js +2 -0
- package/package.json +1 -1
- package/web/dist/assets/index-CLdr6AA0.js +40 -0
- package/web/dist/assets/index-DHAcGIoF.css +2 -0
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-sebWClE0.js} +1 -1
- package/web/dist/assets/settings-workflows-BvArjkes.js +23 -0
- package/web/dist/assets/workflow-editors-Tztq_Opa.js +139 -0
- package/web/dist/assets/workflows-CdDynCfW.js +7 -0
- package/web/dist/assets/workflows-pane-DaqHEeXu.js +1 -0
- package/web/dist/index.html +3 -3
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
- package/web/dist/assets/index-DRfeO6GJ.js +0 -40
- package/web/dist/assets/index-DgQFpKbn.css +0 -2
- package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
- package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
- package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
- package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
|
@@ -1,10 +1,48 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { deriveResultSchema } from "../workflows/calls.js";
|
|
1
3
|
import { validSecretName } from "../protocol/secrets.js";
|
|
2
4
|
import { validateDefinition } from "../workflows/graph.js";
|
|
5
|
+
export function workflowCatalogue(workflows) {
|
|
6
|
+
const entries = [];
|
|
7
|
+
const errors = [];
|
|
8
|
+
for (const definition of workflows.listDefinitions()) {
|
|
9
|
+
try {
|
|
10
|
+
entries.push({ id: definition.id, name: definition.name, backend: definition.backend, projectId: definition.projectId, contract: { inputSchema: definition.inputSchema, outputSchema: deriveResultSchema(definition) } });
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
errors.push({ id: definition.id, name: definition.name, message: 'Saved Workflow Definition is invalid' });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return { workflows: entries, errors };
|
|
17
|
+
}
|
|
18
|
+
function validateWorkflowContracts(definition, workflows) {
|
|
19
|
+
let original;
|
|
20
|
+
try {
|
|
21
|
+
original = workflows.getDefinition(definition.id);
|
|
22
|
+
}
|
|
23
|
+
catch { }
|
|
24
|
+
const catalogue = workflowCatalogue(workflows).workflows;
|
|
25
|
+
for (const step of definition.steps) {
|
|
26
|
+
if (step.kind !== 'workflow')
|
|
27
|
+
continue;
|
|
28
|
+
const retained = original?.steps.find((candidate) => candidate.id === step.id && candidate.kind === 'workflow');
|
|
29
|
+
if (retained?.workflowId === step.workflowId && isDeepStrictEqual(retained.contract, step.contract))
|
|
30
|
+
continue;
|
|
31
|
+
const selected = catalogue.find(item => item.id === step.workflowId && item.backend === definition.backend);
|
|
32
|
+
if (!selected || !isDeepStrictEqual(selected.contract, step.contract))
|
|
33
|
+
throw new Error(`Workflow step ${step.name} requires a saved host-derived contract`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
3
36
|
export function workflowRequestError(error, redact = message => message) {
|
|
4
37
|
// Redact before truncation: a credential containing ':' must not leak its prefix.
|
|
5
38
|
return error instanceof Error && error.name !== 'ZodError' && error.name !== 'SyntaxError' && error.message ? redact(error.message).split(':')[0] : 'Invalid workflow request';
|
|
6
39
|
}
|
|
7
40
|
export async function workflowRoutes(request, response, pathname, workflows, secrets, executions) {
|
|
41
|
+
if (pathname === '/api/workflow-catalogue') {
|
|
42
|
+
response.writeHead(!workflows ? 404 : request.method === 'GET' ? 200 : 405, { 'content-type': 'application/json' });
|
|
43
|
+
response.end(JSON.stringify(!workflows ? { error: 'Not available' } : request.method === 'GET' ? workflowCatalogue(workflows) : { error: 'Method not allowed' }));
|
|
44
|
+
return true;
|
|
45
|
+
}
|
|
8
46
|
const match = /^\/api\/(workflows|secrets)(?:\/(.*))?$/.exec(pathname);
|
|
9
47
|
if (!match)
|
|
10
48
|
return false;
|
|
@@ -81,6 +119,7 @@ export async function workflowRoutes(request, response, pathname, workflows, sec
|
|
|
81
119
|
let definition;
|
|
82
120
|
try {
|
|
83
121
|
definition = validateDefinition(body).definition;
|
|
122
|
+
validateWorkflowContracts(definition, workflows);
|
|
84
123
|
executions?.validateDefinitionCredentials(definition);
|
|
85
124
|
if (definition.id !== id)
|
|
86
125
|
throw new Error();
|
package/dist/protocol/events.js
CHANGED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { validateDefinition } from "./graph.js";
|
|
2
|
+
function canonical(value) {
|
|
3
|
+
if (Array.isArray(value))
|
|
4
|
+
return value.map(canonical);
|
|
5
|
+
if (value !== null && typeof value === 'object')
|
|
6
|
+
return Object.fromEntries(Object.entries(value).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, canonical(value)]));
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
export function deriveResultSchema(definition) {
|
|
10
|
+
return validateDefinition(definition).resultSchema;
|
|
11
|
+
}
|
|
12
|
+
export function resolveWorkflowCalls(definition, lookup, testStepId) {
|
|
13
|
+
const retained = new Map();
|
|
14
|
+
const visited = new Set();
|
|
15
|
+
const visit = (candidate, ancestry, selected) => {
|
|
16
|
+
if (ancestry.has(candidate.id))
|
|
17
|
+
throw new Error(`Recursive Workflow call: ${candidate.id}`);
|
|
18
|
+
const graph = validateDefinition(candidate);
|
|
19
|
+
const current = graph.definition;
|
|
20
|
+
if (selected !== undefined && !current.steps.some(step => step.id === selected))
|
|
21
|
+
throw new Error('Unknown test step');
|
|
22
|
+
retained.set(current.id, current);
|
|
23
|
+
const path = new Set([...ancestry, current.id]);
|
|
24
|
+
for (const step of current.steps) {
|
|
25
|
+
if (step.kind !== 'workflow' || (selected !== undefined && step.id !== selected))
|
|
26
|
+
continue;
|
|
27
|
+
if (path.has(step.workflowId))
|
|
28
|
+
throw new Error(`Recursive Workflow call: ${step.workflowId}`);
|
|
29
|
+
let target = retained.get(step.workflowId);
|
|
30
|
+
if (!target) {
|
|
31
|
+
try {
|
|
32
|
+
target = lookup(step.workflowId);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw new Error(`Missing Workflow call target: ${step.workflowId}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
if (!target || target.id !== step.workflowId)
|
|
39
|
+
throw new Error(`Missing Workflow call target: ${step.workflowId}`);
|
|
40
|
+
const called = validateDefinition(target);
|
|
41
|
+
if (JSON.stringify(canonical(step.contract.inputSchema)) !== JSON.stringify(canonical(called.definition.inputSchema)) || JSON.stringify(canonical(step.contract.outputSchema)) !== JSON.stringify(canonical(called.resultSchema)))
|
|
42
|
+
throw new Error(`Workflow call contract does not match target: ${step.workflowId}`);
|
|
43
|
+
if (!visited.has(target.id))
|
|
44
|
+
visit(called.definition, path);
|
|
45
|
+
}
|
|
46
|
+
visited.add(current.id);
|
|
47
|
+
};
|
|
48
|
+
visit(definition, new Set(), testStepId);
|
|
49
|
+
return Object.fromEntries(retained);
|
|
50
|
+
}
|
package/dist/workflows/graph.js
CHANGED
|
@@ -4,7 +4,7 @@ import { z } from 'zod';
|
|
|
4
4
|
import { validSecretName } from "../protocol/secrets.js";
|
|
5
5
|
import { Decisions } from "./decisions.js";
|
|
6
6
|
import { analyzeLoops } from "./loops.js";
|
|
7
|
-
import { dictionaryKey, dictionaryRecord, declaredOutputSchema, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
|
|
7
|
+
import { dictionaryKey, dictionaryRecord, declaredOutputSchema, parseValue, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
|
|
8
8
|
const reference = z.discriminatedUnion('source', [
|
|
9
9
|
z.object({ source: z.literal('input'), path: z.array(z.string()) }).strict(),
|
|
10
10
|
z.object({ source: z.literal('step'), stepId: z.string(), path: z.array(z.string()) }).strict(),
|
|
@@ -37,12 +37,19 @@ export const workflowDefinitionValidator = z.object({
|
|
|
37
37
|
z.object({ ...base, kind: z.literal('typescript'), code: z.string(), outputSchema: visualSchemaValidator }).strict(),
|
|
38
38
|
z.object({ ...base, kind: z.literal('branch'), condition }).strict(),
|
|
39
39
|
z.object({ ...base, kind: z.literal('join') }).strict(),
|
|
40
|
+
z.object({ ...base, kind: z.literal('workflow'), workflowId: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), contract: z.object({ inputSchema: visualSchemaValidator.refine(schema => schema.type === 'object'), outputSchema: visualSchemaValidator }).strict() }).strict(),
|
|
40
41
|
z.object({ ...base, kind: z.literal('mcp'), tool: z.object({ connectionId: z.string().min(1), connectionName: z.string(), identity: z.string().regex(/^[a-f0-9]{64}$/), serverIdentity: z.string().regex(/^[a-f0-9]{64}$/), toolName: z.string().min(1), inputSchema: originalSchema, outputSchema: originalSchema.optional() }).strict() }).strict(),
|
|
41
42
|
])).min(1),
|
|
42
43
|
loopSettings: dictionaryRecord(z.object({ maxTries: z.number().int().min(1).max(100) }).strict()).optional(),
|
|
43
44
|
edges: z.array(z.object({ id: z.string().min(1), from: z.string(), to: z.string(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']) }).strict()),
|
|
44
45
|
}).strict();
|
|
45
46
|
export function validateDefinition(value) {
|
|
47
|
+
return buildGraph(value);
|
|
48
|
+
}
|
|
49
|
+
export function mappingSourceGraph(value) {
|
|
50
|
+
return buildGraph(value, true);
|
|
51
|
+
}
|
|
52
|
+
function buildGraph(value, mappingSources = false) {
|
|
46
53
|
const definition = workflowDefinitionValidator.parse(value);
|
|
47
54
|
const skillStep = definition.steps.find(step => step.kind === 'agent' && leadingSkillInvocation(step.instructions));
|
|
48
55
|
if (skillStep && !definition.projectId) {
|
|
@@ -167,7 +174,31 @@ export function validateDefinition(value) {
|
|
|
167
174
|
node.items.forEach(inspect);
|
|
168
175
|
};
|
|
169
176
|
inspect(mapping.template);
|
|
170
|
-
|
|
177
|
+
const infer = (node) => {
|
|
178
|
+
if (node.kind === 'reference')
|
|
179
|
+
return referenceSchema(node.reference).schema;
|
|
180
|
+
if (node.kind === 'object')
|
|
181
|
+
return { type: 'object', fields: Object.fromEntries(Object.entries(node.fields).map(([key, value]) => [key, { schema: infer(value), required: true }])) };
|
|
182
|
+
if (node.kind === 'array')
|
|
183
|
+
return { type: 'array', items: node.items.length ? unionSchema(node.items.map(infer)) : { type: 'json' } };
|
|
184
|
+
const literal = (value) => {
|
|
185
|
+
if (value === null)
|
|
186
|
+
return { type: 'null' };
|
|
187
|
+
if (typeof value === 'string')
|
|
188
|
+
return { type: 'enum', values: [value] };
|
|
189
|
+
if (typeof value === 'number')
|
|
190
|
+
return { type: 'number', integer: Number.isInteger(value) };
|
|
191
|
+
if (typeof value === 'boolean')
|
|
192
|
+
return { type: 'boolean' };
|
|
193
|
+
if (Array.isArray(value))
|
|
194
|
+
return { type: 'array', items: value.length ? unionSchema(value.map(literal)) : { type: 'json' } };
|
|
195
|
+
return { type: 'object', fields: Object.fromEntries(Object.entries(value).map(([key, value]) => [key, { schema: literal(value), required: true }])) };
|
|
196
|
+
};
|
|
197
|
+
return literal(node.value);
|
|
198
|
+
};
|
|
199
|
+
input = step.kind === 'workflow' ? infer(mapping.template) : { type: 'json' };
|
|
200
|
+
if (step.kind === 'workflow' && !mappingSources && mapping.template.kind === 'literal')
|
|
201
|
+
parseValue(step.contract.inputSchema, mapping.template.value);
|
|
171
202
|
}
|
|
172
203
|
else if (mapping?.kind === 'reference') {
|
|
173
204
|
const field = referenceSchema(mapping.reference);
|
|
@@ -198,9 +229,16 @@ export function validateDefinition(value) {
|
|
|
198
229
|
}
|
|
199
230
|
if (step.inputSchema) {
|
|
200
231
|
validateSchema(step.inputSchema);
|
|
201
|
-
if (!schemaAssignable(input, step.inputSchema))
|
|
232
|
+
if (!(mappingSources && step.kind === 'workflow') && !schemaAssignable(input, step.inputSchema))
|
|
202
233
|
throw new Error('Input does not match the declared input schema');
|
|
203
234
|
}
|
|
235
|
+
if (step.kind === 'workflow') {
|
|
236
|
+
validateSchema(step.contract.inputSchema);
|
|
237
|
+
validateSchema(step.contract.outputSchema);
|
|
238
|
+
if (!mappingSources && (!schemaAssignable(input, step.contract.inputSchema) || (step.inputSchema && !schemaAssignable(step.inputSchema, step.contract.inputSchema))))
|
|
239
|
+
throw new Error('Input does not match the Workflow call input contract');
|
|
240
|
+
return step.contract.inputSchema;
|
|
241
|
+
}
|
|
204
242
|
return step.inputSchema ?? input;
|
|
205
243
|
};
|
|
206
244
|
const inputFor = (id) => {
|
|
@@ -235,7 +273,43 @@ export function validateDefinition(value) {
|
|
|
235
273
|
}
|
|
236
274
|
outputFor(step.id);
|
|
237
275
|
}
|
|
238
|
-
|
|
276
|
+
const terminalConditions = order.map(step => decisions.and(completed.get(step.id), decisions.not(any(outgoing.get(step.id).map(edge => selectedEdges.get(edge.id))))));
|
|
277
|
+
let finished = 1;
|
|
278
|
+
for (const step of order) {
|
|
279
|
+
const handled = any(outgoing.get(step.id).filter(edge => edge.outcome === 'failure' || edge.outcome === 'timeout').map(edge => selectedEdges.get(edge.id)));
|
|
280
|
+
finished = decisions.and(finished, decisions.or(decisions.not(reaches.get(step.id)), decisions.or(completed.get(step.id), handled)));
|
|
281
|
+
if (loops.length)
|
|
282
|
+
finished = decisions.and(finished, decisions.not(any(outgoing.get(step.id).filter(edge => backIds.has(edge.id)).map(edge => selectedEdges.get(edge.id)))));
|
|
283
|
+
}
|
|
284
|
+
const candidates = order.map((step, index) => ({ step, condition: terminalConditions[index] })).filter(({ condition }) => decisions.and(finished, condition) !== 0);
|
|
285
|
+
const variants = [];
|
|
286
|
+
let none = 1;
|
|
287
|
+
let one = 0;
|
|
288
|
+
let many = 0;
|
|
289
|
+
for (const { condition } of candidates) {
|
|
290
|
+
many = decisions.or(many, decisions.and(one, condition));
|
|
291
|
+
one = decisions.or(decisions.and(one, decisions.not(condition)), decisions.and(none, condition));
|
|
292
|
+
none = decisions.and(none, decisions.not(condition));
|
|
293
|
+
}
|
|
294
|
+
if (loops.length || definition.edges.some(edge => edge.outcome === 'failure' || edge.outcome === 'timeout')) {
|
|
295
|
+
const possible = order.filter(step => step.kind === 'branch'
|
|
296
|
+
? ['true', 'false'].some(outcome => !outgoing.get(step.id).some(edge => edge.outcome === outcome))
|
|
297
|
+
: !outgoing.get(step.id).some(edge => edge.outcome === 'success'));
|
|
298
|
+
variants.push(...possible.map(step => outputFor(step.id)));
|
|
299
|
+
if (possible.length > 1)
|
|
300
|
+
variants.push({ type: 'object', fields: Object.fromEntries(possible.map(step => [step.name, { schema: outputFor(step.id) }])) });
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
for (const { step, condition } of candidates)
|
|
304
|
+
if (decisions.and(finished, decisions.and(one, condition)) !== 0)
|
|
305
|
+
variants.push(outputFor(step.id));
|
|
306
|
+
const multiple = decisions.and(finished, many);
|
|
307
|
+
if (multiple !== 0)
|
|
308
|
+
variants.push({ type: 'object', fields: Object.fromEntries(candidates.filter(({ condition }) => decisions.and(multiple, condition) !== 0).map(({ step, condition }) => [step.name, { schema: outputFor(step.id), required: decisions.implies(multiple, condition) }])) });
|
|
309
|
+
if (decisions.and(finished, none) !== 0)
|
|
310
|
+
variants.push({ type: 'object', fields: {} });
|
|
311
|
+
}
|
|
312
|
+
return { ...graph, resultSchema: variants.length ? unionSchema(variants) : { type: 'json' } };
|
|
239
313
|
}
|
|
240
314
|
export function recoverySchema(input, output) {
|
|
241
315
|
return { type: 'object', fields: {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export function invocationExecution(root, invocationId) {
|
|
2
|
+
const invocation = root.invocations?.[invocationId];
|
|
3
|
+
if (!invocation)
|
|
4
|
+
throw new Error('Unknown workflow invocation');
|
|
5
|
+
const retained = root.retainedDefinitions?.[invocation.definitionId];
|
|
6
|
+
if (!retained)
|
|
7
|
+
throw new Error('Missing retained Workflow Definition');
|
|
8
|
+
const definition = structuredClone(retained);
|
|
9
|
+
for (const correction of invocation.definitionUpdates ?? []) {
|
|
10
|
+
const index = definition.steps.findIndex(step => step.id === correction.stepId);
|
|
11
|
+
if (index < 0)
|
|
12
|
+
throw new Error('Invalid invocation correction');
|
|
13
|
+
definition.steps[index] = structuredClone(correction.nextStep);
|
|
14
|
+
}
|
|
15
|
+
return { ...structuredClone(invocation), version: 1, sessionId: root.sessionId, scope: root.scope, definition };
|
|
16
|
+
}
|
|
17
|
+
export function invocationCheckpoint(record, ownership) {
|
|
18
|
+
const { version: _, sessionId: __, scope: ___, definition: ____, ...state } = record;
|
|
19
|
+
return { ...state, ...ownership };
|
|
20
|
+
}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
import { boundedMcpValue, validateMcpOutput } from "./mcp.js";
|
|
2
2
|
import { z } from 'zod';
|
|
3
3
|
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { resolveWorkflowCalls } from "./calls.js";
|
|
5
|
+
import { dictionaryRecord } from "./schema.js";
|
|
4
6
|
import { validateDefinition, workflowDefinitionValidator } from "./graph.js";
|
|
7
|
+
import { validateCompatibleDefinition } from "./recovery.js";
|
|
5
8
|
const errorValidator = z.object({ message: z.string(), kind: z.enum(['failure', 'timeout', 'interrupted']) }).strict();
|
|
6
9
|
const identityValidator = z.object({ headerId: z.string().min(1), activation: z.number().int().positive(), try: z.number().int().positive() }).strict();
|
|
7
10
|
const loopValidator = z.object({
|
|
@@ -11,24 +14,56 @@ const loopValidator = z.object({
|
|
|
11
14
|
}).strict();
|
|
12
15
|
const attemptValidator = z.object({
|
|
13
16
|
loops: z.array(identityValidator).optional(),
|
|
14
|
-
number: z.number().int().positive(), action: z.enum(['execute', 'retry', 'supply']), startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(),
|
|
17
|
+
number: z.number().int().positive(), action: z.enum(['execute', 'retry', 'supply']), startedAt: z.number().nonnegative(), deadlineAt: z.number().nonnegative().optional(), finishedAt: z.number().nonnegative().optional(),
|
|
15
18
|
input: z.json(), output: z.json().optional(), partialOutput: z.json().optional(), error: errorValidator.optional(),
|
|
16
19
|
}).strict();
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
+
const checkpointFields = {
|
|
21
|
+
definitionUpdates: z.array(z.object({
|
|
22
|
+
stepId: z.string().min(1), previousStep: workflowDefinitionValidator.shape.steps.element, nextStep: workflowDefinitionValidator.shape.steps.element,
|
|
23
|
+
appliedAt: z.number().nonnegative(), attempt: z.number().int().min(2),
|
|
24
|
+
}).strict()).optional(),
|
|
25
|
+
input: z.json(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
|
|
20
26
|
startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(), result: z.json().optional(),
|
|
21
|
-
loops:
|
|
22
|
-
steps:
|
|
27
|
+
loops: dictionaryRecord(loopValidator).optional(),
|
|
28
|
+
steps: dictionaryRecord(z.object({
|
|
23
29
|
status: z.enum(['pending', 'running', 'completed', 'failed', 'timed-out', 'interrupted', 'skipped', 'blocked', 'cancelled']), recovery: z.boolean().optional(),
|
|
24
30
|
attempts: z.array(attemptValidator), output: z.json().optional(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']).optional(),
|
|
25
31
|
}).strict()),
|
|
32
|
+
};
|
|
33
|
+
const invocationValidator = z.object({
|
|
34
|
+
...checkpointFields, id: z.string().min(1), parentInvocationId: z.string().min(1).optional(),
|
|
35
|
+
callStepId: z.string().min(1), callAttempt: z.number().int().positive(), definitionId: z.string().min(1),
|
|
26
36
|
}).strict();
|
|
27
|
-
export
|
|
28
|
-
|
|
37
|
+
export const workflowExecutionValidator = z.object({
|
|
38
|
+
...checkpointFields, version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
|
|
39
|
+
retainedDefinitions: z.preprocess(value => value && typeof value === 'object' && !Array.isArray(value) ? new Map(Object.entries(value)) : value, z.map(workflowDefinitionValidator.shape.id, workflowDefinitionValidator)).transform(entries => Object.fromEntries(entries)).optional(),
|
|
40
|
+
invocations: dictionaryRecord(invocationValidator).optional(),
|
|
41
|
+
launchId: z.string().min(1).optional(), naming: z.enum(['pending', 'requested']).optional(), testStepId: z.string().optional(),
|
|
42
|
+
}).strict();
|
|
43
|
+
function validateCheckpoint(record) {
|
|
29
44
|
const graph = validateDefinition(record.definition);
|
|
30
45
|
if (graph.order.length !== Object.keys(record.steps).length || graph.order.some(step => !Object.hasOwn(record.steps, step.id)))
|
|
31
46
|
throw new Error('Execution steps do not match the definition');
|
|
47
|
+
// Walk corrections backwards to validate both their contracts and the snapshot chain.
|
|
48
|
+
// The checkpoint before pump may name the next attempt before it has been appended.
|
|
49
|
+
let definition = record.definition;
|
|
50
|
+
const nextAttempts = new Map();
|
|
51
|
+
for (const update of [...(record.definitionUpdates ?? [])].reverse()) {
|
|
52
|
+
const state = record.steps[update.stepId];
|
|
53
|
+
const next = definition.steps.find(step => step.id === update.stepId);
|
|
54
|
+
if (!state || update.previousStep.id !== update.stepId || !isDeepStrictEqual(next, update.nextStep))
|
|
55
|
+
throw new Error('Invalid definition update snapshot');
|
|
56
|
+
if (update.attempt > state.attempts.length + 1 || (nextAttempts.has(update.stepId) && update.attempt > nextAttempts.get(update.stepId)))
|
|
57
|
+
throw new Error('Invalid definition update attempt');
|
|
58
|
+
const attempt = state.attempts[update.attempt - 1];
|
|
59
|
+
if ((attempt && attempt.action !== 'retry') || !state.attempts[update.attempt - 2]?.error)
|
|
60
|
+
throw new Error('Definition update requires a failed retry attempt');
|
|
61
|
+
nextAttempts.set(update.stepId, update.attempt);
|
|
62
|
+
const previous = { ...definition, steps: definition.steps.map(step => step.id === update.stepId ? update.previousStep : step) };
|
|
63
|
+
validateCompatibleDefinition(previous, definition, update.stepId);
|
|
64
|
+
definition = previous;
|
|
65
|
+
}
|
|
66
|
+
const original = definition;
|
|
32
67
|
if (record.testStepId && !Object.hasOwn(record.steps, record.testStepId))
|
|
33
68
|
throw new Error('Unknown test step');
|
|
34
69
|
if (record.testStepId && record.naming)
|
|
@@ -76,6 +111,11 @@ export function parseExecution(value) {
|
|
|
76
111
|
}
|
|
77
112
|
const containing = loops.filter(loop => loop.memberIds.includes(id));
|
|
78
113
|
for (const [index, attempt] of step.attempts.entries()) {
|
|
114
|
+
if (attempt.deadlineAt !== undefined) {
|
|
115
|
+
const configuration = stepConfiguration(record, original, id, attempt.number);
|
|
116
|
+
if (configuration?.kind !== 'workflow' || configuration.timeoutMs === undefined || attempt.deadlineAt !== attempt.startedAt + configuration.timeoutMs)
|
|
117
|
+
throw new Error('Invalid call attempt deadline');
|
|
118
|
+
}
|
|
79
119
|
if ((attempt.loops ?? []).length !== containing.length || containing.some(loop => !attempt.loops?.some(identity => identity.headerId === loop.headerId)))
|
|
80
120
|
throw new Error('Invalid attempt loop identities');
|
|
81
121
|
if (containing.length && index === 0 && attempt.action !== 'execute')
|
|
@@ -109,5 +149,99 @@ export function parseExecution(value) {
|
|
|
109
149
|
}
|
|
110
150
|
if (['completed', 'completed-with-recovery'].includes(record.status) && Object.values(record.steps).some(step => ['pending', 'running', 'interrupted', 'blocked'].includes(step.status)))
|
|
111
151
|
throw new Error('Completed execution contains unfinished work');
|
|
152
|
+
return original;
|
|
153
|
+
}
|
|
154
|
+
function stepConfiguration(record, original, stepId, attempt) {
|
|
155
|
+
let step = original.steps.find(step => step.id === stepId);
|
|
156
|
+
for (const update of record.definitionUpdates ?? [])
|
|
157
|
+
if (update.stepId === stepId && update.attempt <= attempt)
|
|
158
|
+
step = update.nextStep;
|
|
159
|
+
return step;
|
|
160
|
+
}
|
|
161
|
+
export function parseExecution(value) {
|
|
162
|
+
const record = workflowExecutionValidator.parse(value);
|
|
163
|
+
const original = validateCheckpoint(record);
|
|
164
|
+
const manifest = record.retainedDefinitions;
|
|
165
|
+
if (!manifest) {
|
|
166
|
+
if (record.invocations || record.definition.steps.some(step => step.kind === 'workflow'))
|
|
167
|
+
throw new Error('Missing retained Workflow Definitions');
|
|
168
|
+
return record;
|
|
169
|
+
}
|
|
170
|
+
for (const [id, definition] of Object.entries(manifest))
|
|
171
|
+
if (id !== definition.id)
|
|
172
|
+
throw new Error('Invalid retained definition identity');
|
|
173
|
+
if (!isDeepStrictEqual(manifest[original.id], original))
|
|
174
|
+
throw new Error('Retained root definition does not match the original checkpoint');
|
|
175
|
+
const resolved = resolveWorkflowCalls(original, id => {
|
|
176
|
+
if (!Object.hasOwn(manifest, id))
|
|
177
|
+
throw new Error('Missing retained definition');
|
|
178
|
+
return manifest[id];
|
|
179
|
+
}, record.testStepId);
|
|
180
|
+
if (!isDeepStrictEqual(resolved, manifest))
|
|
181
|
+
throw new Error('Retained definitions do not match the call manifest');
|
|
182
|
+
const locals = new Map();
|
|
183
|
+
const originals = new Map();
|
|
184
|
+
for (const [id, invocation] of Object.entries(record.invocations ?? {})) {
|
|
185
|
+
if (id !== invocation.id || id === record.id)
|
|
186
|
+
throw new Error('Invalid invocation identity');
|
|
187
|
+
const retained = manifest[invocation.definitionId];
|
|
188
|
+
if (!retained)
|
|
189
|
+
throw new Error('Missing invocation definition');
|
|
190
|
+
const definition = structuredClone(retained);
|
|
191
|
+
for (const update of invocation.definitionUpdates ?? []) {
|
|
192
|
+
const index = definition.steps.findIndex(step => step.id === update.stepId);
|
|
193
|
+
if (index < 0)
|
|
194
|
+
throw new Error('Unknown invocation correction step');
|
|
195
|
+
definition.steps[index] = structuredClone(update.nextStep);
|
|
196
|
+
}
|
|
197
|
+
const local = { ...invocation, version: 1, sessionId: record.sessionId, scope: record.scope, definition };
|
|
198
|
+
if (!isDeepStrictEqual(validateCheckpoint(local), retained))
|
|
199
|
+
throw new Error('Invocation corrections do not match the retained definition');
|
|
200
|
+
locals.set(id, local);
|
|
201
|
+
originals.set(id, retained);
|
|
202
|
+
}
|
|
203
|
+
const checked = new Set();
|
|
204
|
+
for (const id of locals.keys()) {
|
|
205
|
+
const path = new Set();
|
|
206
|
+
let current = id;
|
|
207
|
+
while (current !== undefined && !checked.has(current)) {
|
|
208
|
+
if (path.has(current))
|
|
209
|
+
throw new Error('Invocation parent cycle');
|
|
210
|
+
path.add(current);
|
|
211
|
+
const invocation = record.invocations[current];
|
|
212
|
+
if (!invocation)
|
|
213
|
+
throw new Error('Missing parent invocation');
|
|
214
|
+
current = invocation.parentInvocationId;
|
|
215
|
+
}
|
|
216
|
+
for (const ancestor of path)
|
|
217
|
+
checked.add(ancestor);
|
|
218
|
+
}
|
|
219
|
+
const owners = new Set();
|
|
220
|
+
for (const [id, invocation] of Object.entries(record.invocations ?? {})) {
|
|
221
|
+
const parentId = invocation.parentInvocationId;
|
|
222
|
+
const parent = parentId === undefined ? record : locals.get(parentId);
|
|
223
|
+
const parentOriginal = parentId === undefined ? original : originals.get(parentId);
|
|
224
|
+
const step = stepConfiguration(parent, parentOriginal, invocation.callStepId, invocation.callAttempt);
|
|
225
|
+
const state = parent.steps[invocation.callStepId];
|
|
226
|
+
const attempt = state?.attempts[invocation.callAttempt - 1];
|
|
227
|
+
if (step?.kind !== 'workflow' || step.workflowId !== invocation.definitionId || !attempt || attempt.action === 'supply' || (parent.testStepId !== undefined && parent.testStepId !== step.id))
|
|
228
|
+
throw new Error('Invalid invocation call ownership');
|
|
229
|
+
if (!isDeepStrictEqual(invocation.input, attempt.input))
|
|
230
|
+
throw new Error('Invocation input does not match the call attempt');
|
|
231
|
+
if (step.timeoutMs !== undefined && attempt.deadlineAt === undefined)
|
|
232
|
+
throw new Error('Missing call attempt deadline');
|
|
233
|
+
if (invocation.callAttempt < state.attempts.length && ['running', 'recovery-required'].includes(invocation.status))
|
|
234
|
+
throw new Error('Unfinished invocation belongs to an earlier call attempt');
|
|
235
|
+
const owner = JSON.stringify([parentId ?? null, invocation.callStepId, invocation.callAttempt]);
|
|
236
|
+
if (owners.has(owner))
|
|
237
|
+
throw new Error('Duplicate invocation call ownership');
|
|
238
|
+
owners.add(owner);
|
|
239
|
+
if (['completed', 'completed-with-recovery'].includes(invocation.status) && invocation.result === undefined)
|
|
240
|
+
throw new Error('Missing completed invocation result');
|
|
241
|
+
if (['completed', 'completed-with-recovery'].includes(record.status) && ['running', 'recovery-required'].includes(invocation.status))
|
|
242
|
+
throw new Error('Completed execution contains unfinished invocations');
|
|
243
|
+
if (!locals.has(id))
|
|
244
|
+
throw new Error('Missing invocation checkpoint');
|
|
245
|
+
}
|
|
112
246
|
return record;
|
|
113
247
|
}
|
|
@@ -1,15 +1,100 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { validateDefinition } from "./graph.js";
|
|
4
|
+
import { invocationExecution } from "./invocations.js";
|
|
5
|
+
// Object key order is not part of a saved definition's identity; array order is.
|
|
6
|
+
function canonical(value) {
|
|
7
|
+
if (Array.isArray(value))
|
|
8
|
+
return value.map(canonical);
|
|
9
|
+
if (value !== null && typeof value === 'object')
|
|
10
|
+
return Object.fromEntries(Object.entries(value).filter(([, value]) => value !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, value]) => [key, canonical(value)]));
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
/** Authority over exactly the saved definition resolved by the host. Not recoveryRevision. */
|
|
14
|
+
export function savedDefinitionRevision(definition) {
|
|
15
|
+
return createHash('sha256').update(JSON.stringify(canonical(definition))).digest('hex');
|
|
16
|
+
}
|
|
17
|
+
function fixedStep(step) {
|
|
18
|
+
// An allowlist keeps future contracts and policy fields immutable by default.
|
|
19
|
+
const configurable = new Set(['timeoutMs', 'secrets']);
|
|
20
|
+
if (step.kind === 'agent')
|
|
21
|
+
['instructions', 'model', 'effort'].forEach(key => configurable.add(key));
|
|
22
|
+
if (step.kind === 'shell')
|
|
23
|
+
['command', 'acceptedExitCodes'].forEach(key => configurable.add(key));
|
|
24
|
+
if (step.kind === 'typescript')
|
|
25
|
+
configurable.add('code');
|
|
26
|
+
if (step.kind === 'branch')
|
|
27
|
+
configurable.add('condition');
|
|
28
|
+
// MCP tool snapshots include identity and schemas, so they remain fixed.
|
|
29
|
+
return Object.fromEntries(Object.entries(step).filter(([key]) => !configurable.has(key)));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Pure host preflight: validate the candidate and allow executable config edits only on stepId.
|
|
33
|
+
* Eligibility, runtime readiness and saved-definition authority are checked by recover itself.
|
|
34
|
+
* Names, positions, permissions, contracts, mappings, tool snapshots and topology stay fixed.
|
|
35
|
+
*/
|
|
36
|
+
export function validateCompatibleDefinition(previous, candidate, stepId) {
|
|
37
|
+
const graph = validateDefinition(candidate);
|
|
38
|
+
const old = validateDefinition(previous).definition;
|
|
39
|
+
const target = old.steps.find(step => step.id === stepId);
|
|
40
|
+
const next = graph.definition.steps.find(step => step.id === stepId);
|
|
41
|
+
if (!target || !next)
|
|
42
|
+
throw new Error('Unknown recovery step');
|
|
43
|
+
if (!isDeepStrictEqual(fixedStep(target), fixedStep(next)))
|
|
44
|
+
throw new Error('Updated definition changes the recovery step contract or policy');
|
|
45
|
+
const { steps: oldSteps, ...oldRest } = old;
|
|
46
|
+
const { steps: nextSteps, ...nextRest } = graph.definition;
|
|
47
|
+
if (!isDeepStrictEqual(oldRest, nextRest) || !isDeepStrictEqual(oldSteps.map(step => step.id === stepId ? fixedStep(step) : step), nextSteps.map(step => step.id === stepId ? fixedStep(step) : step))) {
|
|
48
|
+
throw new Error('Updated definition may change only the recovery step executable configuration');
|
|
49
|
+
}
|
|
50
|
+
return graph;
|
|
51
|
+
}
|
|
52
|
+
export function recoverySteps(root, action, replacement) {
|
|
53
|
+
const steps = [];
|
|
54
|
+
let invocationId = action.invocationId, selected = true;
|
|
55
|
+
for (;;) {
|
|
56
|
+
const current = invocationId === undefined ? root : invocationExecution(root, invocationId);
|
|
57
|
+
const graph = validateDefinition(selected && replacement ? replacement : current.definition);
|
|
58
|
+
const repeating = new Set(current.testStepId ? [] : graph.loops.filter(loop => ['active', 'repeating', 'limit'].includes(current.loops?.[loop.headerId]?.phase ?? 'inactive')).flatMap(loop => loop.memberIds));
|
|
59
|
+
const owned = new Set(Object.values(root.invocations ?? {}).filter(invocation => {
|
|
60
|
+
const call = current.steps[invocation.callStepId];
|
|
61
|
+
return invocation.parentInvocationId === invocationId && call?.status === 'running' && invocation.callAttempt === call.attempts.length;
|
|
62
|
+
}).map(invocation => invocation.callStepId));
|
|
63
|
+
for (const step of graph.order) {
|
|
64
|
+
if (current.testStepId && current.testStepId !== step.id)
|
|
65
|
+
continue;
|
|
66
|
+
if (!repeating.has(step.id)) {
|
|
67
|
+
const state = current.steps[step.id];
|
|
68
|
+
if (!current.testStepId && ['failed', 'timed-out'].includes(state.status) && !state.recovery && graph.outgoing.get(step.id).some(edge => edge.outcome === state.outcome))
|
|
69
|
+
continue;
|
|
70
|
+
if (state.status === 'completed' || owned.has(step.id))
|
|
71
|
+
continue;
|
|
72
|
+
if (selected && action.kind === 'supply' && action.stepId === step.id)
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
steps.push(step);
|
|
76
|
+
}
|
|
77
|
+
if (invocationId === undefined)
|
|
78
|
+
return steps;
|
|
79
|
+
invocationId = root.invocations[invocationId].parentInvocationId;
|
|
80
|
+
selected = false;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
2
83
|
/** State identity, not wall-clock time: repeated notifications cannot mint new authority. */
|
|
3
84
|
export function recoveryRevision(record) {
|
|
4
85
|
return createHash('sha256').update(JSON.stringify({ id: record.id, status: record.status,
|
|
5
86
|
steps: Object.entries(record.steps).map(([id, step]) => [id, step.status, step.attempts.map(a => [a.number, a.action, a.finishedAt, a.error])]),
|
|
6
|
-
loops: record.loops,
|
|
87
|
+
loops: record.loops, definition: savedDefinitionRevision(record.definition), definitionUpdates: record.definitionUpdates,
|
|
88
|
+
invocations: record.invocations, retainedDefinitions: record.retainedDefinitions,
|
|
7
89
|
})).digest('hex');
|
|
8
90
|
}
|
|
9
91
|
export function successfulProgress(record) {
|
|
10
|
-
|
|
92
|
+
const local = (execution) => Object.entries(execution.steps).reduce((count, [id, step]) => count + (execution.definition.steps.find(step => step.id === id)?.kind === 'workflow' ? 0 : step.attempts.filter(a => a.finishedAt !== undefined && a.output !== undefined && !a.error && a.action !== 'supply').length), 0);
|
|
93
|
+
return local(record) + Object.keys(record.invocations ?? {}).reduce((count, id) => count + local(invocationExecution(record, id)), 0);
|
|
11
94
|
}
|
|
12
95
|
export function safeAutomaticRecovery(record, action) {
|
|
96
|
+
if (action.invocationId)
|
|
97
|
+
record = invocationExecution(record, action.invocationId);
|
|
13
98
|
if (record.status !== 'recovery-required' || Object.values(record.loops ?? {}).some(loop => loop.phase === 'limit'))
|
|
14
99
|
return false;
|
|
15
100
|
if (action.kind === 'retry') {
|