@nathanstephenson/flow 0.1.10-beta.1 → 0.1.10-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (170) hide show
  1. package/README.md +52 -22
  2. package/build/backend-worker-chunks/{chunk-CYE5L6Z5.mjs → chunk-3KDHJA5P.mjs} +41 -10
  3. package/build/backend-worker-chunks/{chunk-UQDH2COY.mjs → chunk-K774KOGL.mjs} +2 -7
  4. package/build/backend-worker-chunks/chunk-LAEUXDNH.mjs +130 -0
  5. package/build/backend-worker-chunks/{chunk-MLOUI3ZM.mjs → chunk-NZZME2I3.mjs} +6 -1
  6. package/build/backend-worker-chunks/claude-JG2FXYBQ.mjs +35859 -0
  7. package/build/backend-worker-chunks/{pi-UKRC4DDM.mjs → pi-KJSP23AO.mjs} +2091 -92
  8. package/build/backend-worker.mjs +69 -122
  9. package/build/workflow-runtime.cjs +12 -12
  10. package/dist/backend/claude/background-calls.js +7 -3
  11. package/dist/backend/claude/import.js +415 -0
  12. package/dist/backend/claude/index.js +188 -25
  13. package/dist/backend/claude/subagents.js +41 -9
  14. package/dist/backend/claude/todo-list.js +114 -0
  15. package/dist/backend/claude/workflow-parent.js +1 -1
  16. package/dist/backend/diff-excerpt-instructions.js +8 -0
  17. package/dist/backend/fake/index.js +54 -6
  18. package/dist/backend/mcp.js +4 -1
  19. package/dist/backend/pi/agent-permissions.js +1 -1
  20. package/dist/backend/pi/cache-warming.js +8 -0
  21. package/dist/backend/pi/canonical-json.js +120 -0
  22. package/dist/backend/pi/compaction-model.js +3 -2
  23. package/dist/backend/pi/host-auth.js +258 -0
  24. package/dist/backend/pi/import.js +269 -0
  25. package/dist/backend/pi/index.js +118 -20
  26. package/dist/backend/pi/model-auth.js +159 -0
  27. package/dist/backend/pi/model-catalog.js +120 -0
  28. package/dist/backend/pi/model-config.js +5 -0
  29. package/dist/backend/pi/model-selection.js +32 -0
  30. package/dist/backend/pi/plan-limits.js +41 -0
  31. package/dist/backend/pi/state.js +19 -1
  32. package/dist/backend/pi/subagents.js +7 -3
  33. package/dist/backend/pi/todo-list.js +23 -0
  34. package/dist/backend/pi/work.js +9 -1
  35. package/dist/backend/pi/workflow-parent.js +1 -1
  36. package/dist/backend/pi/workflow-subagent.js +4 -3
  37. package/dist/backend/plan-limits.js +17 -0
  38. package/dist/backend/session-tools.js +1 -1
  39. package/dist/backend/worker/claude-state.js +48 -0
  40. package/dist/backend/worker/entry.js +42 -8
  41. package/dist/backend/worker/index.js +131 -15
  42. package/dist/backend/worker/launcher.js +11 -4
  43. package/dist/backend/worker/protocol.js +2 -1
  44. package/dist/backend/worker/rpc.js +13 -0
  45. package/dist/backend/worker/sandbox-mcp.js +18 -7
  46. package/dist/backend/workflow-tools.js +9 -7
  47. package/dist/build-id +1 -1
  48. package/dist/cli/application.js +48 -42
  49. package/dist/cli/bootstrap.js +2 -2
  50. package/dist/cli/host-control.js +1 -1
  51. package/dist/cli/install-guard.js +2 -2
  52. package/dist/cli/main.js +4 -4
  53. package/dist/cli/systemd-update.js +3 -3
  54. package/dist/cli/update.js +6 -6
  55. package/dist/cli/web-update.js +6 -6
  56. package/dist/client/connection.js +46 -0
  57. package/dist/client/context-usage.js +3 -4
  58. package/dist/client/diff.js +40 -0
  59. package/dist/client/enquiry.js +0 -6
  60. package/dist/client/markdown.js +3 -2
  61. package/dist/client/model-choices.js +1 -1
  62. package/dist/client/permission.js +1 -2
  63. package/dist/client/project-name.js +3 -1
  64. package/dist/client/reduce.js +77 -3
  65. package/dist/client/relative-time.js +1 -1
  66. package/dist/client/scope-kind.js +6 -3
  67. package/dist/client/search.js +1 -1
  68. package/dist/client/status.js +1 -1
  69. package/dist/client/subagent-tree.js +49 -0
  70. package/dist/client/tool-chains.js +1 -1
  71. package/dist/client/tool-summary.js +28 -18
  72. package/dist/daemon/changes.js +128 -0
  73. package/dist/daemon/commit.js +84 -0
  74. package/dist/daemon/config-store.js +8 -3
  75. package/dist/daemon/config.js +105 -4
  76. package/dist/daemon/diff-excerpts.js +52 -0
  77. package/dist/daemon/git-state.js +197 -0
  78. package/dist/daemon/git.js +53 -10
  79. package/dist/daemon/github-image.js +18 -0
  80. package/dist/daemon/github.js +54 -0
  81. package/dist/daemon/host-control-routes.js +1 -1
  82. package/dist/daemon/host.js +940 -119
  83. package/dist/daemon/http.js +4 -1
  84. package/dist/daemon/log.js +3 -0
  85. package/dist/daemon/mcp-auth.js +1 -1
  86. package/dist/daemon/models.js +2 -2
  87. package/dist/daemon/pi-model-cache.js +44 -0
  88. package/dist/daemon/pull-request.js +223 -138
  89. package/dist/daemon/push.js +43 -0
  90. package/dist/daemon/repository.js +123 -0
  91. package/dist/daemon/runtime.js +103 -22
  92. package/dist/daemon/secret-store.js +1 -1
  93. package/dist/daemon/server.js +111 -14
  94. package/dist/daemon/skills.js +24 -0
  95. package/dist/daemon/spend-ledger.js +118 -0
  96. package/dist/daemon/stack-metadata.js +12 -5
  97. package/dist/daemon/stack.js +162 -657
  98. package/dist/daemon/store.js +2 -0
  99. package/dist/daemon/summariser.js +30 -12
  100. package/dist/daemon/tour.js +56 -0
  101. package/dist/daemon/whisper.js +144 -0
  102. package/dist/daemon/workflow-authoring-scope-checks.js +1 -1
  103. package/dist/daemon/workflow-authoring-scope.js +1 -1
  104. package/dist/daemon/workflow-builder-files.js +2 -2
  105. package/dist/daemon/workflow-builder-guidance.js +1 -1
  106. package/dist/daemon/workflow-builder-routes.js +2 -2
  107. package/dist/daemon/workflow-builder.js +44 -17
  108. package/dist/daemon/workflow-environment.js +193 -0
  109. package/dist/daemon/workflow-execution-launch.js +77 -0
  110. package/dist/daemon/workflow-execution-resources.js +76 -0
  111. package/dist/daemon/workflow-execution-routes.js +12 -9
  112. package/dist/daemon/workflow-execution-values.js +128 -0
  113. package/dist/daemon/workflow-executions.js +400 -311
  114. package/dist/daemon/workflow-mcp-authoring-routes.js +2 -2
  115. package/dist/daemon/workflow-mcp-authoring.js +4 -4
  116. package/dist/daemon/workflow-mcp.js +1 -1
  117. package/dist/daemon/workflow-routes.js +60 -2
  118. package/dist/daemon/workflow-schedule-driver.js +251 -0
  119. package/dist/daemon/workflow-schedule-routes.js +137 -0
  120. package/dist/daemon/workflow-schedules.js +342 -0
  121. package/dist/isolation/filesystem.js +6 -2
  122. package/dist/isolation/sandbox.js +61 -18
  123. package/dist/isolation/shared-sandbox.js +3 -3
  124. package/dist/isolation/toolchain-assets.js +1 -1
  125. package/dist/protocol/events.js +3 -0
  126. package/dist/protocol/plan-limits.js +1 -0
  127. package/dist/protocol/settings.js +1 -0
  128. package/dist/protocol/spend.js +2 -0
  129. package/dist/protocol/stack.js +12 -39
  130. package/dist/protocol/workflow-schedules.js +1 -0
  131. package/dist/workflows/calls.js +53 -0
  132. package/dist/workflows/errors.js +2 -0
  133. package/dist/workflows/executors.js +6 -5
  134. package/dist/workflows/graph.js +83 -9
  135. package/dist/workflows/invocations.js +23 -0
  136. package/dist/workflows/mcp.js +1 -1
  137. package/dist/workflows/owner.js +45 -0
  138. package/dist/workflows/records.js +127 -11
  139. package/dist/workflows/recovery.js +38 -2
  140. package/dist/workflows/runtime-settings.js +16 -16
  141. package/dist/workflows/runtime.js +2 -2
  142. package/dist/workflows/schedule-errors.js +2 -0
  143. package/dist/workflows/schedule-store.js +385 -0
  144. package/dist/workflows/scheduler.js +367 -96
  145. package/dist/workflows/schedules.js +130 -0
  146. package/dist/workflows/schema.js +3 -1
  147. package/dist/workflows/store.js +126 -13
  148. package/package.json +10 -6
  149. package/web/dist/assets/index-C76t-z4w.css +2 -0
  150. package/web/dist/assets/{index-DRfeO6GJ.js → index-WPfbYVQ4.js} +39 -23
  151. package/web/dist/assets/{switch-DIogWclb.js → select-C5Ly2OpB.js} +1 -1
  152. package/web/dist/assets/{settings-mcp-Clp_jMWW.js → settings-mcp-BF-yqpeQ.js} +1 -1
  153. package/web/dist/assets/{settings-secrets-BIO_hXZ1.js → settings-secrets-WLarr2QP.js} +1 -1
  154. package/web/dist/assets/settings-workflows-DdcdRWFD.js +23 -0
  155. package/web/dist/assets/workflow-api-GjAmHc22.js +6 -0
  156. package/web/dist/assets/workflows-BhY3Uibo.js +149 -0
  157. package/web/dist/assets/workflows-pane-DElCcEpN.js +1 -0
  158. package/web/dist/index.html +6 -5
  159. package/build/backend-worker-chunks/claude-UXZDJKZQ.mjs +0 -30816
  160. package/dist/daemon/publish.js +0 -289
  161. package/dist/tui/app.js +0 -612
  162. package/dist/tui/keys.js +0 -90
  163. package/dist/tui/render.js +0 -411
  164. package/web/dist/assets/index-DgQFpKbn.css +0 -2
  165. package/web/dist/assets/settings-workflows-H-6eCff3.js +0 -23
  166. package/web/dist/assets/workflow-api-BfExddae.js +0 -6
  167. package/web/dist/assets/workflow-editors-CsbVx4WJ.js +0 -139
  168. package/web/dist/assets/workflows-Bv0sj7d0.js +0 -7
  169. package/web/dist/assets/workflows-pane-DHm44w7P.js +0 -1
  170. /package/dist/protocol/{publish.js → imports.js} +0 -0
@@ -1,24 +1,36 @@
1
- import { recoveryRevision, safeAutomaticRecovery, successfulProgress, savedDefinitionRevision, validateCompatibleDefinition } from "../workflows/recovery.js";
2
- import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../backend/workflow-tools.js";
3
- import { redactCredentials } from "./credential-redaction.js";
4
- import { workflowAgentNameInput, workflowOutcomeNameInput } from "./summariser.js";
5
- import { connectionIdentity, snapshotTool, sameSchema } from "./workflow-mcp.js";
6
- import { validateJsonSchema } from "../workflows/json-schema.js";
7
- 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
1
  import { randomUUID } from 'node:crypto';
12
- import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { closeSync, createReadStream, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
13
3
  import { join } from 'node:path';
14
- import { leadingSkillInvocation } from "../protocol/skills.js";
15
- import { createCodeExecutors } from "../workflows/executors.js";
16
- import { parseValue } from "../workflows/schema.js";
17
- import { WorkflowStepError, WorkflowScheduler, WorkflowLoopConflict } from "../workflows/scheduler.js";
18
- import { workflowRuntimeOptions } from "../workflows/runtime-settings.js";
19
- import { SessionHost } from "./host.js";
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";
14
+ import { workflowInspectInput, workflowRecoverInput, workflowRelayInput } from "../backend/workflow-tools.js";
15
+ import { redactCredentials } from './credential-redaction.js';
16
+ import { workflowAgentNameInput, workflowOutcomeNameInput } from './summariser.js';
17
+ import { connectionIdentity, snapshotTool, sameSchema } from './workflow-mcp.js';
18
+ import { validateJsonSchema } from '../workflows/json-schema.js';
19
+ import { boundedMcpValue, validateMcpSchemas } from '../workflows/mcp.js';
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';
21
+ import { leadingSkillInvocation } from '../protocol/skills.js';
22
+ import { createCodeExecutors } from '../workflows/executors.js';
23
+ import { parseValue } from '../workflows/schema.js';
24
+ import { WorkflowStepError, WorkflowScheduler, WorkflowLoopConflict } from '../workflows/scheduler.js';
25
+ import { workflowRuntimeOptions } from '../workflows/runtime-settings.js';
26
+ import { SessionHost } from './host.js';
27
+ import { hasDiffReference } from './diff-excerpts.js';
28
+ export { WorkflowConflict } from './workflow-execution-values.js';
20
29
  export class WorkflowExecutionService {
21
30
  scheduler;
31
+ resources;
32
+ onScheduledResult;
33
+ scheduledOwnershipAvailable = true;
22
34
  host;
23
35
  store;
24
36
  secrets;
@@ -40,6 +52,7 @@ export class WorkflowExecutionService {
40
52
  runtimeSnapshots = new Map();
41
53
  runtimeOptions;
42
54
  checkingCode;
55
+ scheduledPublications = new Map();
43
56
  cancelling = new Map();
44
57
  constructor(host, store, secrets, config, runtimePath) {
45
58
  store.redact = value => redactCredentials(value, host.workflowMcpCredentials());
@@ -48,6 +61,7 @@ export class WorkflowExecutionService {
48
61
  this.secrets = secrets;
49
62
  this.config = config;
50
63
  this.runtimePath = runtimePath;
64
+ this.resources = new WorkflowExecutionResources(host, store, runtimePath);
51
65
  const code = (kind) => ({
52
66
  check: (step, session) => {
53
67
  const executor = (this.checkingCode ?? this.code)[kind];
@@ -72,7 +86,7 @@ export class WorkflowExecutionService {
72
86
  check: (step, session) => {
73
87
  if (step.kind !== 'mcp')
74
88
  throw new Error('Invalid MCP step');
75
- this.checkMcp(session.sessionId, step.tool);
89
+ this.checkMcp(executionOwner(session), step.tool);
76
90
  },
77
91
  execute: context => this.mcp(context),
78
92
  },
@@ -81,33 +95,64 @@ export class WorkflowExecutionService {
81
95
  check: (step, session) => {
82
96
  if (step.kind !== 'agent')
83
97
  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
- }
98
+ if (session.sessionId)
99
+ this.checkAgent(session.sessionId, step);
97
100
  },
98
101
  execute: async (context) => {
99
102
  try {
100
- return await this.agent(context);
103
+ return await this.agent(await this.attachContext(context));
101
104
  }
102
105
  catch (error) {
103
106
  throw safeError(error, this.secretValues.get(context.executionId) ?? []);
104
107
  }
105
108
  },
106
109
  },
107
- });
110
+ }, record => this.watch(record));
108
111
  host.workflowOwner = this;
109
112
  this.refresh();
110
113
  }
114
+ async attachContext(context) {
115
+ if (context.sessionId)
116
+ return { ...context, sessionId: context.sessionId };
117
+ const identity = executionOwnerOf(context);
118
+ if (identity.kind !== 'occurrence')
119
+ throw new Error('Agent Session required');
120
+ const sessionId = await this.resources.occurrence(executionOwnerKey(identity)).attach();
121
+ context.signal.throwIfAborted();
122
+ this.scheduler.associate(identity.occurrenceId, context.executionId, sessionId);
123
+ return { ...context, sessionId };
124
+ }
125
+ startScheduled(options) { return this.launch({ kind: 'occurrence', options }); }
126
+ async expireScheduled(occurrenceId) {
127
+ const owner = executionOwnerKey({ kind: 'occurrence', occurrenceId });
128
+ while (this.scheduledPublications.has(owner))
129
+ await Promise.allSettled([...this.scheduledPublications.get(owner)]);
130
+ await this.resources.forget(owner);
131
+ this.scheduler.forgetSession(owner);
132
+ for (const record of this.store.listExecutions(owner)) {
133
+ this.views.delete(record.id);
134
+ this.snapshots.delete(record.id);
135
+ this.secretValues.delete(record.id);
136
+ this.runtimeSnapshots.delete(record.id);
137
+ }
138
+ }
139
+ async stopScheduled() {
140
+ const stopped = await Promise.allSettled(this.store.listOwners().filter(owner => owner.kind === 'occurrence').map(owner => this.stop(executionOwnerKey(owner))));
141
+ while (this.scheduledPublications.size)
142
+ await Promise.allSettled([...this.scheduledPublications.values()].flatMap(publications => [...publications]));
143
+ const closed = await Promise.allSettled([this.resources.closeAll()]);
144
+ const errors = [...stopped, ...closed].flatMap(result => result.status === 'rejected' ? [result.reason] : []);
145
+ if (errors.length)
146
+ throw new AggregateError(errors, 'Scheduled work shutdown failed');
147
+ }
148
+ connections(owner) { return this.resources.get(owner).connections(); }
149
+ openMcp(owner, connectionId, mode, signal) {
150
+ return this.resources.get(owner).mcp(connectionId, mode, signal);
151
+ }
152
+ restoreScheduled(record, connectionIds, attach) {
153
+ this.privateView(executionOwner(record), record.id);
154
+ this.resources.restore(record, connectionIds, attach);
155
+ }
111
156
  filesystemPolicy() {
112
157
  const stateRoot = this.host.filesystemStateRoot();
113
158
  return stateRoot ? { stateRoot } : {};
@@ -124,7 +169,7 @@ export class WorkflowExecutionService {
124
169
  this.code = {};
125
170
  this.ready = (async () => {
126
171
  try {
127
- const executors = await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), isolationMode: options.isolationMode, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) });
172
+ const executors = await createCodeExecutors({ ...this.filesystemPolicy(), sandbox: (sessionId) => this.host.workflowSandbox(sessionId), readOnly: (sessionId) => this.host.isReadOnly(sessionId), isolationMode: options.isolationMode, runtimePath: this.runtimePath, nodePath: options.nodePath ?? '', resolveSecret: async (name, signal) => this.secrets.resolve(name, signal) });
128
173
  if (key !== this.runtimeKey)
129
174
  return;
130
175
  this.code = executors;
@@ -152,7 +197,7 @@ export class WorkflowExecutionService {
152
197
  const view = this.privateView(sessionId, record.id);
153
198
  if (view.spend)
154
199
  this.host.workflowSpend(sessionId, record.id, view.spend);
155
- if (!view.completionAnnounced)
200
+ if (!record.occurrenceId && !view.completionAnnounced)
156
201
  this.publishResult(record);
157
202
  }
158
203
  }
@@ -170,13 +215,24 @@ export class WorkflowExecutionService {
170
215
  this.host.logFor(sessionId);
171
216
  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
217
  }
173
- view(sessionId, executionId) {
174
- const execution = this.scheduler.get(sessionId, executionId);
218
+ view(sessionId, executionId, invocationId) {
219
+ const execution = selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), invocationId);
175
220
  const view = this.privateView(sessionId, executionId);
176
- return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
221
+ if (invocationId === undefined)
222
+ return redactCredentials(structuredClone({ execution, ...view }), this.host.workflowMcpCredentials());
223
+ const stepSpend = Object.fromEntries(execution.definition.steps.flatMap(step => {
224
+ const spend = view.stepSpend[spendKey(step.id, invocationId)];
225
+ return spend ? [[step.id, spend]] : [];
226
+ }));
227
+ return redactCredentials(structuredClone({ execution, invocationId, ...view,
228
+ activity: view.activity.filter(item => item.invocationId === invocationId),
229
+ enquiries: view.enquiries.filter(item => item.invocationId === invocationId),
230
+ permissions: view.permissions.filter(item => item.invocationId === invocationId),
231
+ stepSpend, spend: sumSpend(Object.values(stepSpend)),
232
+ }), this.host.workflowMcpCredentials());
177
233
  }
178
234
  async activity(sessionId, executionId, options = {}) {
179
- this.scheduler.get(sessionId, executionId); // ownership check, including historical records
235
+ selectWorkflowInvocation(this.scheduler.get(sessionId, executionId), options.invocationId);
180
236
  const view = this.privateView(sessionId, executionId);
181
237
  const limit = Math.max(1, Math.min(200, options.limit ?? 100));
182
238
  const after = options.after ?? 0;
@@ -186,7 +242,8 @@ export class WorkflowExecutionService {
186
242
  throw new Error('Invalid activity cursor');
187
243
  if (![limit, after, before, options.attempt ?? 1].every(Number.isSafeInteger) || after < 0 || before < 1)
188
244
  throw new Error('Invalid activity cursor');
189
- const belongs = (event) => (!options.stepId || event.stepId === options.stepId) &&
245
+ const belongs = (event) => (options.invocationId === undefined ? !options.stepId || event.invocationId === undefined : event.invocationId === options.invocationId) &&
246
+ (!options.stepId || event.stepId === options.stepId) &&
190
247
  (options.attempt === undefined || event.attempt === options.attempt);
191
248
  const activity = [];
192
249
  const path = this.privatePath(sessionId, executionId) + 'l';
@@ -241,12 +298,11 @@ export class WorkflowExecutionService {
241
298
  }, this.host.workflowMcpCredentials());
242
299
  }
243
300
  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());
301
+ const path = this.privatePath(executionOwner(context), context.executionId) + 'l';
302
+ const item = redactCredentials({ sequence: (view.activity.at(-1)?.sequence ?? 0) + 1, at: Date.now(), ...attemptIdentity(context), subagentId, event }, this.host.workflowMcpCredentials());
247
303
  // Seed a legacy log with exactly what was retained, never invented backfill.
248
304
  if (!existsSync(path)) {
249
- this.savePrivate(context.sessionId, context.executionId, view);
305
+ this.savePrivate(executionOwner(context), context.executionId, view);
250
306
  const fd = openSync(path, 'wx', 0o600);
251
307
  try {
252
308
  writeFileSync(fd, view.activity.map(item => JSON.stringify(item) + '\n').join(''));
@@ -274,10 +330,13 @@ export class WorkflowExecutionService {
274
330
  const record = records.find(record => ['running', 'recovery-required'].includes(record.status)) ?? records[0];
275
331
  return record && this.scheduler.get(sessionId, record.id);
276
332
  }
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,
333
+ summary(root, invocationId) {
334
+ const record = selectWorkflowInvocation(root, invocationId);
335
+ const view = this.privateView(executionOwner(root), root.id);
336
+ return { executionId: root.id, workflowId: record.definition.id, name: record.definition.name, status: record.status,
337
+ ...(invocationId ? { invocationId } : {}),
338
+ 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 })),
339
+ revision: recoveryRevision(root), savedDefinition: this.savedDefinitionSummary(record), automaticRecoveryAvailable: view.automaticAtProgress === undefined || successfulProgress(root) > view.automaticAtProgress,
281
340
  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
341
  loops: Object.entries(record.loops ?? {}).map(([id, loop]) => ({ id, phase: loop.phase, activation: loop.activation, try: loop.try })),
283
342
  historyComplete: view.historyComplete === true, };
@@ -296,6 +355,7 @@ export class WorkflowExecutionService {
296
355
  updatedRecoveryDefinition(record, action) {
297
356
  if (action.kind !== 'retry-updated')
298
357
  return undefined;
358
+ record = selectWorkflowInvocation(record, action.invocationId);
299
359
  const definition = this.store.getDefinition(record.definition.id);
300
360
  if (savedDefinitionRevision(definition) !== action.definitionRevision)
301
361
  throw new WorkflowConflict();
@@ -373,34 +433,39 @@ export class WorkflowExecutionService {
373
433
  if (input.section === 'activity')
374
434
  return this.activity(sessionId, record.id, input);
375
435
  if (input.section === 'execution') {
436
+ const selected = selectWorkflowInvocation(record, input.invocationId);
376
437
  let savedDefinition = null;
377
438
  try {
378
- const definition = this.store.getDefinition(record.definition.id);
379
- savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.namingCredentials({ ...record, definition }));
439
+ const definition = this.store.getDefinition(selected.definition.id);
440
+ savedDefinition = redactCredentials({ revision: savedDefinitionRevision(definition), definition }, this.availableCredentials({ ...selected, definition }));
380
441
  }
381
442
  catch { /* Retained execution remains inspectable if the saved copy was deleted. */ }
382
- return { ...this.view(sessionId, record.id), savedDefinition };
443
+ return { ...this.view(sessionId, record.id, input.invocationId), savedDefinition };
383
444
  }
384
- return redactCredentials(this.summary(record), this.host.workflowMcpCredentials());
445
+ return redactCredentials(this.summary(record, input.invocationId), this.host.workflowMcpCredentials());
385
446
  },
386
447
  recover: async (raw, signal) => {
387
448
  const input = workflowRecoverInput.parse(raw);
449
+ if (input.invocationId !== undefined && input.action.invocationId !== undefined && input.invocationId !== input.action.invocationId)
450
+ throw new Error('Conflicting Workflow invocation selectors');
451
+ const action = { ...input.action, ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }) };
388
452
  const record = this.scheduler.get(sessionId, input.executionId);
389
453
  if (record.status !== 'recovery-required' || recoveryRevision(record) !== input.revision)
390
454
  throw new WorkflowConflict();
391
- const updated = this.updatedRecoveryDefinition(record, input.action);
455
+ const updated = this.updatedRecoveryDefinition(record, action);
392
456
  let authorized = false;
393
457
  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);
458
+ const selected = selectWorkflowInvocation(record, action.invocationId);
459
+ const correction = updated && action.kind === 'retry-updated'
460
+ ? `\nSaved step configuration to adopt: ${JSON.stringify(updated.steps.find(step => 'stepId' in action && step.id === action.stepId))}` : '';
461
+ const credentials = uniqueCredentials([...this.availableCredentials(record, updated ? [updated] : []), ...this.recoveryCredentials(record, action, updated)]);
462
+ 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
463
  if (!authorized)
399
464
  throw new Error('Recovery was not authorized');
400
465
  }
401
466
  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));
467
+ await this.recover(sessionId, record.id, action, { revision: input.revision, authorized, signal });
468
+ return this.summary(this.scheduler.get(sessionId, record.id), action.invocationId);
404
469
  },
405
470
  relayEnquiry: async (raw, signal) => {
406
471
  const input = workflowRelayInput.parse(raw);
@@ -463,122 +528,140 @@ export class WorkflowExecutionService {
463
528
  redactRequestError(message) {
464
529
  return redactCredentials(message, this.host.workflowMcpCredentials());
465
530
  }
531
+ async validateScheduledAgents(definition, input, scope, projectId = scope) {
532
+ const manifest = resolveWorkflowCalls(definition, id => this.store.getDefinition(id));
533
+ const definitions = Object.values(manifest);
534
+ for (const candidate of definitions) {
535
+ if (candidate.backend !== definition.backend)
536
+ throw new WorkflowValidationError('Backend Adapter mismatch');
537
+ if (candidate.projectId && !sameProject(candidate.projectId, projectId))
538
+ throw new WorkflowValidationError('Workflow is restricted to another Project');
539
+ }
540
+ try {
541
+ parseValue(definition.inputSchema, input);
542
+ }
543
+ catch (error) {
544
+ if (error instanceof ZodError)
545
+ throw new WorkflowValidationError('Workflow input does not match its schema');
546
+ throw error;
547
+ }
548
+ const values = uniqueCredentials([...this.host.workflowMcpCredentials(), ...definitions.flatMap(candidate => this.referencedSecrets(candidate))]);
549
+ for (const candidate of definitions)
550
+ assertNoSecrets(publicDefinition(candidate), values);
551
+ assertNoSecrets(input, values, true);
552
+ const agents = definitions.flatMap(candidate => candidate.steps.filter(step => step.kind === 'agent'));
553
+ if (!agents.length)
554
+ return;
555
+ const models = await this.host.workflowAgentModels(scope, definition.backend);
556
+ for (const step of agents)
557
+ this.checkAgentModel(step, models);
558
+ if (!isDeepStrictEqual(resolveWorkflowCalls(definition, id => this.store.getDefinition(id)), manifest))
559
+ throw new WorkflowConflict();
560
+ }
466
561
  validateDefinitionCredentials(definition) {
467
562
  assertNoSecrets(publicDefinition(definition), this.host.workflowMcpCredentials(), true);
468
563
  }
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))
564
+ start(options) { return this.launch({ kind: 'session', options }); }
565
+ async launch(launch) {
566
+ const manual = launch.kind === 'session' ? launch.options : undefined;
567
+ const owner = launch.kind === 'session' ? launch.options.sessionId : executionOwnerKey({ kind: 'occurrence', occurrenceId: launch.options.occurrenceId });
568
+ const existing = () => manual?.launchId && !manual.stepId ? this.store.listExecutions(owner).find(record => record.launchId === manual.launchId) : undefined;
569
+ const prior = existing();
570
+ if (prior)
571
+ return this.view(owner, prior.id);
572
+ if (this.scheduler.occupied(owner))
482
573
  throw new WorkflowConflict();
483
574
  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
575
  let record;
525
- this.checkingCode = snapshot.code;
576
+ let values = [];
526
577
  try {
527
- record = this.scheduler.start(preparedDefinition, session, input, stepId, launchId, nameSession && !stepId);
578
+ const prepared = await prepareWorkflowLaunch(launch, {
579
+ host: this.host, store: this.store, secrets: this.secrets, resources: this.resources, runtimePath: this.runtimePath,
580
+ snapshot: async (needsCode) => needsCode ? this.codeSnapshot() : { runtime: this.runtimeOptions, code: this.code },
581
+ discover: (id, connection, tools, mode, signal) => this.discoverMcp(id, connection, tools, mode, signal),
582
+ validateScheduledAgents: (definition, input, scope, projectId) => this.validateScheduledAgents(definition, input, scope, projectId),
583
+ });
584
+ values = prepared.values;
585
+ const raced = existing();
586
+ if (raced)
587
+ return this.view(owner, raced.id);
588
+ if (this.scheduler.occupied(owner))
589
+ throw new WorkflowConflict();
590
+ prepared.assertCurrent();
591
+ this.checkingCode = prepared.code;
592
+ try {
593
+ record = this.scheduler.start(prepared.definition, prepared.session, launch.options.input, manual?.stepId, manual?.launchId, !!manual?.nameSession && !manual.stepId, prepared.manifest);
594
+ }
595
+ finally {
596
+ this.checkingCode = undefined;
597
+ }
598
+ this.secretValues.set(record.id, values);
599
+ this.runtimeSnapshots.set(record.id, prepared.runtime);
600
+ this.snapshots.set(record.id, prepared.code);
601
+ this.privateView(owner, record.id).historyComplete = true;
602
+ this.savePrivate(owner, record.id, this.privateView(owner, record.id));
603
+ this.watch(record);
604
+ return this.view(owner, record.id);
528
605
  }
529
- finally {
530
- this.checkingCode = undefined;
606
+ catch (error) {
607
+ if (launch.kind === 'occurrence') {
608
+ record ??= this.store.listExecutions(owner)[0];
609
+ if (record) {
610
+ const interrupted = await this.scheduler.interrupt(owner, record.id);
611
+ this.watch(interrupted);
612
+ return this.view(owner, record.id);
613
+ }
614
+ await this.resources.forget(owner);
615
+ }
616
+ if (error instanceof WorkflowConflict)
617
+ throw error;
618
+ throw safeError(error, values);
531
619
  }
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
620
  }
540
621
  async recover(sessionId, executionId, action, authority) {
541
622
  const saved = this.scheduler.get(sessionId, executionId);
542
623
  if (saved.status !== 'recovery-required')
543
624
  throw new WorkflowConflict();
544
625
  const updated = this.updatedRecoveryDefinition(saved, action);
545
- const definition = updated ?? saved.definition;
626
+ const selected = selectWorkflowInvocation(saved, action.invocationId);
627
+ const definition = updated ?? selected.definition;
628
+ const definitions = [saved.definition, ...Object.values(saved.retainedDefinitions ?? {}), ...Object.keys(saved.invocations ?? {}).map(id => invocationExecution(saved, id).definition), definition];
546
629
  const session = await this.host.openWorkflowSession(sessionId);
547
630
  this.privateView(sessionId, executionId);
548
631
  // 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);
632
+ const options = saved.runtime ?? this.runtimeSnapshots.get(executionId) ?? { ...workflowRuntimeOptions(this.config.view().workflowRuntime), isolationMode: 'bubblewrap' };
633
+ const needsCode = definitions.some(candidate => candidate.steps.some(step => ['shell', 'typescript'].includes(step.kind)));
634
+ const resources = this.resources.get(executionOwner(saved));
635
+ 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) }) : {};
636
+ for (const candidate of definitions) {
637
+ if (candidate.backend !== session.backend)
638
+ throw new Error('Backend Adapter mismatch');
639
+ if (candidate.projectId && !sameProject(candidate.projectId, session.projectId))
640
+ throw new Error('Workflow is restricted to another Project');
641
+ }
642
+ const values = uniqueCredentials([...this.availableCredentials(saved, [definition]), ...this.recoveryCredentials(saved, action, updated)]);
643
+ assertNoSecrets({ ...publicExecutionData(saved), action }, values);
556
644
  if (updated)
557
645
  assertNoSecrets(publicDefinition(updated), values);
558
646
  if (action.kind === 'supply')
559
647
  assertNoSecrets(action.output, values, true);
560
648
  this.secretValues.set(executionId, values);
561
649
  this.host.assertWorkflowSession(sessionId, session.session);
650
+ this.recoveryAuthority(sessionId, executionId, action, authority);
651
+ if (saved.occurrenceId)
652
+ await this.resources.occurrence(executionOwner(saved)).environment.recover(authority?.signal);
562
653
  let record;
563
654
  this.checkingCode = code;
564
655
  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);
656
+ const consent = this.recoveryAuthority(sessionId, executionId, action, authority);
657
+ if (consent) {
658
+ consent.view.automaticAtProgress = consent.progress;
659
+ this.savePrivate(sessionId, executionId, consent.view);
577
660
  }
578
661
  // Re-read after readiness/Revive and human confirmation: saving again revokes consent.
579
- if (updated && savedDefinitionRevision(this.store.getDefinition(saved.definition.id)) !== savedDefinitionRevision(updated))
662
+ if (updated && savedDefinitionRevision(this.store.getDefinition(updated.id)) !== savedDefinitionRevision(updated))
580
663
  throw new WorkflowConflict();
581
- record = this.scheduler.recover(session, executionId, action, updated);
664
+ record = this.scheduler.recover({ ...session, ...(saved.occurrenceId ? { occurrenceId: saved.occurrenceId } : {}), matchesProject: project => sameProject(project, session.projectId) }, executionId, action, updated);
582
665
  }
583
666
  catch (error) {
584
667
  if (error instanceof WorkflowLoopConflict)
@@ -592,6 +675,19 @@ export class WorkflowExecutionService {
592
675
  this.watch(record);
593
676
  return this.view(sessionId, executionId);
594
677
  }
678
+ recoveryAuthority(sessionId, executionId, action, authority) {
679
+ if (!authority)
680
+ return;
681
+ authority.signal?.throwIfAborted();
682
+ const current = this.scheduler.get(sessionId, executionId);
683
+ if (current.status !== 'recovery-required' || recoveryRevision(current) !== authority.revision)
684
+ throw new WorkflowConflict();
685
+ const progress = successfulProgress(current);
686
+ const view = this.privateView(sessionId, executionId);
687
+ if (!authority.authorized && (!safeAutomaticRecovery(current, action) || (view.automaticAtProgress !== undefined && progress <= view.automaticAtProgress)))
688
+ throw new Error('User direction required. Explain the failure and proposed recovery, then request confirmation.');
689
+ return { view, progress };
690
+ }
595
691
  async cancel(sessionId, executionId) {
596
692
  this.scheduler.get(sessionId, executionId);
597
693
  this.host.cancelWorkflowConfirmation(sessionId);
@@ -607,6 +703,8 @@ export class WorkflowExecutionService {
607
703
  this.cancelling.set(executionId, { sessionId, done });
608
704
  try {
609
705
  await done;
706
+ if (record.occurrenceId)
707
+ await this.resources.close(executionOwner(record));
610
708
  }
611
709
  finally {
612
710
  this.cancelling.delete(executionId);
@@ -617,11 +715,29 @@ export class WorkflowExecutionService {
617
715
  this.host.cancelWorkflowConfirmation(sessionId);
618
716
  await Promise.all([...this.cancelling.values()].filter(item => item.sessionId === sessionId).map(item => item.done));
619
717
  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);
718
+ if (record.status === 'running' || record.status === 'recovery-required') {
719
+ const interrupted = await this.scheduler.interrupt(sessionId, record.id);
720
+ if (interrupted.occurrenceId)
721
+ await this.onScheduledResult?.(interrupted);
722
+ }
622
723
  }
623
724
  }
725
+ canForget(sessionId, occurrenceId) {
726
+ // Consult durable records: host.load() may reap before scheduler reconciliation.
727
+ const records = this.store.listExecutions(sessionId);
728
+ // Session metadata can precede the checkpoint's association write during attachment.
729
+ if (occurrenceId) {
730
+ const owned = this.store.listExecutions({ kind: 'occurrence', occurrenceId });
731
+ if (!owned.length && !this.scheduledOwnershipAvailable)
732
+ return false;
733
+ records.push(...owned);
734
+ }
735
+ return !records.some(record => record.occurrenceId &&
736
+ (record.status === 'running' || record.status === 'recovery-required'));
737
+ }
624
738
  async forget(sessionId) {
739
+ if (!this.canForget(sessionId))
740
+ throw new WorkflowConflict();
625
741
  await this.stop(sessionId);
626
742
  this.scheduler.forgetSession(sessionId);
627
743
  for (const record of this.store.listExecutions(sessionId)) {
@@ -670,7 +786,7 @@ export class WorkflowExecutionService {
670
786
  // never resurrect a canceled or superseded attempt.
671
787
  if (request.kind === 'enquiry' || !request.direct) {
672
788
  const launch = this.launches.get(request.subagentId);
673
- if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.stepId !== request.stepId)
789
+ if (!launch || launch.sessionId !== sessionId || launch.executionId !== request.executionId || launch.invocationId !== request.invocationId || launch.stepId !== request.stepId || launch.attempt !== request.attempt)
674
790
  throw new WorkflowConflict();
675
791
  }
676
792
  else {
@@ -735,19 +851,40 @@ export class WorkflowExecutionService {
735
851
  if (oldest && !oldest.announced && !oldest.relaying)
736
852
  this.host.workflowInput(sessionId);
737
853
  }
854
+ checkAgent(sessionId, step) {
855
+ const backend = this.host.workflowSession(sessionId).session;
856
+ if (!backend?.startWorkflowSubagent)
857
+ throw new Error('Workflow agent capabilities are unavailable. Retry after the Backend Session is ready.');
858
+ return this.checkAgentModel(step, backend.capabilities.models);
859
+ }
860
+ checkAgentModel(step, models) {
861
+ step = confirmedAgentStep(step, models);
862
+ const model = models.find(model => model.id === step.model);
863
+ if (!model)
864
+ throw new WorkflowValidationError(`Agent model “${step.model}” is unavailable. Refresh models and select an available model.`);
865
+ const levels = model.effortLevels ?? [];
866
+ if (levels.length ? !levels.includes(step.effort) : step.effort !== 'off')
867
+ throw new WorkflowValidationError(`Effort “${step.effort}” is unsupported for ${model.label ?? model.id}. Choose one of ${levels.length ? levels.join(', ') : 'off'}.`);
868
+ return step;
869
+ }
738
870
  checkMcp(sessionId, tool) {
739
- const connection = this.host.workflowMcpConnections(sessionId).find(connection => connection.id === tool.connectionId);
871
+ const connection = this.connections(sessionId).find(connection => connection.id === tool.connectionId);
740
872
  if (!connection || connectionIdentity(connection) !== tool.identity)
741
873
  throw new Error('MCP connection removed, disabled or changed. Enable the original connection or reselect the tool in the workflow editor.');
742
874
  validateMcpSchemas(tool);
743
875
  }
744
- async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode()) {
876
+ async discoverMcp(sessionId, connectionId, expected, isolationMode = this.config.filesystemIsolationMode(), signal) {
745
877
  const pinned = expected ? (Array.isArray(expected) ? expected : [expected]) : [];
746
878
  for (const tool of pinned)
747
879
  this.checkMcp(sessionId, tool);
748
- const session = await this.host.openWorkflowMcp(sessionId, connectionId, isolationMode);
880
+ signal?.throwIfAborted();
881
+ const session = await this.openMcp(sessionId, connectionId, isolationMode, signal);
882
+ const abort = () => { void session.dispose().catch(() => { }); };
883
+ signal?.addEventListener('abort', abort, { once: true });
749
884
  try {
885
+ signal?.throwIfAborted();
750
886
  await session.open();
887
+ signal?.throwIfAborted();
751
888
  if (session.status()[0]?.state !== 'connected')
752
889
  throw new Error('MCP connection unavailable. Sign in in MCP Settings or reconfigure the server, then retry manually.');
753
890
  // Preflight validates only pinned tools, not unrelated advertised schemas.
@@ -774,6 +911,7 @@ export class WorkflowExecutionService {
774
911
  return { tools, errors };
775
912
  }
776
913
  finally {
914
+ signal?.removeEventListener('abort', abort);
777
915
  await session.dispose();
778
916
  }
779
917
  }
@@ -784,22 +922,22 @@ export class WorkflowExecutionService {
784
922
  if (context.permission !== 'ask')
785
923
  return;
786
924
  const id = randomUUID(), callId = randomUUID();
787
- const view = this.privateView(context.sessionId, context.executionId);
925
+ const view = this.privateView(executionOwner(context), context.executionId);
788
926
  const tool = context.step.kind === 'mcp' ? context.step.tool.toolName : 'MCP';
789
927
  const decision = new Promise(resolve => this.directPermissions.set(id, { sessionId: context.sessionId, executionId: context.executionId, callId, resolve }));
790
928
  const abort = () => { this.directPermissions.get(id)?.resolve(false); };
791
929
  context.signal.addEventListener('abort', abort, { once: true });
792
930
  const details = redactCredentials(context.input, this.host.workflowMcpCredentials());
793
931
  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;
932
+ view.permissions.push({ direct: true, subagentId: id, ...attemptIdentity(context), callId, tool, details, scope });
933
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
934
+ const attempt = context.attempt ?? 1;
797
935
  this.registerRelay({
798
936
  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),
937
+ ...attemptIdentity(context), subagentId: id, callId, tool, direct: true,
938
+ details, scope, context: relayContext(execution, context.step.id, attempt, context.invocationId),
801
939
  });
802
- this.savePrivate(context.sessionId, context.executionId, view);
940
+ this.savePrivate(executionOwner(context), context.executionId, view);
803
941
  if (context.signal.aborted)
804
942
  abort();
805
943
  let decided = false;
@@ -817,30 +955,31 @@ export class WorkflowExecutionService {
817
955
  this.directPermissions.delete(id);
818
956
  this.dropRelays(request => request.subagentId === id, !decided);
819
957
  view.permissions = view.permissions.filter(prompt => prompt.subagentId !== id);
820
- this.savePrivate(context.sessionId, context.executionId, view);
958
+ this.savePrivate(executionOwner(context), context.executionId, view);
821
959
  }
822
960
  }
823
961
  async mcp(context) {
824
962
  if (context.step.kind !== 'mcp')
825
963
  throw new Error('Invalid MCP step');
826
964
  const expected = context.step.tool;
827
- this.checkMcp(context.sessionId, expected);
965
+ this.checkMcp(executionOwner(context), expected);
828
966
  validateJsonSchema(expected.inputSchema, context.input);
829
967
  if (!context.input || typeof context.input !== 'object' || Array.isArray(context.input))
830
968
  throw new Error('MCP arguments must be an object');
831
969
  assertNoSecrets(context.input, this.host.workflowMcpCredentials(), true);
832
- await this.mcpPermission(context);
833
- this.checkMcp(context.sessionId, expected);
970
+ if (context.permission === 'ask')
971
+ await this.mcpPermission(await this.attachContext(context));
972
+ this.checkMcp(executionOwner(context), expected);
834
973
  context.signal.throwIfAborted();
835
974
  const isolationMode = this.runtimeSnapshots.get(context.executionId)?.isolationMode ?? 'bubblewrap';
836
- const session = await this.host.openWorkflowMcp(context.sessionId, expected.connectionId, isolationMode);
975
+ const session = await this.openMcp(executionOwner(context), expected.connectionId, isolationMode, context.signal);
837
976
  const abort = () => { void session.dispose(); };
838
977
  context.signal.addEventListener('abort', abort, { once: true });
839
978
  const values = () => [...(this.secretValues.get(context.executionId) ?? []), ...this.host.workflowMcpCredentials()];
840
- const view = this.privateView(context.sessionId, context.executionId);
979
+ const view = this.privateView(executionOwner(context), context.executionId);
841
980
  const activity = (text) => {
842
981
  this.appendActivity(context, view, { type: 'notice', level: 'info', text }, context.step.id);
843
- this.savePrivate(context.sessionId, context.executionId, view);
982
+ this.savePrivate(executionOwner(context), context.executionId, view);
844
983
  };
845
984
  try {
846
985
  await session.open();
@@ -850,7 +989,7 @@ export class WorkflowExecutionService {
850
989
  throw new Error('MCP tool unavailable. Sign in in MCP Settings or reconfigure the original server; retry manually.');
851
990
  if (tool.serverIdentity !== expected.serverIdentity || !sameSchema(tool.definition.inputSchema, expected.inputSchema) || !sameSchema(tool.definition.outputSchema, expected.outputSchema))
852
991
  throw new Error('MCP tool schema changed. Reselect the tool; this execution cannot retarget it.');
853
- this.checkMcp(context.sessionId, expected);
992
+ this.checkMcp(executionOwner(context), expected);
854
993
  activity('Calling MCP directly. No model or tokens. Cancellation is not rollback; remote effects may already occur.');
855
994
  const result = await tool.call(context.input, context.signal, context.step.timeoutMs ?? 60_000);
856
995
  const output = boundedMcpValue({ structuredContent: result.structuredContent ?? null, content: result.content });
@@ -868,15 +1007,16 @@ export class WorkflowExecutionService {
868
1007
  await session.dispose();
869
1008
  }
870
1009
  }
871
- async agent(context) {
872
- if (context.step.kind !== 'agent')
1010
+ async agent(incoming) {
1011
+ if (incoming.step.kind !== 'agent')
873
1012
  throw new Error('Invalid Agent step');
1013
+ const context = { ...incoming, step: this.checkAgent(incoming.sessionId, incoming.step) };
874
1014
  const resolvedInstructions = context.step.instructions;
875
1015
  const backend = this.host.workflowSession(context.sessionId).session;
876
1016
  if (!backend?.startWorkflowSubagent)
877
1017
  throw new Error('Workflow Backend Session is unavailable');
878
1018
  context.signal.throwIfAborted();
879
- const savedStep = this.scheduler.get(context.sessionId, context.executionId).definition.steps.find(step => step.id === context.step.id);
1019
+ const savedStep = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId).definition.steps.find(step => step.id === context.step.id);
880
1020
  const instructions = savedStep.kind === 'agent' ? savedStep.instructions : context.step.instructions;
881
1021
  const invocation = leadingSkillInvocation(instructions);
882
1022
  if (invocation) {
@@ -899,8 +1039,9 @@ export class WorkflowExecutionService {
899
1039
  aliases[alias] = this.secrets.resolve(reference, context.signal);
900
1040
  const values = uniqueCredentials([...(this.secretValues.get(context.executionId) ?? []), ...Object.values(aliases)]);
901
1041
  const id = randomUUID();
902
- const view = this.privateView(context.sessionId, context.executionId);
903
- const priorSpend = view.stepSpend[context.step.id];
1042
+ const view = this.privateView(executionOwner(context), context.executionId);
1043
+ const key = spendKey(context.step.id, context.invocationId);
1044
+ const priorSpend = view.stepSpend[key];
904
1045
  const requestIds = new Map();
905
1046
  const publicIds = new Map();
906
1047
  const publicId = (raw) => {
@@ -916,18 +1057,24 @@ export class WorkflowExecutionService {
916
1057
  emit: ({ event: rawEvent }) => {
917
1058
  const event = redactEvent(rawEvent, values, publicId);
918
1059
  this.appendActivity(context, view, event, id);
1060
+ if (event.type === 'message' && event.final && hasDiffReference(event.text)) {
1061
+ void this.host.diffExcerpts(context.sessionId, event.text).then(excerpts => {
1062
+ this.appendActivity(context, view, { type: 'diff_excerpts', messageId: event.id, excerpts }, id);
1063
+ this.savePrivate(executionOwner(context), context.executionId, view);
1064
+ });
1065
+ }
919
1066
  if (event.type === 'enquiry') {
920
1067
  view.enquiries = view.enquiries.filter(item => item.subagentId !== id || item.askId !== event.askId);
921
1068
  if (event.state !== 'asked')
922
1069
  this.dropRelays(request => request.subagentId === id && request.kind === 'enquiry' && request.askId === event.askId, event.state === 'aborted');
923
1070
  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;
1071
+ view.enquiries.push({ subagentId: id, ...attemptIdentity(context), askId: event.askId, questions: event.questions });
1072
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
1073
+ const attempt = context.attempt ?? 1;
927
1074
  this.registerRelay({
928
1075
  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),
1076
+ ...attemptIdentity(context), subagentId: id, askId: event.askId,
1077
+ questions: event.questions, context: relayContext(execution, context.step.id, attempt, context.invocationId),
931
1078
  });
932
1079
  }
933
1080
  }
@@ -939,22 +1086,22 @@ export class WorkflowExecutionService {
939
1086
  const started = view.activity.findLast(item => item.event.type === 'tool_started' && item.event.callId === event.callId);
940
1087
  const details = started?.event.type === 'tool_started' ? started.event.input : undefined;
941
1088
  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;
1089
+ view.permissions.push({ subagentId: id, ...attemptIdentity(context), callId: event.callId, tool: event.tool, ...(details === undefined ? {} : { details }), scope });
1090
+ const execution = selectWorkflowInvocation(this.scheduler.get(context.sessionId, context.executionId), context.invocationId);
1091
+ const attempt = context.attempt ?? 1;
945
1092
  this.registerRelay({
946
1093
  kind: 'permission', sessionId: context.sessionId, executionId: context.executionId,
947
- stepId: context.step.id, attempt, subagentId: id, callId: event.callId,
1094
+ ...attemptIdentity(context), subagentId: id, callId: event.callId,
948
1095
  tool: event.tool, direct: false, ...(details === undefined ? {} : { details }), scope,
949
- context: relayContext(execution, context.step.id, attempt),
1096
+ context: relayContext(execution, context.step.id, attempt, context.invocationId),
950
1097
  });
951
1098
  }
952
1099
  }
953
1100
  if (event.type === 'spend') {
954
- view.stepSpend[context.step.id] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
1101
+ view.stepSpend[key] = sumSpend([...(priorSpend ? [priorSpend] : []), event.spend]);
955
1102
  view.spend = sumSpend(Object.values(view.stepSpend));
956
1103
  }
957
- this.savePrivate(context.sessionId, context.executionId, view);
1104
+ this.savePrivate(executionOwner(context), context.executionId, view);
958
1105
  if (event.type === 'spend' && view.spend)
959
1106
  this.host.workflowSpend(context.sessionId, context.executionId, view.spend);
960
1107
  },
@@ -971,7 +1118,7 @@ export class WorkflowExecutionService {
971
1118
  await handle.cancel();
972
1119
  throw new Error('Workflow Agent permissions are unavailable');
973
1120
  }
974
- this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, stepId: context.step.id, handle, requestIds });
1121
+ this.launches.set(id, { sessionId: context.sessionId, executionId: context.executionId, ...attemptIdentity(context), handle, requestIds });
975
1122
  const abort = () => { void handle.cancel().catch(() => { }); };
976
1123
  context.signal.addEventListener('abort', abort, { once: true });
977
1124
  if (context.signal.aborted)
@@ -992,22 +1139,77 @@ export class WorkflowExecutionService {
992
1139
  this.dropRelays(request => request.subagentId === id);
993
1140
  view.enquiries = view.enquiries.filter(item => item.subagentId !== id);
994
1141
  view.permissions = view.permissions.filter(item => item.subagentId !== id);
995
- this.savePrivate(context.sessionId, context.executionId, view);
1142
+ this.savePrivate(executionOwner(context), context.executionId, view);
1143
+ }
1144
+ }
1145
+ recoveryCredentials(record, action, updated) {
1146
+ const steps = recoverySteps(record, action, updated);
1147
+ const checked = new Set();
1148
+ for (const step of steps) {
1149
+ if (step.kind !== 'workflow' || checked.has(step.workflowId))
1150
+ continue;
1151
+ checked.add(step.workflowId);
1152
+ const target = record.retainedDefinitions?.[step.workflowId];
1153
+ if (!target)
1154
+ throw new Error('Missing retained called Workflow Definition');
1155
+ steps.push(...target.steps);
996
1156
  }
1157
+ return [...new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))].map(name => this.secrets.resolve(name));
997
1158
  }
998
1159
  referencedSecrets(definition, stepId) {
999
1160
  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
1161
  }
1001
1162
  watch(record) {
1002
- void this.scheduler.wait(record.sessionId, record.id).then(result => {
1163
+ const publication = this.scheduler.wait(executionOwner(record), record.id).then(result => {
1003
1164
  const credentials = this.secretValues.get(record.id) ?? [];
1004
- this.publishResult(result, credentials);
1165
+ return this.publishScheduledResult(result, credentials);
1005
1166
  }).catch(() => { }).finally(() => {
1167
+ const owner = executionOwner(record);
1168
+ if (this.scheduler.get(owner, record.id).status === 'running' || this.scheduler.hasPendingDeadline(owner, record.id))
1169
+ return;
1006
1170
  this.snapshots.delete(record.id);
1007
1171
  this.secretValues.delete(record.id);
1008
1172
  });
1173
+ if (record.occurrenceId) {
1174
+ const owner = executionOwner(record);
1175
+ const publications = this.scheduledPublications.get(owner) ?? new Set();
1176
+ this.scheduledPublications.set(owner, publications);
1177
+ publications.add(publication);
1178
+ const settled = () => {
1179
+ publications.delete(publication);
1180
+ if (!publications.size)
1181
+ this.scheduledPublications.delete(owner);
1182
+ };
1183
+ void publication.then(settled, settled);
1184
+ }
1185
+ }
1186
+ async publishScheduledResult(result, credentials) {
1187
+ if (result.occurrenceId && result.status === 'recovery-required' && !result.sessionId) {
1188
+ try {
1189
+ const sessionId = await this.resources.occurrence(executionOwner(result)).attach();
1190
+ this.scheduler.associate(result.occurrenceId, result.id, sessionId);
1191
+ result = this.scheduler.get(executionOwner(result), result.id);
1192
+ }
1193
+ catch { }
1194
+ }
1195
+ try {
1196
+ if (result.occurrenceId)
1197
+ await this.onScheduledResult?.(result);
1198
+ if (result.sessionId)
1199
+ this.publishResult(result, credentials);
1200
+ }
1201
+ finally {
1202
+ if (result.occurrenceId) {
1203
+ const owner = executionOwner(result);
1204
+ const current = this.scheduler.get(owner, result.id);
1205
+ if (current.status !== 'running' && current.status !== 'recovery-required' && !this.scheduler.hasPendingDeadline(owner, result.id))
1206
+ await this.resources.close(owner);
1207
+ }
1208
+ }
1009
1209
  }
1010
1210
  publishResult(result, knownCredentials = []) {
1211
+ if (!result.sessionId)
1212
+ return;
1011
1213
  if (!result.testStepId && ['recovery-required', 'completed', 'completed-with-recovery', 'cancelled'].includes(result.status)) {
1012
1214
  this.requestNaming(result.sessionId, result.id, () => {
1013
1215
  const { results, errors } = outcomeNamingData(result);
@@ -1017,7 +1219,7 @@ export class WorkflowExecutionService {
1017
1219
  outcome: result.status,
1018
1220
  results,
1019
1221
  errors,
1020
- }, uniqueCredentials([...knownCredentials, ...this.namingCredentials(result)]));
1222
+ }, uniqueCredentials([...knownCredentials, ...this.availableCredentials(result)]));
1021
1223
  });
1022
1224
  }
1023
1225
  if (!result.testStepId && result.status === 'recovery-required')
@@ -1046,13 +1248,15 @@ export class WorkflowExecutionService {
1046
1248
  }
1047
1249
  void this.host.nameWorkflow(sessionId, input).catch(() => { });
1048
1250
  }
1049
- namingCredentials(record) {
1251
+ availableCredentials(record, additional = []) {
1050
1252
  const values = [...this.host.workflowMcpCredentials()];
1051
- for (const reference of new Set(record.definition.steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1253
+ const definitions = [record.definition, ...Object.values(record.retainedDefinitions ?? {}), ...additional];
1254
+ const steps = [...definitions.flatMap(definition => definition.steps), ...[record, ...Object.values(record.invocations ?? {})].flatMap(checkpoint => (checkpoint.definitionUpdates ?? []).flatMap(update => [update.previousStep, update.nextStep]))];
1255
+ for (const reference of new Set(steps.flatMap(step => Object.values(step.secrets ?? {})))) {
1052
1256
  try {
1053
1257
  values.push(this.secrets.resolve(reference));
1054
1258
  }
1055
- catch { /* Missing secrets cannot make naming affect execution. */ }
1259
+ catch { }
1056
1260
  }
1057
1261
  return uniqueCredentials(values);
1058
1262
  }
@@ -1083,14 +1287,15 @@ export class WorkflowExecutionService {
1083
1287
  privatePath(sessionId, executionId) {
1084
1288
  if (![sessionId, executionId].every(value => /^[a-zA-Z0-9_-]+$/.test(value)))
1085
1289
  throw new Error('Invalid execution identity');
1086
- return join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity', executionId + '.json');
1290
+ const record = this.scheduler.get(sessionId, executionId);
1291
+ return join(this.store.ownerPath(executionOwner(record)), 'workflow-activity', executionId + '.json');
1087
1292
  }
1088
1293
  savePrivate(sessionId, executionId, view) {
1089
1294
  const path = this.privatePath(sessionId, executionId);
1090
- const directoryPath = join(this.store.stateRoot, 'sessions', sessionId, 'workflow-activity');
1295
+ const directoryPath = join(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'workflow-activity');
1091
1296
  if (!existsSync(directoryPath)) {
1092
- mkdirSync(directoryPath, { mode: 0o700 });
1093
- const parent = openSync(join(this.store.stateRoot, 'sessions', sessionId), 'r');
1297
+ mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
1298
+ const parent = openSync(this.store.ownerPath(executionOwner(this.scheduler.get(sessionId, executionId))), 'r');
1094
1299
  try {
1095
1300
  fsyncSync(parent);
1096
1301
  }
@@ -1116,119 +1321,3 @@ export class WorkflowExecutionService {
1116
1321
  }
1117
1322
  }
1118
1323
  }
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
- }