@nathanstephenson/flow 0.1.10-beta.2 → 0.1.10-beta.3

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.
Files changed (60) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{claude-COCNALN2.mjs → claude-6L5KCQWJ.mjs} +63 -15
  3. package/build/backend-worker-chunks/{pi-HJKTV2TH.mjs → pi-QNU2YE4G.mjs} +10 -10
  4. package/build/backend-worker.mjs +42 -5
  5. package/dist/backend/claude/background-calls.js +7 -3
  6. package/dist/backend/claude/index.js +37 -5
  7. package/dist/backend/claude/subagents.js +30 -9
  8. package/dist/backend/fake/index.js +20 -5
  9. package/dist/backend/pi/index.js +1 -0
  10. package/dist/backend/pi/subagents.js +7 -3
  11. package/dist/backend/worker/entry.js +19 -5
  12. package/dist/backend/worker/index.js +21 -2
  13. package/dist/backend/worker/rpc.js +13 -0
  14. package/dist/backend/worker/sandbox-mcp.js +18 -7
  15. package/dist/build-id +1 -1
  16. package/dist/cli/bootstrap.js +1 -1
  17. package/dist/client/reduce.js +9 -3
  18. package/dist/client/subagent-tree.js +49 -0
  19. package/dist/daemon/git.js +10 -7
  20. package/dist/daemon/host.js +88 -21
  21. package/dist/daemon/runtime.js +63 -3
  22. package/dist/daemon/server.js +3 -0
  23. package/dist/daemon/store.js +2 -0
  24. package/dist/daemon/workflow-environment.js +191 -0
  25. package/dist/daemon/workflow-execution-launch.js +77 -0
  26. package/dist/daemon/workflow-execution-resources.js +76 -0
  27. package/dist/daemon/workflow-execution-values.js +128 -0
  28. package/dist/daemon/workflow-executions.js +272 -285
  29. package/dist/daemon/workflow-schedule-driver.js +247 -0
  30. package/dist/daemon/workflow-schedule-routes.js +137 -0
  31. package/dist/daemon/workflow-schedules.js +341 -0
  32. package/dist/isolation/sandbox.js +30 -14
  33. package/dist/isolation/shared-sandbox.js +3 -3
  34. package/dist/protocol/workflow-schedules.js +1 -0
  35. package/dist/tui/render.js +7 -1
  36. package/dist/workflows/calls.js +10 -7
  37. package/dist/workflows/errors.js +2 -0
  38. package/dist/workflows/executors.js +1 -1
  39. package/dist/workflows/invocations.js +8 -5
  40. package/dist/workflows/owner.js +45 -0
  41. package/dist/workflows/records.js +8 -2
  42. package/dist/workflows/schedule-errors.js +2 -0
  43. package/dist/workflows/schedule-store.js +385 -0
  44. package/dist/workflows/scheduler.js +29 -18
  45. package/dist/workflows/schedules.js +129 -0
  46. package/dist/workflows/store.js +110 -11
  47. package/package.json +2 -1
  48. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  49. package/web/dist/assets/index-Miy2nveb.js +40 -0
  50. package/web/dist/assets/{settings-mcp-sebWClE0.js → settings-mcp-Vf_fCXyE.js} +1 -1
  51. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  52. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  53. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  54. package/web/dist/index.html +4 -3
  55. package/web/dist/assets/index-CLdr6AA0.js +0 -40
  56. package/web/dist/assets/index-DHAcGIoF.css +0 -2
  57. package/web/dist/assets/settings-workflows-BvArjkes.js +0 -23
  58. package/web/dist/assets/workflow-editors-Tztq_Opa.js +0 -139
  59. package/web/dist/assets/workflows-CdDynCfW.js +0 -7
  60. package/web/dist/assets/workflows-pane-DaqHEeXu.js +0 -1
@@ -4,6 +4,9 @@ import { ConfigStore } from "./config-store.js";
4
4
  import { SecretStore } from "./secret-store.js";
5
5
  import { WorkflowStore } from "../workflows/store.js";
6
6
  import { WorkflowExecutionService } from "./workflow-executions.js";
7
+ import { WorkflowScheduleStore } from "../workflows/schedule-store.js";
8
+ import { WorkflowScheduleService } from "./workflow-schedules.js";
9
+ import { scheduleDriver } from "./workflow-schedule-driver.js";
7
10
  import { WorkflowBuilderService } from "./workflow-builder.js";
8
11
  import { workflowCatalogue } from "./workflow-routes.js";
9
12
  import { WorkflowMcpAuthoringService } from "./workflow-mcp-authoring.js";
@@ -52,6 +55,8 @@ export async function startRuntime(options) {
52
55
  defaultEffort: config.defaultEffort, defaultPermissionMode: config.defaultPermissionMode, autoCompaction: config.autoCompaction, compactionModel: config.compactionModel, summaryModel: config.summaryModel,
53
56
  });
54
57
  const shells = new ShellRegistry();
58
+ let workflowSchedules;
59
+ let workflowExecutions;
55
60
  let workflowBuilders;
56
61
  let workflowMcpAuthoring;
57
62
  let running;
@@ -61,6 +66,19 @@ export async function startRuntime(options) {
61
66
  let stopping;
62
67
  const stop = () => stopping ??= (async () => {
63
68
  clearInterval(sweep);
69
+ const scheduledErrors = [];
70
+ try {
71
+ await workflowSchedules?.stopAdmission();
72
+ }
73
+ catch (error) {
74
+ scheduledErrors.push(error);
75
+ }
76
+ try {
77
+ await workflowExecutions?.stopScheduled();
78
+ }
79
+ catch (error) {
80
+ scheduledErrors.push(error);
81
+ }
64
82
  const interrupt = async () => { await Promise.all([host.shutdown(), workflowBuilders?.shutdown(), workflowMcpAuthoring?.shutdown(), shells.killAll(), reaping]); };
65
83
  if (running)
66
84
  await running.stopAdmission(interrupt);
@@ -78,13 +96,16 @@ export async function startRuntime(options) {
78
96
  oidc?.dispose();
79
97
  }
80
98
  ownership.release();
99
+ if (scheduledErrors.length)
100
+ throw new AggregateError(scheduledErrors, 'Scheduled workflow cleanup failed');
81
101
  })();
82
102
  cleanup = stop;
83
103
  registerBackends(host);
84
104
  trimTimings(root);
85
105
  void host.models(config.projectRoot() ?? process.cwd());
86
106
  const workflows = new WorkflowStore(root);
87
- const workflowExecutions = new WorkflowExecutionService(host, workflows, secrets, config, options.workflowRuntime());
107
+ store.onSessionDeleted = sessionId => workflows.deleteOwner({ kind: 'session', sessionId });
108
+ workflowExecutions = new WorkflowExecutionService(host, workflows, secrets, config, options.workflowRuntime());
88
109
  workflowMcpAuthoring = new WorkflowMcpAuthoringService({ host, config, scope: process.cwd() });
89
110
  workflowBuilders = new WorkflowBuilderService({
90
111
  host, config, scope: process.cwd(), stateRoot: root,
@@ -99,9 +120,47 @@ export async function startRuntime(options) {
99
120
  mcpCatalogue: (scope, projectId, scopeIdentity) => workflowMcpAuthoring.catalogue(projectId, { scope, scopeIdentity }),
100
121
  mcpTool: (scope, projectId, scopeIdentity, connectionId, toolName) => workflowMcpAuthoring.tool(projectId, connectionId, toolName, { scope, scopeIdentity }),
101
122
  });
123
+ try {
124
+ const schedules = new WorkflowScheduleStore(root);
125
+ workflowSchedules = new WorkflowScheduleService(schedules, scheduleDriver({ host, config, workflows, executions: workflowExecutions, schedules, transcripts: store }));
126
+ workflowExecutions.onScheduledResult = async (record) => { workflowSchedules.result(record); };
127
+ }
128
+ catch {
129
+ workflowExecutions.scheduledOwnershipAvailable = false;
130
+ console.error('Workflow Schedule initialization failed. Scheduling is disabled. Other Session Host services will continue.');
131
+ }
102
132
  await host.load();
133
+ try {
134
+ await workflowSchedules?.start();
135
+ }
136
+ catch {
137
+ console.error('Workflow Schedule reconciliation failed. Other Session Host services will continue.');
138
+ }
103
139
  workflowExecutions.reconcile();
104
- sweep = setInterval(() => { reaping = reaping.then(async () => { await host.reap(); }); }, 60 * 60 * 1000);
140
+ reaping = reaping.then(async () => {
141
+ try {
142
+ await workflowSchedules?.prune();
143
+ }
144
+ catch {
145
+ console.error('Workflow Schedule retention failed. Cleanup will be retried.');
146
+ }
147
+ });
148
+ sweep = setInterval(() => {
149
+ reaping = reaping.then(async () => {
150
+ try {
151
+ await host.reap();
152
+ }
153
+ catch {
154
+ console.error('Agent Session Reaping failed. The next sweep will retry.');
155
+ }
156
+ try {
157
+ await workflowSchedules?.prune();
158
+ }
159
+ catch {
160
+ console.error('Workflow Schedule retention failed. The next sweep will retry.');
161
+ }
162
+ });
163
+ }, 60 * 60 * 1000);
105
164
  sweep.unref();
106
165
  host.onSessionClosed(sessionId => shells.killFor(sessionId));
107
166
  const token = readOrCreateToken(root);
@@ -110,7 +169,7 @@ export async function startRuntime(options) {
110
169
  instanceId: ownership.instanceId, pid: process.pid, version: options.version, url: '', token, mode: options.mode,
111
170
  settings: { port: options.port ?? 0, address: options.address ?? '127.0.0.1', cwd: process.cwd(), oidc: oidcFingerprint() },
112
171
  };
113
- const hasActiveWork = () => host.hasActiveWork() || workflowBuilders.hasActiveWork() || workflowMcpAuthoring.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
172
+ const hasActiveWork = () => !!workflowSchedules?.hasActiveWork() || host.hasActiveWork() || workflowBuilders.hasActiveWork() || workflowMcpAuthoring.hasActiveWork() || shells.hasLiveShells() || host.list().some(session => workflowExecutions.list(session.id).occupied);
114
173
  const updates = new WebUpdateController({
115
174
  root,
116
175
  installedVersion: options.version,
@@ -124,6 +183,7 @@ export async function startRuntime(options) {
124
183
  control: { identity, stop, hasActiveWork },
125
184
  updates,
126
185
  host, token, shells, config, mcpAuth, store, workflows, secrets, workflowExecutions, workflowBuilders, workflowMcpAuthoring,
186
+ ...(workflowSchedules === undefined ? {} : { workflowSchedules }),
127
187
  assets: options.assets(), scope: process.cwd(),
128
188
  ...(oidc === undefined ? {} : { oidc }),
129
189
  ...(options.port === undefined ? {} : { port: options.port }),
@@ -2,6 +2,7 @@ import { createServer } from "node:http";
2
2
  import { mediaTypeOf } from "../protocol/attachments.js";
3
3
  import { ConfigError } from "./config.js";
4
4
  import { workflowRoutes } from "./workflow-routes.js";
5
+ import { workflowScheduleRoutes } from "./workflow-schedule-routes.js";
5
6
  import { workflowBuilderRoutes } from "./workflow-builder-routes.js";
6
7
  import { workflowMcpAuthoringRoutes } from "./workflow-mcp-authoring-routes.js";
7
8
  import { hostControlRoute } from "./host-control-routes.js";
@@ -291,6 +292,8 @@ ${ICON_LINKS}</head><body><script>window.location.replace(${JSON.stringify(locat
291
292
  }
292
293
  if (await workflowMcpAuthoringRoutes(request, response, url.pathname, options.workflowMcpAuthoring))
293
294
  return;
295
+ if (await workflowScheduleRoutes(request, response, url, options.workflowSchedules, options.workflowExecutions))
296
+ return;
294
297
  if (await workflowBuilderRoutes(request, response, url.pathname, options.workflowBuilders))
295
298
  return;
296
299
  if (await workflowExecutionRoutes(request, response, url.pathname, options.workflowExecutions, options.workflows))
@@ -9,6 +9,7 @@ export function defaultStateRoot() {
9
9
  }
10
10
  export class TranscriptStore {
11
11
  root;
12
+ onSessionDeleted;
12
13
  constructor(root = defaultStateRoot()) {
13
14
  this.root = root;
14
15
  }
@@ -117,6 +118,7 @@ export class TranscriptStore {
117
118
  */
118
119
  deleteSession(sessionId) {
119
120
  rmSync(this.sessionDir(sessionId), { recursive: true, force: true });
121
+ this.onSessionDeleted?.(sessionId);
120
122
  }
121
123
  async listSessionIds() {
122
124
  try {
@@ -0,0 +1,191 @@
1
+ import { existsSync, mkdirSync } 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
+ constructor(host, ownerId, scope, connectionIds, mode, stateDir, readablePaths = []) {
31
+ this.host = host;
32
+ this.ownerId = ownerId;
33
+ this.scope = scope;
34
+ this.connectionIds = connectionIds;
35
+ this.mode = mode;
36
+ this.stateDir = stateDir;
37
+ this.readablePaths = readablePaths;
38
+ }
39
+ async prepare(signal) {
40
+ this.lifetime.signal.throwIfAborted();
41
+ signal?.throwIfAborted();
42
+ await waitForAbort(this.opening ??= this.open(signal ? AbortSignal.any([signal, this.lifetime.signal]) : this.lifetime.signal), signal);
43
+ signal?.throwIfAborted();
44
+ this.lifetime.signal.throwIfAborted();
45
+ }
46
+ recover(signal) {
47
+ return this.recovering ??= (async () => {
48
+ let failed = false;
49
+ await this.opening?.catch(() => { failed = true; });
50
+ signal?.throwIfAborted();
51
+ this.lifetime.signal.throwIfAborted();
52
+ if (failed || this.workerFailure) {
53
+ await this.stopWorker();
54
+ this.worker = undefined;
55
+ this.rpc = undefined;
56
+ this.mcp = undefined;
57
+ this.workerFailure = undefined;
58
+ this.opening = undefined;
59
+ }
60
+ await this.prepare(signal);
61
+ })().finally(() => { this.recovering = undefined; });
62
+ }
63
+ async open(signal) {
64
+ if (this.mode !== 'none')
65
+ validateFilesystemScope({ scope: this.scope, expectedScope: this.scope, ...(this.host.filesystemStateRoot() ? { stateRoot: this.host.filesystemStateRoot() } : {}) });
66
+ if (this.mode !== 'sandbox')
67
+ return;
68
+ const support = this.host.sandboxSupport();
69
+ if (!support?.supported || isSea())
70
+ throw sandboxUnavailable();
71
+ const packageRoot = fileURLToPath(new URL('../..', import.meta.url));
72
+ const bundle = join(packageRoot, 'build/backend-worker.mjs');
73
+ if (!existsSync(bundle))
74
+ throw new Error('Sandbox worker bundle unavailable');
75
+ if (!this.sandbox) {
76
+ mkdirSync(this.stateDir, { recursive: true, mode: 0o700 });
77
+ const shared = this.host.sharedSandbox();
78
+ const roots = shared?.roots();
79
+ if (roots && !roots.slice(0, 3).some(root => this.scope === root || this.scope.startsWith(root + '/')))
80
+ throw new Error('Scope is outside shared Sandbox roots');
81
+ const attachment = shared ? this.host.scheduledSandboxMounts(this.scope) : { writable: [], readable: [] };
82
+ const mounts = sandboxMounts([...(roots ?? [this.scope, this.stateDir]), ...attachment.writable], [packageRoot, ...this.readablePaths, ...nodeExecutionAssets([bundle]), ...attachment.readable]);
83
+ if (shared) {
84
+ const lease = await shared.acquire(support.provider, roots[0], mounts, signal);
85
+ this.sandbox = lease.sandbox;
86
+ this.release = lease.release;
87
+ }
88
+ else {
89
+ this.ownedProvider = support.provider;
90
+ this.sandbox = await createSandbox(support.provider, { name: `flow-${this.ownerId}`, workspace: this.scope, mounts, env: {} }, join(this.stateDir, 'sandbox.json'), signal);
91
+ }
92
+ }
93
+ signal.throwIfAborted();
94
+ if (!this.connectionIds.length)
95
+ return;
96
+ const mcp = this.mcp = await this.host.scheduledSandboxMcp(this.scope, this.connectionIds);
97
+ signal.throwIfAborted();
98
+ const launch = this.sandbox.command(this.scope, [support.provider.nodePath, bundle], { FLOW_BACKEND_WORKER: '1' });
99
+ const worker = this.worker = launchWorker({ command: launch.command, args: launch.args, env: {} });
100
+ const fail = (error) => {
101
+ if (this.worker === worker)
102
+ this.workerFailure ??= error;
103
+ rpc.close(error);
104
+ };
105
+ const rpc = this.rpc = new WorkerRpc(message => {
106
+ try {
107
+ worker.send(message, error => { if (error)
108
+ fail(error); });
109
+ }
110
+ catch (error) {
111
+ fail(error instanceof Error ? error : new Error(String(error)));
112
+ throw error;
113
+ }
114
+ }, async (method, args) => {
115
+ if (method !== 'mcp.token' || typeof args[0] !== 'string' || typeof args[1] !== 'boolean')
116
+ throw new Error('Unexpected worker callback');
117
+ return mcp.token(args[0], args[1]);
118
+ }, () => { });
119
+ worker.onMessage(message => rpc.receive(message), fail);
120
+ worker.child.once('error', fail);
121
+ worker.child.stdout?.once('close', () => fail(new Error('Workflow worker disconnected')));
122
+ worker.child.once('exit', () => fail(new Error('Workflow worker exited')));
123
+ try {
124
+ await rpc.call('mcp.initialize', [{ scope: this.scope, connections: mcp.definitions() }], AbortSignal.any([signal, AbortSignal.timeout(300_000)]));
125
+ signal.throwIfAborted();
126
+ mcp.attach((method, args, callSignal) => rpc.call(method, args, callSignal));
127
+ }
128
+ catch (error) {
129
+ fail(error instanceof Error ? error : new Error(String(error)));
130
+ await this.stopWorker();
131
+ throw error;
132
+ }
133
+ }
134
+ async vm() { await this.prepare(); if (!this.sandbox)
135
+ throw sandboxUnavailable(); return this.sandbox; }
136
+ async client(connectionId, signal) {
137
+ await this.prepare(signal);
138
+ if (!this.connectionIds.includes(connectionId))
139
+ throw new Error('MCP connection not selected');
140
+ if (this.workerFailure)
141
+ throw this.workerFailure;
142
+ const client = this.mode === 'sandbox' ? await this.mcp.directView(connectionId, signal) : await this.host.scheduledMcp(this.scope, [connectionId], this.mode);
143
+ this.clients.add(client);
144
+ if (this.lifetime.signal.aborted || signal?.aborted) {
145
+ await client.dispose({ waitForExit: true });
146
+ this.clients.delete(client);
147
+ this.lifetime.signal.throwIfAborted();
148
+ signal?.throwIfAborted();
149
+ }
150
+ const dispose = client.dispose.bind(client);
151
+ client.dispose = async (...args) => { await dispose(...args); this.clients.delete(client); };
152
+ return client;
153
+ }
154
+ async stopWorker() {
155
+ try {
156
+ await this.worker?.stop(() => this.rpc.call('dispose'));
157
+ }
158
+ finally {
159
+ this.rpc?.close(new Error('Workflow worker stopped'));
160
+ }
161
+ }
162
+ close() {
163
+ this.lifetime.abort(new Error('Workflow environment is stopping'));
164
+ return this.closing ??= (async () => {
165
+ await Promise.allSettled([this.opening, this.recovering]);
166
+ const results = await Promise.allSettled([
167
+ ...[...this.clients].map(client => Promise.resolve().then(() => client.dispose({ waitForExit: true }))),
168
+ this.stopWorker(),
169
+ ]);
170
+ const errors = results.filter(result => result.status === 'rejected').map(result => result.reason);
171
+ try {
172
+ if (this.release) {
173
+ this.release();
174
+ this.release = undefined;
175
+ this.sandbox = undefined;
176
+ }
177
+ else if (this.sandbox) {
178
+ await this.sandbox.close();
179
+ this.sandbox = undefined;
180
+ }
181
+ else if (this.ownedProvider)
182
+ await removeOwnedSandbox(this.ownedProvider, join(this.stateDir, 'sandbox.json'), `flow-${this.ownerId}`);
183
+ }
184
+ catch (error) {
185
+ errors.push(error);
186
+ }
187
+ if (errors.length)
188
+ throw new AggregateError(errors, 'Workflow environment cleanup failed');
189
+ })().catch(error => { this.closing = undefined; throw error; });
190
+ }
191
+ }
@@ -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(); }
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
+ }
@@ -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
+ }