@nathanstephenson/flow 0.1.3 → 0.1.4
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 +46 -2
- package/build/workflow-runtime.cjs +1 -46
- package/dist/backend/claude/index.js +108 -34
- package/dist/backend/claude/permissions.js +26 -15
- package/dist/backend/claude/subagents.js +4 -0
- package/dist/backend/mcp-stdio-supervisor.js +196 -0
- package/dist/backend/mcp.js +146 -51
- package/dist/backend/permission-errors.js +3 -0
- package/dist/backend/pi/agent-permissions.js +74 -0
- package/dist/backend/pi/index.js +29 -9
- package/dist/backend/registry.js +5 -30
- package/dist/backend/worker/assets.js +16 -0
- package/dist/backend/worker/claude-state.js +61 -0
- package/dist/backend/worker/entry.js +186 -0
- package/dist/backend/worker/index.js +255 -0
- package/dist/backend/worker/launcher.js +67 -0
- package/dist/backend/worker/protocol.js +11 -0
- package/dist/backend/worker/rpc.js +108 -0
- package/dist/build-id +1 -1
- package/dist/cli/bootstrap.js +1 -1
- package/dist/cli/main.js +9 -1
- package/dist/client/connection.js +107 -2
- package/dist/client/diff.js +43 -0
- package/dist/client/reduce.js +3 -0
- package/dist/daemon/config-store.js +36 -1
- package/dist/daemon/config.js +54 -18
- package/dist/daemon/host.js +279 -29
- package/dist/daemon/log.js +98 -0
- package/dist/daemon/runtime.js +10 -1
- package/dist/daemon/server.js +67 -1
- package/dist/daemon/workflow-execution-routes.js +1 -1
- package/dist/daemon/workflow-executions.js +63 -25
- package/dist/daemon/workflow-mcp.js +2 -4
- package/dist/daemon/workflow-routes.js +4 -3
- package/dist/isolation/filesystem.js +382 -0
- package/dist/isolation/launcher.js +40 -0
- package/dist/isolation/node-assets.js +84 -0
- package/dist/isolation/support.js +40 -0
- package/dist/isolation/toolchain-assets.js +62 -0
- package/dist/protocol/presentation.js +230 -0
- package/dist/protocol/settings.js +1 -4
- package/dist/workflows/executors.js +118 -62
- package/dist/workflows/graph.js +3 -6
- package/dist/workflows/json-schema.js +8 -3
- package/dist/workflows/mcp.js +15 -1
- package/dist/workflows/runtime-settings.js +7 -7
- package/dist/workflows/runtime.js +1 -34
- package/package.json +1 -1
- package/web/dist/assets/index-Bn-ECZ7w.js +174 -0
- package/web/dist/assets/index-DL0CGVaN.css +2 -0
- package/web/dist/assets/input-NIrLDFaS.js +6 -0
- package/web/dist/assets/settings-mcp-B60T2XUv.js +1 -0
- package/web/dist/assets/settings-secrets-BtQwc-w4.js +1 -0
- package/web/dist/assets/settings-workflows-BZ4W0Ja8.js +23 -0
- package/web/dist/assets/switch-DyYU6B5T.js +1 -0
- package/web/dist/assets/workflows-BAdf2yKH.js +7 -0
- package/web/dist/assets/workflows-pane-MSSNIrgu.js +1 -0
- package/web/dist/index.html +4 -4
- package/web/dist/assets/index-BmX_AxCZ.js +0 -170
- package/web/dist/assets/index-DWF4-3Fh.css +0 -2
- package/web/dist/assets/select-6i3wxovH.js +0 -1
- package/web/dist/assets/settings-mcp-CSLXJftV.js +0 -1
- package/web/dist/assets/settings-secrets-DpEwZLL4.js +0 -1
- package/web/dist/assets/settings-workflows-Dt-GaRtX.js +0 -23
- package/web/dist/assets/switch-ftZleVB8.js +0 -6
- package/web/dist/assets/workflows-DDRfFnAE.js +0 -7
- package/web/dist/assets/workflows-pane-g5njqean.js +0 -1
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Derived alongside the full reducer, never from a bounded tail. One latest boundary per row keeps
|
|
3
|
+
* proof bounded by the reduced transcript. Shared with raw-replay clients so both transports agree.
|
|
4
|
+
* A proof does not itself create Attention: the host supplies the qualifying boundary to observe.
|
|
5
|
+
*/
|
|
6
|
+
export class OutcomeProvenance {
|
|
7
|
+
outcomes = new Map();
|
|
8
|
+
// Recency is by last update, not ordinal: upserts can revisit an older row. Sets keep
|
|
9
|
+
// candidates bounded by Entry count while allowing a superseded candidate to fall back.
|
|
10
|
+
parentRows = new Set();
|
|
11
|
+
parentAnswers = new Set();
|
|
12
|
+
parentFailures = new Set();
|
|
13
|
+
parentTools = new Set();
|
|
14
|
+
turnId;
|
|
15
|
+
turnStart;
|
|
16
|
+
get(index) { return this.outcomes.get(index); }
|
|
17
|
+
resetTurn() {
|
|
18
|
+
this.parentRows.clear();
|
|
19
|
+
this.parentAnswers.clear();
|
|
20
|
+
this.parentFailures.clear();
|
|
21
|
+
this.parentTools.clear();
|
|
22
|
+
this.turnId = undefined;
|
|
23
|
+
this.turnStart = undefined;
|
|
24
|
+
}
|
|
25
|
+
/** Returns proof-only changes too: turn_ended commonly leaves every Entry identity unchanged. */
|
|
26
|
+
advance(logged, previous, entries) {
|
|
27
|
+
const event = logged.event;
|
|
28
|
+
const changed = new Set();
|
|
29
|
+
const stamp = (index) => {
|
|
30
|
+
if (index < 0 || this.outcomes.get(index) === logged.seq)
|
|
31
|
+
return;
|
|
32
|
+
this.outcomes.set(index, logged.seq);
|
|
33
|
+
changed.add(index);
|
|
34
|
+
};
|
|
35
|
+
const revoke = (index) => {
|
|
36
|
+
if (this.outcomes.delete(index))
|
|
37
|
+
changed.add(index);
|
|
38
|
+
};
|
|
39
|
+
const row = (kind, id) => entries.findIndex(item => item.kind === kind && item.id === id);
|
|
40
|
+
// A replacement card may carry the spawning tool's proof. Reusing either surface
|
|
41
|
+
// invalidates that shared proof too, but must not erase a later independent failure.
|
|
42
|
+
const supersede = (index) => {
|
|
43
|
+
const boundary = this.outcomes.get(index);
|
|
44
|
+
if (boundary === undefined)
|
|
45
|
+
return;
|
|
46
|
+
const item = entries[index];
|
|
47
|
+
revoke(index);
|
|
48
|
+
if (item.kind === "tool" || item.kind === "enquiry" || item.kind === "subagent") {
|
|
49
|
+
for (const kind of ["tool", "enquiry", "subagent"]) {
|
|
50
|
+
const related = row(kind, item.id);
|
|
51
|
+
if (this.outcomes.get(related) === boundary)
|
|
52
|
+
revoke(related);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
const reusedInTurn = (index) => {
|
|
57
|
+
const boundary = this.outcomes.get(index);
|
|
58
|
+
return boundary !== undefined && this.turnStart !== undefined && boundary < this.turnStart;
|
|
59
|
+
};
|
|
60
|
+
const eligible = (index) => {
|
|
61
|
+
const item = entries[index];
|
|
62
|
+
return item !== undefined && !("producer" in item && item.producer) &&
|
|
63
|
+
!(item.kind === "tool" && (item.status === "running" || item.authorisation === "asked")) &&
|
|
64
|
+
!(item.kind === "enquiry" && item.status === "asked");
|
|
65
|
+
};
|
|
66
|
+
const failure = (index) => {
|
|
67
|
+
const item = entries[index];
|
|
68
|
+
return eligible(index) && ((item?.kind === "tool" && item.status === "error") ||
|
|
69
|
+
(item?.kind === "notice" && item.level === "error"));
|
|
70
|
+
};
|
|
71
|
+
const touch = (set, index, valid) => {
|
|
72
|
+
set.delete(index);
|
|
73
|
+
if (valid)
|
|
74
|
+
set.add(index);
|
|
75
|
+
};
|
|
76
|
+
const parent = (index) => {
|
|
77
|
+
touch(this.parentRows, index, eligible(index));
|
|
78
|
+
touch(this.parentAnswers, index, eligible(index) && entries[index]?.kind === "assistant");
|
|
79
|
+
touch(this.parentFailures, index, failure(index));
|
|
80
|
+
};
|
|
81
|
+
const latest = (candidates, valid) => {
|
|
82
|
+
let latest;
|
|
83
|
+
for (const index of candidates)
|
|
84
|
+
if (valid(index))
|
|
85
|
+
latest = index;
|
|
86
|
+
return latest;
|
|
87
|
+
};
|
|
88
|
+
switch (event.type) {
|
|
89
|
+
case "turn_started":
|
|
90
|
+
this.resetTurn();
|
|
91
|
+
this.turnId = event.turnId;
|
|
92
|
+
this.turnStart = logged.seq;
|
|
93
|
+
break;
|
|
94
|
+
case "message": {
|
|
95
|
+
const index = row("assistant", event.id);
|
|
96
|
+
const old = previous[index];
|
|
97
|
+
const item = entries[index];
|
|
98
|
+
if (reusedInTurn(index) || (old?.kind === "assistant" && item?.kind === "assistant" &&
|
|
99
|
+
(old.final && !item.final || old.producer?.subagentId !== item.producer?.subagentId)))
|
|
100
|
+
supersede(index);
|
|
101
|
+
parent(index);
|
|
102
|
+
break;
|
|
103
|
+
}
|
|
104
|
+
case "tool_started":
|
|
105
|
+
case "tool_updated":
|
|
106
|
+
case "tool_ended":
|
|
107
|
+
{
|
|
108
|
+
const index = row("tool", event.callId);
|
|
109
|
+
const old = previous[index];
|
|
110
|
+
const item = entries[index];
|
|
111
|
+
// A newer turn does not make an old receipt a new result. Progress and equivalent
|
|
112
|
+
// terminal snapshots preserve its proof; a restart, attribution or outcome change does not.
|
|
113
|
+
if ((event.type === "tool_started" && reusedInTurn(index)) ||
|
|
114
|
+
(old?.kind === "tool" && item?.kind === "tool" &&
|
|
115
|
+
(old.status !== item.status || old.producer?.subagentId !== item.producer?.subagentId ||
|
|
116
|
+
(event.type === "tool_ended" && old.result !== item.result &&
|
|
117
|
+
outcomePayload(old.result) !== outcomePayload(item.result)))))
|
|
118
|
+
supersede(index);
|
|
119
|
+
if (event.type === "tool_started") {
|
|
120
|
+
touch(this.parentTools, index, item?.kind === "tool" && !item.producer);
|
|
121
|
+
parent(index);
|
|
122
|
+
}
|
|
123
|
+
else if (event.type === "tool_ended" && this.parentTools.has(index) && item?.kind === "tool" &&
|
|
124
|
+
(old?.kind !== "tool" || old.status === "running" || old.status !== item.status)) {
|
|
125
|
+
parent(index);
|
|
126
|
+
}
|
|
127
|
+
else if (!eligible(index)) {
|
|
128
|
+
this.parentRows.delete(index);
|
|
129
|
+
this.parentFailures.delete(index);
|
|
130
|
+
}
|
|
131
|
+
// Progress and duplicate terminal snapshots cannot introduce an old call from another
|
|
132
|
+
// turn or displace the most recent real result in a tool-only parent turn.
|
|
133
|
+
break;
|
|
134
|
+
}
|
|
135
|
+
case "enquiry": {
|
|
136
|
+
const index = row("enquiry", event.askId);
|
|
137
|
+
const old = previous[index];
|
|
138
|
+
const item = entries[index];
|
|
139
|
+
if (reusedInTurn(index) || (old?.kind === "enquiry" && item?.kind === "enquiry" &&
|
|
140
|
+
(old.status !== item.status || old.producer?.subagentId !== item.producer?.subagentId)))
|
|
141
|
+
supersede(index);
|
|
142
|
+
parent(index);
|
|
143
|
+
break;
|
|
144
|
+
}
|
|
145
|
+
case "permission": {
|
|
146
|
+
const index = row("tool", event.callId);
|
|
147
|
+
if (event.state === "asked")
|
|
148
|
+
supersede(index);
|
|
149
|
+
// Permission snapshots are not results, but can invalidate an earlier candidate.
|
|
150
|
+
if (!eligible(index)) {
|
|
151
|
+
this.parentRows.delete(index);
|
|
152
|
+
this.parentFailures.delete(index);
|
|
153
|
+
}
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
case "notice": {
|
|
157
|
+
const workflow = event.text === "Workflow requires recovery. The parent will inspect it when free." ||
|
|
158
|
+
event.text === "Workflow completed. The parent will prepare the result when free.";
|
|
159
|
+
// Host-owned Workflow boundaries are independent, never parent fallback candidates.
|
|
160
|
+
if (!workflow)
|
|
161
|
+
parent(entries.length - 1);
|
|
162
|
+
// Dispatch failures have arbitrary error text; Workflow notices have their own raw boundary.
|
|
163
|
+
if (event.level === "error" || workflow)
|
|
164
|
+
stamp(entries.length - 1);
|
|
165
|
+
break;
|
|
166
|
+
}
|
|
167
|
+
case "compacted":
|
|
168
|
+
parent(entries.length - 1);
|
|
169
|
+
break;
|
|
170
|
+
case "subagent":
|
|
171
|
+
case "background_call": {
|
|
172
|
+
const kind = event.type;
|
|
173
|
+
const id = event.type === "subagent" ? event.subagentId : event.callId;
|
|
174
|
+
const index = row(kind, id);
|
|
175
|
+
const old = previous[index];
|
|
176
|
+
const item = entries[index];
|
|
177
|
+
if (old && item && (old.kind === "subagent" || old.kind === "background_call") &&
|
|
178
|
+
(item.kind === "subagent" || item.kind === "background_call") &&
|
|
179
|
+
((old.status !== "running" && old.status !== "waiting" && old.status !== event.state) ||
|
|
180
|
+
old.producer?.subagentId !== item.producer?.subagentId))
|
|
181
|
+
supersede(index);
|
|
182
|
+
// Match host markAttention: only an error transition from previously open independent work.
|
|
183
|
+
if (event.state === "error" && old && (old.kind === "subagent" || old.kind === "background_call") &&
|
|
184
|
+
(old.status === "running" || old.status === "waiting"))
|
|
185
|
+
stamp(index);
|
|
186
|
+
break;
|
|
187
|
+
}
|
|
188
|
+
case "turn_ended": {
|
|
189
|
+
// Late tool progress and independent Workflow notices must not stand in for an answer
|
|
190
|
+
// outside the tail. An explicit parent failure takes precedence on failed turns.
|
|
191
|
+
const index = (event.reason === "error" ? latest(this.parentFailures, failure) : undefined) ??
|
|
192
|
+
latest(this.parentAnswers, eligible) ?? latest(this.parentRows, eligible);
|
|
193
|
+
if (event.reason !== "aborted" && (this.turnId === undefined || this.turnId === event.turnId) && index !== undefined) {
|
|
194
|
+
const item = entries[index];
|
|
195
|
+
// An upsert can have changed attribution since this row became the parent candidate.
|
|
196
|
+
if (!("producer" in item && item.producer)) {
|
|
197
|
+
stamp(index);
|
|
198
|
+
// These cards replace their spawning tool in the human-facing transcript.
|
|
199
|
+
if (item.kind === "tool") {
|
|
200
|
+
stamp(row("subagent", item.id));
|
|
201
|
+
const enquiry = row("enquiry", item.id);
|
|
202
|
+
if (eligible(enquiry))
|
|
203
|
+
stamp(enquiry);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
this.resetTurn();
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
case "session_dormant":
|
|
211
|
+
if (event.reason === "backend worker lost")
|
|
212
|
+
stamp(entries.length - 1);
|
|
213
|
+
this.resetTurn();
|
|
214
|
+
break;
|
|
215
|
+
case "session_settled":
|
|
216
|
+
case "session_ended":
|
|
217
|
+
case "revived":
|
|
218
|
+
case "session_started":
|
|
219
|
+
this.resetTurn();
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
return [...changed];
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
/** Agent Event payloads are JSON data; property insertion order is not a changed tool outcome. */
|
|
226
|
+
function outcomePayload(value) {
|
|
227
|
+
return JSON.stringify(value, (_key, item) => item !== null && typeof item === "object" && !Array.isArray(item)
|
|
228
|
+
? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]]))
|
|
229
|
+
: item);
|
|
230
|
+
}
|
|
@@ -11,10 +11,7 @@
|
|
|
11
11
|
* renders the first and sends the second. `src/daemon/config.ts` owns how they are parsed and what
|
|
12
12
|
* they mean on disk; this file owns only their shape.
|
|
13
13
|
*/
|
|
14
|
-
export const DEFAULT_WORKFLOW_RUNTIME = {
|
|
15
|
-
externalSandbox: true,
|
|
16
|
-
dockerImage: 'flow-workflow-runtime:local',
|
|
17
|
-
};
|
|
14
|
+
export const DEFAULT_WORKFLOW_RUNTIME = {};
|
|
18
15
|
/** Explicitly configured backends never silently fall back to a different inference route. */
|
|
19
16
|
export function resolveDefaultBackend(backends, configured) {
|
|
20
17
|
return configured ?? (backends.includes("claude") ? "claude" : backends[0]);
|
|
@@ -1,28 +1,56 @@
|
|
|
1
1
|
import { spawn } from 'node:child_process';
|
|
2
|
-
import { existsSync, realpathSync, statSync } from 'node:fs';
|
|
3
|
-
import { isAbsolute } from 'node:path';
|
|
4
|
-
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdtempSync, realpathSync, rmSync, statSync } from 'node:fs';
|
|
3
|
+
import { isAbsolute, join, resolve } from 'node:path';
|
|
5
4
|
import { parseValue, toTypeScript } from "./schema.js";
|
|
5
|
+
import { prepareFilesystemIsolation, validateFilesystemScope } from "../isolation/filesystem.js";
|
|
6
6
|
const environment = { PATH: '/usr/local/bin:/usr/bin:/bin', LANG: 'C.UTF-8' };
|
|
7
|
-
|
|
8
|
-
function probe(command, args) {
|
|
7
|
+
function probe(command, args, stdioFds = [], env = environment) {
|
|
9
8
|
if (!isAbsolute(command))
|
|
10
9
|
return Promise.resolve(false);
|
|
11
10
|
return new Promise(resolve => {
|
|
12
|
-
const child = spawn(command, args, { env
|
|
13
|
-
const timer = setTimeout(() =>
|
|
11
|
+
const child = spawn(command, args, { env, stdio: ['ignore', 'ignore', 'ignore', ...stdioFds] });
|
|
12
|
+
const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
|
|
14
13
|
child.once('error', () => { clearTimeout(timer); resolve(false); });
|
|
15
14
|
child.once('close', code => { clearTimeout(timer); resolve(code === 0); });
|
|
16
15
|
});
|
|
17
16
|
}
|
|
18
17
|
export async function createCodeExecutors(options) {
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
18
|
+
const isolationEnabled = options.isolationEnabled ?? true;
|
|
19
|
+
function canonicalScope(scope) {
|
|
20
|
+
if (isolationEnabled)
|
|
21
|
+
return validateFilesystemScope({ scope, expectedScope: resolve(scope),
|
|
22
|
+
...(options.stateRoot ? { stateRoot: options.stateRoot } : {}) });
|
|
23
|
+
const canonical = realpathSync(scope);
|
|
24
|
+
if (!statSync(canonical).isDirectory())
|
|
25
|
+
throw new Error('Scope must be a directory');
|
|
26
|
+
return canonical;
|
|
27
|
+
}
|
|
28
|
+
if (options.scope)
|
|
29
|
+
canonicalScope(options.scope);
|
|
30
|
+
let boundaryError;
|
|
31
|
+
async function probeNode() {
|
|
32
|
+
const args = ['-e', 'process.exit(Number(process.versions.node.split(".")[0]) >= 22 ? 0 : 1)'];
|
|
33
|
+
if (!isolationEnabled)
|
|
34
|
+
return probe(options.nodePath, args);
|
|
35
|
+
const scope = mkdtempSync(join(realpathSync('/tmp'), 'flow-runtime-probe-'));
|
|
36
|
+
let isolation;
|
|
37
|
+
try {
|
|
38
|
+
isolation = await prepareFilesystemIsolation({ scope, command: options.nodePath, args, credentials: 'none',
|
|
39
|
+
env: { ...Object.fromEntries(Object.keys(process.env).map(key => [key, undefined])), ...environment,
|
|
40
|
+
FLOW_BWRAP_PATH: process.env.FLOW_BWRAP_PATH }, readablePaths: [options.nodePath],
|
|
41
|
+
...(options.stateRoot ? { stateRoot: options.stateRoot } : {}) });
|
|
42
|
+
return await probe(isolation.command, isolation.args, isolation.stdioFds, isolation.env);
|
|
43
|
+
}
|
|
44
|
+
catch (error) {
|
|
45
|
+
boundaryError = error.message;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
finally {
|
|
49
|
+
isolation?.cleanup();
|
|
50
|
+
rmSync(scope, { recursive: true, force: true });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const nodeAvailable = await probeNode();
|
|
26
54
|
function check(step) {
|
|
27
55
|
if (!['shell', 'typescript'].includes(step.kind))
|
|
28
56
|
throw new Error('Unsupported executor kind');
|
|
@@ -30,12 +58,8 @@ export async function createCodeExecutors(options) {
|
|
|
30
58
|
throw new Error('Code executors require POSIX');
|
|
31
59
|
if (!isAbsolute(options.runtimePath) || !existsSync(options.runtimePath) || !statSync(options.runtimePath).isFile())
|
|
32
60
|
throw new Error('Workflow runtime bundle is unavailable; run build:workflow-runtime');
|
|
33
|
-
if (sandbox.enabled) {
|
|
34
|
-
if (!runtimeAvailable)
|
|
35
|
-
throw new Error('External sandbox is enabled but unavailable');
|
|
36
|
-
}
|
|
37
61
|
if (!nodeAvailable)
|
|
38
|
-
throw new Error('Host Node 22 or later runtime is unavailable');
|
|
62
|
+
throw new Error(boundaryError ?? 'Host Node 22 or later runtime is unavailable');
|
|
39
63
|
if (step.secrets && Object.keys(step.secrets).length && !options.resolveSecret)
|
|
40
64
|
throw new Error('Secret resolver is unavailable');
|
|
41
65
|
if (step.kind === 'shell' && Object.keys(step.secrets ?? {}).some(name => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || /^(PATH|OUTPUT|ENV|BASH_ENV|SHELLOPTS|BASHOPTS|LD_.*|DYLD_.*|NODE_.*)$/.test(name)))
|
|
@@ -44,6 +68,7 @@ export async function createCodeExecutors(options) {
|
|
|
44
68
|
const executor = {
|
|
45
69
|
check,
|
|
46
70
|
async execute(context) {
|
|
71
|
+
canonicalScope(context.scope);
|
|
47
72
|
check(context.step);
|
|
48
73
|
context.signal.throwIfAborted();
|
|
49
74
|
const secrets = Object.create(null);
|
|
@@ -63,54 +88,85 @@ export async function createCodeExecutors(options) {
|
|
|
63
88
|
},
|
|
64
89
|
};
|
|
65
90
|
async function executeRuntime(context, secrets, inputSchema) {
|
|
66
|
-
const
|
|
67
|
-
const
|
|
68
|
-
const
|
|
69
|
-
|
|
70
|
-
|
|
91
|
+
const stateRoot = options.stateRoot ? { stateRoot: options.stateRoot } : {};
|
|
92
|
+
const scope = canonicalScope(context.scope);
|
|
93
|
+
const runtimePath = realpathSync(options.runtimePath);
|
|
94
|
+
const nodePath = realpathSync(options.nodePath);
|
|
95
|
+
const args = ['--noprofile', '--norc', '-c', 'ulimit -c 0; exec "$@"', 'flow-workflow', nodePath, '--max-old-space-size=128', runtimePath];
|
|
71
96
|
const timeout = Math.min(context.step.timeoutMs ?? 60_000, 2_147_000_000);
|
|
72
|
-
const request = JSON.stringify({ ...context.step, scope
|
|
97
|
+
const request = JSON.stringify({ ...context.step, scope, input: context.input, inputType: inputSchema ? toTypeScript(inputSchema) : 'unknown', outputType: context.step.kind === 'typescript' ? toTypeScript(context.step.outputSchema) : 'unknown', secrets, timeout });
|
|
73
98
|
context.signal.throwIfAborted();
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (!sandbox.enabled)
|
|
83
|
-
killTimer = setTimeout(() => { child.kill('SIGKILL'); }, 5000);
|
|
84
|
-
};
|
|
85
|
-
context.signal.addEventListener('abort', abort, { once: true });
|
|
86
|
-
child.stdin.on('error', () => { });
|
|
87
|
-
child.stdin.write((sandbox.enabled ? JSON.stringify({ docker, args, name, request: JSON.parse(request) }) : request) + '\n');
|
|
88
|
-
const heartbeat = setInterval(() => { if (!stopped)
|
|
89
|
-
child.stdin.write('\n'); }, 500);
|
|
90
|
-
const deadline = setTimeout(abort, timeout + 1000);
|
|
91
|
-
for (const [stream, label] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']])
|
|
92
|
-
stream.setEncoding('utf8').on('data', (chunk) => {
|
|
93
|
-
if (label === 'stdout')
|
|
94
|
-
stdout += chunk.toString();
|
|
95
|
-
else
|
|
96
|
-
stderr += chunk.toString();
|
|
97
|
-
});
|
|
99
|
+
// When enabled, the local supervisor, QuickJS guest and Shell descendants share a boundary.
|
|
100
|
+
// Explicitly unset inherited variables before the isolation launcher merges environments.
|
|
101
|
+
const env = { ...Object.fromEntries(Object.keys(process.env).map(key => [key, undefined])), ...environment,
|
|
102
|
+
FLOW_BWRAP_PATH: process.env.FLOW_BWRAP_PATH, FLOW_STATE_DIR: process.env.FLOW_STATE_DIR,
|
|
103
|
+
HOME: process.env.HOME, PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR,
|
|
104
|
+
CLAUDE_CONFIG_DIR: process.env.CLAUDE_CONFIG_DIR };
|
|
105
|
+
const isolation = isolationEnabled ? await prepareFilesystemIsolation({ scope, expectedScope: resolve(context.scope),
|
|
106
|
+
...stateRoot, command: '/bin/bash', args, env, readablePaths: [nodePath, runtimePath], credentials: 'none' }) : undefined;
|
|
98
107
|
try {
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
+
context.signal.throwIfAborted();
|
|
109
|
+
const child = spawn(isolation?.command ?? '/bin/bash', isolation?.args ?? args, { env: isolation?.env ?? environment, ...(!isolation ? { cwd: scope } : {}), detached: true,
|
|
110
|
+
stdio: ['pipe', 'pipe', 'pipe', ...(isolation?.stdioFds ?? [])] });
|
|
111
|
+
let stdout = '', stderr = '', stopped = false;
|
|
112
|
+
// Restricted launches also end the PID namespace. Unrestricted detached descendants
|
|
113
|
+
// can escape the process group; this lifecycle supervision is not confinement.
|
|
114
|
+
const kill = () => {
|
|
115
|
+
if (!child.pid)
|
|
116
|
+
return;
|
|
117
|
+
try {
|
|
118
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
if (error.code !== 'ESRCH')
|
|
122
|
+
throw error;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
let killTimer;
|
|
126
|
+
const abort = () => {
|
|
127
|
+
if (stopped)
|
|
128
|
+
return;
|
|
129
|
+
stopped = true;
|
|
130
|
+
child.stdin.end();
|
|
131
|
+
killTimer = setTimeout(kill, 5000);
|
|
132
|
+
};
|
|
133
|
+
context.signal.addEventListener('abort', abort, { once: true });
|
|
134
|
+
child.stdin.on('error', () => { });
|
|
135
|
+
if (context.signal.aborted)
|
|
136
|
+
abort();
|
|
137
|
+
if (!stopped)
|
|
138
|
+
child.stdin.write(request + '\n');
|
|
139
|
+
const heartbeat = setInterval(() => { if (!stopped)
|
|
140
|
+
child.stdin.write('\n'); }, 500);
|
|
141
|
+
const deadline = setTimeout(abort, timeout + 1000);
|
|
142
|
+
for (const [stream, label] of [[child.stdout, 'stdout'], [child.stderr, 'stderr']])
|
|
143
|
+
stream.setEncoding('utf8').on('data', (chunk) => {
|
|
144
|
+
if (label === 'stdout')
|
|
145
|
+
stdout += chunk.toString();
|
|
146
|
+
else
|
|
147
|
+
stderr += chunk.toString();
|
|
148
|
+
});
|
|
149
|
+
try {
|
|
150
|
+
const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
|
|
151
|
+
if (code !== 0)
|
|
152
|
+
throw new Error(`Workflow runtime exited (${code}): ${stderr.slice(0, 1000)}`);
|
|
153
|
+
const response = JSON.parse(stdout);
|
|
154
|
+
if (Object.hasOwn(response, 'error'))
|
|
155
|
+
throw new Error(redact(response.error, secrets));
|
|
156
|
+
if (stopped || context.signal.aborted)
|
|
157
|
+
throw new Error('Code execution stopped');
|
|
158
|
+
return redactValue(response.output, secrets);
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
clearInterval(heartbeat);
|
|
162
|
+
clearTimeout(deadline);
|
|
163
|
+
clearTimeout(killTimer);
|
|
164
|
+
context.signal.removeEventListener('abort', abort);
|
|
165
|
+
kill();
|
|
166
|
+
}
|
|
108
167
|
}
|
|
109
168
|
finally {
|
|
110
|
-
|
|
111
|
-
clearTimeout(deadline);
|
|
112
|
-
clearTimeout(killTimer);
|
|
113
|
-
context.signal.removeEventListener('abort', abort);
|
|
169
|
+
isolation?.cleanup();
|
|
114
170
|
}
|
|
115
171
|
}
|
|
116
172
|
return { shell: executor, typescript: executor };
|
package/dist/workflows/graph.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { validateMcpSchemas } from "./mcp.js";
|
|
2
2
|
import { leadingSkillInvocation } from "../protocol/skills.js";
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { validSecretName } from "../protocol/secrets.js";
|
|
@@ -224,11 +224,8 @@ export function validateDefinition(value) {
|
|
|
224
224
|
return input;
|
|
225
225
|
};
|
|
226
226
|
for (const step of order) {
|
|
227
|
-
if (step.kind === 'mcp')
|
|
228
|
-
|
|
229
|
-
if (step.tool.outputSchema !== undefined)
|
|
230
|
-
compileJsonSchema(step.tool.outputSchema);
|
|
231
|
-
}
|
|
227
|
+
if (step.kind === 'mcp')
|
|
228
|
+
validateMcpSchemas(step.tool);
|
|
232
229
|
const input = inputFor(step.id);
|
|
233
230
|
if (step.kind === 'branch') {
|
|
234
231
|
const field = schemaAt(step.inputSchema ?? input, step.condition.path);
|
|
@@ -2,10 +2,14 @@ import { Ajv } from 'ajv';
|
|
|
2
2
|
import { Ajv2019 } from 'ajv/dist/2019.js';
|
|
3
3
|
import { Ajv2020 } from 'ajv/dist/2020.js';
|
|
4
4
|
import { default as formats } from 'ajv-formats';
|
|
5
|
-
//
|
|
5
|
+
// Only recognizable presentation annotations may be ignored, never validation extensions.
|
|
6
|
+
const annotationKeywords = ['example', 'externalDocs', 'xml', 'markdownDescription', 'enumDescriptions', 'enumNames', 'enumTitles'];
|
|
7
|
+
// No coercion, defaults, removal of properties or remote schema fetching.
|
|
6
8
|
function engineFor(Engine) {
|
|
7
9
|
const engine = new Engine({ strict: true, strictTypes: false, strictTuples: false, strictRequired: false, allowUnionTypes: true, allErrors: true });
|
|
8
10
|
formats(engine);
|
|
11
|
+
for (const keyword of annotationKeywords)
|
|
12
|
+
engine.addKeyword({ keyword, valid: true });
|
|
9
13
|
return engine;
|
|
10
14
|
}
|
|
11
15
|
const cache = new Map();
|
|
@@ -25,8 +29,9 @@ export function compileJsonSchema(schema) {
|
|
|
25
29
|
cache.set(key, validator);
|
|
26
30
|
return validator;
|
|
27
31
|
}
|
|
28
|
-
catch {
|
|
29
|
-
|
|
32
|
+
catch (error) {
|
|
33
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
34
|
+
throw new Error(`MCP JSON Schema cannot be validated: ${reason}. Reconfigure the tool schema (supported dialects: draft-07, 2019-09, 2020-12). No validation was skipped.`);
|
|
30
35
|
}
|
|
31
36
|
}
|
|
32
37
|
export function validateJsonSchema(schema, value) {
|
package/dist/workflows/mcp.js
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import { validateJsonSchema } from "./json-schema.js";
|
|
2
|
+
import { compileJsonSchema, validateJsonSchema } from "./json-schema.js";
|
|
3
|
+
/** Keep tool and schema context at discovery, save and execution boundaries. */
|
|
4
|
+
export function validateMcpSchemas(tool) {
|
|
5
|
+
for (const field of ['inputSchema', 'outputSchema']) {
|
|
6
|
+
const schema = tool[field];
|
|
7
|
+
if (schema === undefined)
|
|
8
|
+
continue;
|
|
9
|
+
try {
|
|
10
|
+
compileJsonSchema(schema);
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
throw new Error(`MCP tool ${JSON.stringify(tool.toolName)} ${field}: ${error instanceof Error ? error.message : String(error)}`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
3
17
|
const jsonSchema = z.json();
|
|
4
18
|
const envelopeSchema = z.object({
|
|
5
19
|
structuredContent: jsonSchema,
|
|
@@ -1,13 +1,15 @@
|
|
|
1
|
-
import { accessSync, constants } from 'node:fs';
|
|
1
|
+
import { accessSync, constants, statSync } from 'node:fs';
|
|
2
2
|
import { delimiter, isAbsolute, join } from 'node:path';
|
|
3
3
|
import { DEFAULT_WORKFLOW_RUNTIME } from "../protocol/settings.js";
|
|
4
|
-
export function workflowRuntimeOptions(settings = DEFAULT_WORKFLOW_RUNTIME, path
|
|
5
|
-
const discover = (name) => {
|
|
6
|
-
for (const directory of
|
|
4
|
+
export function workflowRuntimeOptions(settings = DEFAULT_WORKFLOW_RUNTIME, path) {
|
|
5
|
+
const discover = (name, search) => {
|
|
6
|
+
for (const directory of search.split(delimiter)) {
|
|
7
7
|
if (!isAbsolute(directory))
|
|
8
8
|
continue;
|
|
9
9
|
const candidate = join(directory, name);
|
|
10
10
|
try {
|
|
11
|
+
if (!statSync(candidate).isFile())
|
|
12
|
+
continue;
|
|
11
13
|
accessSync(candidate, constants.X_OK);
|
|
12
14
|
return candidate;
|
|
13
15
|
}
|
|
@@ -16,8 +18,6 @@ export function workflowRuntimeOptions(settings = DEFAULT_WORKFLOW_RUNTIME, path
|
|
|
16
18
|
return undefined;
|
|
17
19
|
};
|
|
18
20
|
return {
|
|
19
|
-
|
|
20
|
-
nodePath: settings.nodePath ?? discover('node'),
|
|
21
|
-
dockerPath: settings.dockerPath ?? discover('docker'),
|
|
21
|
+
nodePath: settings.nodePath ?? discover('node', path ?? process.env.PATH ?? ''),
|
|
22
22
|
};
|
|
23
23
|
}
|
|
@@ -18,45 +18,12 @@ lines.on('line', line => {
|
|
|
18
18
|
if (started)
|
|
19
19
|
return;
|
|
20
20
|
started = true;
|
|
21
|
-
void
|
|
21
|
+
void run(JSON.parse(line)).then(output => finish({ output }), error => finish({ error: error instanceof Error ? error.message : String(error) }));
|
|
22
22
|
});
|
|
23
23
|
function finish(result) {
|
|
24
24
|
clearTimeout(lease);
|
|
25
25
|
process.stdout.write(JSON.stringify(result) + '\n', () => process.exit(0));
|
|
26
26
|
}
|
|
27
|
-
async function dockerSupervisor(config) {
|
|
28
|
-
const child = spawn(config.docker, config.args, { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
29
|
-
let output = '', error = '', stopped = false;
|
|
30
|
-
stop = () => { stopped = true; controller.abort(); child.kill('SIGKILL'); };
|
|
31
|
-
const deadline = setTimeout(stop, config.request.timeout);
|
|
32
|
-
child.stdin.on('error', () => { });
|
|
33
|
-
child.stdin.write(JSON.stringify(config.request) + '\n');
|
|
34
|
-
const heartbeat = setInterval(() => { if (!stopped)
|
|
35
|
-
child.stdin.write('\n'); }, 500);
|
|
36
|
-
child.stdout.setEncoding('utf8').on('data', (chunk) => { output += chunk; });
|
|
37
|
-
child.stderr.setEncoding('utf8').on('data', (chunk) => { error = (error + chunk).slice(-1000); });
|
|
38
|
-
try {
|
|
39
|
-
const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
|
|
40
|
-
if (stopped || code !== 0)
|
|
41
|
-
throw new Error(`Docker runtime stopped (${code}): ${error}`);
|
|
42
|
-
const result = JSON.parse(output);
|
|
43
|
-
if (Object.hasOwn(result, 'error'))
|
|
44
|
-
throw new Error(result.error);
|
|
45
|
-
return result.output;
|
|
46
|
-
}
|
|
47
|
-
finally {
|
|
48
|
-
clearInterval(heartbeat);
|
|
49
|
-
clearTimeout(deadline);
|
|
50
|
-
clearTimeout(lease);
|
|
51
|
-
await new Promise((resolve, reject) => {
|
|
52
|
-
const cleanup = spawn(config.docker, ['--host', 'unix:///var/run/docker.sock', 'rm', '--force', config.name], { stdio: ['ignore', 'ignore', 'pipe'], timeout: 5000, killSignal: 'SIGKILL' });
|
|
53
|
-
let error = '';
|
|
54
|
-
cleanup.stderr.on('data', (chunk) => { error = (error + chunk.toString()).slice(-1000); });
|
|
55
|
-
cleanup.once('error', reject);
|
|
56
|
-
cleanup.once('close', code => code === 0 || error.includes('No such container') ? resolve() : reject(new Error(`Docker container cleanup failed: ${error}`)));
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
27
|
async function run(request) {
|
|
61
28
|
const timer = setTimeout(() => stop(), request.timeout);
|
|
62
29
|
try {
|