@nathanstephenson/flow 0.1.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/README.md +641 -0
- package/build/workflow-runtime.cjs +213964 -0
- package/dist/backend/claude/async-queue.js +44 -0
- package/dist/backend/claude/auto-compaction.js +10 -0
- package/dist/backend/claude/background-calls.js +116 -0
- package/dist/backend/claude/enquiries.js +162 -0
- package/dist/backend/claude/index.js +1138 -0
- package/dist/backend/claude/mcp.js +55 -0
- package/dist/backend/claude/permissions.js +106 -0
- package/dist/backend/claude/streamed-message.js +120 -0
- package/dist/backend/claude/subagents.js +128 -0
- package/dist/backend/claude/workflow-parent.js +12 -0
- package/dist/backend/claude/workflow-processes.js +95 -0
- package/dist/backend/claude/workflow-subagent.js +234 -0
- package/dist/backend/effort.js +30 -0
- package/dist/backend/fake/index.js +570 -0
- package/dist/backend/mcp.js +190 -0
- package/dist/backend/pi/auto-compaction.js +16 -0
- package/dist/backend/pi/background-calls.js +56 -0
- package/dist/backend/pi/enquiries.js +63 -0
- package/dist/backend/pi/index.js +597 -0
- package/dist/backend/pi/mcp.js +35 -0
- package/dist/backend/pi/subagents.js +23 -0
- package/dist/backend/pi/work.js +104 -0
- package/dist/backend/pi/workflow-parent.js +21 -0
- package/dist/backend/pi/workflow-subagent.js +199 -0
- package/dist/backend/registry.js +34 -0
- package/dist/backend/types.js +1 -0
- package/dist/backend/workflow-tools.js +25 -0
- package/dist/build-id +1 -0
- package/dist/cli/application.js +397 -0
- package/dist/cli/bootstrap.js +535 -0
- package/dist/cli/host-control.js +100 -0
- package/dist/cli/install-guard.js +270 -0
- package/dist/cli/install-process.js +52 -0
- package/dist/cli/main.js +12 -0
- package/dist/cli/update.js +128 -0
- package/dist/client/connection.js +183 -0
- package/dist/client/context-usage.js +66 -0
- package/dist/client/diff.js +36 -0
- package/dist/client/enquiry.js +105 -0
- package/dist/client/markdown.js +192 -0
- package/dist/client/model-choices.js +32 -0
- package/dist/client/permission.js +60 -0
- package/dist/client/project-name.js +19 -0
- package/dist/client/reduce.js +463 -0
- package/dist/client/relative-time.js +30 -0
- package/dist/client/scope-kind.js +28 -0
- package/dist/client/search.js +136 -0
- package/dist/client/session-label.js +9 -0
- package/dist/client/status.js +84 -0
- package/dist/client/tool-chains.js +52 -0
- package/dist/client/tool-summary.js +98 -0
- package/dist/daemon/auth.js +590 -0
- package/dist/daemon/config-store.js +183 -0
- package/dist/daemon/config.js +687 -0
- package/dist/daemon/credential-redaction.js +9 -0
- package/dist/daemon/git.js +312 -0
- package/dist/daemon/host-control-routes.js +29 -0
- package/dist/daemon/host.js +2343 -0
- package/dist/daemon/http.js +19 -0
- package/dist/daemon/log.js +44 -0
- package/dist/daemon/mcp-auth.js +164 -0
- package/dist/daemon/models.js +85 -0
- package/dist/daemon/ownership.js +104 -0
- package/dist/daemon/projects.js +317 -0
- package/dist/daemon/publish.js +289 -0
- package/dist/daemon/pull-request.js +198 -0
- package/dist/daemon/runtime.js +100 -0
- package/dist/daemon/secret-store.js +65 -0
- package/dist/daemon/server.js +827 -0
- package/dist/daemon/shell.js +220 -0
- package/dist/daemon/skills.js +104 -0
- package/dist/daemon/stack-metadata.js +24 -0
- package/dist/daemon/stack.js +743 -0
- package/dist/daemon/store.js +130 -0
- package/dist/daemon/summariser.js +476 -0
- package/dist/daemon/workflow-execution-routes.js +105 -0
- package/dist/daemon/workflow-executions.js +1018 -0
- package/dist/daemon/workflow-mcp.js +20 -0
- package/dist/daemon/workflow-routes.js +102 -0
- package/dist/protocol/attachments.js +59 -0
- package/dist/protocol/commands.js +1 -0
- package/dist/protocol/events.js +20 -0
- package/dist/protocol/fonts.js +26 -0
- package/dist/protocol/git.js +12 -0
- package/dist/protocol/mcp.js +51 -0
- package/dist/protocol/projects.js +21 -0
- package/dist/protocol/publish.js +1 -0
- package/dist/protocol/pull-request.js +1 -0
- package/dist/protocol/secrets.js +4 -0
- package/dist/protocol/settings.js +63 -0
- package/dist/protocol/shells.js +8 -0
- package/dist/protocol/skills.js +16 -0
- package/dist/protocol/stack.js +41 -0
- package/dist/protocol/workflow-executions.js +1 -0
- package/dist/protocol/workflows.js +1 -0
- package/dist/tui/app.js +518 -0
- package/dist/tui/keys.js +54 -0
- package/dist/tui/render.js +366 -0
- package/dist/web/assets.js +10 -0
- package/dist/web/embedded.js +12 -0
- package/dist/web/manifest.js +70 -0
- package/dist/workflows/decisions.js +65 -0
- package/dist/workflows/executors.js +132 -0
- package/dist/workflows/graph.js +276 -0
- package/dist/workflows/json-schema.js +49 -0
- package/dist/workflows/loops.js +102 -0
- package/dist/workflows/mcp.js +18 -0
- package/dist/workflows/records.js +111 -0
- package/dist/workflows/recovery.js +25 -0
- package/dist/workflows/runtime-asset.js +17 -0
- package/dist/workflows/runtime-libs.js +1 -0
- package/dist/workflows/runtime-settings.js +23 -0
- package/dist/workflows/runtime.js +343 -0
- package/dist/workflows/scheduler.js +573 -0
- package/dist/workflows/schema.js +161 -0
- package/dist/workflows/store.js +93 -0
- package/package.json +87 -0
- package/web/dist/assets/__vite-browser-external-2447137e-BvRk9kiK.js +0 -0
- package/web/dist/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/web/dist/assets/index-BC0gLS53.js +106 -0
- package/web/dist/assets/index-CCeZYKES.css +2 -0
- package/web/dist/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
- package/web/dist/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
- package/web/dist/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
- package/web/dist/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
- package/web/dist/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
- package/web/dist/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
- package/web/dist/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
- package/web/dist/assets/rolldown-runtime-B0Z9INg1.js +1 -0
- package/web/dist/assets/select-6i3wxovH.js +1 -0
- package/web/dist/assets/settings-mcp-CcT0ADJR.js +1 -0
- package/web/dist/assets/settings-secrets-CK4uF7fd.js +1 -0
- package/web/dist/assets/settings-workflows-CrbZF-nM.js +23 -0
- package/web/dist/assets/switch-ftZleVB8.js +6 -0
- package/web/dist/assets/workflow-editors-naPqAmYO.js +65 -0
- package/web/dist/assets/workflows-D4T4Gy_7.css +1 -0
- package/web/dist/assets/workflows-hh6ioeEA.js +7 -0
- package/web/dist/assets/workflows-pane-Db-MHf7Z.js +1 -0
- package/web/dist/index.html +31 -0
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { compileJsonSchema } from "./json-schema.js";
|
|
2
|
+
import { leadingSkillInvocation } from "../protocol/skills.js";
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { validSecretName } from "../protocol/secrets.js";
|
|
5
|
+
import { Decisions } from "./decisions.js";
|
|
6
|
+
import { analyzeLoops } from "./loops.js";
|
|
7
|
+
import { dictionaryKey, dictionaryRecord, declaredOutputSchema, partialSchema, schemaAssignable, schemaAt, unionSchema, validateSchema, valueAt, visualSchemaValidator } from "./schema.js";
|
|
8
|
+
const reference = z.discriminatedUnion('source', [
|
|
9
|
+
z.object({ source: z.literal('input'), path: z.array(z.string()) }).strict(),
|
|
10
|
+
z.object({ source: z.literal('step'), stepId: z.string(), path: z.array(z.string()) }).strict(),
|
|
11
|
+
]);
|
|
12
|
+
const template = z.lazy(() => z.discriminatedUnion('kind', [
|
|
13
|
+
z.object({ kind: z.literal('literal'), value: z.json() }).strict(),
|
|
14
|
+
z.object({ kind: z.literal('reference'), reference }).strict(),
|
|
15
|
+
z.object({ kind: z.literal('object'), fields: dictionaryRecord(template) }).strict(),
|
|
16
|
+
z.object({ kind: z.literal('array'), items: z.array(template) }).strict(),
|
|
17
|
+
]));
|
|
18
|
+
const originalSchema = z.union([z.boolean(), z.record(z.string(), z.json())]);
|
|
19
|
+
const mapping = z.discriminatedUnion('kind', [z.object({ kind: z.literal('template'), template }).strict(), z.object({ kind: z.literal('reference'), reference }).strict(), z.object({ kind: z.literal('object'), fields: dictionaryRecord(reference) }).strict()]);
|
|
20
|
+
const base = {
|
|
21
|
+
id: dictionaryKey.min(1), name: dictionaryKey.min(1), inputSchema: visualSchemaValidator.optional(),
|
|
22
|
+
mapping: mapping.optional(), repeatMapping: mapping.optional(),
|
|
23
|
+
permission: z.enum(['ask', 'auto-accept']).optional(), timeoutMs: z.number().int().positive().max(2147483647).optional(),
|
|
24
|
+
secrets: dictionaryRecord(z.string().refine(validSecretName, 'Invalid secret reference')).optional(), position: z.object({ x: z.number(), y: z.number() }).strict().optional(),
|
|
25
|
+
};
|
|
26
|
+
const condition = z.discriminatedUnion('operator', [
|
|
27
|
+
z.object({ operator: z.literal('truthy'), path: z.array(z.string()) }).strict(),
|
|
28
|
+
z.object({ operator: z.enum(['equals', 'not-equals']), path: z.array(z.string()), value: z.json() }).strict(),
|
|
29
|
+
z.object({ operator: z.enum(['greater-than', 'less-than']), path: z.array(z.string()), value: z.number() }).strict(),
|
|
30
|
+
]);
|
|
31
|
+
export const workflowDefinitionValidator = z.object({
|
|
32
|
+
version: z.literal(1), id: z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/), name: z.string().min(1), backend: z.string().min(1), projectId: z.string().optional(),
|
|
33
|
+
permission: z.enum(['ask', 'auto-accept']).optional(), inputSchema: visualSchemaValidator.refine(schema => schema.type === 'object'),
|
|
34
|
+
steps: z.array(z.discriminatedUnion('kind', [
|
|
35
|
+
z.object({ ...base, kind: z.literal('agent'), instructions: z.string(), model: z.string().min(1), effort: z.enum(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max']), outputSchema: visualSchemaValidator }).strict(),
|
|
36
|
+
z.object({ ...base, kind: z.literal('shell'), command: z.string(), acceptedExitCodes: z.array(z.number().int()).min(1).optional() }).strict(),
|
|
37
|
+
z.object({ ...base, kind: z.literal('typescript'), code: z.string(), outputSchema: visualSchemaValidator }).strict(),
|
|
38
|
+
z.object({ ...base, kind: z.literal('branch'), condition }).strict(),
|
|
39
|
+
z.object({ ...base, kind: z.literal('join') }).strict(),
|
|
40
|
+
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
|
+
])).min(1),
|
|
42
|
+
loopSettings: dictionaryRecord(z.object({ maxTries: z.number().int().min(1).max(100) }).strict()).optional(),
|
|
43
|
+
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
|
+
}).strict();
|
|
45
|
+
export function validateDefinition(value) {
|
|
46
|
+
const definition = workflowDefinitionValidator.parse(value);
|
|
47
|
+
const skillStep = definition.steps.find(step => step.kind === 'agent' && leadingSkillInvocation(step.instructions));
|
|
48
|
+
if (skillStep && !definition.projectId) {
|
|
49
|
+
throw new Error(`Workflow Step ${JSON.stringify(skillStep.name)} invokes a Skill and requires a Project binding`);
|
|
50
|
+
}
|
|
51
|
+
validateSchema(definition.inputSchema);
|
|
52
|
+
const steps = new Map(definition.steps.map(step => [step.id, step]));
|
|
53
|
+
if (steps.size !== definition.steps.length || new Set(definition.steps.map(step => step.name)).size !== steps.size)
|
|
54
|
+
throw new Error('Step IDs and names must be unique');
|
|
55
|
+
if (new Set(definition.edges.map(edge => edge.id)).size !== definition.edges.length)
|
|
56
|
+
throw new Error('Edge IDs must be unique');
|
|
57
|
+
const incoming = new Map(definition.steps.map(step => [step.id, []]));
|
|
58
|
+
const outgoing = new Map(definition.steps.map(step => [step.id, []]));
|
|
59
|
+
const connections = new Set();
|
|
60
|
+
for (const edge of definition.edges) {
|
|
61
|
+
const source = steps.get(edge.from);
|
|
62
|
+
if (!source || !steps.has(edge.to))
|
|
63
|
+
throw new Error('Unknown edge endpoint');
|
|
64
|
+
const key = JSON.stringify([edge.from, edge.to, edge.outcome]);
|
|
65
|
+
if (connections.has(key))
|
|
66
|
+
throw new Error('Duplicate connection');
|
|
67
|
+
connections.add(key);
|
|
68
|
+
if (source.kind === 'branch' ? !['true', 'false', 'failure', 'timeout'].includes(edge.outcome) : ['true', 'false'].includes(edge.outcome))
|
|
69
|
+
throw new Error('Invalid edge outcome');
|
|
70
|
+
incoming.get(edge.to).push(edge);
|
|
71
|
+
outgoing.get(edge.from).push(edge);
|
|
72
|
+
}
|
|
73
|
+
const topology = analyzeLoops(definition);
|
|
74
|
+
const loops = topology.loops.map(loop => ({ ...loop, maxTries: definition.loopSettings?.[loop.headerId]?.maxTries ?? 3 }));
|
|
75
|
+
const headers = new Map(loops.map(loop => [loop.headerId, loop]));
|
|
76
|
+
for (const id of Object.keys(definition.loopSettings ?? {}))
|
|
77
|
+
if (!headers.has(id))
|
|
78
|
+
throw new Error('Loop settings require a loop header');
|
|
79
|
+
for (const step of steps.values())
|
|
80
|
+
if (step.repeatMapping && !headers.has(step.id))
|
|
81
|
+
throw new Error('Repeat mapping requires a loop header');
|
|
82
|
+
const backIds = new Set(loops.flatMap(loop => loop.backEdgeIds));
|
|
83
|
+
const forwardIncoming = new Map([...incoming].map(([id, edges]) => [id, edges.filter(edge => !backIds.has(edge.id))]));
|
|
84
|
+
const order = topology.order.map(id => steps.get(id));
|
|
85
|
+
const decisions = new Decisions();
|
|
86
|
+
const completed = new Map();
|
|
87
|
+
const recovery = new Map();
|
|
88
|
+
const selectedEdges = new Map();
|
|
89
|
+
const blockedEdges = new Map();
|
|
90
|
+
const any = (values) => values.reduce((left, right) => decisions.or(left, right), 0);
|
|
91
|
+
const ancestors = new Map();
|
|
92
|
+
const outputSchemas = new Map();
|
|
93
|
+
const inputSchemas = new Map();
|
|
94
|
+
const firstInputSchemas = new Map();
|
|
95
|
+
const repeatInputSchemas = new Map();
|
|
96
|
+
const reaches = new Map();
|
|
97
|
+
const graph = { definition, order, incoming, outgoing, forwardIncoming, loops, outputSchemas, inputSchemas, firstInputSchemas, repeatInputSchemas };
|
|
98
|
+
for (const step of order) {
|
|
99
|
+
const edges = forwardIncoming.get(step.id);
|
|
100
|
+
const blockedHere = any(edges.map(edge => blockedEdges.get(edge.id)));
|
|
101
|
+
const reach = decisions.and(edges.length ? any(edges.map(edge => selectedEdges.get(edge.id))) : 1, decisions.not(blockedHere));
|
|
102
|
+
const recovering = decisions.or(any(edges.map(edge => decisions.and(selectedEdges.get(edge.id), edge.outcome === 'failure' || edge.outcome === 'timeout' ? 1 : recovery.get(edge.from)))), headers.has(step.id) ? decisions.and(reach, decisions.outcome(order.length + order.indexOf(step), 1)) : 0);
|
|
103
|
+
reaches.set(step.id, reach);
|
|
104
|
+
recovery.set(step.id, recovering);
|
|
105
|
+
const variable = order.indexOf(step);
|
|
106
|
+
const failure = decisions.outcome(variable, 1);
|
|
107
|
+
const timeout = decisions.outcome(variable, 2);
|
|
108
|
+
const success = decisions.not(decisions.or(failure, timeout));
|
|
109
|
+
completed.set(step.id, decisions.and(reach, success));
|
|
110
|
+
const outcomes = { success, failure, timeout, true: any([decisions.outcome(variable, 0), decisions.outcome(variable, 3)]), false: decisions.outcome(variable, 4) };
|
|
111
|
+
const outgoingEdges = outgoing.get(step.id);
|
|
112
|
+
const unhandled = decisions.or(decisions.and(failure, outgoingEdges.some(edge => edge.outcome === 'failure') ? recovering : 1), decisions.and(timeout, outgoingEdges.some(edge => edge.outcome === 'timeout') ? recovering : 1));
|
|
113
|
+
for (const edge of outgoingEdges) {
|
|
114
|
+
const isRecovery = edge.outcome === 'failure' || edge.outcome === 'timeout';
|
|
115
|
+
selectedEdges.set(edge.id, decisions.and(reach, decisions.and(outcomes[edge.outcome], isRecovery ? decisions.not(recovering) : 1)));
|
|
116
|
+
blockedEdges.set(edge.id, decisions.or(blockedHere, isRecovery ? 0 : decisions.and(reach, unhandled)));
|
|
117
|
+
}
|
|
118
|
+
ancestors.set(step.id, new Set(edges.flatMap(edge => [edge.from, ...ancestors.get(edge.from)])));
|
|
119
|
+
}
|
|
120
|
+
for (const loop of loops) {
|
|
121
|
+
const repeat = any(loop.backEdgeIds.map(id => selectedEdges.get(id)));
|
|
122
|
+
const terminals = loop.memberIds.map(id => {
|
|
123
|
+
const connected = any(outgoing.get(id).map(edge => selectedEdges.get(edge.id)));
|
|
124
|
+
return decisions.and(completed.get(id), decisions.not(connected));
|
|
125
|
+
});
|
|
126
|
+
const exit = any([...loop.exitEdgeIds.map(id => selectedEdges.get(id)), ...terminals]);
|
|
127
|
+
if (decisions.and(repeat, exit) !== 0)
|
|
128
|
+
throw new Error(`Loop ${loop.headerId} can select exit and repeat together`);
|
|
129
|
+
}
|
|
130
|
+
const resolving = new Set();
|
|
131
|
+
const outputFor = (id) => {
|
|
132
|
+
const cached = outputSchemas.get(id);
|
|
133
|
+
if (cached)
|
|
134
|
+
return cached;
|
|
135
|
+
const step = steps.get(id);
|
|
136
|
+
const output = declaredOutputSchema(step) ?? step.inputSchema ?? inputFor(id);
|
|
137
|
+
validateSchema(output);
|
|
138
|
+
outputSchemas.set(id, output);
|
|
139
|
+
return output;
|
|
140
|
+
};
|
|
141
|
+
const phaseInput = (step, repeat) => {
|
|
142
|
+
const loop = headers.get(step.id);
|
|
143
|
+
const edges = repeat ? incoming.get(step.id).filter(edge => loop.backEdgeIds.includes(edge.id)) : forwardIncoming.get(step.id);
|
|
144
|
+
const reach = repeat ? any(edges.map(edge => selectedEdges.get(edge.id))) : reaches.get(step.id);
|
|
145
|
+
const available = repeat ? new Set(edges.flatMap(edge => [edge.from, ...ancestors.get(edge.from)])) : ancestors.get(step.id);
|
|
146
|
+
const mapping = repeat ? step.repeatMapping : step.mapping;
|
|
147
|
+
const referenceSchema = (ref) => {
|
|
148
|
+
if (ref.source === 'input')
|
|
149
|
+
return schemaAt(definition.inputSchema, ref.path);
|
|
150
|
+
const source = steps.get(ref.stepId);
|
|
151
|
+
if (!source || !available.has(ref.stepId))
|
|
152
|
+
throw new Error('Mapping must reference an earlier step');
|
|
153
|
+
if (!decisions.implies(reach, completed.get(source.id)))
|
|
154
|
+
throw new Error(`Output is not guaranteed: ${source.name}`);
|
|
155
|
+
return schemaAt(outputFor(source.id), ref.path);
|
|
156
|
+
};
|
|
157
|
+
if (step.kind === 'join' && mapping)
|
|
158
|
+
throw new Error('Joins collect selected incoming outputs without mappings');
|
|
159
|
+
let input;
|
|
160
|
+
if (mapping?.kind === 'template') {
|
|
161
|
+
const inspect = (node) => {
|
|
162
|
+
if (node.kind === 'reference')
|
|
163
|
+
referenceSchema(node.reference);
|
|
164
|
+
if (node.kind === 'object')
|
|
165
|
+
Object.values(node.fields).forEach(inspect);
|
|
166
|
+
if (node.kind === 'array')
|
|
167
|
+
node.items.forEach(inspect);
|
|
168
|
+
};
|
|
169
|
+
inspect(mapping.template);
|
|
170
|
+
input = { type: 'json' };
|
|
171
|
+
}
|
|
172
|
+
else if (mapping?.kind === 'reference') {
|
|
173
|
+
const field = referenceSchema(mapping.reference);
|
|
174
|
+
if (field.optional)
|
|
175
|
+
throw new Error('A direct input reference must be required or have a default');
|
|
176
|
+
input = field.schema;
|
|
177
|
+
}
|
|
178
|
+
else if (mapping?.kind === 'object')
|
|
179
|
+
input = { type: 'object', fields: Object.fromEntries(Object.entries(mapping.fields).map(([name, ref]) => {
|
|
180
|
+
const field = referenceSchema(ref);
|
|
181
|
+
return [name, { schema: field.schema, required: !field.optional }];
|
|
182
|
+
})) };
|
|
183
|
+
else if (!edges.length)
|
|
184
|
+
input = definition.inputSchema;
|
|
185
|
+
else {
|
|
186
|
+
const sources = [...new Set(edges.map(edge => edge.from))];
|
|
187
|
+
const fields = Object.fromEntries(sources.map(id => {
|
|
188
|
+
const source = steps.get(id);
|
|
189
|
+
const connections = edges.filter(edge => edge.from === id);
|
|
190
|
+
const schema = unionSchema(connections.map(edge => edge.outcome === 'failure' || edge.outcome === 'timeout' ? recoverySchema(steps.get(id).inputSchema ?? inputFor(id), outputFor(id)) : outputFor(id)));
|
|
191
|
+
return [source.name, { schema, required: decisions.implies(reach, any(connections.map(edge => selectedEdges.get(edge.id)))) }];
|
|
192
|
+
}));
|
|
193
|
+
const collected = { type: 'object', fields };
|
|
194
|
+
const required = Object.values(fields).filter(field => field.required).length;
|
|
195
|
+
input = step.kind === 'join' || required > 1 ? collected : unionSchema([
|
|
196
|
+
...Object.values(fields).map(field => field.schema), ...(sources.length > 1 ? [collected] : []),
|
|
197
|
+
]);
|
|
198
|
+
}
|
|
199
|
+
if (step.inputSchema) {
|
|
200
|
+
validateSchema(step.inputSchema);
|
|
201
|
+
if (!schemaAssignable(input, step.inputSchema))
|
|
202
|
+
throw new Error('Input does not match the declared input schema');
|
|
203
|
+
}
|
|
204
|
+
return step.inputSchema ?? input;
|
|
205
|
+
};
|
|
206
|
+
const inputFor = (id) => {
|
|
207
|
+
const cached = inputSchemas.get(id);
|
|
208
|
+
if (cached)
|
|
209
|
+
return cached;
|
|
210
|
+
if (resolving.has(id))
|
|
211
|
+
throw new Error(`Cyclic input schema at ${id}; declare a loop header inputSchema`);
|
|
212
|
+
resolving.add(id);
|
|
213
|
+
const step = steps.get(id);
|
|
214
|
+
const first = phaseInput(step, false);
|
|
215
|
+
firstInputSchemas.set(id, first);
|
|
216
|
+
let input = first;
|
|
217
|
+
if (headers.has(id)) {
|
|
218
|
+
const repeat = phaseInput(step, true);
|
|
219
|
+
repeatInputSchemas.set(id, repeat);
|
|
220
|
+
input = unionSchema([first, repeat]);
|
|
221
|
+
}
|
|
222
|
+
inputSchemas.set(id, input);
|
|
223
|
+
resolving.delete(id);
|
|
224
|
+
return input;
|
|
225
|
+
};
|
|
226
|
+
for (const step of order) {
|
|
227
|
+
if (step.kind === 'mcp') {
|
|
228
|
+
compileJsonSchema(step.tool.inputSchema);
|
|
229
|
+
if (step.tool.outputSchema !== undefined)
|
|
230
|
+
compileJsonSchema(step.tool.outputSchema);
|
|
231
|
+
}
|
|
232
|
+
const input = inputFor(step.id);
|
|
233
|
+
if (step.kind === 'branch') {
|
|
234
|
+
const field = schemaAt(step.inputSchema ?? input, step.condition.path);
|
|
235
|
+
const expected = step.condition.operator === 'truthy' ? 'boolean' : ['greater-than', 'less-than'].includes(step.condition.operator) ? 'number' : undefined;
|
|
236
|
+
if (expected && (field.optional || !schemaAssignable(field.schema, { type: expected })))
|
|
237
|
+
throw new Error(`Branch condition requires a required ${expected}`);
|
|
238
|
+
}
|
|
239
|
+
outputFor(step.id);
|
|
240
|
+
}
|
|
241
|
+
return graph;
|
|
242
|
+
}
|
|
243
|
+
export function recoverySchema(input, output) {
|
|
244
|
+
return { type: 'object', fields: {
|
|
245
|
+
input: { schema: input, required: true },
|
|
246
|
+
error: { required: true, schema: { type: 'object', fields: { message: { schema: { type: 'string' }, required: true }, kind: { schema: { type: 'enum', values: ['failure', 'timeout', 'interrupted'] }, required: true } } } },
|
|
247
|
+
partialOutput: { schema: partialSchema(output) },
|
|
248
|
+
} };
|
|
249
|
+
}
|
|
250
|
+
export function resolveMapping(execution, step) {
|
|
251
|
+
const get = (ref) => valueAt(ref.source === 'input' ? execution.input : execution.steps[ref.stepId].output, ref.path);
|
|
252
|
+
if (step.mapping?.kind === 'template') {
|
|
253
|
+
const resolve = (node) => {
|
|
254
|
+
if (node.kind === 'literal')
|
|
255
|
+
return node.value;
|
|
256
|
+
if (node.kind === 'reference') {
|
|
257
|
+
const value = get(node.reference);
|
|
258
|
+
if (value === undefined)
|
|
259
|
+
throw new Error('Mapped MCP argument is missing');
|
|
260
|
+
return value;
|
|
261
|
+
}
|
|
262
|
+
if (node.kind === 'array')
|
|
263
|
+
return node.items.map(resolve);
|
|
264
|
+
return Object.fromEntries(Object.entries(node.fields).map(([key, value]) => [key, resolve(value)]));
|
|
265
|
+
};
|
|
266
|
+
return resolve(step.mapping.template);
|
|
267
|
+
}
|
|
268
|
+
if (step.mapping?.kind === 'reference')
|
|
269
|
+
return get(step.mapping.reference);
|
|
270
|
+
if (step.mapping?.kind === 'object')
|
|
271
|
+
return Object.fromEntries(Object.entries(step.mapping.fields).flatMap(([name, ref]) => {
|
|
272
|
+
const value = get(ref);
|
|
273
|
+
return value === undefined ? [] : [[name, value]];
|
|
274
|
+
}));
|
|
275
|
+
return undefined;
|
|
276
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Ajv } from 'ajv';
|
|
2
|
+
import { Ajv2019 } from 'ajv/dist/2019.js';
|
|
3
|
+
import { Ajv2020 } from 'ajv/dist/2020.js';
|
|
4
|
+
import { default as formats } from 'ajv-formats';
|
|
5
|
+
// No coercion, defaults, removal of properties, remote schema fetching or ignored keywords.
|
|
6
|
+
function engineFor(Engine) {
|
|
7
|
+
const engine = new Engine({ strict: true, strictTypes: false, strictTuples: false, strictRequired: false, allowUnionTypes: true, allErrors: true });
|
|
8
|
+
formats(engine);
|
|
9
|
+
return engine;
|
|
10
|
+
}
|
|
11
|
+
const cache = new Map();
|
|
12
|
+
export function compileJsonSchema(schema) {
|
|
13
|
+
const key = JSON.stringify(schema);
|
|
14
|
+
const prior = cache.get(key);
|
|
15
|
+
if (prior)
|
|
16
|
+
return prior;
|
|
17
|
+
const dialect = typeof schema === 'object' ? schema.$schema : undefined;
|
|
18
|
+
const engine = engineFor(typeof dialect === 'string' && dialect.includes('draft-07') ? Ajv : typeof dialect === 'string' && dialect.includes('2019-09') ? Ajv2019 : Ajv2020);
|
|
19
|
+
try {
|
|
20
|
+
const validator = engine.compile(schema);
|
|
21
|
+
if ('$async' in validator)
|
|
22
|
+
throw new Error('Asynchronous schemas are not supported');
|
|
23
|
+
if (cache.size >= 200)
|
|
24
|
+
cache.clear();
|
|
25
|
+
cache.set(key, validator);
|
|
26
|
+
return validator;
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
throw new Error('MCP JSON Schema cannot be validated. Reconfigure the tool schema (supported dialects: draft-07, 2019-09, 2020-12). No validation was skipped.');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function validateJsonSchema(schema, value) {
|
|
33
|
+
const validate = compileJsonSchema(schema);
|
|
34
|
+
if (!validate(value))
|
|
35
|
+
throw new Error('MCP schema validation failed: ' + (validate.errors ?? []).map(error => `${error.instancePath || '/'} ${error.keyword}`).join('; '));
|
|
36
|
+
}
|
|
37
|
+
// Projection is only for mapping discovery; validation always uses the original schema.
|
|
38
|
+
export function jsonSchemaAt(schema, path) {
|
|
39
|
+
if (!path.length)
|
|
40
|
+
return schema;
|
|
41
|
+
if (typeof schema === 'boolean')
|
|
42
|
+
return schema;
|
|
43
|
+
const [key, ...rest] = path;
|
|
44
|
+
const properties = schema.properties;
|
|
45
|
+
const child = properties && typeof properties === 'object' && !Array.isArray(properties) ? properties[key] : undefined;
|
|
46
|
+
if (child !== undefined && (typeof child === 'boolean' || (child && typeof child === 'object' && !Array.isArray(child))))
|
|
47
|
+
return jsonSchemaAt(child, rest);
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
export function analyzeLoops(definition) {
|
|
2
|
+
const ids = definition.steps.map(step => step.id);
|
|
3
|
+
const all = new Set(ids);
|
|
4
|
+
if (all.size !== ids.length)
|
|
5
|
+
throw new Error('Step IDs must be unique');
|
|
6
|
+
if (new Set(definition.edges.map(edge => edge.id)).size !== definition.edges.length)
|
|
7
|
+
throw new Error('Edge IDs must be unique');
|
|
8
|
+
const incoming = new Map(ids.map(id => [id, []]));
|
|
9
|
+
const outgoing = new Map(ids.map(id => [id, []]));
|
|
10
|
+
for (const edge of definition.edges) {
|
|
11
|
+
if (!all.has(edge.from) || !all.has(edge.to))
|
|
12
|
+
throw new Error('Unknown edge endpoint');
|
|
13
|
+
incoming.get(edge.to).push(edge);
|
|
14
|
+
outgoing.get(edge.from).push(edge);
|
|
15
|
+
}
|
|
16
|
+
const roots = ids.filter(id => !incoming.get(id).length);
|
|
17
|
+
const reachable = new Set(roots);
|
|
18
|
+
const queue = [...roots];
|
|
19
|
+
for (let index = 0; index < queue.length; index++) {
|
|
20
|
+
for (const edge of outgoing.get(queue[index])) {
|
|
21
|
+
if (reachable.has(edge.to))
|
|
22
|
+
continue;
|
|
23
|
+
reachable.add(edge.to);
|
|
24
|
+
queue.push(edge.to);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
if (reachable.size !== all.size)
|
|
28
|
+
throw new Error('Workflow cycle has no entry from a root');
|
|
29
|
+
const dominators = new Map(ids.map(id => [id, new Set(roots.includes(id) ? [id] : ids)]));
|
|
30
|
+
let changed = true;
|
|
31
|
+
while (changed) {
|
|
32
|
+
changed = false;
|
|
33
|
+
for (const id of queue) {
|
|
34
|
+
const edges = incoming.get(id);
|
|
35
|
+
if (!edges.length)
|
|
36
|
+
continue;
|
|
37
|
+
const common = new Set([...dominators.get(edges[0].from)].filter(candidate => edges.every(edge => dominators.get(edge.from).has(candidate))));
|
|
38
|
+
common.add(id);
|
|
39
|
+
const previous = dominators.get(id);
|
|
40
|
+
if (common.size !== previous.size || [...common].some(candidate => !previous.has(candidate))) {
|
|
41
|
+
dominators.set(id, common);
|
|
42
|
+
changed = true;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const backEdges = definition.edges.filter(edge => dominators.get(edge.from).has(edge.to));
|
|
47
|
+
const backIds = new Set(backEdges.map(edge => edge.id));
|
|
48
|
+
const members = new Map();
|
|
49
|
+
for (const edge of backEdges) {
|
|
50
|
+
const region = members.get(edge.to) ?? new Set([edge.to]);
|
|
51
|
+
const pending = [edge.from];
|
|
52
|
+
while (pending.length) {
|
|
53
|
+
const id = pending.pop();
|
|
54
|
+
if (region.has(id))
|
|
55
|
+
continue;
|
|
56
|
+
region.add(id);
|
|
57
|
+
pending.push(...incoming.get(id).map(previous => previous.from));
|
|
58
|
+
}
|
|
59
|
+
members.set(edge.to, region);
|
|
60
|
+
}
|
|
61
|
+
const loops = [...members].map(([headerId, region]) => ({
|
|
62
|
+
headerId,
|
|
63
|
+
memberIds: ids.filter(id => region.has(id)),
|
|
64
|
+
backEdgeIds: backEdges.filter(edge => edge.to === headerId).map(edge => edge.id),
|
|
65
|
+
entryEdgeIds: definition.edges.filter(edge => !region.has(edge.from) && region.has(edge.to)).map(edge => edge.id),
|
|
66
|
+
exitEdgeIds: definition.edges.filter(edge => region.has(edge.from) && !region.has(edge.to)).map(edge => edge.id),
|
|
67
|
+
}));
|
|
68
|
+
for (const loop of loops) {
|
|
69
|
+
const region = members.get(loop.headerId);
|
|
70
|
+
if (definition.edges.some(edge => !region.has(edge.from) && region.has(edge.to) && edge.to !== loop.headerId))
|
|
71
|
+
throw new Error('Workflow loop has multiple entry steps');
|
|
72
|
+
const parents = [];
|
|
73
|
+
for (const other of loops) {
|
|
74
|
+
if (other === loop)
|
|
75
|
+
continue;
|
|
76
|
+
const container = members.get(other.headerId);
|
|
77
|
+
const intersection = loop.memberIds.filter(id => container.has(id)).length;
|
|
78
|
+
if (!intersection)
|
|
79
|
+
continue;
|
|
80
|
+
if (intersection === region.size && region.size < container.size)
|
|
81
|
+
parents.push(other);
|
|
82
|
+
else if (intersection !== container.size || region.size === container.size)
|
|
83
|
+
throw new Error('Workflow loops overlap without strict nesting');
|
|
84
|
+
}
|
|
85
|
+
parents.sort((left, right) => left.memberIds.length - right.memberIds.length);
|
|
86
|
+
if (parents[0])
|
|
87
|
+
loop.parentHeaderId = parents[0].headerId;
|
|
88
|
+
}
|
|
89
|
+
const order = [];
|
|
90
|
+
const remaining = new Set(ids);
|
|
91
|
+
while (remaining.size) {
|
|
92
|
+
const ready = [...remaining].filter(id => incoming.get(id).every(edge => backIds.has(edge.id) || !remaining.has(edge.from)));
|
|
93
|
+
if (!ready.length)
|
|
94
|
+
throw new Error('Workflow contains an irreducible or multiple-entry cycle');
|
|
95
|
+
for (const id of ready) {
|
|
96
|
+
order.push(id);
|
|
97
|
+
remaining.delete(id);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
loops.sort((left, right) => right.memberIds.length - left.memberIds.length || ids.indexOf(left.headerId) - ids.indexOf(right.headerId));
|
|
101
|
+
return { loops, order };
|
|
102
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { validateJsonSchema } from "./json-schema.js";
|
|
3
|
+
const jsonSchema = z.json();
|
|
4
|
+
const envelopeSchema = z.object({
|
|
5
|
+
structuredContent: jsonSchema,
|
|
6
|
+
content: z.array(z.object({ type: z.string() }).catchall(jsonSchema)),
|
|
7
|
+
}).strict();
|
|
8
|
+
export function boundedMcpValue(value) {
|
|
9
|
+
const json = jsonSchema.parse(value);
|
|
10
|
+
return json;
|
|
11
|
+
}
|
|
12
|
+
// Scheduler boundary: validate executor results and manually supplied outputs alike.
|
|
13
|
+
export function validateMcpOutput(tool, value) {
|
|
14
|
+
const envelope = envelopeSchema.parse(value);
|
|
15
|
+
if (tool.outputSchema !== undefined)
|
|
16
|
+
validateJsonSchema(tool.outputSchema, envelope.structuredContent);
|
|
17
|
+
return envelope;
|
|
18
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { boundedMcpValue, validateMcpOutput } from "./mcp.js";
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
4
|
+
import { validateDefinition, workflowDefinitionValidator } from "./graph.js";
|
|
5
|
+
const errorValidator = z.object({ message: z.string(), kind: z.enum(['failure', 'timeout', 'interrupted']) }).strict();
|
|
6
|
+
const identityValidator = z.object({ headerId: z.string().min(1), activation: z.number().int().positive(), try: z.number().int().positive() }).strict();
|
|
7
|
+
const loopValidator = z.object({
|
|
8
|
+
activation: z.number().int().nonnegative(), try: z.number().int().nonnegative(),
|
|
9
|
+
phase: z.enum(['inactive', 'active', 'repeating', 'limit', 'exited']), headerInput: z.json().optional(), headerRecovery: z.boolean().optional(),
|
|
10
|
+
grants: z.array(z.object({ activation: z.number().int().positive(), try: z.number().int().positive(), guidance: z.string().max(100_000).optional() }).strict()),
|
|
11
|
+
}).strict();
|
|
12
|
+
const attemptValidator = z.object({
|
|
13
|
+
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(),
|
|
15
|
+
input: z.json(), output: z.json().optional(), partialOutput: z.json().optional(), error: errorValidator.optional(),
|
|
16
|
+
}).strict();
|
|
17
|
+
export const workflowExecutionValidator = z.object({
|
|
18
|
+
version: z.literal(1), id: z.string().min(1), sessionId: z.string().min(1), scope: z.string(), definition: workflowDefinitionValidator,
|
|
19
|
+
input: z.json(), launchId: z.string().min(1).optional(), testStepId: z.string().optional(), status: z.enum(['running', 'recovery-required', 'completed', 'completed-with-recovery', 'cancelled']),
|
|
20
|
+
startedAt: z.number().nonnegative(), finishedAt: z.number().nonnegative().optional(), result: z.json().optional(),
|
|
21
|
+
loops: z.record(z.string(), loopValidator).optional(),
|
|
22
|
+
steps: z.record(z.string(), z.object({
|
|
23
|
+
status: z.enum(['pending', 'running', 'completed', 'failed', 'timed-out', 'interrupted', 'skipped', 'blocked', 'cancelled']), recovery: z.boolean().optional(),
|
|
24
|
+
attempts: z.array(attemptValidator), output: z.json().optional(), outcome: z.enum(['success', 'failure', 'timeout', 'true', 'false']).optional(),
|
|
25
|
+
}).strict()),
|
|
26
|
+
}).strict();
|
|
27
|
+
export function parseExecution(value) {
|
|
28
|
+
const record = workflowExecutionValidator.parse(value);
|
|
29
|
+
const graph = validateDefinition(record.definition);
|
|
30
|
+
if (graph.order.length !== Object.keys(record.steps).length || graph.order.some(step => !Object.hasOwn(record.steps, step.id)))
|
|
31
|
+
throw new Error('Execution steps do not match the definition');
|
|
32
|
+
if (record.testStepId && !Object.hasOwn(record.steps, record.testStepId))
|
|
33
|
+
throw new Error('Unknown test step');
|
|
34
|
+
const loops = record.testStepId ? [] : graph.loops;
|
|
35
|
+
if (loops.length !== Object.keys(record.loops ?? {}).length || loops.some(loop => !record.loops?.[loop.headerId]))
|
|
36
|
+
throw new Error('Execution loops do not match the definition');
|
|
37
|
+
for (const loop of loops) {
|
|
38
|
+
const state = record.loops[loop.headerId];
|
|
39
|
+
if ((state.phase === 'inactive' && state.try !== 0) || (state.phase !== 'inactive' && state.phase !== 'exited' && (!state.activation || !state.try)))
|
|
40
|
+
throw new Error('Invalid loop phase');
|
|
41
|
+
if (state.phase === 'exited' && loop.memberIds.some(id => ['pending', 'running', 'interrupted', 'blocked'].includes(record.steps[id].status)))
|
|
42
|
+
throw new Error('Exited loop contains unfinished work');
|
|
43
|
+
if (state.phase === 'inactive' && loop.memberIds.some(id => !['pending', 'blocked', 'skipped', 'cancelled'].includes(record.steps[id].status)))
|
|
44
|
+
throw new Error('Inactive loop contains active work');
|
|
45
|
+
if (state.phase === 'active' && state.try > 1 && state.headerInput === undefined)
|
|
46
|
+
throw new Error('Missing repeat header input');
|
|
47
|
+
const grants = new Set();
|
|
48
|
+
for (const grant of state.grants) {
|
|
49
|
+
const key = `${grant.activation}:${grant.try}`;
|
|
50
|
+
if (grants.has(key) || grant.activation > state.activation || grant.try <= loop.maxTries)
|
|
51
|
+
throw new Error('Invalid loop grant');
|
|
52
|
+
if (grant.try > loop.maxTries + 1 && !grants.has(`${grant.activation}:${grant.try - 1}`))
|
|
53
|
+
throw new Error('Invalid loop grant sequence');
|
|
54
|
+
grants.add(key);
|
|
55
|
+
}
|
|
56
|
+
if (state.try > loop.maxTries && !grants.has(`${state.activation}:${state.try}`))
|
|
57
|
+
throw new Error('Missing loop grant');
|
|
58
|
+
if (state.phase === 'limit' && (state.try < loop.maxTries || grants.has(`${state.activation}:${state.try + 1}`)))
|
|
59
|
+
throw new Error('Invalid loop limit');
|
|
60
|
+
if (state.phase === 'limit' && ['completed', 'completed-with-recovery'].includes(record.status))
|
|
61
|
+
throw new Error('Completed execution has a loop limit');
|
|
62
|
+
}
|
|
63
|
+
for (const [id, step] of Object.entries(record.steps)) {
|
|
64
|
+
const definition = graph.order.find(candidate => candidate.id === id);
|
|
65
|
+
if (definition.kind === 'mcp') {
|
|
66
|
+
if (step.output !== undefined)
|
|
67
|
+
validateMcpOutput(definition.tool, step.output);
|
|
68
|
+
for (const attempt of step.attempts) {
|
|
69
|
+
if (attempt.output !== undefined)
|
|
70
|
+
validateMcpOutput(definition.tool, attempt.output);
|
|
71
|
+
if (attempt.partialOutput !== undefined)
|
|
72
|
+
boundedMcpValue(attempt.partialOutput);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
const containing = loops.filter(loop => loop.memberIds.includes(id));
|
|
76
|
+
for (const [index, attempt] of step.attempts.entries()) {
|
|
77
|
+
if ((attempt.loops ?? []).length !== containing.length || containing.some(loop => !attempt.loops?.some(identity => identity.headerId === loop.headerId)))
|
|
78
|
+
throw new Error('Invalid attempt loop identities');
|
|
79
|
+
if (containing.length && index === 0 && attempt.action !== 'execute')
|
|
80
|
+
throw new Error('Invalid initial loop attempt');
|
|
81
|
+
const previous = step.attempts[index - 1];
|
|
82
|
+
if (containing.length && previous) {
|
|
83
|
+
const same = isDeepStrictEqual(previous.loops, attempt.loops);
|
|
84
|
+
if ((attempt.action === 'execute') === same)
|
|
85
|
+
throw new Error('Invalid attempt action for loop try');
|
|
86
|
+
for (const identity of attempt.loops) {
|
|
87
|
+
const prior = previous.loops.find(prior => prior.headerId === identity.headerId);
|
|
88
|
+
if (identity.activation < prior.activation || (identity.activation === prior.activation && identity.try < prior.try))
|
|
89
|
+
throw new Error('Loop attempt identity moved backwards');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
for (const identity of attempt.loops ?? []) {
|
|
93
|
+
const state = record.loops[identity.headerId];
|
|
94
|
+
const loop = loops.find(loop => loop.headerId === identity.headerId);
|
|
95
|
+
if (identity.activation > state.activation || (identity.activation === state.activation && state.try > 0 && identity.try > state.try))
|
|
96
|
+
throw new Error('Invalid attempt loop identity');
|
|
97
|
+
if (identity.try > loop.maxTries && !state.grants.some(grant => grant.activation === identity.activation && grant.try === identity.try))
|
|
98
|
+
throw new Error('Attempt lacks a loop grant');
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (step.attempts.some((attempt, index) => attempt.number !== index + 1))
|
|
102
|
+
throw new Error('Invalid attempt sequence');
|
|
103
|
+
if (['running', 'completed', 'failed', 'timed-out', 'interrupted'].includes(step.status) && !step.attempts.length)
|
|
104
|
+
throw new Error('Missing step attempt');
|
|
105
|
+
if (step.status === 'completed' && step.output === undefined)
|
|
106
|
+
throw new Error('Missing completed output');
|
|
107
|
+
}
|
|
108
|
+
if (['completed', 'completed-with-recovery'].includes(record.status) && Object.values(record.steps).some(step => ['pending', 'running', 'interrupted', 'blocked'].includes(step.status)))
|
|
109
|
+
throw new Error('Completed execution contains unfinished work');
|
|
110
|
+
return record;
|
|
111
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/** State identity, not wall-clock time: repeated notifications cannot mint new authority. */
|
|
3
|
+
export function recoveryRevision(record) {
|
|
4
|
+
return createHash('sha256').update(JSON.stringify({ id: record.id, status: record.status,
|
|
5
|
+
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,
|
|
7
|
+
})).digest('hex');
|
|
8
|
+
}
|
|
9
|
+
export function successfulProgress(record) {
|
|
10
|
+
return Object.values(record.steps).reduce((count, step) => count + step.attempts.filter(a => a.finishedAt !== undefined && a.output !== undefined && !a.error && a.action !== 'supply').length, 0);
|
|
11
|
+
}
|
|
12
|
+
export function safeAutomaticRecovery(record, action) {
|
|
13
|
+
if (record.status !== 'recovery-required' || Object.values(record.loops ?? {}).some(loop => loop.phase === 'limit'))
|
|
14
|
+
return false;
|
|
15
|
+
if (action.kind === 'retry') {
|
|
16
|
+
// External tools, arbitrary code and agents cannot prove that replay is free of effects.
|
|
17
|
+
const step = record.definition.steps.find(step => step.id === action.stepId);
|
|
18
|
+
return !!step && ['branch', 'join'].includes(step.kind);
|
|
19
|
+
}
|
|
20
|
+
if (action.kind === 'continue') {
|
|
21
|
+
// Continue is safe only for work which has not been attempted, never an implicit replay.
|
|
22
|
+
return Object.values(record.steps).every(step => ['completed', 'skipped'].includes(step.status) || (['pending', 'blocked'].includes(step.status) && !step.attempts.length));
|
|
23
|
+
}
|
|
24
|
+
return false;
|
|
25
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { getAsset, isSea } from 'node:sea';
|
|
2
|
+
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
let extracted;
|
|
6
|
+
export function embeddedWorkflowRuntime() {
|
|
7
|
+
if (extracted)
|
|
8
|
+
return extracted;
|
|
9
|
+
if (!isSea())
|
|
10
|
+
throw new Error('Supply runtimePath from build:workflow-runtime for a source installation');
|
|
11
|
+
const bytes = getAsset('workflow-runtime.cjs');
|
|
12
|
+
const directory = mkdtempSync(join(tmpdir(), 'flow-workflow-runtime-'));
|
|
13
|
+
extracted = join(directory, 'runtime.cjs');
|
|
14
|
+
writeFileSync(extracted, Buffer.from(bytes), { mode: 0o400 });
|
|
15
|
+
process.once('exit', () => rmSync(directory, { recursive: true, force: true }));
|
|
16
|
+
return extracted;
|
|
17
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const libraries = {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { accessSync, constants } from 'node:fs';
|
|
2
|
+
import { delimiter, isAbsolute, join } from 'node:path';
|
|
3
|
+
import { DEFAULT_WORKFLOW_RUNTIME } from "../protocol/settings.js";
|
|
4
|
+
export function workflowRuntimeOptions(settings = DEFAULT_WORKFLOW_RUNTIME, path = process.env.PATH ?? '') {
|
|
5
|
+
const discover = (name) => {
|
|
6
|
+
for (const directory of path.split(delimiter)) {
|
|
7
|
+
if (!isAbsolute(directory))
|
|
8
|
+
continue;
|
|
9
|
+
const candidate = join(directory, name);
|
|
10
|
+
try {
|
|
11
|
+
accessSync(candidate, constants.X_OK);
|
|
12
|
+
return candidate;
|
|
13
|
+
}
|
|
14
|
+
catch { }
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
};
|
|
18
|
+
return {
|
|
19
|
+
...settings,
|
|
20
|
+
nodePath: settings.nodePath ?? discover('node'),
|
|
21
|
+
dockerPath: settings.dockerPath ?? discover('docker'),
|
|
22
|
+
};
|
|
23
|
+
}
|