@nathanstephenson/flow 0.1.10-beta.1 → 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 (73) hide show
  1. package/README.md +18 -0
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-LO7O6NAM.mjs} +9 -7
  3. package/build/backend-worker-chunks/{claude-UXZDJKZQ.mjs → claude-6L5KCQWJ.mjs} +99 -21
  4. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-QNU2YE4G.mjs} +45 -13
  5. package/build/backend-worker.mjs +48 -7
  6. package/dist/backend/claude/background-calls.js +7 -3
  7. package/dist/backend/claude/index.js +72 -10
  8. package/dist/backend/claude/subagents.js +30 -9
  9. package/dist/backend/fake/index.js +36 -6
  10. package/dist/backend/pi/index.js +34 -2
  11. package/dist/backend/pi/state.js +16 -1
  12. package/dist/backend/pi/subagents.js +7 -3
  13. package/dist/backend/worker/claude-state.js +22 -0
  14. package/dist/backend/worker/entry.js +25 -6
  15. package/dist/backend/worker/index.js +30 -5
  16. package/dist/backend/worker/protocol.js +1 -1
  17. package/dist/backend/worker/rpc.js +13 -0
  18. package/dist/backend/worker/sandbox-mcp.js +18 -7
  19. package/dist/backend/workflow-tools.js +9 -7
  20. package/dist/build-id +1 -1
  21. package/dist/cli/bootstrap.js +1 -1
  22. package/dist/client/reduce.js +29 -3
  23. package/dist/client/subagent-tree.js +49 -0
  24. package/dist/daemon/git.js +10 -7
  25. package/dist/daemon/host.js +226 -26
  26. package/dist/daemon/runtime.js +71 -3
  27. package/dist/daemon/server.js +3 -0
  28. package/dist/daemon/store.js +2 -0
  29. package/dist/daemon/workflow-builder-guidance.js +1 -1
  30. package/dist/daemon/workflow-builder.js +36 -11
  31. package/dist/daemon/workflow-environment.js +191 -0
  32. package/dist/daemon/workflow-execution-launch.js +77 -0
  33. package/dist/daemon/workflow-execution-resources.js +76 -0
  34. package/dist/daemon/workflow-execution-routes.js +9 -6
  35. package/dist/daemon/workflow-execution-values.js +128 -0
  36. package/dist/daemon/workflow-executions.js +382 -300
  37. package/dist/daemon/workflow-routes.js +39 -0
  38. package/dist/daemon/workflow-schedule-driver.js +247 -0
  39. package/dist/daemon/workflow-schedule-routes.js +137 -0
  40. package/dist/daemon/workflow-schedules.js +341 -0
  41. package/dist/isolation/sandbox.js +30 -14
  42. package/dist/isolation/shared-sandbox.js +3 -3
  43. package/dist/protocol/events.js +2 -0
  44. package/dist/protocol/workflow-schedules.js +1 -0
  45. package/dist/tui/render.js +7 -1
  46. package/dist/workflows/calls.js +53 -0
  47. package/dist/workflows/errors.js +2 -0
  48. package/dist/workflows/executors.js +1 -1
  49. package/dist/workflows/graph.js +78 -4
  50. package/dist/workflows/invocations.js +23 -0
  51. package/dist/workflows/owner.js +45 -0
  52. package/dist/workflows/records.js +124 -8
  53. package/dist/workflows/recovery.js +37 -1
  54. package/dist/workflows/schedule-errors.js +2 -0
  55. package/dist/workflows/schedule-store.js +385 -0
  56. package/dist/workflows/scheduler.js +351 -92
  57. package/dist/workflows/schedules.js +129 -0
  58. package/dist/workflows/schema.js +2 -0
  59. package/dist/workflows/store.js +110 -11
  60. package/package.json +2 -1
  61. package/web/dist/assets/index-BGu3YSP7.css +2 -0
  62. package/web/dist/assets/index-Miy2nveb.js +40 -0
  63. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-Vf_fCXyE.js} +1 -1
  64. package/web/dist/assets/settings-workflows-DVKxJWQm.js +23 -0
  65. package/web/dist/assets/workflows-Dobqzjg-.js +146 -0
  66. package/web/dist/assets/workflows-pane-KB-Q76KZ.js +1 -0
  67. package/web/dist/index.html +4 -3
  68. package/web/dist/assets/index-DRfeO6GJ.js +0 -40
  69. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  70. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  71. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  72. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  73. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
@@ -1,24 +1,35 @@
1
- import { recoveryRevision, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, createReadStream, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { isDeepStrictEqual } from 'node:util';
6
+ import { ZodError } from 'zod';
7
+ import { executionOwner } from "../workflows/records.js";
8
+ import { executionOwnerKey, executionOwnerOf } from "../workflows/owner.js";
9
+ import { WorkflowExecutionResources } from "./workflow-execution-resources.js";
10
+ import { prepareWorkflowLaunch } from "./workflow-execution-launch.js";
11
+ import { resolveWorkflowCalls } from "../workflows/calls.js";
12
+ import { invocationExecution } from "../workflows/invocations.js";
13
+ import { recoveryRevision, recoverySteps, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
2
14
  import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../backend/workflow-tools.js";
3
15
  import { redactCredentials } from "./credential-redaction.js";
4
16
  import { workflowAgentNameInput, workflowOutcomeNameInput } from "./summariser.js";
5
17
  import { connectionIdentity, snapshotTool, sameSchema } from "./workflow-mcp.js";
6
18
  import { validateJsonSchema } from "../workflows/json-schema.js";
7
19
  import { boundedMcpValue, validateMcpSchemas } from "../workflows/mcp.js";
8
- import { createReadStream } from 'node:fs';
9
- import { isDeepStrictEqual } from 'node:util';
10
- import { createInterface } from 'node:readline';
11
- import { randomUUID } from 'node:crypto';
12
- import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
13
- import { join } from 'node:path';
20
+ import { assertNoSecrets, attemptIdentity, confirmedAgentStep, outcomeNamingData, publicDefinition, publicExecutionData, redact, redactEvent, relayContext, relaySignal, safeError, sameProject, selectWorkflowInvocation, spendKey, sumSpend, uniqueCredentials, WorkflowConflict, WorkflowValidationError } from "./workflow-execution-values.js";
14
21
  import { leadingSkillInvocation } from "../protocol/skills.js";
15
22
  import { createCodeExecutors } from "../workflows/executors.js";
16
23
  import { parseValue } from "../workflows/schema.js";
17
24
  import { WorkflowStepError, WorkflowScheduler, WorkflowLoopConflict } from "../workflows/scheduler.js";
18
25
  import { workflowRuntimeOptions } from "../workflows/runtime-settings.js";
19
26
  import { SessionHost } from "./host.js";
27
+ export { WorkflowConflict } from "./workflow-execution-values.js";
20
28
  export class WorkflowExecutionService {
21
29
  scheduler;
30
+ resources;
31
+ onScheduledResult;
32
+ scheduledOwnershipAvailable = true;
22
33
  host;
23
34
  store;
24
35
  secrets;
@@ -40,6 +51,7 @@ export class WorkflowExecutionService {
40
51
  runtimeSnapshots = new Map();
41
52
  runtimeOptions;
42
53
  checkingCode;
54
+ scheduledPublications = new Map();
43
55
  cancelling = new Map();
44
56
  constructor(host, store, secrets, config, runtimePath) {
45
57
  store.redact = value => redactCredentials(value, host.workflowMcpCredentials());
@@ -48,6 +60,7 @@ export class WorkflowExecutionService {
48
60
  this.secrets = secrets;
49
61
  this.config = config;
50
62
  this.runtimePath = runtimePath;
63
+ this.resources = new WorkflowExecutionResources(host, store, runtimePath);
51
64
  const code = (kind) => ({
52
65
  check: (step, session) => {
53
66
  const executor = (this.checkingCode ?? this.code)[kind];
@@ -72,7 +85,7 @@ export class WorkflowExecutionService {
72
85
  check: (step, session) => {
73
86
  if (step.kind !== 'mcp')
74
87
  throw new Error('Invalid MCP step');
75
- this.checkMcp(session.sessionId, step.tool);
88
+ this.checkMcp(executionOwner(session), step.tool);
76
89
  },
77
90
  execute: context => this.mcp(context),
78
91
  },
@@ -81,33 +94,64 @@ export class WorkflowExecutionService {
81
94
  check: (step, session) => {
82
95
  if (step.kind !== 'agent')
83
96
  throw new Error('Invalid Agent step');
84
- const backend = host.workflowSession(session.sessionId).session;
85
- if (!backend?.startWorkflowSubagent)
86
- throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
87
- const model = backend.capabilities.models.find(model => model.id === step.model);
88
- if (!model)
89
- throw new Error(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
90
- const levels = model.effortLevels ?? [];
91
- if (levels.length > 0 && !levels.includes(step.effort)) {
92
- throw new Error(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.join(', ')}.`);
93
- }
94
- if (levels.length === 0 && step.effort !== 'off') {
95
- throw new Error(`${model.label ?? model.id} has no Effort control. Re-select the model to use internal off.`);
96
- }
97
+ if (session.sessionId)
98
+ this.checkAgent(session.sessionId, step);
97
99
  },
98
100
  execute: async (context) => {
99
101
  try {
100
- return await this.agent(context);
102
+ return await this.agent(await this.attachContext(context));
101
103
  }
102
104
  catch (error) {
103
105
  throw safeError(error, this.secretValues.get(context.executionId) ?? []);
104
106
  }
105
107
  },
106
108
  },
107
- });
109
+ }, record => this.watch(record));
108
110
  host.workflowOwner = this;
109
111
  this.refresh();
110
112
  }
113
+ async attachContext(context) {
114
+ if (context.sessionId)
115
+ return { ...context, sessionId: context.sessionId };
116
+ const identity = executionOwnerOf(context);
117
+ if (identity.kind !== 'occurrence')
118
+ throw new Error('Agent Session required');
119
+ const sessionId = await this.resources.occurrence(executionOwnerKey(identity)).attach();
120
+ context.signal.throwIfAborted();
121
+ this.scheduler.associate(identity.occurrenceId, context.executionId, sessionId);
122
+ return { ...context, sessionId };
123
+ }
124
+ startScheduled(options) { return this.launch({ kind: 'occurrence', options }); }
125
+ async expireScheduled(occurrenceId) {
126
+ const owner = executionOwnerKey({ kind: 'occurrence', occurrenceId });
127
+ while (this.scheduledPublications.has(owner))
128
+ await Promise.allSettled([...this.scheduledPublications.get(owner)]);
129
+ await this.resources.forget(owner);
130
+ this.scheduler.forgetSession(owner);
131
+ for (const record of this.store.listExecutions(owner)) {
132
+ this.views.delete(record.id);
133
+ this.snapshots.delete(record.id);
134
+ this.secretValues.delete(record.id);
135
+ this.runtimeSnapshots.delete(record.id);
136
+ }
137
+ }
138
+ async stopScheduled() {
139
+ const stopped = await Promise.allSettled(this.store.listOwners().filter(owner => owner.kind === 'occurrence').map(owner => this.stop(executionOwnerKey(owner))));
140
+ while (this.scheduledPublications.size)
141
+ await Promise.allSettled([...this.scheduledPublications.values()].flatMap(publications => [...publications]));
142
+ const closed = await Promise.allSettled([this.resources.closeAll()]);
143
+ const errors = [...stopped, ...closed].flatMap(result => result.status === 'rejected' ? [result.reason] : []);
144
+ if (errors.length)
145
+ throw new AggregateError(errors, 'Scheduled work shutdown failed');
146
+ }
147
+ connections(owner) { return this.resources.get(owner).connections(); }
148
+ openMcp(owner, connectionId, mode, signal) {
149
+ return this.resources.get(owner).mcp(connectionId, mode, signal);
150
+ }
151
+ restoreScheduled(record, connectionIds, attach) {
152
+ this.privateView(executionOwner(record), record.id);
153
+ this.resources.restore(record, connectionIds, attach);
154
+ }
111
155
  filesystemPolicy() {
112
156
  const stateRoot = this.host.filesystemStateRoot();
113
157
  return stateRoot ? { stateRoot } : {};
@@ -152,7 +196,7 @@ export class WorkflowExecutionService {
152
196
  const view = this.privateView(sessionId, record.id);
153
197
  if (view.spend)
154
198
  this.host.workflowSpend(sessionId, record.id, view.spend);
155
- if (!view.completionAnnounced)
199
+ if (!record.occurrenceId && !view.completionAnnounced)
156
200
  this.publishResult(record);
157
201
  }
158
202
  }
@@ -170,13 +214,24 @@ export class WorkflowExecutionService {
170
214
  this.host.logFor(sessionId);
171
215
  return { occupied: this.scheduler.occupied(sessionId), executions: this.store.listExecutions(sessionId).map(record => ({ id: record.id, workflowId: record.definition.id, name: record.definition.name, status: record.status, startedAt: record.startedAt, ...(record.finishedAt === undefined ? {} : { finishedAt: record.finishedAt }), ...(record.testStepId ? { testStepId: record.testStepId } : {}) })) };
172
216
  }
173
- view(sessionId, executionId) {
174
- const execution = this.scheduler.get(sessionId, executionId);
217
+ view(sessionId, executionId, invocationId) {
218
+ const execution = selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), invocationId);
175
219
  const view = this.privateView(sessionId, executionId);
176
- return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
220
+ if (invocationId === undefined)
221
+ return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
222
+ const stepSpend = Object.fromEntries(execution.definition.steps.flatMap(step => {
223
+ const spend = view.stepSpend[spendKey(step.id, invocationId)];
224
+ return spend ? [[step.id, spend]] : [];
225
+ }));
226
+ return redactCredentials(structuredClone({ execution, invocationId, ...view,
227
+ activity: view.activity.filter(item => item.invocationId === invocationId),
228
+ enquiries: view.enquiries.filter(item => item.invocationId === invocationId),
229
+ permissions: view.permissions.filter(item => item.invocationId === invocationId),
230
+ stepSpend, spend: sumSpend(Object.values(stepSpend)),
231
+ }), this.host.workflowMcpCredentials());
177
232
  }
178
233
  async activity(sessionId, executionId, options = {}) {
179
- this.scheduler.get(sessionId, executionId); // ownership check, including historical records
234
+ selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), options.invocationId);
180
235
  const view = this.privateView(sessionId, executionId);
181
236
  const limit = Math.max(1, Math.min(200, options.limit ?? 100));
182
237
  const after = options.after ?? 0;
@@ -186,7 +241,8 @@ export class WorkflowExecutionService {
186
241
  throw new Error('Invalid activity cursor');
187
242
  if (![limit, after, before, options.attempt ?? 1].every(Number.isSafeInteger) || after < 0 || before < 1)
188
243
  throw new Error('Invalid activity cursor');
189
- const belongs = (event) => (!options.stepId || event.stepId === options.stepId) &&
244
+ const belongs = (event) => (options.invocationId === undefined ? !options.stepId || event.invocationId === undefined : event.invocationId === options.invocationId) &&
245
+ (!options.stepId || event.stepId === options.stepId) &&
190
246
  (options.attempt === undefined || event.attempt === options.attempt);
191
247
  const activity = [];
192
248
  const path = this.privatePath(sessionId, executionId) + 'l';
@@ -241,12 +297,11 @@ export class WorkflowExecutionService {
241
297
  }, this.host.workflowMcpCredentials());
242
298
  }
243
299
  appendActivity(context, view, event, subagentId) {
244
- const path = this.privatePath(context.sessionId, context.executionId) + 'l';
245
- const attempt = this.scheduler.get(context.sessionId, context.executionId).steps[context.step.id].attempts.at(-1).number;
246
- const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), stepId: context.step.id, attempt, subagentId, event }, this.host.workflowMcpCredentials());
300
+ const path = this.privatePath(executionOwner(context), context.executionId) + 'l';
301
+ const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), ...attemptIdentity(context), subagentId, event }, this.host.workflowMcpCredentials());
247
302
  // Seed a legacy log with exactly what was retained, never invented backfill.
248
303
  if (!existsSync(path)) {
249
- this.savePrivate(context.sessionId, context.executionId, view);
304
+ this.savePrivate(executionOwner(context), context.executionId, view);
250
305
  const fd = openSync(path, 'wx', 0o600);
251
306
  try {
252
307
  writeFileSync(fd, view.activity.map(item => JSON.stringify(item) + '\n').join(''));
@@ -274,10 +329,13 @@ export class WorkflowExecutionService {
274
329
  const record = records.find(record => ['running', 'recovery-required'].includes(record.status)) ?? records[0];
275
330
  return record && this.scheduler.get(sessionId, record.id);
276
331
  }
277
- summary(record) {
278
- const view = this.privateView(record.sessionId, record.id);
279
- return { executionId: record.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
280
- revision: recoveryRevision(record), savedDefinition: this.savedDefinitionSummary(record), automaticRecoveryAvailable: view.automaticAtProgress === undefined || successfulProgress(record) > view.automaticAtProgress,
332
+ summary(root, invocationId) {
333
+ const record = selectWorkflowInvocation(root, invocationId);
334
+ const view = this.privateView(executionOwner(root), root.id);
335
+ return { executionId: root.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
336
+ ...(invocationId ? { invocationId } : {}),
337
+ invocations: Object.values(root.invocations ?? {}).map(item => ({ id: item.id, parentInvocationId: item.parentInvocationId, callStepId: item.callStepId, callAttempt: item.callAttempt, workflowId: item.definitionId, status: item.status })),
338
+ revision: recoveryRevision(root), savedDefinition: this.savedDefinitionSummary(record), automaticRecoveryAvailable: view.automaticAtProgress === undefined || successfulProgress(root) > view.automaticAtProgress,
281
339
  steps: Object.entries(record.steps).map(([id, step]) => ({ id, name: record.definition.steps.find(s => s.id === id).name, status: step.status, attempts: step.attempts.length, error: step.attempts.at(-1)?.error })),
282
340
  loops: Object.entries(record.loops ?? {}).map(([id, loop]) => ({ id, phase: loop.phase, activation: loop.activation, try: loop.try })),
283
341
  historyComplete: view.historyComplete === true, };
@@ -296,6 +354,7 @@ export class WorkflowExecutionService {
296
354
  updatedRecoveryDefinition(record, action) {
297
355
  if (action.kind !== 'retry-updated')
298
356
  return undefined;
357
+ record = selectWorkflowInvocation(record, action.invocationId);
299
358
  const definition = this.store.getDefinition(record.definition.id);
300
359
  if (savedDefinitionRevision(definition) !== action.definitionRevision)
301
360
  throw new WorkflowConflict();
@@ -373,34 +432,39 @@ export class WorkflowExecutionService {
373
432
  if (input.section === 'activity')
374
433
  return this.activity(sessionId, record.id, input);
375
434
  if (input.section === 'execution') {
435
+ const selected = selectWorkflowInvocation(record, input.invocationId);
376
436
  let savedDefinition = null;
377
437
  try {
378
- const definition = this.store.getDefinition(record.definition.id);
379
- savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.namingCredentials({ ...record, definition }));
438
+ const definition = this.store.getDefinition(selected.definition.id);
439
+ savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.availableCredentials({ ...selected, definition }));
380
440
  }
381
441
  catch { /* Retained execution remains inspectable if the saved copy was deleted. */ }
382
- return { ...this.view(sessionId, record.id), savedDefinition };
442
+ return { ...this.view(sessionId, record.id, input.invocationId), savedDefinition };
383
443
  }
384
- return redactCredentials(this.summary(record), this.host.workflowMcpCredentials());
444
+ return redactCredentials(this.summary(record, input.invocationId), this.host.workflowMcpCredentials());
385
445
  },
386
446
  recover: async (raw, signal) => {
387
447
  const input = workflowRecoverInput.parse(raw);
448
+ if (input.invocationId !== undefined && input.action.invocationId !== undefined && input.invocationId !== input.action.invocationId)
449
+ throw new Error('Conflicting Workflow invocation selectors');
450
+ const action = { ...input.action, ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }) };
388
451
  const record = this.scheduler.get(sessionId, input.executionId);
389
452
  if (record.status !== 'recovery-required' || recoveryRevision(record) !== input.revision)
390
453
  throw new WorkflowConflict();
391
- const updated = this.updatedRecoveryDefinition(record, input.action);
454
+ const updated = this.updatedRecoveryDefinition(record, action);
392
455
  let authorized = false;
393
456
  if (input.confirm) {
394
- const correction = updated && input.action.kind === 'retry-updated'
395
- ? `\nSaved step configuration to adopt: ${JSON.stringify(updated.steps.find(step => 'stepId' in input.action && step.id === input.action.stepId))}` : '';
396
- const credentials = updated ? [...this.namingCredentials(record), ...this.referencedSecrets(updated, record.testStepId)] : this.referencedSecrets(record.definition, record.testStepId);
397
- authorized = await this.host.confirmWorkflow(sessionId, redactCredentials(`Recover ${record.definition.name}: ${JSON.stringify(input.action)}.${correction} This authorizes only the current execution state and saved definition revision.`, credentials), signal);
457
+ const selected = selectWorkflowInvocation(record, action.invocationId);
458
+ const correction = updated && action.kind === 'retry-updated'
459
+ ? `\nSaved step configuration to adopt: ${JSON.stringify(updated.steps.find(step => 'stepId' in action && step.id === action.stepId))}` : '';
460
+ const credentials = uniqueCredentials([...this.availableCredentials(record, updated ? [updated] : []), ...this.recoveryCredentials(record, action, updated)]);
461
+ authorized = await this.host.confirmWorkflow(sessionId, redactCredentials(`Recover ${selected.definition.name}: ${JSON.stringify(action)}.${correction} This authorizes only the current execution state and saved definition revision.`, credentials), signal);
398
462
  if (!authorized)
399
463
  throw new Error('Recovery was not authorized');
400
464
  }
401
465
  signal?.throwIfAborted();
402
- await this.recover(sessionId, record.id, input.action, { revision: input.revision, authorized, signal });
403
- return this.summary(this.scheduler.get(sessionId, record.id));
466
+ await this.recover(sessionId, record.id, action, { revision: input.revision, authorized, signal });
467
+ return this.summary(this.scheduler.get(sessionId, record.id), action.invocationId);
404
468
  },
405
469
  relayEnquiry: async (raw, signal) => {
406
470
  const input = workflowRelayInput.parse(raw);
@@ -463,122 +527,140 @@ export class WorkflowExecutionService {
463
527
  redactRequestError(message) {
464
528
  return redactCredentials(message, this.host.workflowMcpCredentials());
465
529
  }
530
+ async validateScheduledAgents(definition, input, scope, projectId = scope) {
531
+ const manifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id));
532
+ const definitions = Object.values(manifest);
533
+ for (const candidate of definitions) {
534
+ if (candidate.backend !== definition.backend)
535
+ throw new WorkflowValidationError('Backend Adapter mismatch');
536
+ if (candidate.projectId && !sameProject(candidate.projectId, projectId))
537
+ throw new WorkflowValidationError('Workflow is restricted to another Project');
538
+ }
539
+ try {
540
+ parseValue(definition.inputSchema, input);
541
+ }
542
+ catch (error) {
543
+ if (error instanceof ZodError)
544
+ throw new WorkflowValidationError('Workflow input does not match its schema');
545
+ throw error;
546
+ }
547
+ const values = uniqueCredentials([...this.host.workflowMcpCredentials(), ...definitions.flatMap(candidate => this.referencedSecrets(candidate))]);
548
+ for (const candidate of definitions)
549
+ assertNoSecrets(publicDefinition(candidate), values);
550
+ assertNoSecrets(input, values, true);
551
+ const agents = definitions.flatMap(candidate => candidate.steps.filter(step => step.kind === 'agent'));
552
+ if (!agents.length)
553
+ return;
554
+ const models = await this.host.workflowAgentModels(scope, definition.backend);
555
+ for (const step of agents)
556
+ this.checkAgentModel(step, models);
557
+ if (!isDeepStrictEqual(resolveWorkflowCalls(definition, id => this.store.getDefinition(id)), manifest))
558
+ throw new WorkflowConflict();
559
+ }
466
560
  validateDefinitionCredentials(definition) {
467
561
  assertNoSecrets(publicDefinition(definition), this.host.workflowMcpCredentials(), true);
468
562
  }
469
- async start(options) {
470
- const { sessionId, definition, input, stepId, nameSession = false, launchId } = options;
471
- if (launchId && !stepId) {
472
- const existing = this.store.listExecutions(sessionId).find(record => record.launchId === launchId);
473
- if (existing)
474
- return this.view(sessionId, existing.id);
475
- }
476
- const identity = this.host.workflowSession(sessionId);
477
- if (definition.backend !== identity.backend)
478
- throw new Error('Backend Adapter mismatch');
479
- if (definition.projectId && !sameProject(definition.projectId, identity.projectId))
480
- throw new Error('Workflow is restricted to another Project');
481
- if (this.scheduler.occupied(sessionId))
563
+ start(options) { return this.launch({ kind: 'session', options }); }
564
+ async launch(launch) {
565
+ const manual = launch.kind === 'session' ? launch.options : undefined;
566
+ const owner = launch.kind === 'session' ? launch.options.sessionId : executionOwnerKey({ kind: 'occurrence', occurrenceId: launch.options.occurrenceId });
567
+ const existing = () => manual?.launchId && !manual.stepId ? this.store.listExecutions(owner).find(record => record.launchId === manual.launchId) : undefined;
568
+ const prior = existing();
569
+ if (prior)
570
+ return this.view(owner, prior.id);
571
+ if (this.scheduler.occupied(owner))
482
572
  throw new WorkflowConflict();
483
573
  this.refresh();
484
- const needsCode = definition.steps.some(step => (!stepId || step.id === stepId) && ['shell', 'typescript'].includes(step.kind));
485
- const snapshot = needsCode ? await this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code };
486
- const values = this.referencedSecrets(definition, stepId);
487
- assertNoSecrets(publicDefinition(definition), values);
488
- assertNoSecrets(input, values, true);
489
- const session = await this.host.openWorkflowSession(sessionId);
490
- if (definition.projectId) {
491
- if (!sameProject(definition.projectId, session.projectId))
492
- throw new Error('Workflow is restricted to another Project');
493
- session.projectId = definition.projectId;
494
- }
495
- this.host.assertWorkflowSession(sessionId, session.session);
496
- const workflowBackend = session.session;
497
- if (!workflowBackend)
498
- throw new Error('Workflow Backend Session is unavailable');
499
- // Confirmed no-control is the sole automatic persisted-effort correction. Do it before the
500
- // scheduler validates or records the definition, so old drafts and direct launches both run
501
- // with the same internal sentinel the editor applies.
502
- const preparedDefinition = withConfirmedNoControlOff(definition, workflowBackend.capabilities.models);
503
- const pinned = new Map();
504
- for (const step of definition.steps) {
505
- if (step.kind !== 'mcp' || (stepId && step.id !== stepId))
506
- continue;
507
- const tools = pinned.get(step.tool.connectionId) ?? [];
508
- tools.push(step.tool);
509
- pinned.set(step.tool.connectionId, tools);
510
- }
511
- for (const [connectionId, tools] of pinned)
512
- await this.discoverMcp(sessionId, connectionId, tools, snapshot.runtime.isolationMode);
513
- this.host.assertWorkflowSession(sessionId, session.session);
514
- // All setup above may yield. Resolve an overlapping retry by its durable identity before
515
- // treating the session as occupied, then make occupancy the final check before the synchronous
516
- // scheduler start.
517
- if (launchId && !stepId) {
518
- const existing = this.store.listExecutions(sessionId).find(record => record.launchId === launchId);
519
- if (existing)
520
- return this.view(sessionId, existing.id);
521
- }
522
- if (this.scheduler.occupied(sessionId))
523
- throw new WorkflowConflict();
524
574
  let record;
525
- this.checkingCode = snapshot.code;
575
+ let values = [];
526
576
  try {
527
- record = this.scheduler.start(preparedDefinition, session, input, stepId, launchId, nameSession && !stepId);
577
+ const prepared = await prepareWorkflowLaunch(launch, {
578
+ host: this.host, store: this.store, secrets: this.secrets, resources: this.resources, runtimePath: this.runtimePath,
579
+ snapshot: async (needsCode) => needsCode ? this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code },
580
+ discover: (id, connection, tools, mode, signal) => this.discoverMcp(id, connection, tools, mode, signal),
581
+ validateScheduledAgents: (definition, input, scope, projectId) => this.validateScheduledAgents(definition, input, scope, projectId),
582
+ });
583
+ values = prepared.values;
584
+ const raced = existing();
585
+ if (raced)
586
+ return this.view(owner, raced.id);
587
+ if (this.scheduler.occupied(owner))
588
+ throw new WorkflowConflict();
589
+ prepared.assertCurrent();
590
+ this.checkingCode = prepared.code;
591
+ try {
592
+ record = this.scheduler.start(prepared.definition, prepared.session, launch.options.input, manual?.stepId, manual?.launchId, !!manual?.nameSession && !manual.stepId, prepared.manifest);
593
+ }
594
+ finally {
595
+ this.checkingCode = undefined;
596
+ }
597
+ this.secretValues.set(record.id, values);
598
+ this.runtimeSnapshots.set(record.id, prepared.runtime);
599
+ this.snapshots.set(record.id, prepared.code);
600
+ this.privateView(owner, record.id).historyComplete = true;
601
+ this.savePrivate(owner, record.id, this.privateView(owner, record.id));
602
+ this.watch(record);
603
+ return this.view(owner, record.id);
528
604
  }
529
- finally {
530
- this.checkingCode = undefined;
605
+ catch (error) {
606
+ if (launch.kind === 'occurrence') {
607
+ record ??= this.store.listExecutions(owner)[0];
608
+ if (record) {
609
+ const interrupted = await this.scheduler.interrupt(owner, record.id);
610
+ this.watch(interrupted);
611
+ return this.view(owner, record.id);
612
+ }
613
+ await this.resources.forget(owner);
614
+ }
615
+ if (error instanceof WorkflowConflict)
616
+ throw error;
617
+ throw safeError(error, values);
531
618
  }
532
- this.secretValues.set(record.id, values);
533
- this.runtimeSnapshots.set(record.id, snapshot.runtime);
534
- this.privateView(sessionId, record.id).historyComplete = true;
535
- this.savePrivate(sessionId, record.id, this.privateView(sessionId, record.id));
536
- this.snapshots.set(record.id, snapshot.code);
537
- this.watch(record);
538
- return this.view(sessionId, record.id);
539
619
  }
540
620
  async recover(sessionId, executionId, action, authority) {
541
621
  const saved = this.scheduler.get(sessionId, executionId);
542
622
  if (saved.status !== 'recovery-required')
543
623
  throw new WorkflowConflict();
544
624
  const updated = this.updatedRecoveryDefinition(saved, action);
545
- const definition = updated ?? saved.definition;
625
+ const selected = selectWorkflowInvocation(saved, action.invocationId);
626
+ const definition = updated ?? selected.definition;
627
+ const definitions = [saved.definition, ...Object.values(saved.retainedDefinitions ?? {}), ...Object.keys(saved.invocations ?? {}).map(id => invocationExecution(saved, id).definition), definition];
546
628
  const session = await this.host.openWorkflowSession(sessionId);
547
629
  this.privateView(sessionId, executionId);
548
630
  // Pre-toggle records were always restricted. Missing historical policy must never downgrade them.
549
- const options = this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
550
- const needsCode = definition.steps.some(step => ['shell', 'typescript'].includes(step.kind));
551
- const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), isolationMode: options.isolationMode, scope: session.scope, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) }) : {};
552
- if (saved.definition.projectId && !sameProject(saved.definition.projectId, session.projectId))
553
- throw new Error('Workflow is restricted to another Project');
554
- const values = updated ? [...this.namingCredentials(saved), ...this.referencedSecrets(definition, saved.testStepId)] : this.referencedSecrets(definition, saved.testStepId);
555
- assertNoSecrets({ ...saved, definition: publicDefinition(saved.definition), action }, values);
631
+ const options = saved.runtime ?? this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
632
+ const needsCode = definitions.some(candidate => candidate.steps.some(step => ['shell', 'typescript'].includes(step.kind)));
633
+ const resources = this.resources.get(executionOwner(saved));
634
+ const code = needsCode ? await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: () => resources.sandbox(), isolationMode: options.isolationMode, scope: saved.scope, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) }) : {};
635
+ for (const candidate of definitions) {
636
+ if (candidate.backend !== session.backend)
637
+ throw new Error('Backend Adapter mismatch');
638
+ if (candidate.projectId && !sameProject(candidate.projectId, session.projectId))
639
+ throw new Error('Workflow is restricted to another Project');
640
+ }
641
+ const values = uniqueCredentials([...this.availableCredentials(saved, [definition]), ...this.recoveryCredentials(saved, action, updated)]);
642
+ assertNoSecrets({ ...publicExecutionData(saved), action }, values);
556
643
  if (updated)
557
644
  assertNoSecrets(publicDefinition(updated), values);
558
645
  if (action.kind === 'supply')
559
646
  assertNoSecrets(action.output, values, true);
560
647
  this.secretValues.set(executionId, values);
561
648
  this.host.assertWorkflowSession(sessionId, session.session);
649
+ this.recoveryAuthority(sessionId, executionId, action, authority);
650
+ if (saved.occurrenceId)
651
+ await this.resources.occurrence(executionOwner(saved)).environment.recover(authority?.signal);
562
652
  let record;
563
653
  this.checkingCode = code;
564
654
  try {
565
- if (authority) {
566
- authority.signal?.throwIfAborted();
567
- const current = this.scheduler.get(sessionId, executionId);
568
- if (current.status !== 'recovery-required' || recoveryRevision(current) !== authority.revision)
569
- throw new WorkflowConflict();
570
- const view = this.privateView(sessionId, executionId);
571
- const progress = successfulProgress(current);
572
- if (!authority.authorized && (!safeAutomaticRecovery(current, action) || (view.automaticAtProgress !== undefined && progress <= view.automaticAtProgress)))
573
- throw new Error('User direction required. Explain the failure and proposed recovery, then request confirmation.');
574
- // Persist before launching, so crashes cannot refund an automatic attempt.
575
- view.automaticAtProgress = progress;
576
- this.savePrivate(sessionId, executionId, view);
655
+ const consent = this.recoveryAuthority(sessionId, executionId, action, authority);
656
+ if (consent) {
657
+ consent.view.automaticAtProgress = consent.progress;
658
+ this.savePrivate(sessionId, executionId, consent.view);
577
659
  }
578
660
  // Re-read after readiness/Revive and human confirmation: saving again revokes consent.
579
- if (updated && savedDefinitionRevision(this.store.getDefinition(saved.definition.id)) !== savedDefinitionRevision(updated))
661
+ if (updated && savedDefinitionRevision(this.store.getDefinition(updated.id)) !== savedDefinitionRevision(updated))
580
662
  throw new WorkflowConflict();
581
- record = this.scheduler.recover(session, executionId, action, updated);
663
+ record = this.scheduler.recover({ ...session, ...(saved.occurrenceId ? { occurrenceId: saved.occurrenceId } : {}), matchesProject: project => sameProject(project, session.projectId) }, executionId, action, updated);
582
664
  }
583
665
  catch (error) {
584
666
  if (error instanceof WorkflowLoopConflict)
@@ -592,6 +674,19 @@ export class WorkflowExecutionService {
592
674
  this.watch(record);
593
675
  return this.view(sessionId, executionId);
594
676
  }
677
+ recoveryAuthority(sessionId, executionId, action, authority) {
678
+ if (!authority)
679
+ return;
680
+ authority.signal?.throwIfAborted();
681
+ const current = this.scheduler.get(sessionId, executionId);
682
+ if (current.status !== 'recovery-required' || recoveryRevision(current) !== authority.revision)
683
+ throw new WorkflowConflict();
684
+ const progress = successfulProgress(current);
685
+ const view = this.privateView(sessionId, executionId);
686
+ if (!authority.authorized && (!safeAutomaticRecovery(current, action) || (view.automaticAtProgress !== undefined && progress <= view.automaticAtProgress)))
687
+ throw new Error('User direction required. Explain the failure and proposed recovery, then request confirmation.');
688
+ return { view, progress };
689
+ }
595
690
  async cancel(sessionId, executionId) {
596
691
  this.scheduler.get(sessionId, executionId);
597
692
  this.host.cancelWorkflowConfirmation(sessionId);
@@ -607,6 +702,8 @@ export class WorkflowExecutionService {
607
702
  this.cancelling.set(executionId, { sessionId, done });
608
703
  try {
609
704
  await done;
705
+ if (record.occurrenceId)
706
+ await this.resources.close(executionOwner(record));
610
707
  }
611
708
  finally {
612
709
  this.cancelling.delete(executionId);
@@ -617,11 +714,29 @@ export class WorkflowExecutionService {
617
714
  this.host.cancelWorkflowConfirmation(sessionId);
618
715
  await Promise.all([...this.cancelling.values()].filter(item => item.sessionId === sessionId).map(item => item.done));
619
716
  for (const record of this.store.listExecutions(sessionId)) {
620
- if (record.status === 'running' || record.status === 'recovery-required')
621
- await this.scheduler.interrupt(sessionId, record.id);
717
+ if (record.status === 'running' || record.status === 'recovery-required') {
718
+ const interrupted = await this.scheduler.interrupt(sessionId, record.id);
719
+ if (interrupted.occurrenceId)
720
+ await this.onScheduledResult?.(interrupted);
721
+ }
722
+ }
723
+ }
724
+ canForget(sessionId, occurrenceId) {
725
+ // Consult durable records: host.load() may reap before scheduler reconciliation.
726
+ const records = this.store.listExecutions(sessionId);
727
+ // Session metadata can precede the checkpoint's association write during attachment.
728
+ if (occurrenceId) {
729
+ const owned = this.store.listExecutions({ kind: 'occurrence', occurrenceId });
730
+ if (!owned.length && !this.scheduledOwnershipAvailable)
731
+ return false;
732
+ records.push(...owned);
622
733
  }
734
+ return !records.some(record => record.occurrenceId &&
735
+ (record.status === 'running' || record.status === 'recovery-required'));
623
736
  }
624
737
  async forget(sessionId) {
738
+ if (!this.canForget(sessionId))
739
+ throw new WorkflowConflict();
625
740
  await this.stop(sessionId);
626
741
  this.scheduler.forgetSession(sessionId);
627
742
  for (const record of this.store.listExecutions(sessionId)) {
@@ -670,7 +785,7 @@ export class WorkflowExecutionService {
670
785
  // never resurrect a canceled or superseded attempt.
671
786
  if (request.kind === 'enquiry' || !request.direct) {
672
787
  const launch = this.launches.get(request.subagentId);
673
- if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.stepId !== request.stepId)
788
+ if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.invocationId !== request.invocationId || launch.stepId !== request.stepId || launch.attempt !== request.attempt)
674
789
  throw new WorkflowConflict();
675
790
  }
676
791
  else {
@@ -735,19 +850,40 @@ export class WorkflowExecutionService {
735
850
  if (oldest && !oldest.announced && !oldest.relaying)
736
851
  this.host.workflowInput(sessionId);
737
852
  }
853
+ checkAgent(sessionId, step) {
854
+ const backend = this.host.workflowSession(sessionId).session;
855
+ if (!backend?.startWorkflowSubagent)
856
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
857
+ return this.checkAgentModel(step, backend.capabilities.models);
858
+ }
859
+ checkAgentModel(step, models) {
860
+ step = confirmedAgentStep(step, models);
861
+ const model = models.find(model => model.id === step.model);
862
+ if (!model)
863
+ throw new WorkflowValidationError(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
864
+ const levels = model.effortLevels ?? [];
865
+ if (levels.length ? !levels.includes(step.effort) : step.effort !== 'off')
866
+ throw new WorkflowValidationError(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.length ? levels.join(', ') : 'off'}.`);
867
+ return step;
868
+ }
738
869
  checkMcp(sessionId, tool) {
739
- const connection = this.host.workflowMcpConnections(sessionId).find(connection => connection.id === tool.connectionId);
870
+ const connection = this.connections(sessionId).find(connection => connection.id === tool.connectionId);
740
871
  if (!connection || connectionIdentity(connection) !== tool.identity)
741
872
  throw new Error('MCP connection removed, disabled or changed. Enable the original connection or reselect the tool in the workflow editor.');
742
873
  validateMcpSchemas(tool);
743
874
  }
744
- async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode()) {
875
+ async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode(), signal) {
745
876
  const pinned = expected ? (Array.isArray(expected) ? expected : [expected]) : [];
746
877
  for (const tool of pinned)
747
878
  this.checkMcp(sessionId, tool);
748
- const session = await this.host.openWorkflowMcp(sessionId, connectionId, isolationMode);
879
+ signal?.throwIfAborted();
880
+ const session = await this.openMcp(sessionId, connectionId, isolationMode, signal);
881
+ const abort = () => { void session.dispose().catch(() => { }); };
882
+ signal?.addEventListener('abort', abort, { once: true });
749
883
  try {
884
+ signal?.throwIfAborted();
750
885
  await session.open();
886
+ signal?.throwIfAborted();
751
887
  if (session.status()[0]?.state !== 'connected')
752
888
  throw new Error('MCP connection unavailable. Sign in in MCP Settings or reconfigure the server, then retry manually.');
753
889
  // Preflight validates only pinned tools, not unrelated advertised schemas.
@@ -774,6 +910,7 @@ export class WorkflowExecutionService {
774
910
  return { tools, errors };
775
911
  }
776
912
  finally {
913
+ signal?.removeEventListener('abort', abort);
777
914
  await session.dispose();
778
915
  }
779
916
  }
@@ -784,22 +921,22 @@ export class WorkflowExecutionService {
784
921
  if (context.permission !== 'ask')
785
922
  return;
786
923
  const id = randomUUID(), callId = randomUUID();
787
- const view = this.privateView(context.sessionId, context.executionId);
924
+ const view = this.privateView(executionOwner(context), context.executionId);
788
925
  const tool = context.step.kind === 'mcp' ? context.step.tool.toolName : 'MCP';
789
926
  const decision = new Promise(resolve => this.directPermissions.set(id, { sessionId: context.sessionId, executionId: context.executionId, callId, resolve }));
790
927
  const abort = () => { this.directPermissions.get(id)?.resolve(false); };
791
928
  context.signal.addEventListener('abort', abort, { once: true });
792
929
  const details = redactCredentials(context.input, this.host.workflowMcpCredentials());
793
930
  const scope = 'Allow or deny this direct Workflow tool call once. Standing authorization is unavailable.';
794
- view.permissions.push({ direct: true, subagentId: id, stepId: context.step.id, callId, tool, details, scope });
795
- const execution = this.scheduler.get(context.sessionId, context.executionId);
796
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
931
+ view.permissions.push({ direct: true, subagentId: id, ...attemptIdentity(context), callId, tool, details, scope });
932
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
933
+ const attempt = context.attempt ?? 1;
797
934
  this.registerRelay({
798
935
  kind: 'permission', sessionId: context.sessionId, executionId: context.executionId,
799
- stepId: context.step.id, attempt, subagentId: id, callId, tool, direct: true,
800
- details, scope, context: relayContext(execution, context.step.id, attempt),
936
+ ...attemptIdentity(context), subagentId: id, callId, tool, direct: true,
937
+ details, scope, context: relayContext(execution, context.step.id, attempt, context.invocationId),
801
938
  });
802
- this.savePrivate(context.sessionId, context.executionId, view);
939
+ this.savePrivate(executionOwner(context), context.executionId, view);
803
940
  if (context.signal.aborted)
804
941
  abort();
805
942
  let decided = false;
@@ -817,30 +954,31 @@ export class WorkflowExecutionService {
817
954
  this.directPermissions.delete(id);
818
955
  this.dropRelays(request => request.subagentId === id, !decided);
819
956
  view.permissions = view.permissions.filter(prompt => prompt.subagentId !== id);
820
- this.savePrivate(context.sessionId, context.executionId, view);
957
+ this.savePrivate(executionOwner(context), context.executionId, view);
821
958
  }
822
959
  }
823
960
  async mcp(context) {
824
961
  if (context.step.kind !== 'mcp')
825
962
  throw new Error('Invalid MCP step');
826
963
  const expected = context.step.tool;
827
- this.checkMcp(context.sessionId, expected);
964
+ this.checkMcp(executionOwner(context), expected);
828
965
  validateJsonSchema(expected.inputSchema, context.input);
829
966
  if (!context.input || typeof context.input !== 'object' || Array.isArray(context.input))
830
967
  throw new Error('MCP arguments must be an object');
831
968
  assertNoSecrets(context.input, this.host.workflowMcpCredentials(), true);
832
- await this.mcpPermission(context);
833
- this.checkMcp(context.sessionId, expected);
969
+ if (context.permission === 'ask')
970
+ await this.mcpPermission(await this.attachContext(context));
971
+ this.checkMcp(executionOwner(context), expected);
834
972
  context.signal.throwIfAborted();
835
973
  const isolationMode = this.runtimeSnapshots.get(context.executionId)?.isolationMode ?? 'bubblewrap';
836
- const session = await this.host.openWorkflowMcp(context.sessionId, expected.connectionId, isolationMode);
974
+ const session = await this.openMcp(executionOwner(context), expected.connectionId, isolationMode, context.signal);
837
975
  const abort = () => { void session.dispose(); };
838
976
  context.signal.addEventListener('abort', abort, { once: true });
839
977
  const values = () => [...(this.secretValues.get(context.executionId) ?? []), ...this.host.workflowMcpCredentials()];
840
- const view = this.privateView(context.sessionId, context.executionId);
978
+ const view = this.privateView(executionOwner(context), context.executionId);
841
979
  const activity = (text) => {
842
980
  this.appendActivity(context, view, { type: 'notice', level: 'info', text }, context.step.id);
843
- this.savePrivate(context.sessionId, context.executionId, view);
981
+ this.savePrivate(executionOwner(context), context.executionId, view);
844
982
  };
845
983
  try {
846
984
  await session.open();
@@ -850,7 +988,7 @@ export class WorkflowExecutionService {
850
988
  throw new Error('MCP tool unavailable. Sign in in MCP Settings or reconfigure the original server; retry manually.');
851
989
  if (tool.serverIdentity !== expected.serverIdentity || !sameSchema(tool.definition.inputSchema, expected.inputSchema) || !sameSchema(tool.definition.outputSchema, expected.outputSchema))
852
990
  throw new Error('MCP tool schema changed. Reselect the tool; this execution cannot retarget it.');
853
- this.checkMcp(context.sessionId, expected);
991
+ this.checkMcp(executionOwner(context), expected);
854
992
  activity('Calling MCP directly. No model or tokens. Cancellation is not rollback; remote effects may already occur.');
855
993
  const result = await tool.call(context.input, context.signal, context.step.timeoutMs ?? 60_000);
856
994
  const output = boundedMcpValue({ structuredContent: result.structuredContent ?? null, content: result.content });
@@ -868,15 +1006,16 @@ export class WorkflowExecutionService {
868
1006
  await session.dispose();
869
1007
  }
870
1008
  }
871
- async agent(context) {
872
- if (context.step.kind !== 'agent')
1009
+ async agent(incoming) {
1010
+ if (incoming.step.kind !== 'agent')
873
1011
  throw new Error('Invalid Agent step');
1012
+ const context = { ...incoming, step: this.checkAgent(incoming.sessionId, incoming.step) };
874
1013
  const resolvedInstructions = context.step.instructions;
875
1014
  const backend = this.host.workflowSession(context.sessionId).session;
876
1015
  if (!backend?.startWorkflowSubagent)
877
1016
  throw new Error('Workflow Backend Session is unavailable');
878
1017
  context.signal.throwIfAborted();
879
- const savedStep = this.scheduler.get(context.sessionId, context.executionId).definition.steps.find(step => step.id === context.step.id);
1018
+ const savedStep = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId).definition.steps.find(step => step.id === context.step.id);
880
1019
  const instructions = savedStep.kind === 'agent' ? savedStep.instructions : context.step.instructions;
881
1020
  const invocation = leadingSkillInvocation(instructions);
882
1021
  if (invocation) {
@@ -899,8 +1038,9 @@ export class WorkflowExecutionService {
899
1038
  aliases[alias] = this.secrets.resolve(reference, context.signal);
900
1039
  const values = uniqueCredentials([...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)]);
901
1040
  const id = randomUUID();
902
- const view = this.privateView(context.sessionId, context.executionId);
903
- const priorSpend = view.stepSpend[context.step.id];
1041
+ const view = this.privateView(executionOwner(context), context.executionId);
1042
+ const key = spendKey(context.step.id, context.invocationId);
1043
+ const priorSpend = view.stepSpend[key];
904
1044
  const requestIds = new Map();
905
1045
  const publicIds = new Map();
906
1046
  const publicId = (raw) => {
@@ -921,13 +1061,13 @@ export class WorkflowExecutionService {
921
1061
  if (event.state !== 'asked')
922
1062
  this.dropRelays(request => request.subagentId === id && request.kind === 'enquiry' && request.askId === event.askId, event.state === 'aborted');
923
1063
  if (event.state === 'asked') {
924
- view.enquiries.push({ subagentId: id, stepId: context.step.id, askId: event.askId, questions: event.questions });
925
- const execution = this.scheduler.get(context.sessionId, context.executionId);
926
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
1064
+ view.enquiries.push({ subagentId: id, ...attemptIdentity(context), askId: event.askId, questions: event.questions });
1065
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
1066
+ const attempt = context.attempt ?? 1;
927
1067
  this.registerRelay({
928
1068
  kind: 'enquiry', sessionId: context.sessionId, executionId: context.executionId,
929
- stepId: context.step.id, attempt, subagentId: id, askId: event.askId,
930
- questions: event.questions, context: relayContext(execution, context.step.id, attempt),
1069
+ ...attemptIdentity(context), subagentId: id, askId: event.askId,
1070
+ questions: event.questions, context: relayContext(execution, context.step.id, attempt, context.invocationId),
931
1071
  });
932
1072
  }
933
1073
  }
@@ -939,22 +1079,22 @@ export class WorkflowExecutionService {
939
1079
  const started = view.activity.findLast(item => item.event.type === 'tool_started' && item.event.callId === event.callId);
940
1080
  const details = started?.event.type === 'tool_started' ? started.event.input : undefined;
941
1081
  const scope = `Allow once, deny, or always allow ${event.tool} on this machine.`;
942
- view.permissions.push({ subagentId: id, stepId: context.step.id, callId: event.callId, tool: event.tool, ...(details === undefined ? {} : { details }), scope });
943
- const execution = this.scheduler.get(context.sessionId, context.executionId);
944
- const attempt = execution.steps[context.step.id].attempts.at(-1).number;
1082
+ view.permissions.push({ subagentId: id, ...attemptIdentity(context), callId: event.callId, tool: event.tool, ...(details === undefined ? {} : { details }), scope });
1083
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
1084
+ const attempt = context.attempt ?? 1;
945
1085
  this.registerRelay({
946
1086
  kind: 'permission', sessionId: context.sessionId, executionId: context.executionId,
947
- stepId: context.step.id, attempt, subagentId: id, callId: event.callId,
1087
+ ...attemptIdentity(context), subagentId: id, callId: event.callId,
948
1088
  tool: event.tool, direct: false, ...(details === undefined ? {} : { details }), scope,
949
- context: relayContext(execution, context.step.id, attempt),
1089
+ context: relayContext(execution, context.step.id, attempt, context.invocationId),
950
1090
  });
951
1091
  }
952
1092
  }
953
1093
  if (event.type === 'spend') {
954
- view.stepSpend[context.step.id] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
1094
+ view.stepSpend[key] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
955
1095
  view.spend = sumSpend(Object.values(view.stepSpend));
956
1096
  }
957
- this.savePrivate(context.sessionId, context.executionId, view);
1097
+ this.savePrivate(executionOwner(context), context.executionId, view);
958
1098
  if (event.type === 'spend' && view.spend)
959
1099
  this.host.workflowSpend(context.sessionId, context.executionId, view.spend);
960
1100
  },
@@ -971,7 +1111,7 @@ export class WorkflowExecutionService {
971
1111
  await handle.cancel();
972
1112
  throw new Error('Workflow Agent permissions are unavailable');
973
1113
  }
974
- this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, stepId: context.step.id, handle, requestIds });
1114
+ this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, ...attemptIdentity(context), handle, requestIds });
975
1115
  const abort = () => { void handle.cancel().catch(() => { }); };
976
1116
  context.signal.addEventListener('abort', abort, { once: true });
977
1117
  if (context.signal.aborted)
@@ -992,22 +1132,77 @@ export class WorkflowExecutionService {
992
1132
  this.dropRelays(request => request.subagentId === id);
993
1133
  view.enquiries = view.enquiries.filter(item => item.subagentId !== id);
994
1134
  view.permissions = view.permissions.filter(item => item.subagentId !== id);
995
- this.savePrivate(context.sessionId, context.executionId, view);
1135
+ this.savePrivate(executionOwner(context), context.executionId, view);
996
1136
  }
997
1137
  }
1138
+ recoveryCredentials(record, action, updated) {
1139
+ const steps = recoverySteps(record, action, updated);
1140
+ const checked = new Set();
1141
+ for (const step of steps) {
1142
+ if (step.kind !== 'workflow' || checked.has(step.workflowId))
1143
+ continue;
1144
+ checked.add(step.workflowId);
1145
+ const target = record.retainedDefinitions?.[step.workflowId];
1146
+ if (!target)
1147
+ throw new Error('Missing retained called Workflow Definition');
1148
+ steps.push(...target.steps);
1149
+ }
1150
+ return [...new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))].map(name => this.secrets.resolve(name));
1151
+ }
998
1152
  referencedSecrets(definition, stepId) {
999
1153
  return [...this.host.workflowMcpCredentials(), ...[...new Set(definition.steps.filter(step => !stepId || step.id === stepId).flatMap(step => Object.values(step.secrets ?? {})))].map(name => this.secrets.resolve(name))];
1000
1154
  }
1001
1155
  watch(record) {
1002
- void this.scheduler.wait(record.sessionId, record.id).then(result => {
1156
+ const publication = this.scheduler.wait(executionOwner(record), record.id).then(result => {
1003
1157
  const credentials = this.secretValues.get(record.id) ?? [];
1004
- this.publishResult(result, credentials);
1158
+ return this.publishScheduledResult(result, credentials);
1005
1159
  }).catch(() => { }).finally(() => {
1160
+ const owner = executionOwner(record);
1161
+ if (this.scheduler.get(owner, record.id).status === 'running' || this.scheduler.hasPendingDeadline(owner, record.id))
1162
+ return;
1006
1163
  this.snapshots.delete(record.id);
1007
1164
  this.secretValues.delete(record.id);
1008
1165
  });
1166
+ if (record.occurrenceId) {
1167
+ const owner = executionOwner(record);
1168
+ const publications = this.scheduledPublications.get(owner) ?? new Set();
1169
+ this.scheduledPublications.set(owner, publications);
1170
+ publications.add(publication);
1171
+ const settled = () => {
1172
+ publications.delete(publication);
1173
+ if (!publications.size)
1174
+ this.scheduledPublications.delete(owner);
1175
+ };
1176
+ void publication.then(settled, settled);
1177
+ }
1178
+ }
1179
+ async publishScheduledResult(result, credentials) {
1180
+ if (result.occurrenceId && result.status === 'recovery-required' && !result.sessionId) {
1181
+ try {
1182
+ const sessionId = await this.resources.occurrence(executionOwner(result)).attach();
1183
+ this.scheduler.associate(result.occurrenceId, result.id, sessionId);
1184
+ result = this.scheduler.get(executionOwner(result), result.id);
1185
+ }
1186
+ catch { }
1187
+ }
1188
+ try {
1189
+ if (result.occurrenceId)
1190
+ await this.onScheduledResult?.(result);
1191
+ if (result.sessionId)
1192
+ this.publishResult(result, credentials);
1193
+ }
1194
+ finally {
1195
+ if (result.occurrenceId) {
1196
+ const owner = executionOwner(result);
1197
+ const current = this.scheduler.get(owner, result.id);
1198
+ if (current.status !== 'running' && current.status !== 'recovery-required' && !this.scheduler.hasPendingDeadline(owner, result.id))
1199
+ await this.resources.close(owner);
1200
+ }
1201
+ }
1009
1202
  }
1010
1203
  publishResult(result, knownCredentials = []) {
1204
+ if (!result.sessionId)
1205
+ return;
1011
1206
  if (!result.testStepId && ['recovery-required', 'completed', 'completed-with-recovery', 'cancelled'].includes(result.status)) {
1012
1207
  this.requestNaming(result.sessionId, result.id, () => {
1013
1208
  const { results, errors } = outcomeNamingData(result);
@@ -1017,7 +1212,7 @@ export class WorkflowExecutionService {
1017
1212
  outcome: result.status,
1018
1213
  results,
1019
1214
  errors,
1020
- }, uniqueCredentials([...knownCredentials, ...this.namingCredentials(result)]));
1215
+ }, uniqueCredentials([...knownCredentials, ...this.availableCredentials(result)]));
1021
1216
  });
1022
1217
  }
1023
1218
  if (!result.testStepId && result.status === 'recovery-required')
@@ -1046,13 +1241,15 @@ export class WorkflowExecutionService {
1046
1241
  }
1047
1242
  void this.host.nameWorkflow(sessionId, input).catch(() => { });
1048
1243
  }
1049
- namingCredentials(record) {
1244
+ availableCredentials(record, additional = []) {
1050
1245
  const values = [...this.host.workflowMcpCredentials()];
1051
- for (const reference of new Set(record.definition.steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1246
+ const definitions = [record.definition, ...Object.values(record.retainedDefinitions ?? {}), ...additional];
1247
+ const steps = [...definitions.flatMap(definition => definition.steps), ...[record, ...Object.values(record.invocations ?? {})].flatMap(checkpoint => (checkpoint.definitionUpdates ?? []).flatMap(update => [update.previousStep, update.nextStep]))];
1248
+ for (const reference of new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1052
1249
  try {
1053
1250
  values.push(this.secrets.resolve(reference));
1054
1251
  }
1055
- catch { /* Missing secrets cannot make naming affect execution. */ }
1252
+ catch { }
1056
1253
  }
1057
1254
  return uniqueCredentials(values);
1058
1255
  }
@@ -1083,14 +1280,15 @@ export class WorkflowExecutionService {
1083
1280
  privatePath(sessionId, executionId) {
1084
1281
  if (![sessionId, executionId].every(value => /^[a-zA-Z0-9_-]+$/.test(value)))
1085
1282
  throw new Error('Invalid execution identity');
1086
- return join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity', executionId + '.json');
1283
+ const record = this.scheduler.get(sessionId, executionId);
1284
+ return join(this.store.ownerPath(executionOwner(record)), 'workflow-activity', executionId + '.json');
1087
1285
  }
1088
1286
  savePrivate(sessionId, executionId, view) {
1089
1287
  const path = this.privatePath(sessionId, executionId);
1090
- const directoryPath = join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity');
1288
+ const directoryPath = join(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'workflow-activity');
1091
1289
  if (!existsSync(directoryPath)) {
1092
- mkdirSync(directoryPath, { mode: 0o700 });
1093
- const parent = openSync(join(this.store.stateRoot, 'sessions', sessionId), 'r');
1290
+ mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
1291
+ const parent = openSync(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'r');
1094
1292
  try {
1095
1293
  fsyncSync(parent);
1096
1294
  }
@@ -1116,119 +1314,3 @@ export class WorkflowExecutionService {
1116
1314
  }
1117
1315
  }
1118
1316
  }
1119
- export class WorkflowConflict extends Error {
1120
- constructor() { super('Workflow decision or slot is no longer available'); }
1121
- }
1122
- function sameProject(project, scope) {
1123
- try {
1124
- return realpathSync(project) === scope;
1125
- }
1126
- catch {
1127
- return false;
1128
- }
1129
- }
1130
- function redact(value, secrets) { return redactCredentials(value, secrets); }
1131
- function redactEvent(event, secrets, publicId) {
1132
- const visit = (item, path = []) => {
1133
- if (typeof item === 'string') {
1134
- const key = path.at(-1);
1135
- if (path.length === 1 && ['type', 'state', 'on', 'decision', 'reason', 'level', 'trigger', 'effort'].includes(key))
1136
- return item;
1137
- if (['id', 'callId', 'askId', 'subagentId', 'turnId'].includes(key) && (path.length === 1 || path[0] === 'producer'))
1138
- return publicId(item);
1139
- return redact(item, secrets);
1140
- }
1141
- if (Array.isArray(item))
1142
- return item.map(value => visit(value, path));
1143
- if (item && typeof item === 'object')
1144
- return Object.fromEntries(Object.entries(item).map(([key, value]) => [key,
1145
- path.length === 0 && ['input', 'update', 'result'].includes(key) ? redact(value, secrets) : visit(value, [...path, key]),
1146
- ]));
1147
- return item;
1148
- };
1149
- return visit(event);
1150
- }
1151
- function withConfirmedNoControlOff(definition, models) {
1152
- let changed = false;
1153
- const steps = definition.steps.map(step => {
1154
- if (step.kind !== 'agent')
1155
- return step;
1156
- const model = models.find(candidate => candidate.id === step.model);
1157
- if (!model || (model.effortLevels?.length ?? 0) > 0 || step.effort === 'off')
1158
- return step;
1159
- changed = true;
1160
- return { ...step, effort: 'off' };
1161
- });
1162
- return changed ? { ...definition, steps } : definition;
1163
- }
1164
- function publicDefinition(definition) {
1165
- return { ...definition, steps: definition.steps.map(({ secrets, ...step }) => step) };
1166
- }
1167
- function assertNoSecrets(value, secrets, checkKeys = false) {
1168
- const visit = (item) => {
1169
- if (typeof item === 'string')
1170
- return redact(item, secrets) !== item;
1171
- if (Array.isArray(item))
1172
- return item.some(visit);
1173
- return !!item && typeof item === 'object' && Object.entries(item).some(([key, value]) => (checkKeys && visit(key)) || visit(value));
1174
- };
1175
- if (visit(value))
1176
- throw new Error('Saved workflow data cannot contain secret values');
1177
- }
1178
- function safeError(error, values) {
1179
- const message = redact(error instanceof Error ? error.message : String(error), values);
1180
- return error instanceof WorkflowStepError ? new WorkflowStepError(message, error.partialOutput === undefined ? undefined : redact(error.partialOutput, values)) : new Error(message);
1181
- }
1182
- function outcomeNamingData(record) {
1183
- const stepNames = new Map(record.definition.steps.map(step => [step.id, step.name]));
1184
- function* results() {
1185
- for (const id in record.steps) {
1186
- const output = record.steps[id].output;
1187
- if (output !== undefined)
1188
- yield { step: stepNames.get(id) ?? id, output };
1189
- }
1190
- }
1191
- function* errors() {
1192
- for (const id in record.steps)
1193
- for (const attempt of record.steps[id].attempts) {
1194
- if (attempt.error !== undefined)
1195
- yield {
1196
- step: stepNames.get(id) ?? id, attempt: attempt.number, error: attempt.error,
1197
- ...(attempt.partialOutput === undefined ? {} : { partialOutput: attempt.partialOutput }),
1198
- };
1199
- }
1200
- }
1201
- return {
1202
- results: record.result === undefined ? results() : record.result,
1203
- errors: errors(),
1204
- };
1205
- }
1206
- function uniqueCredentials(values) {
1207
- return [...new Set(values.filter(Boolean))];
1208
- }
1209
- function relayContext(record, stepId, attempt) {
1210
- const step = record.definition.steps.find(item => item.id === stepId);
1211
- return `Workflow “${record.definition.name}” · Step “${step?.name ?? stepId}” · Attempt ${attempt}${record.testStepId ? ' · Step test' : ''}`;
1212
- }
1213
- function relaySignal(request, parent) {
1214
- return parent ? AbortSignal.any([request, parent]) : request;
1215
- }
1216
- function sumSpend(values) {
1217
- const result = { tokens: 0, cached: 0, costUSD: 0, models: [] };
1218
- for (const value of values) {
1219
- result.tokens += value.tokens;
1220
- result.cached += value.cached;
1221
- result.costUSD += value.costUSD;
1222
- for (const model of value.models) {
1223
- const existing = result.models.find(item => item.id === model.id);
1224
- if (existing) {
1225
- existing.tokens += model.tokens;
1226
- existing.cached += model.cached;
1227
- existing.costUSD += model.costUSD;
1228
- }
1229
- else
1230
- result.models.push({ ...model });
1231
- }
1232
- }
1233
- return result;
1234
- }