@nathanstephenson/flow 0.1.9 → 0.1.10-beta.10
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 +60 -21
- package/build/backend-worker-chunks/chunk-3KDHJA5P.mjs +162 -0
- package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
- package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
- package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
- package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
- package/build/backend-worker-chunks/{pi-M4OA2FGL.mjs → pi-KJSP23AO.mjs} +2138 -93
- package/build/backend-worker.mjs +77 -123
- package/build/workflow-runtime.cjs +12 -12
- package/dist/backend/claude/background-calls.js +7 -3
- package/dist/backend/claude/import.js +415 -0
- package/dist/backend/claude/index.js +201 -21
- package/dist/backend/claude/session-tools.js +14 -0
- package/dist/backend/claude/subagents.js +41 -9
- package/dist/backend/claude/todo-list.js +114 -0
- package/dist/backend/claude/workflow-parent.js +1 -1
- package/dist/backend/diff-excerpt-instructions.js +8 -0
- package/dist/backend/fake/index.js +54 -6
- package/dist/backend/mcp.js +4 -1
- package/dist/backend/pi/agent-permissions.js +1 -1
- package/dist/backend/pi/cache-warming.js +8 -0
- package/dist/backend/pi/canonical-json.js +120 -0
- package/dist/backend/pi/compaction-model.js +3 -2
- package/dist/backend/pi/host-auth.js +258 -0
- package/dist/backend/pi/import.js +269 -0
- package/dist/backend/pi/index.js +125 -21
- package/dist/backend/pi/model-auth.js +159 -0
- package/dist/backend/pi/model-catalog.js +120 -0
- package/dist/backend/pi/model-config.js +5 -0
- package/dist/backend/pi/model-selection.js +32 -0
- package/dist/backend/pi/plan-limits.js +41 -0
- package/dist/backend/pi/session-tools.js +21 -0
- package/dist/backend/pi/state.js +19 -1
- package/dist/backend/pi/subagents.js +7 -3
- package/dist/backend/pi/todo-list.js +23 -0
- package/dist/backend/pi/work.js +9 -1
- package/dist/backend/pi/workflow-parent.js +1 -1
- package/dist/backend/pi/workflow-subagent.js +4 -3
- package/dist/backend/plan-limits.js +17 -0
- package/dist/backend/session-tools.js +27 -0
- package/dist/backend/worker/claude-state.js +48 -0
- package/dist/backend/worker/entry.js +49 -8
- package/dist/backend/worker/index.js +155 -17
- package/dist/backend/worker/launcher.js +11 -4
- package/dist/backend/worker/protocol.js +2 -1
- package/dist/backend/worker/rpc.js +13 -0
- package/dist/backend/worker/sandbox-mcp.js +18 -7
- package/dist/backend/workflow-tools.js +9 -6
- package/dist/build-id +1 -1
- package/dist/cli/application.js +48 -42
- package/dist/cli/bootstrap.js +2 -2
- package/dist/cli/host-control.js +1 -1
- package/dist/cli/install-guard.js +2 -2
- package/dist/cli/main.js +4 -4
- package/dist/cli/systemd-update.js +3 -3
- package/dist/cli/update.js +6 -6
- package/dist/cli/web-update.js +6 -6
- package/dist/client/connection.js +46 -0
- package/dist/client/context-usage.js +3 -4
- package/dist/client/diff.js +40 -0
- package/dist/client/enquiry.js +0 -6
- package/dist/client/markdown.js +3 -2
- package/dist/client/model-choices.js +1 -1
- package/dist/client/permission.js +1 -2
- package/dist/client/project-name.js +3 -1
- package/dist/client/reduce.js +77 -3
- package/dist/client/relative-time.js +1 -1
- package/dist/client/scope-kind.js +6 -3
- package/dist/client/search.js +1 -1
- package/dist/client/status.js +1 -1
- package/dist/client/subagent-tree.js +49 -0
- package/dist/client/tool-chains.js +1 -1
- package/dist/client/tool-summary.js +28 -18
- package/dist/daemon/changes.js +128 -0
- package/dist/daemon/commit.js +84 -0
- package/dist/daemon/config-store.js +8 -3
- package/dist/daemon/config.js +105 -4
- package/dist/daemon/diff-excerpts.js +52 -0
- package/dist/daemon/git-state.js +197 -0
- package/dist/daemon/git.js +53 -10
- package/dist/daemon/github-image.js +18 -0
- package/dist/daemon/github.js +54 -0
- package/dist/daemon/host-control-routes.js +1 -1
- package/dist/daemon/host.js +1010 -116
- package/dist/daemon/http.js +4 -1
- package/dist/daemon/log.js +3 -0
- package/dist/daemon/mcp-auth.js +1 -1
- package/dist/daemon/models.js +2 -2
- package/dist/daemon/pi-model-cache.js +44 -0
- package/dist/daemon/pull-request.js +223 -138
- package/dist/daemon/push.js +43 -0
- package/dist/daemon/repository.js +123 -0
- package/dist/daemon/runtime.js +103 -22
- package/dist/daemon/secret-store.js +1 -1
- package/dist/daemon/server.js +111 -14
- package/dist/daemon/session-tool-views.js +22 -0
- package/dist/daemon/skills.js +24 -0
- package/dist/daemon/spend-ledger.js +118 -0
- package/dist/daemon/stack-metadata.js +12 -5
- package/dist/daemon/stack.js +162 -657
- package/dist/daemon/store.js +2 -0
- package/dist/daemon/summariser.js +30 -12
- package/dist/daemon/tour.js +56 -0
- package/dist/daemon/whisper.js +144 -0
- package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
- package/dist/daemon/workflow-authoring-scope.js +1 -1
- package/dist/daemon/workflow-builder-files.js +2 -2
- package/dist/daemon/workflow-builder-guidance.js +1 -1
- package/dist/daemon/workflow-builder-routes.js +2 -2
- package/dist/daemon/workflow-builder.js +44 -17
- package/dist/daemon/workflow-environment.js +193 -0
- package/dist/daemon/workflow-execution-launch.js +77 -0
- package/dist/daemon/workflow-execution-resources.js +76 -0
- package/dist/daemon/workflow-execution-routes.js +17 -8
- package/dist/daemon/workflow-execution-values.js +128 -0
- package/dist/daemon/workflow-executions.js +434 -305
- package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
- package/dist/daemon/workflow-mcp-authoring.js +4 -4
- package/dist/daemon/workflow-mcp.js +1 -1
- package/dist/daemon/workflow-routes.js +60 -2
- package/dist/daemon/workflow-schedule-driver.js +251 -0
- package/dist/daemon/workflow-schedule-routes.js +137 -0
- package/dist/daemon/workflow-schedules.js +342 -0
- package/dist/isolation/filesystem.js +6 -2
- package/dist/isolation/sandbox.js +61 -18
- package/dist/isolation/shared-sandbox.js +3 -3
- package/dist/isolation/toolchain-assets.js +1 -1
- package/dist/protocol/events.js +3 -0
- package/dist/protocol/plan-limits.js +1 -0
- package/dist/protocol/settings.js +1 -0
- package/dist/protocol/spend.js +2 -0
- package/dist/protocol/stack.js +12 -39
- package/dist/protocol/workflow-schedules.js +1 -0
- package/dist/workflows/calls.js +53 -0
- package/dist/workflows/errors.js +2 -0
- package/dist/workflows/executors.js +6 -5
- package/dist/workflows/graph.js +83 -9
- package/dist/workflows/invocations.js +23 -0
- package/dist/workflows/mcp.js +1 -1
- package/dist/workflows/owner.js +45 -0
- package/dist/workflows/records.js +150 -10
- package/dist/workflows/recovery.js +87 -2
- package/dist/workflows/runtime-settings.js +16 -16
- package/dist/workflows/runtime.js +2 -2
- package/dist/workflows/schedule-errors.js +2 -0
- package/dist/workflows/schedule-store.js +385 -0
- package/dist/workflows/scheduler.js +389 -98
- package/dist/workflows/schedules.js +130 -0
- package/dist/workflows/schema.js +3 -1
- package/dist/workflows/store.js +126 -13
- package/package.json +10 -6
- package/web/dist/assets/index-C76t-z4w.css +2 -0
- package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
- package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
- package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
- package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
- package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
- package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
- package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
- package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
- package/web/dist/index.html +6 -5
- package/build/backend-worker-chunks/chunk-J2DBNTL7.mjs +0 -94
- package/build/backend-worker-chunks/claude-GTW5KHY5.mjs +0 -30778
- package/dist/daemon/publish.js +0 -289
- package/dist/tui/app.js +0 -612
- package/dist/tui/keys.js +0 -90
- package/dist/tui/render.js +0 -411
- 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-api-BfExddae.js +0 -6
- 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
- /package/dist/protocol/{publish.js → imports.js} +0 -0
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, realpathSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { isSea } from 'node:sea';
|
|
5
|
+
import { createSandbox, removeOwnedSandbox, sandboxMounts, sandboxUnavailable } from '../isolation/sandbox.js';
|
|
6
|
+
import { nodeExecutionAssets } from '../isolation/node-assets.js';
|
|
7
|
+
import { validateFilesystemScope } from '../isolation/filesystem.js';
|
|
8
|
+
import { launchWorker } from '../backend/worker/launcher.js';
|
|
9
|
+
import { WorkerRpc, waitForAbort } from '../backend/worker/rpc.js';
|
|
10
|
+
export class WorkflowEnvironment {
|
|
11
|
+
sandbox;
|
|
12
|
+
release;
|
|
13
|
+
ownedProvider;
|
|
14
|
+
worker;
|
|
15
|
+
rpc;
|
|
16
|
+
workerFailure;
|
|
17
|
+
mcp;
|
|
18
|
+
opening;
|
|
19
|
+
recovering;
|
|
20
|
+
closing;
|
|
21
|
+
lifetime = new AbortController();
|
|
22
|
+
clients = new Set();
|
|
23
|
+
host;
|
|
24
|
+
ownerId;
|
|
25
|
+
scope;
|
|
26
|
+
connectionIds;
|
|
27
|
+
mode;
|
|
28
|
+
stateDir;
|
|
29
|
+
readablePaths;
|
|
30
|
+
scopeReadOnly;
|
|
31
|
+
constructor(host, ownerId, scope, connectionIds, mode, stateDir, readablePaths = [], scopeReadOnly = false) {
|
|
32
|
+
this.host = host;
|
|
33
|
+
this.ownerId = ownerId;
|
|
34
|
+
this.scope = scope;
|
|
35
|
+
this.connectionIds = connectionIds;
|
|
36
|
+
this.mode = mode;
|
|
37
|
+
this.stateDir = stateDir;
|
|
38
|
+
this.readablePaths = readablePaths;
|
|
39
|
+
this.scopeReadOnly = scopeReadOnly;
|
|
40
|
+
}
|
|
41
|
+
async prepare(signal) {
|
|
42
|
+
this.lifetime.signal.throwIfAborted();
|
|
43
|
+
signal?.throwIfAborted();
|
|
44
|
+
await waitForAbort(this.opening ??= this.open(signal ? AbortSignal.any([signal, this.lifetime.signal]) : this.lifetime.signal), signal);
|
|
45
|
+
signal?.throwIfAborted();
|
|
46
|
+
this.lifetime.signal.throwIfAborted();
|
|
47
|
+
}
|
|
48
|
+
recover(signal) {
|
|
49
|
+
return this.recovering ??= (async () => {
|
|
50
|
+
let failed = false;
|
|
51
|
+
await this.opening?.catch(() => { failed = true; });
|
|
52
|
+
signal?.throwIfAborted();
|
|
53
|
+
this.lifetime.signal.throwIfAborted();
|
|
54
|
+
if (failed || this.workerFailure) {
|
|
55
|
+
await this.stopWorker();
|
|
56
|
+
this.worker = undefined;
|
|
57
|
+
this.rpc = undefined;
|
|
58
|
+
this.mcp = undefined;
|
|
59
|
+
this.workerFailure = undefined;
|
|
60
|
+
this.opening = undefined;
|
|
61
|
+
}
|
|
62
|
+
await this.prepare(signal);
|
|
63
|
+
})().finally(() => { this.recovering = undefined; });
|
|
64
|
+
}
|
|
65
|
+
async open(signal) {
|
|
66
|
+
if (this.mode !== 'none')
|
|
67
|
+
validateFilesystemScope({ scope: this.scope, expectedScope: this.scope, ...(this.host.filesystemStateRoot() ? { stateRoot: this.host.filesystemStateRoot() } : {}) });
|
|
68
|
+
if (this.mode !== 'sandbox')
|
|
69
|
+
return;
|
|
70
|
+
const support = this.host.sandboxSupport();
|
|
71
|
+
if (!support?.supported || isSea())
|
|
72
|
+
throw sandboxUnavailable();
|
|
73
|
+
const packageRoot = fileURLToPath(new URL('../..', import.meta.url));
|
|
74
|
+
const bundle = join(packageRoot, 'build/backend-worker.mjs');
|
|
75
|
+
if (!existsSync(bundle))
|
|
76
|
+
throw new Error('Sandbox worker bundle unavailable');
|
|
77
|
+
if (!this.sandbox) {
|
|
78
|
+
mkdirSync(this.stateDir, { recursive: true, mode: 0o700 });
|
|
79
|
+
const shared = this.host.sharedSandbox();
|
|
80
|
+
const roots = shared?.roots();
|
|
81
|
+
if (roots && !roots.slice(0, 3).some(root => this.scope === root || this.scope.startsWith(root + '/')))
|
|
82
|
+
throw new Error('Scope is outside shared Sandbox roots');
|
|
83
|
+
const attachment = shared ? this.host.scheduledSandboxMounts(this.scope) : { writable: [], readable: [] };
|
|
84
|
+
const mounts = sandboxMounts([...(roots ?? (this.scopeReadOnly ? [this.stateDir] : [this.scope, this.stateDir])), ...attachment.writable], [...(this.scopeReadOnly ? [this.scope] : []), packageRoot, ...this.readablePaths, ...nodeExecutionAssets([bundle]), ...attachment.readable]);
|
|
85
|
+
if (shared) {
|
|
86
|
+
const lease = await shared.acquire(support.provider, roots[0], mounts, signal);
|
|
87
|
+
this.sandbox = lease.sandbox;
|
|
88
|
+
this.release = lease.release;
|
|
89
|
+
}
|
|
90
|
+
else {
|
|
91
|
+
this.ownedProvider = support.provider;
|
|
92
|
+
this.sandbox = await createSandbox(support.provider, { name: `flow-${this.ownerId}`, workspace: this.scopeReadOnly ? realpathSync(this.stateDir) : this.scope, mounts, env: {} }, join(this.stateDir, 'sandbox.json'), signal);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
signal.throwIfAborted();
|
|
96
|
+
if (!this.connectionIds.length)
|
|
97
|
+
return;
|
|
98
|
+
const mcp = this.mcp = await this.host.scheduledSandboxMcp(this.scope, this.connectionIds);
|
|
99
|
+
signal.throwIfAborted();
|
|
100
|
+
const launch = this.sandbox.command(this.scope, [support.provider.nodePath, bundle], { FLOW_BACKEND_WORKER: '1' });
|
|
101
|
+
const worker = this.worker = launchWorker({ command: launch.command, args: launch.args, env: {} });
|
|
102
|
+
const fail = (error) => {
|
|
103
|
+
if (this.worker === worker)
|
|
104
|
+
this.workerFailure ??= error;
|
|
105
|
+
rpc.close(error);
|
|
106
|
+
};
|
|
107
|
+
const rpc = this.rpc = new WorkerRpc(message => {
|
|
108
|
+
try {
|
|
109
|
+
worker.send(message, error => { if (error)
|
|
110
|
+
fail(error); });
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
}, async (method, args) => {
|
|
117
|
+
if (method !== 'mcp.token' || typeof args[0] !== 'string' || typeof args[1] !== 'boolean')
|
|
118
|
+
throw new Error('Unexpected worker callback');
|
|
119
|
+
return mcp.token(args[0], args[1]);
|
|
120
|
+
}, () => { });
|
|
121
|
+
worker.onMessage(message => rpc.receive(message), fail);
|
|
122
|
+
worker.child.once('error', fail);
|
|
123
|
+
worker.child.stdout?.once('close', () => fail(new Error('Workflow worker disconnected')));
|
|
124
|
+
worker.child.once('exit', () => fail(new Error('Workflow worker exited')));
|
|
125
|
+
try {
|
|
126
|
+
await rpc.call('mcp.initialize', [{ scope: this.scope, connections: mcp.definitions() }], AbortSignal.any([signal, AbortSignal.timeout(300_000)]));
|
|
127
|
+
signal.throwIfAborted();
|
|
128
|
+
mcp.attach((method, args, callSignal) => rpc.call(method, args, callSignal));
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
fail(error instanceof Error ? error : new Error(String(error)));
|
|
132
|
+
await this.stopWorker();
|
|
133
|
+
throw error;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async vm() { await this.prepare(); if (!this.sandbox)
|
|
137
|
+
throw sandboxUnavailable(); return this.sandbox; }
|
|
138
|
+
async client(connectionId, signal) {
|
|
139
|
+
await this.prepare(signal);
|
|
140
|
+
if (!this.connectionIds.includes(connectionId))
|
|
141
|
+
throw new Error('MCP connection not selected');
|
|
142
|
+
if (this.workerFailure)
|
|
143
|
+
throw this.workerFailure;
|
|
144
|
+
const client = this.mode === 'sandbox' ? await this.mcp.directView(connectionId, signal) : await this.host.scheduledMcp(this.scope, [connectionId], this.mode);
|
|
145
|
+
this.clients.add(client);
|
|
146
|
+
if (this.lifetime.signal.aborted || signal?.aborted) {
|
|
147
|
+
await client.dispose({ waitForExit: true });
|
|
148
|
+
this.clients.delete(client);
|
|
149
|
+
this.lifetime.signal.throwIfAborted();
|
|
150
|
+
signal?.throwIfAborted();
|
|
151
|
+
}
|
|
152
|
+
const dispose = client.dispose.bind(client);
|
|
153
|
+
client.dispose = async (...args) => { await dispose(...args); this.clients.delete(client); };
|
|
154
|
+
return client;
|
|
155
|
+
}
|
|
156
|
+
async stopWorker() {
|
|
157
|
+
try {
|
|
158
|
+
await this.worker?.stop(() => this.rpc.call('dispose'));
|
|
159
|
+
}
|
|
160
|
+
finally {
|
|
161
|
+
this.rpc?.close(new Error('Workflow worker stopped'));
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
close() {
|
|
165
|
+
this.lifetime.abort(new Error('Workflow environment is stopping'));
|
|
166
|
+
return this.closing ??= (async () => {
|
|
167
|
+
await Promise.allSettled([this.opening, this.recovering]);
|
|
168
|
+
const results = await Promise.allSettled([
|
|
169
|
+
...[...this.clients].map(client => Promise.resolve().then(() => client.dispose({ waitForExit: true }))),
|
|
170
|
+
this.stopWorker(),
|
|
171
|
+
]);
|
|
172
|
+
const errors = results.filter(result => result.status === 'rejected').map(result => result.reason);
|
|
173
|
+
try {
|
|
174
|
+
if (this.release) {
|
|
175
|
+
this.release();
|
|
176
|
+
this.release = undefined;
|
|
177
|
+
this.sandbox = undefined;
|
|
178
|
+
}
|
|
179
|
+
else if (this.sandbox) {
|
|
180
|
+
await this.sandbox.close();
|
|
181
|
+
this.sandbox = undefined;
|
|
182
|
+
}
|
|
183
|
+
else if (this.ownedProvider)
|
|
184
|
+
await removeOwnedSandbox(this.ownedProvider, join(this.stateDir, 'sandbox.json'), `flow-${this.ownerId}`);
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
errors.push(error);
|
|
188
|
+
}
|
|
189
|
+
if (errors.length)
|
|
190
|
+
throw new AggregateError(errors, 'Workflow environment cleanup failed');
|
|
191
|
+
})().catch(error => { this.closing = undefined; throw error; });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { resolveWorkflowCalls } from '../workflows/calls.js';
|
|
3
|
+
import { executionOwnerKey } from '../workflows/owner.js';
|
|
4
|
+
import { createCodeExecutors } from '../workflows/executors.js';
|
|
5
|
+
import { parseValue } from '../workflows/schema.js';
|
|
6
|
+
import { assertNoSecrets, publicDefinition, sameProject, uniqueCredentials, withConfirmedNoControlOff, WorkflowConflict } from './workflow-execution-values.js';
|
|
7
|
+
export async function prepareWorkflowLaunch(launch, dependencies) {
|
|
8
|
+
const { host, store, secrets, resources, runtimePath } = dependencies;
|
|
9
|
+
const { definition, input } = launch.options;
|
|
10
|
+
const stepId = launch.kind === 'session' ? launch.options.stepId : undefined;
|
|
11
|
+
const signal = launch.kind === 'occurrence' ? launch.options.signal : undefined;
|
|
12
|
+
signal?.throwIfAborted();
|
|
13
|
+
const identity = launch.kind === 'session' ? host.workflowSession(launch.options.sessionId)
|
|
14
|
+
: { backend: definition.backend, scope: launch.options.scope, projectId: launch.options.projectId };
|
|
15
|
+
const manifest = resolveWorkflowCalls(definition, id => store.getDefinition(id), stepId);
|
|
16
|
+
const definitions = Object.values(manifest);
|
|
17
|
+
for (const candidate of definitions) {
|
|
18
|
+
if (candidate.backend !== identity.backend)
|
|
19
|
+
throw new Error('Backend Adapter mismatch');
|
|
20
|
+
if (candidate.projectId && !sameProject(candidate.projectId, identity.projectId))
|
|
21
|
+
throw new Error('Workflow is restricted to another Project');
|
|
22
|
+
}
|
|
23
|
+
const selectedSteps = definitions.flatMap(candidate => candidate.steps.filter(step => candidate.id !== definition.id || !stepId || step.id === stepId));
|
|
24
|
+
const values = uniqueCredentials([...host.workflowMcpCredentials(), ...selectedSteps.flatMap(step => Object.values(step.secrets ?? {}).map(name => secrets.resolve(name)))]);
|
|
25
|
+
for (const candidate of definitions)
|
|
26
|
+
assertNoSecrets(publicDefinition(candidate), values);
|
|
27
|
+
assertNoSecrets(input, values, true);
|
|
28
|
+
if (!stepId)
|
|
29
|
+
parseValue(definition.inputSchema, input);
|
|
30
|
+
if (launch.kind === 'occurrence')
|
|
31
|
+
await dependencies.validateScheduledAgents(definition, input, identity.scope, launch.options.projectId);
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
const needsCode = selectedSteps.some(step => step.kind === 'shell' || step.kind === 'typescript');
|
|
34
|
+
const snapshot = await dependencies.snapshot(needsCode);
|
|
35
|
+
signal?.throwIfAborted();
|
|
36
|
+
const owner = launch.kind === 'session' ? launch.options.sessionId : executionOwnerKey({ kind: 'occurrence', occurrenceId: launch.options.occurrenceId });
|
|
37
|
+
let session;
|
|
38
|
+
let prepared = manifest;
|
|
39
|
+
let assertSession = () => { };
|
|
40
|
+
if (launch.kind === 'session') {
|
|
41
|
+
const opened = await host.openWorkflowSession(launch.options.sessionId);
|
|
42
|
+
host.assertWorkflowSession(launch.options.sessionId, opened.session);
|
|
43
|
+
if (opened.scope !== identity.scope || opened.projectId !== identity.projectId || opened.backend !== identity.backend)
|
|
44
|
+
throw new WorkflowConflict();
|
|
45
|
+
if (!opened.session)
|
|
46
|
+
throw new Error('Workflow Backend Session is unavailable');
|
|
47
|
+
session = opened;
|
|
48
|
+
prepared = Object.fromEntries(definitions.map(candidate => [candidate.id, withConfirmedNoControlOff(candidate, opened.session.capabilities.models)]));
|
|
49
|
+
const sessionId = launch.options.sessionId;
|
|
50
|
+
assertSession = () => host.assertWorkflowSession(sessionId, opened.session);
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
const environment = resources.create(owner, identity.scope, launch.options.mcpConnectionIds, snapshot.runtime, launch.options.attach).environment;
|
|
54
|
+
await environment.prepare(signal);
|
|
55
|
+
session = { occurrenceId: launch.options.occurrenceId, runtime: snapshot.runtime, ...identity };
|
|
56
|
+
}
|
|
57
|
+
const environment = resources.get(owner);
|
|
58
|
+
const stateRoot = host.filesystemStateRoot();
|
|
59
|
+
const code = launch.kind === 'occurrence' && needsCode ? await createCodeExecutors({
|
|
60
|
+
...(stateRoot ? { stateRoot } : {}), scope: identity.scope, sandbox: () => environment.sandbox(), isolationMode: snapshot.runtime.isolationMode,
|
|
61
|
+
runtimePath, nodePath: snapshot.runtime.nodePath ?? '', resolveSecret: async (name, abort) => secrets.resolve(name, abort),
|
|
62
|
+
}) : snapshot.code;
|
|
63
|
+
const pinned = new Map();
|
|
64
|
+
for (const step of selectedSteps)
|
|
65
|
+
if (step.kind === 'mcp')
|
|
66
|
+
pinned.set(step.tool.connectionId, [...pinned.get(step.tool.connectionId) ?? [], step.tool]);
|
|
67
|
+
for (const [connection, tools] of pinned)
|
|
68
|
+
await dependencies.discover(owner, connection, tools, snapshot.runtime.isolationMode, signal);
|
|
69
|
+
signal?.throwIfAborted();
|
|
70
|
+
const assertCurrent = () => {
|
|
71
|
+
signal?.throwIfAborted();
|
|
72
|
+
assertSession();
|
|
73
|
+
if (!isDeepStrictEqual(resolveWorkflowCalls(definition, id => store.getDefinition(id), stepId), manifest))
|
|
74
|
+
throw new WorkflowConflict();
|
|
75
|
+
};
|
|
76
|
+
return { owner, definition: prepared[definition.id], manifest: prepared, session: { ...session, matchesProject: (project) => sameProject(project, identity.projectId) }, values, runtime: snapshot.runtime, code, assertCurrent };
|
|
77
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { executionOwner } from '../workflows/records.js';
|
|
2
|
+
import { parseExecutionOwnerKey } from '../workflows/owner.js';
|
|
3
|
+
import { WorkflowEnvironment } from './workflow-environment.js';
|
|
4
|
+
class SessionResources {
|
|
5
|
+
host;
|
|
6
|
+
sessionId;
|
|
7
|
+
constructor(host, sessionId) { this.host = host; this.sessionId = sessionId; }
|
|
8
|
+
connections() { return this.host.workflowMcpConnections(this.sessionId); }
|
|
9
|
+
mcp(connectionId, mode, signal) { return this.host.openWorkflowMcp(this.sessionId, connectionId, mode, signal); }
|
|
10
|
+
sandbox() { return this.host.workflowSandbox(this.sessionId); }
|
|
11
|
+
}
|
|
12
|
+
export class OccurrenceResources {
|
|
13
|
+
attached;
|
|
14
|
+
environment;
|
|
15
|
+
host;
|
|
16
|
+
attachment;
|
|
17
|
+
constructor(environment, host, attachment) {
|
|
18
|
+
this.environment = environment;
|
|
19
|
+
this.host = host;
|
|
20
|
+
this.attachment = attachment;
|
|
21
|
+
}
|
|
22
|
+
connections() { return this.host.scheduledConnections(this.environment.connectionIds); }
|
|
23
|
+
mcp(connectionId, _mode, signal) { return this.environment.client(connectionId, signal); }
|
|
24
|
+
sandbox() { return this.environment.vm(); }
|
|
25
|
+
attach() { return this.attached ??= this.attachment().catch(error => { this.attached = undefined; throw error; }); }
|
|
26
|
+
restoreAttachment(attach) { this.attachment = attach; }
|
|
27
|
+
}
|
|
28
|
+
export class WorkflowExecutionResources {
|
|
29
|
+
occurrences = new Map();
|
|
30
|
+
host;
|
|
31
|
+
store;
|
|
32
|
+
runtimePath;
|
|
33
|
+
constructor(host, store, runtimePath) { this.host = host; this.store = store; this.runtimePath = runtimePath; }
|
|
34
|
+
get(owner) {
|
|
35
|
+
const resources = this.occurrences.get(owner);
|
|
36
|
+
if (resources)
|
|
37
|
+
return resources;
|
|
38
|
+
const identity = parseExecutionOwnerKey(owner);
|
|
39
|
+
if (identity.kind === 'occurrence')
|
|
40
|
+
throw new Error('Scheduled environment unavailable');
|
|
41
|
+
return new SessionResources(this.host, identity.sessionId);
|
|
42
|
+
}
|
|
43
|
+
occurrence(owner) {
|
|
44
|
+
const resources = this.occurrences.get(owner);
|
|
45
|
+
if (!resources)
|
|
46
|
+
throw new Error('Scheduled environment unavailable');
|
|
47
|
+
return resources;
|
|
48
|
+
}
|
|
49
|
+
create(owner, scope, connectionIds, runtime, attach) {
|
|
50
|
+
if (this.occurrences.has(owner))
|
|
51
|
+
throw new Error('Scheduled environment already exists');
|
|
52
|
+
const environment = new WorkflowEnvironment(this.host, owner, scope, connectionIds, runtime.isolationMode, this.store.ownerPath(owner), [this.runtimePath]);
|
|
53
|
+
const resources = new OccurrenceResources(environment, this.host, attach);
|
|
54
|
+
this.occurrences.set(owner, resources);
|
|
55
|
+
return resources;
|
|
56
|
+
}
|
|
57
|
+
restore(record, connectionIds, attach) {
|
|
58
|
+
const owner = executionOwner(record);
|
|
59
|
+
const existing = this.occurrences.get(owner);
|
|
60
|
+
if (existing)
|
|
61
|
+
existing.restoreAttachment(attach);
|
|
62
|
+
else {
|
|
63
|
+
if (!record.runtime)
|
|
64
|
+
throw new Error('Captured scheduled runtime unavailable');
|
|
65
|
+
this.create(owner, record.scope, connectionIds, record.runtime, attach);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async close(owner) { await this.occurrences.get(owner)?.environment.close(); }
|
|
69
|
+
async forget(owner) { await this.close(owner); this.occurrences.delete(owner); }
|
|
70
|
+
async closeAll() {
|
|
71
|
+
const results = await Promise.allSettled([...this.occurrences.keys()].map(owner => this.close(owner)));
|
|
72
|
+
const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
|
73
|
+
if (errors.length)
|
|
74
|
+
throw new AggregateError(errors, 'Workflow environment cleanup failed');
|
|
75
|
+
}
|
|
76
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { validateDefinition } from
|
|
2
|
-
import { WorkflowConflict } from
|
|
3
|
-
import { workflowRequestError } from
|
|
1
|
+
import { validateDefinition } from '../workflows/graph.js';
|
|
2
|
+
import { WorkflowConflict } from './workflow-executions.js';
|
|
3
|
+
import { workflowRequestError } from './workflow-routes.js';
|
|
4
4
|
export async function workflowExecutionRoutes(request, response, pathname, service, store) {
|
|
5
5
|
const match = /^\/api\/sessions\/([a-zA-Z0-9_-]+)\/workflows(?:\/([a-zA-Z0-9_-]+)(?:\/(cancel|recover|activity))?)?$/.exec(pathname);
|
|
6
6
|
const discovery = /^\/api\/sessions\/([a-zA-Z0-9_-]+)\/workflow-mcp(?:\/([a-zA-Z0-9_-]+))?$/.exec(pathname);
|
|
@@ -25,12 +25,13 @@ export async function workflowExecutionRoutes(request, response, pathname, servi
|
|
|
25
25
|
...(query.has('before') ? { before: Number(query.get('before')) } : {}),
|
|
26
26
|
...(query.get('latest') === 'true' ? { latest: true } : {}),
|
|
27
27
|
limit: Number(query.get('limit') ?? 100),
|
|
28
|
+
...(query.has('invocationId') ? { invocationId: query.get('invocationId') } : {}),
|
|
28
29
|
...(query.has('stepId') ? { stepId: query.get('stepId') } : {}),
|
|
29
30
|
...(query.has('attempt') ? { attempt: Number(query.get('attempt')) } : {}),
|
|
30
31
|
}));
|
|
31
32
|
}
|
|
32
33
|
else if (request.method === 'GET' && match && !match[3])
|
|
33
|
-
reply(200, match[2] ? service.view(match[1], match[2]) : service.list(match[1]));
|
|
34
|
+
reply(200, match[2] ? service.view(match[1], match[2], new URL(request.url, 'http://localhost').searchParams.get('invocationId') ?? undefined) : service.list(match[1]));
|
|
34
35
|
else if (request.method === 'POST' && !runtime) {
|
|
35
36
|
const chunks = [];
|
|
36
37
|
for await (const chunk of request) {
|
|
@@ -65,10 +66,12 @@ export async function workflowExecutionRoutes(request, response, pathname, servi
|
|
|
65
66
|
reply(200, await service.cancel(sessionId, executionId));
|
|
66
67
|
break;
|
|
67
68
|
case 'recover': {
|
|
69
|
+
if (body.invocationId !== undefined)
|
|
70
|
+
string('invocationId');
|
|
68
71
|
if (body.kind === 'continue')
|
|
69
|
-
keys('kind');
|
|
72
|
+
keys('kind', 'invocationId');
|
|
70
73
|
else if (body.kind === 'extend-loop') {
|
|
71
|
-
keys('kind', 'headerId', 'activation', 'try', 'guidance');
|
|
74
|
+
keys('kind', 'invocationId', 'headerId', 'activation', 'try', 'guidance');
|
|
72
75
|
string('headerId');
|
|
73
76
|
if (![body.activation, body.try].every(value => Number.isSafeInteger(value) && value > 0))
|
|
74
77
|
throw new Error();
|
|
@@ -76,11 +79,17 @@ export async function workflowExecutionRoutes(request, response, pathname, servi
|
|
|
76
79
|
throw new Error();
|
|
77
80
|
}
|
|
78
81
|
else if (body.kind === 'retry') {
|
|
79
|
-
keys('kind', 'stepId');
|
|
82
|
+
keys('kind', 'invocationId', 'stepId');
|
|
80
83
|
string('stepId');
|
|
81
84
|
}
|
|
85
|
+
else if (body.kind === 'retry-updated') {
|
|
86
|
+
keys('kind', 'invocationId', 'stepId', 'definitionRevision');
|
|
87
|
+
string('stepId');
|
|
88
|
+
if (!/^[a-f0-9]{64}$/.test(string('definitionRevision')))
|
|
89
|
+
throw new Error();
|
|
90
|
+
}
|
|
82
91
|
else if (body.kind === 'supply') {
|
|
83
|
-
keys('kind', 'stepId', 'output');
|
|
92
|
+
keys('kind', 'invocationId', 'stepId', 'output');
|
|
84
93
|
string('stepId');
|
|
85
94
|
if (!Object.hasOwn(body, 'output'))
|
|
86
95
|
throw new Error();
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { realpathSync } from 'node:fs';
|
|
2
|
+
import { invocationExecution } from '../workflows/invocations.js';
|
|
3
|
+
import { WorkflowStepError } from '../workflows/scheduler.js';
|
|
4
|
+
import { redactCredentials } from './credential-redaction.js';
|
|
5
|
+
import { WorkflowValidationError } from '../workflows/errors.js';
|
|
6
|
+
export { WorkflowValidationError } from '../workflows/errors.js';
|
|
7
|
+
export class WorkflowConflict extends Error {
|
|
8
|
+
constructor() { super('Workflow decision or slot is no longer available'); }
|
|
9
|
+
}
|
|
10
|
+
export function sameProject(project, scope) {
|
|
11
|
+
try {
|
|
12
|
+
return realpathSync(project) === scope;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export function redact(value, secrets) { return redactCredentials(value, secrets); }
|
|
19
|
+
export function redactEvent(event, secrets, publicId) {
|
|
20
|
+
const visit = (item, path = []) => {
|
|
21
|
+
if (typeof item === 'string') {
|
|
22
|
+
const key = path.at(-1);
|
|
23
|
+
if (path.length === 1 && ['type', 'state', 'on', 'decision', 'reason', 'level', 'trigger', 'effort'].includes(key))
|
|
24
|
+
return item;
|
|
25
|
+
if (['id', 'callId', 'askId', 'subagentId', 'turnId'].includes(key) && (path.length === 1 || path[0] === 'producer'))
|
|
26
|
+
return publicId(item);
|
|
27
|
+
return redact(item, secrets);
|
|
28
|
+
}
|
|
29
|
+
if (Array.isArray(item))
|
|
30
|
+
return item.map(value => visit(value, path));
|
|
31
|
+
if (item && typeof item === 'object')
|
|
32
|
+
return Object.fromEntries(Object.entries(item).map(([key, value]) => [key,
|
|
33
|
+
path.length === 0 && ['input', 'update', 'result'].includes(key) ? redact(value, secrets) : visit(value, [...path, key]),
|
|
34
|
+
]));
|
|
35
|
+
return item;
|
|
36
|
+
};
|
|
37
|
+
return visit(event);
|
|
38
|
+
}
|
|
39
|
+
export function confirmedAgentStep(step, models) {
|
|
40
|
+
const model = models.find(candidate => candidate.id === step.model);
|
|
41
|
+
return model && !model.effortLevels?.length && step.effort !== 'off' ? { ...step, effort: 'off' } : step;
|
|
42
|
+
}
|
|
43
|
+
export function withConfirmedNoControlOff(definition, models) {
|
|
44
|
+
const steps = definition.steps.map(step => step.kind === 'agent' ? confirmedAgentStep(step, models) : step);
|
|
45
|
+
return steps.some((step, index) => step !== definition.steps[index]) ? { ...definition, steps } : definition;
|
|
46
|
+
}
|
|
47
|
+
function publicStep({ secrets, ...step }) { return step; }
|
|
48
|
+
export function publicDefinition(definition) {
|
|
49
|
+
return { ...definition, steps: definition.steps.map(publicStep) };
|
|
50
|
+
}
|
|
51
|
+
export function publicExecutionData(record) {
|
|
52
|
+
const corrections = (updates) => updates?.map(update => ({ ...update, previousStep: publicStep(update.previousStep), nextStep: publicStep(update.nextStep) }));
|
|
53
|
+
return {
|
|
54
|
+
...record,
|
|
55
|
+
definition: publicDefinition(record.definition),
|
|
56
|
+
definitionUpdates: corrections(record.definitionUpdates),
|
|
57
|
+
retainedDefinitions: record.retainedDefinitions && Object.fromEntries(Object.entries(record.retainedDefinitions).map(([id, definition]) => [id, publicDefinition(definition)])),
|
|
58
|
+
invocations: record.invocations && Object.fromEntries(Object.entries(record.invocations).map(([id, invocation]) => [id, { ...invocation, definitionUpdates: corrections(invocation.definitionUpdates) }])),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export function assertNoSecrets(value, secrets, checkKeys = false) {
|
|
62
|
+
const visit = (item) => {
|
|
63
|
+
if (typeof item === 'string')
|
|
64
|
+
return redact(item, secrets) !== item;
|
|
65
|
+
if (Array.isArray(item))
|
|
66
|
+
return item.some(visit);
|
|
67
|
+
return !!item && typeof item === 'object' && Object.entries(item).some(([key, value]) => (checkKeys && visit(key)) || visit(value));
|
|
68
|
+
};
|
|
69
|
+
if (visit(value))
|
|
70
|
+
throw new WorkflowValidationError('Saved workflow data cannot contain secret values');
|
|
71
|
+
}
|
|
72
|
+
export function safeError(error, values) {
|
|
73
|
+
const message = redact(error instanceof Error ? error.message : String(error), values);
|
|
74
|
+
return error instanceof WorkflowStepError ? new WorkflowStepError(message, error.partialOutput === undefined ? undefined : redact(error.partialOutput, values)) : new Error(message);
|
|
75
|
+
}
|
|
76
|
+
export function outcomeNamingData(record) {
|
|
77
|
+
const stepNames = new Map(record.definition.steps.map(step => [step.id, step.name]));
|
|
78
|
+
function* results() {
|
|
79
|
+
for (const id in record.steps) {
|
|
80
|
+
const output = record.steps[id].output;
|
|
81
|
+
if (output !== undefined)
|
|
82
|
+
yield { step: stepNames.get(id) ?? id, output };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
function* errors() {
|
|
86
|
+
for (const id in record.steps)
|
|
87
|
+
for (const attempt of record.steps[id].attempts) {
|
|
88
|
+
if (attempt.error !== undefined)
|
|
89
|
+
yield {
|
|
90
|
+
step: stepNames.get(id) ?? id, attempt: attempt.number, error: attempt.error,
|
|
91
|
+
...(attempt.partialOutput === undefined ? {} : { partialOutput: attempt.partialOutput }),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return { results: record.result === undefined ? results() : record.result, errors: errors() };
|
|
96
|
+
}
|
|
97
|
+
export function uniqueCredentials(values) { return [...new Set(values.filter(Boolean))]; }
|
|
98
|
+
export function relayContext(record, stepId, attempt, invocationId) {
|
|
99
|
+
const step = record.definition.steps.find(item => item.id === stepId);
|
|
100
|
+
return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${invocationId ? ` · Invocation ${invocationId}` : ''}${record.testStepId ? ' · Step test' : ''}`;
|
|
101
|
+
}
|
|
102
|
+
export function relaySignal(request, parent) { return parent ? AbortSignal.any([request, parent]) : request; }
|
|
103
|
+
export function selectWorkflowInvocation(root, invocationId) {
|
|
104
|
+
return invocationId === undefined ? root : { ...invocationExecution(root, invocationId), id: root.id };
|
|
105
|
+
}
|
|
106
|
+
export function attemptIdentity(context) {
|
|
107
|
+
return { stepId: context.step.id, attempt: context.attempt ?? 1, ...(context.invocationId === undefined ? {} : { invocationId: context.invocationId }) };
|
|
108
|
+
}
|
|
109
|
+
export function spendKey(stepId, invocationId) { return invocationId === undefined ? stepId : JSON.stringify([invocationId, stepId]); }
|
|
110
|
+
export function sumSpend(values) {
|
|
111
|
+
const result = { tokens: 0, cached: 0, costUSD: 0, models: [] };
|
|
112
|
+
for (const value of values) {
|
|
113
|
+
result.tokens += value.tokens;
|
|
114
|
+
result.cached += value.cached;
|
|
115
|
+
result.costUSD += value.costUSD;
|
|
116
|
+
for (const model of value.models) {
|
|
117
|
+
const existing = result.models.find(item => item.id === model.id);
|
|
118
|
+
if (existing) {
|
|
119
|
+
existing.tokens += model.tokens;
|
|
120
|
+
existing.cached += model.cached;
|
|
121
|
+
existing.costUSD += model.costUSD;
|
|
122
|
+
}
|
|
123
|
+
else
|
|
124
|
+
result.models.push({ ...model });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return result;
|
|
128
|
+
}
|