@desplega.ai/agent-swarm 1.167.0 → 1.169.0

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 (184) hide show
  1. package/dist/{acp-adapter-zpvy6321.js → acp-adapter-m47zfx4a.js} +2 -2
  2. package/dist/{actions-fq2zrwtf.js → actions-ws7k3tvq.js} +25 -19
  3. package/dist/{amp-adapter-5gbk7501.js → amp-adapter-nvv8k8j5.js} +1 -1
  4. package/dist/{app-nctetn1e.js → app-80w6qspx.js} +5 -5
  5. package/dist/{assistant-0aq8gjvj.js → assistant-jtq439kw.js} +29 -20
  6. package/dist/{boot-reembed-1ze5853n.js → boot-reembed-3nc0aaed.js} +4 -4
  7. package/dist/{boot-reembed-fmp5ww69.js → boot-reembed-feda8wn8.js} +4 -4
  8. package/dist/{boot-scrub-sweep-cbp8xd4e.js → boot-scrub-sweep-grsa2er0.js} +5 -5
  9. package/dist/{boot-seeds-22tx8a53.js → boot-seeds-gcfgq44f.js} +7 -7
  10. package/dist/{claude-adapter-0jhgeh1d.js → claude-adapter-pjv2q7t8.js} +7 -7
  11. package/dist/{claude-managed-adapter-tzwxy803.js → claude-managed-adapter-0wa8se82.js} +2 -2
  12. package/dist/{claude-managed-setup-nrhfx5b0.js → claude-managed-setup-zxa9p9tx.js} +1 -1
  13. package/dist/{claude-sdk-session-wh77rh83.js → claude-sdk-session-c9j6k9kx.js} +8772 -8663
  14. package/dist/{cli-c2tpw9ck.js → cli-3ry5gx4f.js} +1 -1
  15. package/dist/{cli-wydz3feg.js → cli-61tbnjpf.js} +214 -2472
  16. package/dist/{cli-cexctgn5.js → cli-7vz49g7h.js} +101 -34
  17. package/dist/{cli-6qxmjpem.js → cli-8xjst8q2.js} +34 -22
  18. package/dist/{cli-tx2zvn23.js → cli-91r17hb1.js} +3 -3
  19. package/dist/{cli-577bxkf6.js → cli-a8vps458.js} +182 -2208
  20. package/dist/{cli-tc5zec7v.js → cli-b7y8113e.js} +1 -1
  21. package/dist/{cli-69egj654.js → cli-bqrs5ycj.js} +1 -1
  22. package/dist/{cli-cf2vgn9d.js → cli-dv76vq5d.js} +30 -28
  23. package/dist/{cli-g5erf0zt.js → cli-e2prcx5m.js} +31 -0
  24. package/dist/{cli-c8r99akr.js → cli-e5qk3m2a.js} +209 -31
  25. package/dist/{cli-z1dqhc9y.js → cli-eqfbsxsn.js} +3 -3
  26. package/dist/{cli-kw0jcfje.js → cli-fyeft04q.js} +1 -1
  27. package/dist/{cli-5qkcdv8c.js → cli-gmdajfw5.js} +3 -3
  28. package/dist/{cli-ypgba1a8.js → cli-jkfxpg1b.js} +1 -1
  29. package/dist/{cli-mxvnnv5q.js → cli-jv36y8wz.js} +1 -1
  30. package/dist/{cli-m7vmeepg.js → cli-km8559dm.js} +6 -6
  31. package/dist/{cli-ykt8f7va.js → cli-kp3vfknv.js} +1 -1
  32. package/dist/{cli-ymmc1zxg.js → cli-m23r88re.js} +8 -5
  33. package/dist/{cli-v1pwxreq.js → cli-n4z21pt8.js} +1 -1
  34. package/dist/{cli-mxry91sa.js → cli-qg2zhjfc.js} +73 -4
  35. package/dist/{cli-1yrcfa5s.js → cli-rbr91whd.js} +4 -4
  36. package/dist/{cli-mkdsy1nq.js → cli-rg1c8ccw.js} +93 -7
  37. package/dist/cli-rh44xx46.js +2659 -0
  38. package/dist/cli-s0k2j7q9.js +2084 -0
  39. package/dist/{cli-ty4bzkqr.js → cli-sajr098b.js} +1 -1
  40. package/dist/{cli-6vfz44sr.js → cli-swrz3mj8.js} +1 -1
  41. package/dist/{cli-p8rt8spp.js → cli-vejds37t.js} +2 -2
  42. package/dist/{cli-jbzbr36n.js → cli-w6xa5nf5.js} +1 -1
  43. package/dist/{cli-9q3wt23f.js → cli-x6z90nq9.js} +1 -1
  44. package/dist/{cli-qzmzwegq.js → cli-ysnkvdx6.js} +102 -9
  45. package/dist/{cli-y0kjpfm9.js → cli-yvxfaem2.js} +2 -2
  46. package/dist/{cli-pkj1w46r.js → cli-z48ggfyq.js} +1 -1
  47. package/dist/{cli-6bpvv8h4.js → cli-zzev32jw.js} +1 -1
  48. package/dist/cli.js +20 -17
  49. package/dist/{codex-adapter-cgesnjkr.js → codex-adapter-0kpg09ca.js} +3 -3
  50. package/dist/{codex-hook-15dgc4cb.js → codex-hook-295jpbfa.js} +2 -2
  51. package/dist/{codex-session-runner-8kd7ddhr.js → codex-session-runner-8n672hxh.js} +3 -3
  52. package/dist/{commands-h6zaaxym.js → commands-mhmg5n0x.js} +4 -4
  53. package/dist/{cursor-adapter-v8mm6bp5.js → cursor-adapter-wn8n5zzk.js} +2 -2
  54. package/dist/{db-qg3myn53.js → db-wa6s1mwv.js} +4 -4
  55. package/dist/{dispatcher-7vnwj9qw.js → dispatcher-nhs2pkr8.js} +16 -14
  56. package/dist/{dsh-adapter-tz6hfp5r.js → dsh-adapter-5423p70m.js} +1 -1
  57. package/dist/{grok-adapter-jdt2dz2s.js → grok-adapter-28pkdt80.js} +3 -3
  58. package/dist/{handlers-2qtkpncr.js → handlers-5rtf9nng.js} +19 -17
  59. package/dist/{hook-51yfcgsv.js → hook-krjfkpzy.js} +4 -4
  60. package/dist/{hook-qnbdgwvd.js → hook-qkm73zk6.js} +5 -5
  61. package/dist/{http-jsmtag08.js → http-a397xcn4.js} +4845 -3484
  62. package/dist/{index-2t9kesn1.js → index-ac0v8v9d.js} +4 -4
  63. package/dist/{index-ekywyv2v.js → index-kqre45fr.js} +16 -14
  64. package/dist/{index-bt8wkv1w.js → index-rtxg15ah.js} +17 -15
  65. package/dist/{index-t4g06w93.js → index-vvsq7v45.js} +26 -23
  66. package/dist/{index-cx1sb9bq.js → index-ytdhtdry.js} +50 -11
  67. package/dist/{keepalive-4aezx4bj.js → keepalive-psfh8ysx.js} +6 -6
  68. package/dist/{lead-r44bkpm5.js → lead-m6rppjn7.js} +29 -27
  69. package/dist/{maintenance-grz5jrzh.js → maintenance-41f837ke.js} +4 -4
  70. package/dist/{node-qm9eb6z0.js → node-fkajaq96.js} +1 -1
  71. package/dist/{oauth-refresh-sweep-wm4ctjfj.js → oauth-refresh-sweep-6hr55hm8.js} +5 -5
  72. package/dist/{onboard-v60zgqf0.js → onboard-ktrtd7cz.js} +2 -2
  73. package/dist/{otel-impl-ghh4dyf8.js → otel-impl-dq4f2k3m.js} +1 -1
  74. package/dist/{pi-mono-adapter-0eg8kw2c.js → pi-mono-adapter-e5v9w0hv.js} +3 -2
  75. package/dist/{pricing-refresh-mjrqvnvw.js → pricing-refresh-kmk7j1ra.js} +6 -6
  76. package/dist/{rbac-roles-fd5tskj9.js → rbac-roles-9w1dkkxd.js} +4 -4
  77. package/dist/{rbac-roles-axv4d74x.js → rbac-roles-9ykx9tc5.js} +5 -5
  78. package/dist/{render-v2-k50j33qd.js → render-v2-ycqm53np.js} +5 -5
  79. package/dist/resume-cq2pkp8q.js +70 -0
  80. package/dist/{setup-4syh0pd2.js → setup-0dcmdvbn.js} +2 -2
  81. package/dist/{virtual-modules-ftr9kwe8.js → virtual-modules-1x9k4jcs.js} +1 -1
  82. package/dist/{work-objects-jcdbg8rr.js → work-objects-x01x2fh8.js} +19 -17
  83. package/dist/{worker-x8j8c9sx.js → worker-py1ssb1h.js} +29 -27
  84. package/openapi.json +15622 -15042
  85. package/package.json +8 -5
  86. package/src/apps/store.ts +1 -0
  87. package/src/artifact-sdk/feedback-overlay.ts +528 -0
  88. package/src/be/db/workflow-runs.ts +95 -0
  89. package/src/be/db-queries/slack-inbound.ts +489 -0
  90. package/src/be/db.ts +9 -2
  91. package/src/be/extensions/assets.ts +1 -1
  92. package/src/be/migrations/203_workflow_run_parent_step.sql +10 -0
  93. package/src/be/migrations/204_slack_inbound_receipts.sql +51 -0
  94. package/src/be/script-connections.ts +41 -7
  95. package/src/be/scripts/run-saved.ts +40 -20
  96. package/src/be/swarm-config-guard.ts +4 -0
  97. package/src/extensions/catalog.generated.json +17 -0
  98. package/src/extensions/catalog.ts +1 -1
  99. package/src/extensions/dispatcher.ts +3 -3
  100. package/src/heartbeat/heartbeat.ts +152 -2
  101. package/src/heartbeat/templates.ts +16 -0
  102. package/src/http/all-routes.ts +1 -0
  103. package/src/http/index.ts +2 -0
  104. package/src/http/integrations.ts +3 -1
  105. package/src/http/mcp-bridge.ts +1 -0
  106. package/src/http/pages-public.ts +7 -2
  107. package/src/http/pages.ts +178 -0
  108. package/src/http/script-connections.ts +35 -0
  109. package/src/http/slack-inbound.ts +107 -0
  110. package/src/http/tasks.ts +45 -27
  111. package/src/http/users.ts +1 -1
  112. package/src/http/webhooks.ts +20 -20
  113. package/src/prompts/session-templates.ts +32 -0
  114. package/src/providers/acp-targets.ts +1 -1
  115. package/src/providers/amp-adapter.ts +2 -2
  116. package/src/providers/claude-adapter.ts +6 -0
  117. package/src/providers/claude-background-keepalive.ts +100 -0
  118. package/src/providers/claude-managed-adapter.ts +2 -11
  119. package/src/providers/claude-sdk-session.ts +7 -1
  120. package/src/providers/dsh-adapter.ts +1 -1
  121. package/src/providers/opencode-adapter.ts +1 -2
  122. package/src/providers/pi-mono-adapter.ts +3 -3
  123. package/src/realtime/browser.generated.txt +8 -8
  124. package/src/realtime/browser.ts +3 -3
  125. package/src/scheduler/scheduler.ts +82 -13
  126. package/src/scripts-runtime/executors/quickjs-pool-config.ts +26 -0
  127. package/src/scripts-runtime/executors/quickjs.ts +9 -2
  128. package/src/scripts-runtime/executors/registry.ts +1 -1
  129. package/src/server.ts +1 -0
  130. package/src/slack/actions.ts +6 -2
  131. package/src/slack/app.ts +5 -0
  132. package/src/slack/assistant.ts +15 -5
  133. package/src/slack/egress-scrub.ts +3 -2
  134. package/src/slack/handlers.ts +36 -18
  135. package/src/slack/inbound-dispatch.ts +549 -0
  136. package/src/slack/inbound-files.ts +2 -0
  137. package/src/telemetry-context.ts +1 -0
  138. package/src/tests/claude-background-keepalive-wiring.test.ts +220 -0
  139. package/src/tests/claude-background-keepalive.fixture.ts +162 -0
  140. package/src/tests/claude-background-keepalive.test.ts +139 -0
  141. package/src/tests/codex-oauth-device.test.ts +1 -1
  142. package/src/tests/connection-embedded-auth.test.ts +51 -0
  143. package/src/tests/docs-index-footprint.test.js +3 -3
  144. package/src/tests/dsh-adapter.test.ts +1 -1
  145. package/src/tests/extensions-catalog.test.ts +1 -0
  146. package/src/tests/extensions-example-slack-reply-gate.test.ts +756 -0
  147. package/src/tests/heartbeat-checklist.test.ts +243 -0
  148. package/src/tests/pages-feedback.test.ts +218 -0
  149. package/src/tests/schedule-target-type.test.ts +136 -0
  150. package/src/tests/script-connections-http.test.ts +45 -0
  151. package/src/tests/script-connections-mcp.test.ts +41 -0
  152. package/src/tests/script-connections.test.ts +2 -0
  153. package/src/tests/script-executor-quickjs-pool.test.ts +106 -0
  154. package/src/tests/script-executor-registry.test.ts +56 -0
  155. package/src/tests/send-task-self-send.test.ts +107 -0
  156. package/src/tests/slack-inbound-diagnostics-auth.test.ts +93 -0
  157. package/src/tests/slack-inbound-receipts.test.ts +684 -0
  158. package/src/tests/slack-session-status.test.ts +4 -2
  159. package/src/tests/ui-e2e-ingest-payload.test.ts +5 -1
  160. package/src/tests/user-token-routes.test.ts +1 -1
  161. package/src/tests/workflow-executors.test.ts +3 -2
  162. package/src/tests/workflow-sub-workflow.test.ts +363 -0
  163. package/src/tools/script-connections/tool.ts +35 -3
  164. package/src/tools/send-task.ts +9 -1
  165. package/src/utils/internal-ai/complete-structured.ts +6 -3
  166. package/src/utils/runtime-model-catalog.ts +1 -1
  167. package/src/workflows/engine.ts +17 -1
  168. package/src/workflows/executors/agent-task.ts +2 -2
  169. package/src/workflows/executors/human-in-the-loop.ts +3 -3
  170. package/src/workflows/executors/registry.ts +2 -0
  171. package/src/workflows/executors/script.ts +1 -1
  172. package/src/workflows/executors/sub-workflow.ts +135 -0
  173. package/src/workflows/executors/wait.ts +3 -3
  174. package/src/workflows/recovery.ts +11 -1
  175. package/src/workflows/resume.ts +77 -0
  176. package/src/workflows/wait-filter.ts +5 -7
  177. package/templates/extensions/README.md +1 -0
  178. package/templates/extensions/slack-reply-gate/README.md +98 -0
  179. package/templates/extensions/slack-reply-gate/hooks.ts +582 -0
  180. package/templates/extensions/slack-reply-gate/manifest.json +8 -0
  181. package/templates/skills/heartbeat-runbook/content.md +3 -1
  182. package/templates/skills/pages/content.md +25 -0
  183. package/templates/skills/swarm-scripts/SKILL.md +10 -0
  184. package/templates/skills/swarm-scripts/content.md +10 -0
@@ -0,0 +1,2659 @@
1
+ import {
2
+ BaseExecutor,
3
+ SYSTEM_ONE_DECISION_NODE_TYPE,
4
+ findEntryNodes,
5
+ getNextTargets,
6
+ getSuccessors,
7
+ postApprovalCancellationUpdates,
8
+ resolveValidationPort,
9
+ systemOneRetryViolations,
10
+ systemOneUnresolvedError
11
+ } from "./cli-s0k2j7q9.js";
12
+ import {
13
+ WorkflowReplayStateError,
14
+ cancelPendingApprovalRequestsForRun,
15
+ cancelTask,
16
+ createWorkflowRun,
17
+ createWorkflowRunStep,
18
+ detachTaskFromWorkflowRunStep,
19
+ getChildWorkflowRunId,
20
+ getCompletedStepNodeIds,
21
+ getCurrentStepForNode,
22
+ getDbClient,
23
+ getLastRunStart,
24
+ getLastSuccessfulRun,
25
+ getLatestStepForNode,
26
+ getOAuthApp,
27
+ getOAuthTokens,
28
+ getPendingEventWaitNames,
29
+ getPendingWaitsByEvent,
30
+ getStepByIdempotencyKey,
31
+ getStepCountForNode,
32
+ getSwarmConfigs,
33
+ getTaskById,
34
+ getTaskByWorkflowRunStepId,
35
+ getWaitStateById,
36
+ getWorkflow,
37
+ getWorkflowRun,
38
+ getWorkflowRunLineage,
39
+ getWorkflowRunStep,
40
+ getWorkflowRunStepsByRunId,
41
+ init_db1 as init_db,
42
+ init_oauth,
43
+ init_scrub_json,
44
+ init_telemetry,
45
+ init_workflow_replay,
46
+ init_workflow_runs,
47
+ listCancelledApprovalRequestsForRun,
48
+ listCancelledApprovalRequestsForStep,
49
+ resolveWaitState,
50
+ scrubJsonValue,
51
+ telemetry,
52
+ updateWorkflowRun,
53
+ updateWorkflowRunStep
54
+ } from "./cli-rg1c8ccw.js";
55
+ import {
56
+ RetryPolicySchema,
57
+ init_types
58
+ } from "./cli-xvdgasgy.js";
59
+ import {
60
+ getSlackConfiguration,
61
+ init_config,
62
+ isSlackConfigured
63
+ } from "./cli-dmtrxqhg.js";
64
+ import {
65
+ deepInterpolate,
66
+ init_template
67
+ } from "./cli-5c2j5yvx.js";
68
+ import {
69
+ getAppUrl,
70
+ init_constants
71
+ } from "./cli-gd4favx9.js";
72
+ import {
73
+ init_env_flag,
74
+ isEnvFlagEnabled
75
+ } from "./cli-ej6gbxfb.js";
76
+ import {
77
+ init_zod
78
+ } from "./cli-sd0mxa3c.js";
79
+ import {
80
+ exports_external
81
+ } from "./cli-w5e1d1vv.js";
82
+ import {
83
+ init_event_bus,
84
+ workflowEventBus
85
+ } from "./cli-mb75wpxf.js";
86
+ import {
87
+ init_secret_scrubber,
88
+ isSensitiveKey,
89
+ scrubSecrets
90
+ } from "./cli-wt7ccy4r.js";
91
+ import {
92
+ __require
93
+ } from "./cli-bc05qbss.js";
94
+
95
+ // src/workflows/resume.ts
96
+ init_db();
97
+ init_workflow_runs();
98
+ init_secret_scrubber();
99
+
100
+ // src/workflows/approval-resolution.ts
101
+ function shapeApprovalResolution(registry, definition, nodeId, parkedOutput, approval) {
102
+ const node = definition.nodes.find((candidate) => candidate.id === nodeId);
103
+ if (node && registry.has(node.type)) {
104
+ const shaped = registry.get(node.type).resolveApproval(parkedOutput, approval);
105
+ if (shaped)
106
+ return shaped;
107
+ }
108
+ return {
109
+ output: {
110
+ requestId: approval.requestId,
111
+ status: approval.status,
112
+ responses: approval.responses
113
+ },
114
+ nextPort: approval.status === "timeout" ? "timeout" : approval.status === "rejected" ? "rejected" : "approved"
115
+ };
116
+ }
117
+
118
+ // src/workflows/completed-step-routing.ts
119
+ init_db();
120
+
121
+ // src/workflows/foreach-join.ts
122
+ init_db();
123
+
124
+ // src/workflows/checkpoint.ts
125
+ init_db();
126
+ async function checkpointStep(runId, stepId, nodeId, result, ctx) {
127
+ await getDbClient().transaction(async () => {
128
+ await updateWorkflowRunStep(stepId, {
129
+ status: "completed",
130
+ output: result.output,
131
+ nextPort: result.nextPort || undefined,
132
+ finishedAt: new Date().toISOString()
133
+ });
134
+ ctx[nodeId] = result.output;
135
+ await updateWorkflowRun(runId, {
136
+ context: ctx
137
+ });
138
+ });
139
+ }
140
+ async function checkpointStepFailure(runId, stepId, error, retryCount, retryPolicy, options) {
141
+ const now = new Date().toISOString();
142
+ if (retryPolicy && retryCount < retryPolicy.maxRetries) {
143
+ const delay = calculateBackoff(retryPolicy, retryCount);
144
+ const nextRetryAt = new Date(Date.now() + delay).toISOString();
145
+ await updateWorkflowRunStep(stepId, {
146
+ status: "failed",
147
+ error,
148
+ retryCount: retryCount + 1,
149
+ maxRetries: retryPolicy.maxRetries,
150
+ nextRetryAt
151
+ });
152
+ return { shouldRetry: true };
153
+ }
154
+ await updateWorkflowRunStep(stepId, {
155
+ status: "failed",
156
+ error,
157
+ finishedAt: now,
158
+ nextRetryAt: null
159
+ });
160
+ const markRunFailed = options?.markRunFailed ?? true;
161
+ if (markRunFailed) {
162
+ await getDbClient().transaction(async () => {
163
+ const run = await getWorkflowRun(runId);
164
+ if (run?.status !== "running" && run?.status !== "waiting")
165
+ return;
166
+ await updateWorkflowRun(runId, {
167
+ status: "failed",
168
+ error: `Step failed: ${error}`,
169
+ finishedAt: now
170
+ });
171
+ });
172
+ }
173
+ return { shouldRetry: false };
174
+ }
175
+ async function checkpointStepWaiting(runId, stepId, ctx) {
176
+ return getDbClient().transaction(async () => {
177
+ const step = await getDbClient().get(`UPDATE workflow_run_steps
178
+ SET status = 'waiting'
179
+ WHERE id = ? AND runId = ? AND status = 'running'
180
+ AND EXISTS (
181
+ SELECT 1 FROM workflow_runs
182
+ WHERE id = ? AND status IN ('running', 'waiting')
183
+ )
184
+ RETURNING id`, [stepId, runId, runId]);
185
+ if (!step)
186
+ return false;
187
+ await updateWorkflowRun(runId, { status: "waiting", context: ctx });
188
+ return true;
189
+ });
190
+ }
191
+ function calculateBackoff(policy, attempt) {
192
+ let delay;
193
+ switch (policy.strategy) {
194
+ case "exponential": {
195
+ const base = policy.baseDelayMs * 2 ** attempt;
196
+ delay = Math.random() * Math.min(base, policy.maxDelayMs);
197
+ break;
198
+ }
199
+ case "linear":
200
+ delay = policy.baseDelayMs * (attempt + 1);
201
+ break;
202
+ case "static":
203
+ delay = policy.baseDelayMs;
204
+ break;
205
+ default:
206
+ delay = policy.baseDelayMs;
207
+ }
208
+ return Math.min(delay, policy.maxDelayMs);
209
+ }
210
+
211
+ // src/workflows/foreach-join.ts
212
+ var FOREACH_TERMINAL_STEP_STATUSES = new Set([
213
+ "completed",
214
+ "failed",
215
+ "cancelled",
216
+ "skipped"
217
+ ]);
218
+ function parseSyntheticNodeId(nodeId) {
219
+ const separatorIndex = nodeId.indexOf("#");
220
+ if (separatorIndex <= 0 || separatorIndex === nodeId.length - 1)
221
+ return null;
222
+ return {
223
+ parentNodeId: nodeId.slice(0, separatorIndex),
224
+ itemKey: nodeId.slice(separatorIndex + 1)
225
+ };
226
+ }
227
+ function resolveForeachParent(def, nodeId) {
228
+ const parsed = parseSyntheticNodeId(nodeId);
229
+ if (!parsed)
230
+ return null;
231
+ const parent = def.nodes.find((node) => node.id === parsed.parentNodeId);
232
+ return parent?.type === "foreach" ? parent : null;
233
+ }
234
+ async function joinForeach(def, runId, childStep, ctx) {
235
+ const parent = resolveForeachParent(def, childStep.nodeId);
236
+ if (!parent) {
237
+ throw new Error(`Step "${childStep.nodeId}" is not a foreach child`);
238
+ }
239
+ const children = (await getWorkflowRunStepsByRunId(runId)).filter((step) => resolveForeachParent(def, step.nodeId)?.id === parent.id).sort((a, b) => childIndex(a) - childIndex(b));
240
+ if (children.some((step) => !FOREACH_TERMINAL_STEP_STATUSES.has(step.status))) {
241
+ return { joined: false, parentNodeId: parent.id, successors: [] };
242
+ }
243
+ const parentStep = await getLatestStepForNode(runId, parent.id);
244
+ if (!parentStep) {
245
+ throw new Error(`Waiting foreach parent step "${parent.id}" was not found`);
246
+ }
247
+ if (parentStep.status === "completed") {
248
+ return { joined: false, parentNodeId: parent.id, successors: [] };
249
+ }
250
+ const aggregate = buildForeachAggregate(children);
251
+ await checkpointStep(runId, parentStep.id, parent.id, { output: aggregate }, ctx);
252
+ return {
253
+ joined: true,
254
+ parentNodeId: parent.id,
255
+ successors: getSuccessors(def, parent.id)
256
+ };
257
+ }
258
+ function buildForeachAggregate(children) {
259
+ const orderedChildren = [...children].sort((a, b) => childIndex(a) - childIndex(b));
260
+ const results = orderedChildren.map((step) => {
261
+ const parsed = parseSyntheticNodeId(step.nodeId);
262
+ const status = resultStatus(step);
263
+ return {
264
+ itemKey: parsed.itemKey,
265
+ status,
266
+ output: step.output
267
+ };
268
+ });
269
+ const failedCount = results.filter((result) => result.status !== "completed").length;
270
+ const aggregate = {
271
+ results,
272
+ okCount: results.length - failedCount,
273
+ failedCount
274
+ };
275
+ return aggregate;
276
+ }
277
+ function childIndex(step) {
278
+ if (typeof step.input !== "object" || step.input === null)
279
+ return Number.MAX_SAFE_INTEGER;
280
+ const index = step.input.index;
281
+ return typeof index === "number" ? index : Number.MAX_SAFE_INTEGER;
282
+ }
283
+ function resultStatus(step) {
284
+ if (step.status !== "completed")
285
+ return step.status;
286
+ return step.error ? "failed" : "completed";
287
+ }
288
+
289
+ // src/workflows/completed-step-routing.ts
290
+ async function loadCompletedStepRouting(def, runId, completedNodeIds) {
291
+ const activeEdges = new Set;
292
+ const stepsByNodeId = new Map;
293
+ for (const nodeId of completedNodeIds) {
294
+ if (resolveForeachParent(def, nodeId))
295
+ continue;
296
+ const step = await getLatestStepForNode(runId, nodeId);
297
+ if (step)
298
+ stepsByNodeId.set(nodeId, step);
299
+ const successors = step?.nextPort ? getSuccessors(def, nodeId, step.nextPort) : getSuccessors(def, nodeId);
300
+ for (const successor of successors) {
301
+ activeEdges.add(`${nodeId}→${successor.id}`);
302
+ }
303
+ }
304
+ return { activeEdges, stepsByNodeId };
305
+ }
306
+
307
+ // src/workflows/constants.ts
308
+ var FAILED_TASK_OUTPUT_PREFIX = "[FAILED:";
309
+
310
+ // src/automation-preflight-alert.ts
311
+ init_constants();
312
+ init_secret_scrubber();
313
+ async function notifyAutomationPreflightFailure(preflight) {
314
+ const channel = process.env.SLACK_ALERTS_CHANNEL?.trim();
315
+ if (!channel) {
316
+ console.warn("[Automation Preflight] SLACK_ALERTS_CHANNEL not set; skipping alert");
317
+ return;
318
+ }
319
+ try {
320
+ const { getSlackApp } = await import("./app-80w6qspx.js");
321
+ const app = getSlackApp();
322
+ if (!app) {
323
+ console.warn("[Automation Preflight] Slack not available, cannot send notification");
324
+ return;
325
+ }
326
+ await app.client.chat.postMessage({
327
+ channel,
328
+ text: scrubSecrets(`⚠️ Automation needs setup
329
+ ` + `Automation: ${preflight.kind} "${preflight.name}"
330
+ Missing params: ${preflight.missing.params.join(", ") || "none"}
331
+ Missing integrations: ${preflight.missing.integrations.join(", ") || "none"}
332
+ Fire SKIPPED. It was not retried or queued.
333
+ Fix setup: ${getAppUrl()}${preflight.fixUrl}`),
334
+ unfurl_links: false,
335
+ unfurl_media: false
336
+ });
337
+ } catch (error) {
338
+ console.error("[Automation Preflight] Failed to send Slack notification:", scrubSecrets(error instanceof Error ? error.message : String(error)));
339
+ }
340
+ }
341
+
342
+ // src/be/automation-preflight.ts
343
+ init_config();
344
+ init_env_flag();
345
+ init_secret_scrubber();
346
+ init_db();
347
+ init_oauth();
348
+ init_scrub_json();
349
+ var NEEDS_SETUP_PREFIX = "needs_setup:";
350
+ function hasValue(value) {
351
+ if (value == null)
352
+ return false;
353
+ if (typeof value === "string")
354
+ return value.trim().length > 0;
355
+ if (Array.isArray(value))
356
+ return value.length > 0;
357
+ return true;
358
+ }
359
+ var GITHUB_REPOSITORY_SLUG = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}(?:\.git)?$/;
360
+ var SAFE_SHELL_DATA = /^[A-Za-z0-9._~%/:@ -]+$/;
361
+ var DNS_NAME = /^(?=.{1,253}$)(?:[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?\.)+[A-Za-z]{2,63}$/;
362
+ var SAFE_EXTERNAL_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
363
+ var SAFE_GIT_REF = /^(?!-)(?!.*(?:\.\.|@\{|\/\/))[A-Za-z0-9._/-]+$/;
364
+ var SAFE_TAG_PATTERN = /^(?!-)(?!.*(?:\.\.|\/\/))[A-Za-z0-9._*?/-]+$/;
365
+ var SAFE_RELATIVE_PATH = /^(?![-/])(?!.*(?:^|\/)\.\.(?:\/|$))[A-Za-z0-9._/-]+$/;
366
+ var SAFE_REPORT_NAME = /^(?!\.{1,2}$)[A-Za-z0-9][A-Za-z0-9._ -]{0,127}$/;
367
+ function isSafeRepository(value) {
368
+ if (!SAFE_SHELL_DATA.test(value) || value.trim() !== value || value.includes(" "))
369
+ return false;
370
+ const slug = value.replace(/^https:\/\/github\.com\//, "").replace(/^git@github\.com:/, "").replace(/\/$/, "");
371
+ return GITHUB_REPOSITORY_SLUG.test(slug);
372
+ }
373
+ function isSafeGscProperty(value) {
374
+ if (!SAFE_SHELL_DATA.test(value) || value.trim() !== value)
375
+ return false;
376
+ return value.split(" ").every((property) => {
377
+ if (!property)
378
+ return false;
379
+ if (property.startsWith("sc-domain:"))
380
+ return DNS_NAME.test(property.slice(10));
381
+ if (DNS_NAME.test(property))
382
+ return true;
383
+ try {
384
+ const url = new URL(property);
385
+ return url.protocol === "https:" && !url.username && !url.password && !url.port && !url.search && !url.hash && DNS_NAME.test(url.hostname);
386
+ } catch {
387
+ return false;
388
+ }
389
+ });
390
+ }
391
+ var PARAM_VALIDATORS = {
392
+ REPO_URL: (value) => typeof value === "string" && isSafeRepository(value),
393
+ GSC_PROPERTY: (value) => typeof value === "string" && isSafeGscProperty(value),
394
+ BRANCH: (value) => typeof value === "string" && SAFE_GIT_REF.test(value),
395
+ SCOPE_PATH: (value) => typeof value === "string" && SAFE_RELATIVE_PATH.test(value),
396
+ REPORT_NAME: (value) => typeof value === "string" && value.trim() === value && SAFE_REPORT_NAME.test(value),
397
+ TAG_PATTERN: (value) => typeof value === "string" && SAFE_TAG_PATTERN.test(value),
398
+ AGENT_FS_ORG_ID: (value) => typeof value === "string" && SAFE_EXTERNAL_ID.test(value),
399
+ ORG_ID: (value) => typeof value === "string" && SAFE_EXTERNAL_ID.test(value)
400
+ };
401
+ function isUsableParam(key, value) {
402
+ if (!hasValue(value))
403
+ return false;
404
+ return PARAM_VALIDATORS[key]?.(value) ?? true;
405
+ }
406
+ function uniqueSorted(values) {
407
+ return [...new Set(values)].sort((a, b) => a.localeCompare(b));
408
+ }
409
+ function automationUrl(input) {
410
+ return input.kind === "schedule" ? `/schedules/${input.id}` : `/workflows/${input.id}`;
411
+ }
412
+ var INTEGRATION_FIX_URL = {
413
+ slack: "/settings/integrations/slack",
414
+ github: "/settings/integrations/github",
415
+ linear: "/settings/integrations/linear",
416
+ jira: "/settings/integrations/jira",
417
+ agentmail: "/settings/integrations/agentmail",
418
+ gsc: "/settings/integrations/gsc",
419
+ agentfs: "/settings/integrations/agentfs"
420
+ };
421
+ var INTEGRATION_FIRST_REQUIREMENTS = new Set([
422
+ "gsc",
423
+ "linear",
424
+ "agentmail"
425
+ ]);
426
+ function automationIntegrationFixUrl(id) {
427
+ return INTEGRATION_FIX_URL[id];
428
+ }
429
+ function isNeedsSetupFailure(reason) {
430
+ return reason?.startsWith(NEEDS_SETUP_PREFIX) ?? false;
431
+ }
432
+ function preflightAutomation(input, setup) {
433
+ const params = input.params ?? {};
434
+ const guardedParams = Object.keys(params).filter((key) => (key in PARAM_VALIDATORS));
435
+ const missingParams = uniqueSorted([...input.requiredParams ?? [], ...guardedParams].filter((key) => !isUsableParam(key, params[key])));
436
+ const missingIntegrations = uniqueSorted((input.requires ?? []).filter((id) => setup[id] === "unverified"));
437
+ const missing = { params: missingParams, integrations: missingIntegrations };
438
+ const baseUrl = automationUrl(input);
439
+ const fixes = [
440
+ ...missingParams.map((key) => ({
441
+ type: "param",
442
+ key,
443
+ url: `${baseUrl}?param=${encodeURIComponent(key)}`
444
+ })),
445
+ ...missingIntegrations.map((key) => ({
446
+ type: "integration",
447
+ key,
448
+ url: automationIntegrationFixUrl(key)
449
+ }))
450
+ ];
451
+ if (missingParams.length === 0 && missingIntegrations.length === 0) {
452
+ return {
453
+ id: input.id,
454
+ name: input.name,
455
+ kind: input.kind,
456
+ state: "running",
457
+ missing,
458
+ fixes,
459
+ fixUrl: baseUrl
460
+ };
461
+ }
462
+ const firstParam = missingParams[0];
463
+ const firstIntegration = (input.requires ?? []).find((id) => missingIntegrations.includes(id));
464
+ const integrationFirst = (input.requires ?? []).some((id) => INTEGRATION_FIRST_REQUIREMENTS.has(id));
465
+ const fixUrl = integrationFirst && firstIntegration ? automationIntegrationFixUrl(firstIntegration) : firstParam ? `${baseUrl}?param=${encodeURIComponent(firstParam)}` : firstIntegration ? automationIntegrationFixUrl(firstIntegration) : baseUrl;
466
+ const failureReason = `${NEEDS_SETUP_PREFIX} params=[${missingParams.join(",")}] integrations=[${missingIntegrations.join(",")}]`;
467
+ return {
468
+ id: input.id,
469
+ name: input.name,
470
+ kind: input.kind,
471
+ state: "needs_setup",
472
+ missing,
473
+ fixes,
474
+ fixUrl,
475
+ failureReason
476
+ };
477
+ }
478
+ var EXACT_TOKEN = /^\{\{\s*([^}]+?)\s*\}\}$/;
479
+ var TOKEN = /\{\{\s*([^}]+?)\s*\}\}/g;
480
+ function renderAutomationTokens(value, params) {
481
+ function render(current) {
482
+ if (typeof current === "string") {
483
+ const exact = EXACT_TOKEN.exec(current);
484
+ if (exact?.[1] && Object.hasOwn(params, exact[1]))
485
+ return params[exact[1]];
486
+ return current.replace(TOKEN, (token, key) => {
487
+ if (!Object.hasOwn(params, key))
488
+ return token;
489
+ const replacement = params[key];
490
+ return typeof replacement === "object" ? JSON.stringify(replacement) : String(replacement);
491
+ });
492
+ }
493
+ if (Array.isArray(current))
494
+ return current.map(render);
495
+ if (current != null && typeof current === "object") {
496
+ return Object.fromEntries(Object.entries(current).map(([key, nested]) => [key, render(nested)]));
497
+ }
498
+ return current;
499
+ }
500
+ return render(value);
501
+ }
502
+ function present(value) {
503
+ return !!value?.trim();
504
+ }
505
+ async function getAutomationSetupStates() {
506
+ const [linearTokens, jiraTokens, jiraApp] = await Promise.all([
507
+ getOAuthTokens("linear"),
508
+ getOAuthTokens("jira"),
509
+ getOAuthApp("jira")
510
+ ]);
511
+ let jiraCloudId = false;
512
+ try {
513
+ const metadata = jiraApp?.metadata ? JSON.parse(jiraApp.metadata) : null;
514
+ jiraCloudId = !!(metadata && typeof metadata === "object" && metadata.cloudId);
515
+ } catch {
516
+ jiraCloudId = false;
517
+ }
518
+ const agentFsKey = process.env.API_AGENT_FS_API_KEY ?? process.env.AGENT_FS_API_KEY;
519
+ const agentFsOrg = process.env.AGENT_FS_DEFAULT_ORG_ID ?? process.env.AGENT_FS_SHARED_ORG_ID;
520
+ const gscConfigured = present(process.env.GSC_SERVICE_ACCOUNT_BASE64) || present(process.env.GSC_SERVICE_ACCOUNT_JSON);
521
+ return {
522
+ slack: getSlackConfiguration().mode === "socket" && isSlackConfigured() ? "configured" : "unverified",
523
+ github: present(process.env.GITHUB_WEBHOOK_SECRET) && present(process.env.GITHUB_APP_ID) && present(process.env.GITHUB_APP_PRIVATE_KEY) ? "verified" : "unverified",
524
+ linear: linearTokens ? "verified" : "unverified",
525
+ jira: jiraTokens && jiraCloudId ? "verified" : "unverified",
526
+ gsc: gscConfigured ? "verified" : "unverified",
527
+ agentmail: !isEnvFlagEnabled("AGENTMAIL_DISABLE", false) && present(process.env.AGENTMAIL_API_KEY) ? "verified" : "unverified",
528
+ agentfs: present(process.env.AGENT_FS_API_URL) && present(agentFsKey) && present(agentFsOrg) && present(process.env.AGENT_FS_DEFAULT_DRIVE_ID) ? "verified" : "unverified"
529
+ };
530
+ }
531
+ function schedulePreflightInput(schedule) {
532
+ return { ...schedule, kind: "schedule" };
533
+ }
534
+ function workflowPreflightInput(workflow) {
535
+ return { ...workflow, kind: "workflow" };
536
+ }
537
+ async function listEnabledAutomationPreflightInputs() {
538
+ const rows = await getDbClient().query(`SELECT id, name, 'schedule' AS kind, params, requiredParams, requires
539
+ FROM scheduled_tasks
540
+ WHERE enabled = 1
541
+ UNION ALL
542
+ SELECT id, name, 'workflow' AS kind, params, requiredParams, requires
543
+ FROM workflows
544
+ WHERE enabled = 1`);
545
+ return rows.map((row) => ({
546
+ id: row.id,
547
+ name: row.name,
548
+ kind: row.kind,
549
+ params: JSON.parse(row.params),
550
+ requiredParams: JSON.parse(row.requiredParams),
551
+ requires: JSON.parse(row.requires)
552
+ }));
553
+ }
554
+ function utcDayBounds(now) {
555
+ const start = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
556
+ return { start: start.toISOString(), end: new Date(start.getTime() + 86400000).toISOString() };
557
+ }
558
+ async function recordSchedulePreflightFailure(scheduleId, failureReason, now = new Date) {
559
+ const message = scrubSecrets(failureReason);
560
+ return await getDbClient().transaction(async (tx) => {
561
+ const row = await tx.get("SELECT lastErrorAt, lastErrorMessage FROM scheduled_tasks WHERE id = ?", [scheduleId]);
562
+ if (!row)
563
+ return false;
564
+ if (row.lastErrorMessage === message && row.lastErrorAt?.slice(0, 10) === now.toISOString().slice(0, 10)) {
565
+ return false;
566
+ }
567
+ await tx.run(`UPDATE scheduled_tasks
568
+ SET lastErrorAt = ?, lastErrorMessage = ?, lastUpdatedAt = ?
569
+ WHERE id = ?`, [now.toISOString(), message, now.toISOString(), scheduleId]);
570
+ return true;
571
+ });
572
+ }
573
+ async function recordWorkflowPreflightFailure(input) {
574
+ const now = input.now ?? new Date;
575
+ const bounds = utcDayBounds(now);
576
+ return await getDbClient().transaction(async (tx) => {
577
+ const existing = await tx.get(`SELECT id FROM workflow_runs
578
+ WHERE workflowId = ? AND status = 'failed'
579
+ AND error LIKE 'needs_setup:%'
580
+ AND startedAt >= ? AND startedAt < ?
581
+ ORDER BY startedAt ASC LIMIT 1`, [input.workflowId, bounds.start, bounds.end]);
582
+ if (existing)
583
+ return { runId: existing.id, recorded: false };
584
+ const runId = crypto.randomUUID();
585
+ const timestamp = now.toISOString();
586
+ await tx.run(`INSERT INTO workflow_runs
587
+ (id, workflowId, status, triggerType, triggerData, error, created_by,
588
+ startedAt, lastUpdatedAt, finishedAt)
589
+ VALUES (?, ?, 'failed', ?, ?, ?, ?, ?, ?, ?)`, [
590
+ runId,
591
+ input.workflowId,
592
+ input.triggerType,
593
+ input.triggerData === undefined ? null : scrubJsonValue(input.triggerData),
594
+ scrubSecrets(input.failureReason),
595
+ input.createdBy ?? null,
596
+ timestamp,
597
+ timestamp,
598
+ timestamp
599
+ ]);
600
+ return { runId, recorded: true };
601
+ });
602
+ }
603
+
604
+ // src/workflows/engine.ts
605
+ init_db();
606
+ init_workflow_replay();
607
+ init_telemetry();
608
+
609
+ // src/workflows/cooldown.ts
610
+ init_db();
611
+ function cooldownToMs(cooldown) {
612
+ let ms = 0;
613
+ if (cooldown.hours)
614
+ ms += cooldown.hours * 60 * 60 * 1000;
615
+ if (cooldown.minutes)
616
+ ms += cooldown.minutes * 60 * 1000;
617
+ if (cooldown.seconds)
618
+ ms += cooldown.seconds * 1000;
619
+ return ms;
620
+ }
621
+ async function shouldSkipCooldown(workflowId, cooldown) {
622
+ const cooldownMs = cooldownToMs(cooldown);
623
+ const now = Date.now();
624
+ const lastSuccess = await getLastSuccessfulRun(workflowId);
625
+ if (lastSuccess?.finishedAt) {
626
+ const lastFinished = new Date(lastSuccess.finishedAt).getTime();
627
+ if (now - lastFinished < cooldownMs)
628
+ return true;
629
+ }
630
+ const lastAttempt = await getLastRunStart(workflowId);
631
+ if (lastAttempt?.startedAt) {
632
+ const lastStarted = new Date(lastAttempt.startedAt).getTime();
633
+ if (now - lastStarted < cooldownMs)
634
+ return true;
635
+ }
636
+ return false;
637
+ }
638
+
639
+ // src/workflows/input.ts
640
+ init_db();
641
+ init_secret_scrubber();
642
+ async function resolveInputs(input) {
643
+ const resolved = {};
644
+ for (const [key, value] of Object.entries(input)) {
645
+ resolved[key] = await resolveInputValue(value);
646
+ }
647
+ return resolved;
648
+ }
649
+ async function resolveInputValue(value) {
650
+ const envMatch = /^\$\{(.+)\}$/.exec(value);
651
+ if (envMatch?.[1]) {
652
+ const envName = envMatch[1];
653
+ const envValue = process.env[envName];
654
+ if (envValue === undefined) {
655
+ throw new Error(`Environment variable "${envName}" is not set`);
656
+ }
657
+ return envValue;
658
+ }
659
+ if (value.startsWith("secret.")) {
660
+ const secretName = value.slice("secret.".length);
661
+ const configs = await getSwarmConfigs({ scope: "global", key: secretName });
662
+ const secretConfig = configs.find((c) => c.isSecret);
663
+ if (!secretConfig) {
664
+ throw new Error(`Secret "${secretName}" not found in config store`);
665
+ }
666
+ return secretConfig.value;
667
+ }
668
+ return value;
669
+ }
670
+ var REDACTED_SECRET_VALUE = "***REDACTED***";
671
+ function getSecretInputKeys(input) {
672
+ const keys = new Set;
673
+ if (!input)
674
+ return keys;
675
+ for (const [key, value] of Object.entries(input)) {
676
+ if (typeof value !== "string")
677
+ continue;
678
+ if (value.startsWith("secret.")) {
679
+ keys.add(key);
680
+ continue;
681
+ }
682
+ const envMatch = /^\$\{(.+)\}$/.exec(value);
683
+ if (envMatch?.[1] && isSensitiveKey(envMatch[1])) {
684
+ keys.add(key);
685
+ }
686
+ }
687
+ return keys;
688
+ }
689
+ function redactSecretsForStorage(ctx, secretKeys) {
690
+ if (secretKeys.size === 0)
691
+ return ctx;
692
+ const inputBlock = ctx.input;
693
+ if (!inputBlock || typeof inputBlock !== "object")
694
+ return ctx;
695
+ const redactedInput = { ...inputBlock };
696
+ let touched = false;
697
+ for (const key of secretKeys) {
698
+ if (key in redactedInput) {
699
+ redactedInput[key] = REDACTED_SECRET_VALUE;
700
+ touched = true;
701
+ }
702
+ }
703
+ if (!touched)
704
+ return ctx;
705
+ return { ...ctx, input: redactedInput };
706
+ }
707
+
708
+ // src/workflows/json-schema-validator.ts
709
+ function validateJsonSchema(schema, data) {
710
+ const errors = [];
711
+ validate(schema, data, "", errors);
712
+ return errors;
713
+ }
714
+ function validate(schema, data, path, errors) {
715
+ const prefix = path || "root";
716
+ if (schema.type !== undefined) {
717
+ const expected = schema.type;
718
+ if (!matchesType(expected, data)) {
719
+ errors.push(`${prefix}: expected type "${expected}", got ${typeOf(data)}`);
720
+ return;
721
+ }
722
+ }
723
+ if (Array.isArray(schema.required) && typeof data === "object" && data !== null) {
724
+ const obj = data;
725
+ for (const key of schema.required) {
726
+ if (!(key in obj)) {
727
+ errors.push(`${prefix}: missing required property "${key}"`);
728
+ }
729
+ }
730
+ }
731
+ if (Array.isArray(schema.enum)) {
732
+ const allowed = schema.enum;
733
+ if (!allowed.some((v) => JSON.stringify(v) === JSON.stringify(data))) {
734
+ errors.push(`${prefix}: value ${JSON.stringify(data)} not in enum [${allowed.map((v) => JSON.stringify(v)).join(", ")}]`);
735
+ return;
736
+ }
737
+ }
738
+ if ("const" in schema) {
739
+ if (JSON.stringify(data) !== JSON.stringify(schema.const)) {
740
+ errors.push(`${prefix}: value ${JSON.stringify(data)} does not match const ${JSON.stringify(schema.const)}`);
741
+ return;
742
+ }
743
+ }
744
+ if (schema.properties !== undefined && typeof schema.properties === "object" && schema.properties !== null && typeof data === "object" && data !== null) {
745
+ const props = schema.properties;
746
+ const obj = data;
747
+ for (const [key, subSchema] of Object.entries(props)) {
748
+ if (key in obj) {
749
+ validate(subSchema, obj[key], path ? `${path}.${key}` : key, errors);
750
+ }
751
+ }
752
+ }
753
+ if (schema.items !== undefined && typeof schema.items === "object" && schema.items !== null && Array.isArray(data)) {
754
+ const itemSchema = schema.items;
755
+ for (let i = 0;i < data.length; i++) {
756
+ validate(itemSchema, data[i], `${prefix}[${i}]`, errors);
757
+ }
758
+ }
759
+ }
760
+ function matchesType(expected, data) {
761
+ switch (expected) {
762
+ case "string":
763
+ return typeof data === "string";
764
+ case "number":
765
+ return typeof data === "number";
766
+ case "boolean":
767
+ return typeof data === "boolean";
768
+ case "array":
769
+ return Array.isArray(data);
770
+ case "object":
771
+ return typeof data === "object" && data !== null && !Array.isArray(data);
772
+ default:
773
+ return true;
774
+ }
775
+ }
776
+ function typeOf(data) {
777
+ if (data === null)
778
+ return "null";
779
+ if (data === undefined)
780
+ return "undefined";
781
+ if (Array.isArray(data))
782
+ return "array";
783
+ return typeof data;
784
+ }
785
+ function isPlainObject(value) {
786
+ return typeof value === "object" && value !== null && !Array.isArray(value);
787
+ }
788
+ function findJsonSchemaShapeErrors(schema, path = "outputSchema") {
789
+ const errors = [];
790
+ if (!isPlainObject(schema)) {
791
+ errors.push(`${path}: must be a JSON Schema object, got ${typeOf(schema)}`);
792
+ return errors;
793
+ }
794
+ if (schema.type !== undefined && typeof schema.type !== "string") {
795
+ errors.push(`${path}.type: must be a string, got ${typeOf(schema.type)}`);
796
+ }
797
+ if (schema.required !== undefined && (!Array.isArray(schema.required) || !schema.required.every((v) => typeof v === "string"))) {
798
+ errors.push(`${path}.required: must be an array of strings`);
799
+ }
800
+ if (schema.enum !== undefined && !Array.isArray(schema.enum)) {
801
+ errors.push(`${path}.enum: must be an array`);
802
+ }
803
+ if (schema.properties !== undefined) {
804
+ if (!isPlainObject(schema.properties)) {
805
+ errors.push(`${path}.properties: must be an object mapping property names to schemas`);
806
+ } else {
807
+ for (const [key, value] of Object.entries(schema.properties)) {
808
+ errors.push(...findJsonSchemaShapeErrors(value, `${path}.properties.${key}`));
809
+ }
810
+ }
811
+ }
812
+ if (schema.items !== undefined) {
813
+ errors.push(...findJsonSchemaShapeErrors(schema.items, `${path}.items`));
814
+ }
815
+ return errors;
816
+ }
817
+
818
+ // src/workflows/limits.ts
819
+ var DEFAULT_MAX_STEPS_PER_RUN = 500;
820
+ function getMaxWorkflowStepsPerRun() {
821
+ return Number(process.env.WORKFLOW_MAX_STEPS_PER_RUN) || DEFAULT_MAX_STEPS_PER_RUN;
822
+ }
823
+
824
+ // src/workflows/readiness.ts
825
+ async function findWorkflowReadinessProblems(definition, registry) {
826
+ const nodesByType = new Map;
827
+ for (const node of definition.nodes) {
828
+ if (!registry.has(node.type))
829
+ continue;
830
+ const group = nodesByType.get(node.type) ?? [];
831
+ group.push({ id: node.id, config: node.config });
832
+ nodesByType.set(node.type, group);
833
+ }
834
+ const problems = [];
835
+ for (const [type, nodes] of nodesByType) {
836
+ try {
837
+ for (const problem of await registry.get(type).checkReadiness(nodes)) {
838
+ problems.push({ type, ...problem });
839
+ }
840
+ } catch {
841
+ problems.push({
842
+ type,
843
+ nodeIds: nodes.map((node) => node.id),
844
+ message: `Could not check whether "${type}" nodes are ready to run`
845
+ });
846
+ }
847
+ }
848
+ return problems;
849
+ }
850
+ function describeNodes(problem) {
851
+ const noun = problem.nodeIds.length === 1 ? "node" : "nodes";
852
+ return `${problem.type} ${noun} ${problem.nodeIds.map((id) => `"${id}"`).join(", ")}`;
853
+ }
854
+ function formatReadinessWarning(problem) {
855
+ return `${problem.message} Affects ${describeNodes(problem)}. Runs of this workflow fail before any node executes until this is fixed.`;
856
+ }
857
+ function formatReadinessProblems(problems) {
858
+ return problems.map((problem) => `${problem.message} Needed by ${describeNodes(problem)}.`).join(" ");
859
+ }
860
+ function formatReadinessRunError(problems) {
861
+ return `Run not started, no node executed: ${formatReadinessProblems(problems)}`;
862
+ }
863
+ async function workflowSaveWarnings(definition, registry) {
864
+ return (await findWorkflowReadinessProblems(definition, registry)).map(formatReadinessWarning);
865
+ }
866
+ function withSaveWarnings(text, warnings) {
867
+ return warnings.length === 0 ? text : `${text} ${warnings.map((warning) => `Warning: ${warning}`).join(" ")}`;
868
+ }
869
+
870
+ // src/workflows/template.ts
871
+ init_template();
872
+
873
+ // src/workflows/validation.ts
874
+ function extractPassResult(executorType, output) {
875
+ if (!output || typeof output !== "object")
876
+ return false;
877
+ const o = output;
878
+ switch (executorType) {
879
+ case "validate":
880
+ return o.pass === true;
881
+ case "script":
882
+ return o.exitCode === 0;
883
+ case "property-match":
884
+ return o.passed === true;
885
+ case "raw-llm":
886
+ if (typeof o.result === "object" && o.result !== null) {
887
+ return o.result.pass === true;
888
+ }
889
+ return false;
890
+ default:
891
+ return o.pass === true || o.passed === true || o.exitCode === 0;
892
+ }
893
+ }
894
+ async function runStepValidation(registry, stepNode, stepOutput, context, meta) {
895
+ if (!stepNode.validation) {
896
+ return { outcome: "pass" };
897
+ }
898
+ const validation = stepNode.validation;
899
+ const executorType = validation.executor || "validate";
900
+ const executor = registry.get(executorType);
901
+ const validationConfig = {
902
+ targetNodeId: meta.nodeId,
903
+ ...validation.config
904
+ };
905
+ const validationContext = {
906
+ ...context,
907
+ [meta.nodeId]: stepOutput
908
+ };
909
+ const result = await executor.run({
910
+ config: validationConfig,
911
+ context: validationContext,
912
+ meta: {
913
+ ...meta,
914
+ stepId: crypto.randomUUID()
915
+ }
916
+ });
917
+ const passed = result.status === "success" && extractPassResult(executorType, result.output);
918
+ if (passed) {
919
+ return { outcome: "pass", passed: true };
920
+ }
921
+ if (validation.mustPass) {
922
+ if (validation.retry) {
923
+ return {
924
+ outcome: "retry",
925
+ passed: false,
926
+ retryContext: {
927
+ previousOutput: stepOutput,
928
+ validationResult: result.output
929
+ }
930
+ };
931
+ }
932
+ return { outcome: "halt", passed: false };
933
+ }
934
+ return { outcome: "pass", passed: false };
935
+ }
936
+
937
+ // src/workflows/engine.ts
938
+ var DEFAULT_TIMEOUT_MS = 30000;
939
+ function maxIterations() {
940
+ return Number(process.env.WORKFLOW_MAX_ITERATIONS) || 100;
941
+ }
942
+
943
+ class TriggerSchemaError extends Error {
944
+ validationErrors;
945
+ constructor(validationErrors) {
946
+ super(`Trigger schema validation failed: ${validationErrors.join("; ")}`);
947
+ this.validationErrors = validationErrors;
948
+ this.name = "TriggerSchemaError";
949
+ }
950
+ }
951
+ async function resolveRenderedWorkflowInputs(input) {
952
+ const stringInputs = {};
953
+ const resolved = {};
954
+ for (const [key, value] of Object.entries(input)) {
955
+ if (typeof value === "string")
956
+ stringInputs[key] = value;
957
+ else
958
+ resolved[key] = value;
959
+ }
960
+ return { ...resolved, ...await resolveInputs(stringInputs) };
961
+ }
962
+ async function startWorkflowExecution(workflow, triggerData, registry, options = {}) {
963
+ const preflight = preflightAutomation(workflowPreflightInput(workflow), await getAutomationSetupStates());
964
+ if (preflight.state === "needs_setup") {
965
+ const { runId: runId2, recorded } = await recordWorkflowPreflightFailure({
966
+ workflowId: workflow.id,
967
+ triggerType: options.triggerType ?? "manual",
968
+ triggerData,
969
+ failureReason: preflight.failureReason,
970
+ createdBy: options.requestedByUserId
971
+ });
972
+ if (recorded)
973
+ await notifyAutomationPreflightFailure(preflight);
974
+ return runId2;
975
+ }
976
+ workflow = renderAutomationTokens(workflow, workflow.params ?? {});
977
+ if (workflow.triggerSchema) {
978
+ const validationErrors = validateJsonSchema(workflow.triggerSchema, triggerData);
979
+ if (validationErrors.length > 0) {
980
+ throw new TriggerSchemaError(validationErrors);
981
+ }
982
+ }
983
+ if (workflow.cooldown && await shouldSkipCooldown(workflow.id, workflow.cooldown)) {
984
+ const runId2 = crypto.randomUUID();
985
+ await createWorkflowRun({
986
+ id: runId2,
987
+ workflowId: workflow.id,
988
+ triggerType: options.triggerType ?? "manual",
989
+ triggerData,
990
+ createdBy: options.requestedByUserId,
991
+ parentStepId: options.parentStepId
992
+ });
993
+ await updateWorkflowRun(runId2, {
994
+ status: "skipped",
995
+ error: "cooldown",
996
+ finishedAt: new Date().toISOString()
997
+ });
998
+ return runId2;
999
+ }
1000
+ const runId = crypto.randomUUID();
1001
+ await createWorkflowRun({
1002
+ id: runId,
1003
+ workflowId: workflow.id,
1004
+ triggerType: options.triggerType ?? "manual",
1005
+ triggerData,
1006
+ createdBy: options.requestedByUserId,
1007
+ parentStepId: options.parentStepId
1008
+ });
1009
+ telemetry.workflow("started", {
1010
+ workflowId: workflow.id,
1011
+ nodeCount: workflow.definition.nodes.length,
1012
+ triggerType: options.triggerType ?? "manual"
1013
+ });
1014
+ const notReady = await findWorkflowReadinessProblems(workflow.definition, registry);
1015
+ if (notReady.length > 0) {
1016
+ await updateWorkflowRun(runId, {
1017
+ status: "failed",
1018
+ error: formatReadinessRunError(notReady),
1019
+ finishedAt: new Date().toISOString()
1020
+ });
1021
+ return runId;
1022
+ }
1023
+ const ctx = { trigger: triggerData };
1024
+ if (options.requestedByUserId) {
1025
+ ctx.swarm = { requestedByUserId: options.requestedByUserId };
1026
+ }
1027
+ if (workflow.dir || workflow.vcsRepo) {
1028
+ ctx.workflow = { dir: workflow.dir, vcsRepo: workflow.vcsRepo };
1029
+ }
1030
+ if (workflow.input) {
1031
+ try {
1032
+ const resolved = await resolveRenderedWorkflowInputs(workflow.input);
1033
+ Object.assign(ctx, { input: resolved });
1034
+ } catch (err) {
1035
+ await updateWorkflowRun(runId, {
1036
+ status: "failed",
1037
+ error: `Input resolution failed: ${err}`,
1038
+ finishedAt: new Date().toISOString()
1039
+ });
1040
+ return runId;
1041
+ }
1042
+ }
1043
+ const entryNodes = findEntryNodes(workflow.definition);
1044
+ const secretKeys = getSecretInputKeys(workflow.input);
1045
+ const walk = walkGraph(workflow.definition, runId, ctx, entryNodes, registry, workflow.id, secretKeys, options);
1046
+ if (options.parentStepId) {
1047
+ walk.catch((err) => console.error(`[workflows] Child workflow run ${runId} failed:`, err));
1048
+ return runId;
1049
+ }
1050
+ await walk;
1051
+ return runId;
1052
+ }
1053
+ var activeWalks = new Map;
1054
+ var executingSteps = new Set;
1055
+ async function failRunOnUnreadableReplay(runId, err, stepId) {
1056
+ if (!(err instanceof WorkflowReplayStateError))
1057
+ return false;
1058
+ const finishedAt = new Date().toISOString();
1059
+ console.error(`[workflow] ${err.message}`);
1060
+ if (stepId) {
1061
+ await updateWorkflowRunStep(stepId, {
1062
+ status: "failed",
1063
+ error: err.message,
1064
+ finishedAt,
1065
+ nextRetryAt: null
1066
+ });
1067
+ }
1068
+ await updateWorkflowRun(runId, { status: "failed", error: err.message, finishedAt });
1069
+ return true;
1070
+ }
1071
+ function isWorkflowRunActive(runId) {
1072
+ return activeWalks.has(runId);
1073
+ }
1074
+ function holdWorkflowRun(runId) {
1075
+ activeWalks.set(runId, (activeWalks.get(runId) ?? 0) + 1);
1076
+ let released = false;
1077
+ return () => {
1078
+ if (released)
1079
+ return;
1080
+ released = true;
1081
+ const remaining = activeWalks.get(runId) - 1;
1082
+ if (remaining === 0)
1083
+ activeWalks.delete(runId);
1084
+ else
1085
+ activeWalks.set(runId, remaining);
1086
+ };
1087
+ }
1088
+ async function walkGraph(def, runId, ctx, startNodes, registry, workflowId, secretKeys = new Set, options = {}) {
1089
+ const release = holdWorkflowRun(runId);
1090
+ try {
1091
+ await walkGraphOwned(def, runId, ctx, startNodes, registry, workflowId, secretKeys, options);
1092
+ } catch (err) {
1093
+ if (!await failRunOnUnreadableReplay(runId, err))
1094
+ throw err;
1095
+ } finally {
1096
+ release();
1097
+ }
1098
+ }
1099
+ async function walkGraphOwned(def, runId, ctx, startNodes, registry, workflowId, secretKeys = new Set, options = {}) {
1100
+ if (!options.requestedByUserId) {
1101
+ options = {
1102
+ ...options,
1103
+ requestedByUserId: (await getWorkflowRun(runId))?.createdBy
1104
+ };
1105
+ }
1106
+ let nodeExecutionCount = 0;
1107
+ if (!("run" in ctx)) {
1108
+ ctx.run = { id: runId };
1109
+ }
1110
+ const { completedNodeIds } = await rehydrateCompletedStepOutputs(def, runId, ctx, registry);
1111
+ const { activeEdges } = await loadCompletedStepRouting(def, runId, completedNodeIds);
1112
+ const allSteps = await getWorkflowRunStepsByRunId(runId);
1113
+ if (allSteps.length >= getMaxWorkflowStepsPerRun()) {
1114
+ await updateWorkflowRun(runId, {
1115
+ status: "failed",
1116
+ error: `Circuit breaker: run exceeded ${getMaxWorkflowStepsPerRun()} total steps (WORKFLOW_MAX_STEPS_PER_RUN)`,
1117
+ finishedAt: new Date().toISOString()
1118
+ });
1119
+ return;
1120
+ }
1121
+ for (const step of allSteps) {
1122
+ if (step.status !== "waiting")
1123
+ continue;
1124
+ const successors = getSuccessors(def, step.nodeId);
1125
+ for (const succ of successors) {
1126
+ activeEdges.add(`${step.nodeId}→${succ.id}`);
1127
+ }
1128
+ }
1129
+ const awaited = awaitedNodeIds(allSteps, activeEdges);
1130
+ let pendingNodes = startNodes.filter((n) => {
1131
+ const preds = getAllPredecessors(def, n.id);
1132
+ if (preds.length === 0) {
1133
+ return !completedNodeIds.has(n.id);
1134
+ }
1135
+ const activePreds = preds.filter((predId) => activeEdges.has(`${predId}→${n.id}`) || awaited.has(predId));
1136
+ const predsToCheck = activePreds.length > 0 ? activePreds : preds;
1137
+ return predsToCheck.every((p) => completedNodeIds.has(p));
1138
+ });
1139
+ const executedInThisWalk = new Set;
1140
+ while (pendingNodes.length > 0) {
1141
+ nodeExecutionCount += pendingNodes.length;
1142
+ if (nodeExecutionCount > maxIterations()) {
1143
+ await updateWorkflowRun(runId, {
1144
+ status: "failed",
1145
+ error: `Max node executions (${maxIterations()}) exceeded — possible infinite loop`,
1146
+ finishedAt: new Date().toISOString()
1147
+ });
1148
+ return;
1149
+ }
1150
+ const results = await Promise.all(pendingNodes.map((node) => executeStep(def, runId, ctx, node, registry, workflowId, secretKeys, options).catch(async (err) => {
1151
+ await failRunOnUnreadableReplay(runId, err);
1152
+ return { outcome: "failed", successors: [] };
1153
+ })));
1154
+ const nextBatch = new Map;
1155
+ let hasWaiting = false;
1156
+ for (let i = 0;i < results.length; i++) {
1157
+ const result = results[i];
1158
+ if (result.outcome === "failed") {
1159
+ const currentRun = await getWorkflowRun(runId);
1160
+ if (currentRun?.status === "failed")
1161
+ return;
1162
+ continue;
1163
+ }
1164
+ if (result.outcome === "waiting") {
1165
+ hasWaiting = true;
1166
+ continue;
1167
+ }
1168
+ const sourceNodeId = pendingNodes[i].id;
1169
+ completedNodeIds.add(sourceNodeId);
1170
+ executedInThisWalk.add(sourceNodeId);
1171
+ for (const succ of result.successors) {
1172
+ activeEdges.add(`${sourceNodeId}→${succ.id}`);
1173
+ nextBatch.set(succ.id, succ);
1174
+ }
1175
+ }
1176
+ if (hasWaiting)
1177
+ return;
1178
+ const readyNext = [];
1179
+ const batchSteps = nextBatch.size > 0 ? await getWorkflowRunStepsByRunId(runId) : [];
1180
+ const batchAwaited = awaitedNodeIds(batchSteps, activeEdges);
1181
+ const batchLatest = latestStepByNode(batchSteps);
1182
+ for (const [nodeId, node] of nextBatch) {
1183
+ if (executedInThisWalk.has(nodeId))
1184
+ continue;
1185
+ const allPreds = getAllPredecessors(def, nodeId);
1186
+ for (const predId of allPreds) {
1187
+ if (completedNodeIds.has(predId))
1188
+ continue;
1189
+ const latest = batchLatest.get(predId);
1190
+ if (latest?.status !== "completed")
1191
+ continue;
1192
+ completedNodeIds.add(predId);
1193
+ if (latest.output !== undefined)
1194
+ ctx[predId] = latest.output;
1195
+ }
1196
+ const activePreds = allPreds.filter((predId) => activeEdges.has(`${predId}→${nodeId}`) || batchAwaited.has(predId));
1197
+ const allActivePredsCompleted = activePreds.every((p) => completedNodeIds.has(p));
1198
+ if (allActivePredsCompleted) {
1199
+ readyNext.push(node);
1200
+ }
1201
+ }
1202
+ pendingNodes = readyNext;
1203
+ }
1204
+ await getDbClient().transaction(async () => {
1205
+ const run = await getWorkflowRun(runId);
1206
+ if (!run || run.status !== "running")
1207
+ return;
1208
+ const finalSteps = await getWorkflowRunStepsByRunId(runId);
1209
+ if (hasRunningStep(finalSteps))
1210
+ return;
1211
+ const hasWaitingSteps = finalSteps.some((s) => s.status === "waiting");
1212
+ const hasPendingRetries = finalSteps.some((s) => s.status === "failed" && s.nextRetryAt != null);
1213
+ const failedSteps = finalSteps.filter((s) => s.status === "failed" && s.nextRetryAt == null);
1214
+ const entryNodeIds = new Set(findEntryNodes(def).map((n) => n.id));
1215
+ const hasCompletedSteps = finalSteps.some((s) => s.status === "completed" && !entryNodeIds.has(s.nodeId));
1216
+ if (hasWaitingSteps) {
1217
+ await updateWorkflowRun(runId, { status: "waiting" });
1218
+ } else if (!hasPendingRetries) {
1219
+ if (failedSteps.length > 0 && !hasCompletedSteps) {
1220
+ const failedNodeIds = failedSteps.map((s) => s.nodeId).join(", ");
1221
+ await updateWorkflowRun(runId, {
1222
+ status: "failed",
1223
+ error: `All branches failed. Failed nodes: ${failedNodeIds}`,
1224
+ context: ctx,
1225
+ finishedAt: new Date().toISOString()
1226
+ });
1227
+ } else if (failedSteps.length > 0) {
1228
+ const failedNodeIds = failedSteps.map((s) => s.nodeId).join(", ");
1229
+ await updateWorkflowRun(runId, {
1230
+ status: "completed",
1231
+ error: `Partial failure: nodes [${failedNodeIds}] failed (mustPass validation), but other branches completed successfully`,
1232
+ context: ctx,
1233
+ finishedAt: new Date().toISOString()
1234
+ });
1235
+ } else {
1236
+ await updateWorkflowRun(runId, {
1237
+ status: "completed",
1238
+ context: ctx,
1239
+ finishedAt: new Date().toISOString()
1240
+ });
1241
+ }
1242
+ }
1243
+ });
1244
+ }
1245
+ function latestStepByNode(steps) {
1246
+ const latest = new Map;
1247
+ for (const step of steps)
1248
+ latest.set(step.nodeId, step);
1249
+ return latest;
1250
+ }
1251
+ function awaitedNodeIds(steps, activeEdges) {
1252
+ const latest = latestStepByNode(steps);
1253
+ const awaited = new Set;
1254
+ for (const [nodeId, step] of latest) {
1255
+ if (step.status === "running" || step.status === "waiting")
1256
+ awaited.add(nodeId);
1257
+ }
1258
+ for (const edge of activeEdges) {
1259
+ const target = edge.slice(edge.indexOf("→") + 1);
1260
+ if (!latest.has(target))
1261
+ awaited.add(target);
1262
+ }
1263
+ return awaited;
1264
+ }
1265
+ function hasRunningStep(steps) {
1266
+ for (const step of latestStepByNode(steps).values()) {
1267
+ if (step.status === "running")
1268
+ return true;
1269
+ }
1270
+ return false;
1271
+ }
1272
+ async function rehydrateCompletedStepOutputs(def, runId, ctx, registry) {
1273
+ const completedNodeIds = new Set(await getCompletedStepNodeIds(runId));
1274
+ const latestSteps = new Map;
1275
+ for (const nodeId of completedNodeIds) {
1276
+ if (resolveForeachParent(def, nodeId))
1277
+ continue;
1278
+ const step = await getLatestStepForNode(runId, nodeId);
1279
+ if (!step)
1280
+ continue;
1281
+ if (step.output !== undefined) {
1282
+ const node = def.nodes.find((candidate) => candidate.id === nodeId);
1283
+ if (node && registry.has(node.type)) {
1284
+ const executor = registry.get(node.type);
1285
+ const parseResult = executor.outputSchema.safeParse(step.output);
1286
+ if (!parseResult.success) {
1287
+ console.warn(`[workflow] Recovery: step ${nodeId} output failed validation: ${parseResult.error.message}`);
1288
+ continue;
1289
+ }
1290
+ }
1291
+ ctx[nodeId] = step.output;
1292
+ }
1293
+ latestSteps.set(nodeId, step);
1294
+ }
1295
+ return { completedNodeIds, latestSteps };
1296
+ }
1297
+ function getAllPredecessors(def, nodeId) {
1298
+ const preds = [];
1299
+ for (const node of def.nodes) {
1300
+ if (!node.next)
1301
+ continue;
1302
+ if (getNextTargets(node.next).includes(nodeId)) {
1303
+ preds.push(node.id);
1304
+ }
1305
+ }
1306
+ return preds;
1307
+ }
1308
+ async function executeStep(def, runId, ctx, node, registry, workflowId, secretKeys = new Set, options = {}) {
1309
+ let claimedStepId;
1310
+ const claimStep = async () => {
1311
+ const run = await getWorkflowRun(runId);
1312
+ if (!run || run.status !== "running" && run.status !== "waiting") {
1313
+ return { halted: true };
1314
+ }
1315
+ if (node.type !== "foreach") {
1316
+ const current = await getCurrentStepForNode(runId, node.id, getAllPredecessors(def, node.id));
1317
+ if (current && (current.status !== "running" || executingSteps.has(current.id))) {
1318
+ return { current };
1319
+ }
1320
+ }
1321
+ const iteration = await getStepCountForNode(runId, node.id);
1322
+ const idempotencyKey = `${runId}:${node.id}:${iteration}`;
1323
+ const existingStep = await getStepByIdempotencyKey(idempotencyKey);
1324
+ if (existingStep && (existingStep.status === "completed" || existingStep.status === "waiting")) {
1325
+ return { existingStep, stepId: existingStep.id, deduped: true };
1326
+ }
1327
+ const latestForeachStep = node.type === "foreach" ? await getLatestStepForNode(runId, node.id) : undefined;
1328
+ const reusableForeachStep = latestForeachStep && !FOREACH_TERMINAL_STEP_STATUSES.has(latestForeachStep.status) ? latestForeachStep : undefined;
1329
+ const stepId = reusableForeachStep?.id ?? crypto.randomUUID();
1330
+ if (!reusableForeachStep) {
1331
+ await createWorkflowRunStep({
1332
+ id: stepId,
1333
+ runId,
1334
+ nodeId: node.id,
1335
+ nodeType: node.type,
1336
+ input: redactSecretsForStorage(ctx, secretKeys),
1337
+ idempotencyKey
1338
+ });
1339
+ }
1340
+ claimedStepId = stepId;
1341
+ executingSteps.add(stepId);
1342
+ return { existingStep, stepId, deduped: false };
1343
+ };
1344
+ const dedup = await getDbClient().transaction(claimStep).catch((err) => {
1345
+ if (claimedStepId)
1346
+ executingSteps.delete(claimedStepId);
1347
+ throw err;
1348
+ });
1349
+ if ("halted" in dedup)
1350
+ return { outcome: "completed", successors: [] };
1351
+ if ("current" in dedup && dedup.current) {
1352
+ if (dedup.current.status !== "completed")
1353
+ return { outcome: "waiting", successors: [] };
1354
+ ctx[node.id] = dedup.current.output;
1355
+ return { outcome: "completed", successors: [] };
1356
+ }
1357
+ if (dedup.deduped && dedup.existingStep) {
1358
+ if (dedup.existingStep.status === "completed") {
1359
+ ctx[node.id] = dedup.existingStep.output;
1360
+ const successors = getSuccessors(def, node.id);
1361
+ return { outcome: "completed", successors };
1362
+ }
1363
+ return { outcome: "waiting", successors: [] };
1364
+ }
1365
+ try {
1366
+ return await runClaimedStep(def, runId, ctx, node, registry, dedup.existingStep, dedup.stepId, workflowId, options);
1367
+ } catch (err) {
1368
+ if (await failRunOnUnreadableReplay(runId, err, dedup.stepId)) {
1369
+ return { outcome: "failed", successors: [] };
1370
+ }
1371
+ throw err;
1372
+ } finally {
1373
+ executingSteps.delete(dedup.stepId);
1374
+ }
1375
+ }
1376
+ async function runClaimedStep(def, runId, ctx, node, registry, existingStep, stepId, workflowId, options = {}) {
1377
+ const executor = registry.get(node.type);
1378
+ const systemOneRetryProblems = systemOneRetryViolations(node);
1379
+ if (systemOneRetryProblems.length > 0) {
1380
+ await checkpointStepFailure(runId, stepId, systemOneRetryProblems.join("; "), 0);
1381
+ return { outcome: "failed", successors: [] };
1382
+ }
1383
+ const interpolationCtx = buildNodeInterpolationCtx(node, ctx);
1384
+ if (node.inputSchema) {
1385
+ const inputErrors = validateJsonSchema(node.inputSchema, interpolationCtx);
1386
+ if (inputErrors.length > 0) {
1387
+ const errorMsg = `Input schema validation failed: ${inputErrors.join("; ")}`;
1388
+ await checkpointStepFailure(runId, stepId, errorMsg, 0);
1389
+ throw new Error(errorMsg);
1390
+ }
1391
+ }
1392
+ const {
1393
+ value: interpolatedValue,
1394
+ unresolved,
1395
+ scriptBodyUnresolved,
1396
+ strictUnresolved
1397
+ } = interpolateNodeConfig(node, interpolationCtx);
1398
+ const interpolatedConfig = interpolatedValue;
1399
+ const executionCtx = { ...ctx, ...interpolationCtx };
1400
+ if (scriptBodyUnresolved && scriptBodyUnresolved.length > 0) {
1401
+ const errorMsg = scriptBodyInterpolationError(node.id, scriptBodyUnresolved);
1402
+ await checkpointStepFailure(runId, stepId, errorMsg, 0);
1403
+ return { outcome: "failed", successors: [] };
1404
+ }
1405
+ if (strictUnresolved && strictUnresolved.length > 0) {
1406
+ await checkpointStepFailure(runId, stepId, systemOneUnresolvedError(node.id, strictUnresolved), 0);
1407
+ return { outcome: "failed", successors: [] };
1408
+ }
1409
+ if (unresolved.length > 0) {
1410
+ console.warn(`[workflow] Step ${node.id}: unresolved interpolation tokens: ${unresolved.join(", ")}`);
1411
+ await updateWorkflowRunStep(stepId, {
1412
+ diagnostics: JSON.stringify({ unresolvedTokens: unresolved })
1413
+ });
1414
+ }
1415
+ const meta = {
1416
+ runId,
1417
+ stepId,
1418
+ nodeId: node.id,
1419
+ workflowId: workflowId || "",
1420
+ dryRun: false,
1421
+ requestedByUserId: options.requestedByUserId,
1422
+ inputCtx: interpolationCtx
1423
+ };
1424
+ const configuredTimeoutMs = typeof node.config?.timeoutMs === "number" ? node.config.timeoutMs : node.type === "script" && typeof node.config?.timeout === "number" ? node.config.timeout : undefined;
1425
+ const timeoutMs = configuredTimeoutMs ?? DEFAULT_TIMEOUT_MS;
1426
+ let result;
1427
+ try {
1428
+ result = await Promise.race([
1429
+ executor.run({
1430
+ config: interpolatedConfig,
1431
+ context: executionCtx,
1432
+ meta
1433
+ }),
1434
+ timeoutPromise(timeoutMs)
1435
+ ]);
1436
+ } catch (err) {
1437
+ const errorMsg = err instanceof Error ? err.message : String(err);
1438
+ const retryPolicy = node.retry || executor.retryPolicy;
1439
+ const currentRetryCount = existingStep?.retryCount || 0;
1440
+ const { shouldRetry } = await checkpointStepFailure(runId, stepId, errorMsg, currentRetryCount, retryPolicy);
1441
+ if (!shouldRetry) {
1442
+ throw err;
1443
+ }
1444
+ return { outcome: "completed", successors: [] };
1445
+ }
1446
+ if (result.status === "failed") {
1447
+ const retryPolicy = node.retry || executor.retryPolicy;
1448
+ const currentRetryCount = existingStep?.retryCount || 0;
1449
+ const { shouldRetry } = await checkpointStepFailure(runId, stepId, result.error || "Executor returned failed status", currentRetryCount, retryPolicy);
1450
+ if (result.output !== undefined) {
1451
+ await updateWorkflowRunStep(stepId, { output: result.output });
1452
+ }
1453
+ if (!shouldRetry) {
1454
+ throw new Error(result.error || "Step execution failed");
1455
+ }
1456
+ return { outcome: "completed", successors: [] };
1457
+ }
1458
+ if ("async" in result && result.async) {
1459
+ const waiting = await checkpointStepWaiting(runId, stepId, ctx);
1460
+ if (waiting && result.waitFor === "workflow.child.finished") {
1461
+ const { resumeFromChildRun } = await import("./resume-cq2pkp8q.js");
1462
+ await resumeFromChildRun(stepId, registry);
1463
+ }
1464
+ return { outcome: waiting ? "waiting" : "completed", successors: [] };
1465
+ }
1466
+ if (node.outputSchema && result.status === "success") {
1467
+ const outputErrors = validateJsonSchema(node.outputSchema, result.output);
1468
+ if (outputErrors.length > 0) {
1469
+ const errorMsg = `Output schema validation failed: ${outputErrors.join("; ")}`;
1470
+ await checkpointStepFailure(runId, stepId, errorMsg, 0);
1471
+ throw new Error(errorMsg);
1472
+ }
1473
+ }
1474
+ let validationResult;
1475
+ if (node.validation) {
1476
+ validationResult = await runStepValidation(registry, node, result.output, executionCtx, meta);
1477
+ if (validationResult.outcome === "halt") {
1478
+ const errorMsg = "Validation failed (mustPass)";
1479
+ await checkpointStepFailure(runId, stepId, errorMsg, 0, undefined, { markRunFailed: false });
1480
+ return { outcome: "failed", successors: [] };
1481
+ }
1482
+ if (validationResult.outcome === "retry") {
1483
+ if (validationResult.retryContext) {
1484
+ const historyKey = `${node.id}_validations`;
1485
+ const existing = ctx[historyKey] || [];
1486
+ ctx[historyKey] = [...existing, validationResult.retryContext];
1487
+ }
1488
+ const retryPolicy = node.validation.retry || node.retry;
1489
+ const currentRetryCount = existingStep?.retryCount || 0;
1490
+ await checkpointStepFailure(runId, stepId, "Validation failed, retrying", currentRetryCount, retryPolicy);
1491
+ return { outcome: "completed", successors: [] };
1492
+ }
1493
+ }
1494
+ result.nextPort = resolveValidationPort(node.next, result.nextPort, validationResult?.passed);
1495
+ await checkpointStep(runId, stepId, node.id, result, ctx);
1496
+ const successors = result.nextPort ? getSuccessors(def, node.id, result.nextPort) : getSuccessors(def, node.id);
1497
+ return { outcome: "completed", successors };
1498
+ }
1499
+ function findReadyNodes(def, completedNodeIds, activeEdges) {
1500
+ const predecessors = new Map;
1501
+ for (const node of def.nodes) {
1502
+ if (!predecessors.has(node.id)) {
1503
+ predecessors.set(node.id, new Set);
1504
+ }
1505
+ }
1506
+ for (const node of def.nodes) {
1507
+ if (!node.next)
1508
+ continue;
1509
+ for (const target of getNextTargets(node.next)) {
1510
+ if (!predecessors.has(target)) {
1511
+ predecessors.set(target, new Set);
1512
+ }
1513
+ predecessors.get(target).add(node.id);
1514
+ }
1515
+ }
1516
+ return def.nodes.filter((node) => {
1517
+ if (completedNodeIds.has(node.id))
1518
+ return false;
1519
+ const preds = predecessors.get(node.id);
1520
+ if (!preds || preds.size === 0)
1521
+ return true;
1522
+ if (activeEdges) {
1523
+ const activePreds = [...preds].filter((predId) => activeEdges.has(`${predId}→${node.id}`));
1524
+ if (activePreds.length === 0)
1525
+ return false;
1526
+ return activePreds.every((pred) => completedNodeIds.has(pred));
1527
+ }
1528
+ for (const pred of preds) {
1529
+ if (!completedNodeIds.has(pred))
1530
+ return false;
1531
+ }
1532
+ return true;
1533
+ });
1534
+ }
1535
+ function buildNodeInterpolationCtx(node, ctx) {
1536
+ const interpolationCtx = {};
1537
+ if (ctx.trigger !== undefined)
1538
+ interpolationCtx.trigger = ctx.trigger;
1539
+ if (ctx.input !== undefined)
1540
+ interpolationCtx.input = ctx.input;
1541
+ if (ctx.workflow !== undefined)
1542
+ interpolationCtx.workflow = ctx.workflow;
1543
+ if (ctx.swarm !== undefined)
1544
+ interpolationCtx.swarm = ctx.swarm;
1545
+ if (ctx.run !== undefined)
1546
+ interpolationCtx.run = ctx.run;
1547
+ if (!node.inputs)
1548
+ return interpolationCtx;
1549
+ for (const [localName, sourcePath] of Object.entries(node.inputs)) {
1550
+ const keys = sourcePath.split(".");
1551
+ let value = ctx;
1552
+ for (const key of keys) {
1553
+ if (value == null || typeof value !== "object") {
1554
+ value = undefined;
1555
+ break;
1556
+ }
1557
+ value = value[key];
1558
+ }
1559
+ interpolationCtx[localName] = value;
1560
+ }
1561
+ return interpolationCtx;
1562
+ }
1563
+ var SCRIPT_BODY_ALLOWED_SOURCES = new Set(["input", "workflow", "swarm", "run"]);
1564
+ function buildScriptBodyCtx(node, interpolationCtx) {
1565
+ const aliases = node.inputs ?? {};
1566
+ const safe = {};
1567
+ for (const [key, value] of Object.entries(interpolationCtx)) {
1568
+ const sourcePath = aliases[key];
1569
+ const root = sourcePath === undefined ? key : sourcePath.split(".")[0] ?? "";
1570
+ if (SCRIPT_BODY_ALLOWED_SOURCES.has(root))
1571
+ safe[key] = value;
1572
+ }
1573
+ return safe;
1574
+ }
1575
+ function interpolateNodeConfig(node, interpolationCtx) {
1576
+ if (node.type === SYSTEM_ONE_DECISION_NODE_TYPE) {
1577
+ const { state, questions, ...rest } = node.config;
1578
+ const restResult = deepInterpolate(rest, interpolationCtx);
1579
+ const dynamic = {};
1580
+ if (Object.hasOwn(node.config, "state"))
1581
+ dynamic.state = state;
1582
+ if (Object.hasOwn(node.config, "questions"))
1583
+ dynamic.questions = questions;
1584
+ const dynamicResult = deepInterpolate(dynamic, interpolationCtx, { preserveRawTokens: true });
1585
+ const unresolved = [...restResult.unresolved, ...dynamicResult.unresolved];
1586
+ return {
1587
+ value: {
1588
+ ...restResult.value,
1589
+ ...dynamicResult.value
1590
+ },
1591
+ unresolved,
1592
+ strictUnresolved: unresolved
1593
+ };
1594
+ }
1595
+ if (node.type === "foreach" && Object.hasOwn(node.config, "over")) {
1596
+ const { over, body, ...configWithoutOverAndBody } = node.config;
1597
+ const configResult2 = deepInterpolate(configWithoutOverAndBody, interpolationCtx);
1598
+ const overResult = deepInterpolate(over, interpolationCtx, { preserveRawTokens: true });
1599
+ return {
1600
+ value: {
1601
+ ...configResult2.value,
1602
+ over: overResult.value,
1603
+ body
1604
+ },
1605
+ unresolved: [...configResult2.unresolved, ...overResult.unresolved]
1606
+ };
1607
+ }
1608
+ if (node.type === "human-in-the-loop" && typeof node.config.questions === "string") {
1609
+ const { questions, ...configWithoutQuestions } = node.config;
1610
+ const configResult2 = deepInterpolate(configWithoutQuestions, interpolationCtx);
1611
+ const questionsResult = deepInterpolate(questions, interpolationCtx, {
1612
+ preserveRawTokens: true
1613
+ });
1614
+ return {
1615
+ value: {
1616
+ ...configResult2.value,
1617
+ questions: questionsResult.value
1618
+ },
1619
+ unresolved: [...configResult2.unresolved, ...questionsResult.unresolved]
1620
+ };
1621
+ }
1622
+ if (node.type === "script" && typeof node.config.script === "string") {
1623
+ const { script, ...configWithoutScript } = node.config;
1624
+ const restResult = deepInterpolate(configWithoutScript, interpolationCtx);
1625
+ const scriptResult = deepInterpolate(script, buildScriptBodyCtx(node, interpolationCtx));
1626
+ return {
1627
+ value: {
1628
+ ...restResult.value,
1629
+ script: scriptResult.unresolved.length > 0 ? script : scriptResult.value
1630
+ },
1631
+ unresolved: [...restResult.unresolved, ...scriptResult.unresolved],
1632
+ scriptBodyUnresolved: scriptResult.unresolved
1633
+ };
1634
+ }
1635
+ if (node.type !== "swarm-script" || !Object.hasOwn(node.config, "args")) {
1636
+ return deepInterpolate(node.config, interpolationCtx);
1637
+ }
1638
+ const { args, ...configWithoutArgs } = node.config;
1639
+ const configResult = deepInterpolate(configWithoutArgs, interpolationCtx);
1640
+ const argsResult = deepInterpolate(args, interpolationCtx, { preserveRawTokens: true });
1641
+ return {
1642
+ value: {
1643
+ ...configResult.value,
1644
+ args: argsResult.value
1645
+ },
1646
+ unresolved: [...configResult.unresolved, ...argsResult.unresolved]
1647
+ };
1648
+ }
1649
+ function scriptBodyInterpolationError(nodeId, tokens) {
1650
+ const renderedTokens = [...new Set(tokens)].map((token) => `{{${token}}}`).join(", ");
1651
+ return `Script body interpolation failed for node "${nodeId}": unresolved or disallowed token(s): ${renderedTokens}. Executable source may interpolate only input, workflow, swarm, or run values. Pass dynamic trigger or upstream values through config.args and read them from argv.`;
1652
+ }
1653
+ function timeoutPromise(ms) {
1654
+ return new Promise((_, reject) => {
1655
+ setTimeout(() => reject(new Error(`Step timed out after ${ms}ms`)), ms);
1656
+ });
1657
+ }
1658
+
1659
+ // src/workflows/resume.ts
1660
+ init_event_bus();
1661
+
1662
+ // src/workflows/executors/sub-workflow.ts
1663
+ init_zod();
1664
+ init_workflow_runs();
1665
+ var SubWorkflowConfigSchema = exports_external.object({
1666
+ workflowId: exports_external.string().min(1).describe("Workflow to run as a child"),
1667
+ inputs: exports_external.record(exports_external.string(), exports_external.unknown()).optional().describe("Trigger data for the child run, validated against its triggerSchema")
1668
+ });
1669
+ var SubWorkflowOutputSchema = exports_external.object({
1670
+ runId: exports_external.string(),
1671
+ outputs: exports_external.record(exports_external.string(), exports_external.unknown()),
1672
+ error: exports_external.string().optional()
1673
+ });
1674
+ var MAX_SUB_WORKFLOW_DEPTH = 16;
1675
+ var NON_NODE_CONTEXT_KEYS = new Set(["trigger", "input", "swarm", "workflow"]);
1676
+ function childRunOutcome(child) {
1677
+ if (child.status === "running" || child.status === "waiting")
1678
+ return null;
1679
+ if (child.status !== "completed") {
1680
+ const reason = child.error ? `: ${child.error}` : "";
1681
+ return { error: `Child workflow run ${child.id} ${child.status}${reason}` };
1682
+ }
1683
+ const outputs = {};
1684
+ for (const [key, value] of Object.entries(child.context ?? {})) {
1685
+ if (!NON_NODE_CONTEXT_KEYS.has(key))
1686
+ outputs[key] = value;
1687
+ }
1688
+ return { output: { runId: child.id, outputs, error: child.error } };
1689
+ }
1690
+
1691
+ class SubWorkflowExecutor extends BaseExecutor {
1692
+ registry;
1693
+ type = "sub-workflow";
1694
+ mode = "async";
1695
+ configSchema = SubWorkflowConfigSchema;
1696
+ outputSchema = SubWorkflowOutputSchema;
1697
+ constructor(deps, registry) {
1698
+ super(deps);
1699
+ this.registry = registry;
1700
+ }
1701
+ async execute(config, _context, meta) {
1702
+ const { db } = this.deps;
1703
+ const existingId = await getChildWorkflowRunId(meta.stepId);
1704
+ const existing = existingId ? await db.getWorkflowRun(existingId) : null;
1705
+ if (existing)
1706
+ return this.settle(existing);
1707
+ const lineage = await getWorkflowRunLineage(meta.runId, MAX_SUB_WORKFLOW_DEPTH);
1708
+ if (lineage.length > MAX_SUB_WORKFLOW_DEPTH) {
1709
+ return {
1710
+ status: "failed",
1711
+ error: `Sub-workflow nesting exceeds ${MAX_SUB_WORKFLOW_DEPTH} levels`
1712
+ };
1713
+ }
1714
+ if (config.workflowId === meta.workflowId || lineage.includes(config.workflowId)) {
1715
+ return {
1716
+ status: "failed",
1717
+ error: `Sub-workflow recursion: workflow ${config.workflowId} is already running in this run's ancestry`
1718
+ };
1719
+ }
1720
+ const workflow = await db.getWorkflow(config.workflowId);
1721
+ if (!workflow)
1722
+ return { status: "failed", error: `Workflow ${config.workflowId} not found` };
1723
+ if (!workflow.enabled) {
1724
+ return { status: "failed", error: `Workflow ${config.workflowId} is disabled` };
1725
+ }
1726
+ const childRunId = await startWorkflowExecution(workflow, config.inputs ?? {}, this.registry, {
1727
+ requestedByUserId: meta.requestedByUserId,
1728
+ parentStepId: meta.stepId
1729
+ });
1730
+ const child = await db.getWorkflowRun(childRunId);
1731
+ if (!child)
1732
+ return { status: "failed", error: `Child workflow run ${childRunId} not found` };
1733
+ return this.settle(child);
1734
+ }
1735
+ settle(child) {
1736
+ const outcome = childRunOutcome(child);
1737
+ if (!outcome) {
1738
+ return {
1739
+ status: "success",
1740
+ async: true,
1741
+ waitFor: "workflow.child.finished",
1742
+ correlationId: child.id
1743
+ };
1744
+ }
1745
+ if ("error" in outcome)
1746
+ return { status: "failed", error: outcome.error };
1747
+ return { status: "success", output: outcome.output, nextPort: "success" };
1748
+ }
1749
+ }
1750
+
1751
+ // src/workflows/executors/wait.ts
1752
+ init_zod();
1753
+
1754
+ // src/workflows/wait-filter.ts
1755
+ var PARAM_SHADOW_KEYS = [
1756
+ "require",
1757
+ "process",
1758
+ "Bun",
1759
+ "globalThis",
1760
+ "global",
1761
+ "fetch",
1762
+ "setTimeout",
1763
+ "setInterval"
1764
+ ];
1765
+ var PARAM_SHADOW_VALUES = PARAM_SHADOW_KEYS.map(() => {
1766
+ return;
1767
+ });
1768
+ var BODY_SHADOW_KEYS = ["eval", "Function", "AsyncFunction"];
1769
+ var BODY_SHADOW_PREAMBLE = BODY_SHADOW_KEYS.map((k) => `var ${k} = undefined;`).join(" ");
1770
+ var FILTER_TIMEOUT_MS = 50;
1771
+ function getByDotPath(obj, path) {
1772
+ if (obj === null || typeof obj !== "object") {
1773
+ return { found: false, value: undefined };
1774
+ }
1775
+ const segments = path.split(".");
1776
+ let cursor = obj;
1777
+ for (const seg of segments) {
1778
+ if (cursor === null || typeof cursor !== "object") {
1779
+ return { found: false, value: undefined };
1780
+ }
1781
+ const rec = cursor;
1782
+ if (!(seg in rec)) {
1783
+ return { found: false, value: undefined };
1784
+ }
1785
+ cursor = rec[seg];
1786
+ }
1787
+ return { found: true, value: cursor };
1788
+ }
1789
+ function deepEqual(a, b) {
1790
+ if (a === b)
1791
+ return true;
1792
+ if (typeof a !== typeof b)
1793
+ return false;
1794
+ if (a === null || b === null)
1795
+ return false;
1796
+ if (Array.isArray(a)) {
1797
+ if (!Array.isArray(b))
1798
+ return false;
1799
+ if (a.length !== b.length)
1800
+ return false;
1801
+ for (let i = 0;i < a.length; i++) {
1802
+ if (!deepEqual(a[i], b[i]))
1803
+ return false;
1804
+ }
1805
+ return true;
1806
+ }
1807
+ if (typeof a === "object" && typeof b === "object") {
1808
+ const aKeys = Object.keys(a);
1809
+ const bKeys = Object.keys(b);
1810
+ if (aKeys.length !== bKeys.length)
1811
+ return false;
1812
+ for (const k of aKeys) {
1813
+ if (!deepEqual(a[k], b[k])) {
1814
+ return false;
1815
+ }
1816
+ }
1817
+ return true;
1818
+ }
1819
+ return false;
1820
+ }
1821
+ function matchObjectFilter(payload, filter) {
1822
+ for (const [key, expected] of Object.entries(filter)) {
1823
+ const { found, value } = getByDotPath(payload, key);
1824
+ if (!found)
1825
+ return false;
1826
+ if (!deepEqual(value, expected))
1827
+ return false;
1828
+ }
1829
+ return true;
1830
+ }
1831
+ async function runWithTimeout(fn) {
1832
+ return new Promise((resolve) => {
1833
+ let settled = false;
1834
+ const timer = setTimeout(() => {
1835
+ if (settled)
1836
+ return;
1837
+ settled = true;
1838
+ resolve(null);
1839
+ }, FILTER_TIMEOUT_MS);
1840
+ queueMicrotask(() => {
1841
+ if (settled)
1842
+ return;
1843
+ try {
1844
+ const v = fn();
1845
+ const then = v !== null && typeof v === "object" ? v.then : undefined;
1846
+ if (typeof then === "function") {
1847
+ then.call(v, undefined, () => {});
1848
+ settled = true;
1849
+ clearTimeout(timer);
1850
+ resolve({ __asyncRejected: true });
1851
+ return;
1852
+ }
1853
+ if (settled)
1854
+ return;
1855
+ settled = true;
1856
+ clearTimeout(timer);
1857
+ resolve(v);
1858
+ } catch {
1859
+ if (settled)
1860
+ return;
1861
+ settled = true;
1862
+ clearTimeout(timer);
1863
+ resolve(null);
1864
+ }
1865
+ });
1866
+ });
1867
+ }
1868
+ var ASYNC_SENTINEL = "__asyncRejected";
1869
+ function isAsyncSentinel(value) {
1870
+ return value !== null && typeof value === "object" && value[ASYNC_SENTINEL] === true;
1871
+ }
1872
+ function compileStringFilter(filter) {
1873
+ if (filter.length > 2048) {
1874
+ throw new Error(`wait filter source exceeds 2KB cap (${filter.length} bytes)`);
1875
+ }
1876
+ let fn;
1877
+ try {
1878
+ fn = new Function(...PARAM_SHADOW_KEYS, "payload", `${BODY_SHADOW_PREAMBLE} return (${filter})(payload);`);
1879
+ } catch (err) {
1880
+ const msg = err instanceof Error ? err.message : String(err);
1881
+ throw new Error(`wait filter compile error: ${msg}`);
1882
+ }
1883
+ return (payload) => fn(...PARAM_SHADOW_VALUES, payload);
1884
+ }
1885
+ function nullifyPrototypes(value) {
1886
+ if (value === null || typeof value !== "object")
1887
+ return value;
1888
+ if (Array.isArray(value)) {
1889
+ return value.map(nullifyPrototypes);
1890
+ }
1891
+ const out = Object.create(null);
1892
+ for (const [k, v] of Object.entries(value)) {
1893
+ out[k] = nullifyPrototypes(v);
1894
+ }
1895
+ return out;
1896
+ }
1897
+ async function matchesFilter(payload, filter) {
1898
+ if (filter === undefined || filter === null)
1899
+ return true;
1900
+ if (typeof filter === "object" && !Array.isArray(filter)) {
1901
+ return matchObjectFilter(payload, filter);
1902
+ }
1903
+ if (typeof filter === "string") {
1904
+ let userFn;
1905
+ try {
1906
+ userFn = compileStringFilter(filter);
1907
+ } catch {
1908
+ return false;
1909
+ }
1910
+ let cloned;
1911
+ try {
1912
+ const cloneOnce = structuredClone(payload);
1913
+ cloned = nullifyPrototypes(cloneOnce);
1914
+ } catch {
1915
+ try {
1916
+ cloned = nullifyPrototypes(payload);
1917
+ } catch {
1918
+ cloned = payload;
1919
+ }
1920
+ }
1921
+ const result = await runWithTimeout(() => userFn(cloned));
1922
+ if (result === null)
1923
+ return false;
1924
+ if (isAsyncSentinel(result))
1925
+ return false;
1926
+ return !!result;
1927
+ }
1928
+ return false;
1929
+ }
1930
+
1931
+ // src/workflows/executors/wait.ts
1932
+ var WaitConfigSchema = exports_external.discriminatedUnion("mode", [
1933
+ exports_external.object({
1934
+ mode: exports_external.literal("time"),
1935
+ durationMs: exports_external.number().int().min(1).max(31536000000).describe("Wait duration in milliseconds (effective resolution ~5s)")
1936
+ }),
1937
+ exports_external.object({
1938
+ mode: exports_external.literal("event"),
1939
+ eventName: exports_external.string().min(1),
1940
+ filter: exports_external.union([exports_external.record(exports_external.string(), exports_external.unknown()), exports_external.string().max(2048)]).optional(),
1941
+ scope: exports_external.enum(["run", "global"]).default("run"),
1942
+ timeoutMs: exports_external.number().int().min(1).max(31536000000).optional().describe("Timeout in milliseconds (effective resolution ~5s) — when reached, routes via 'timeout' port")
1943
+ })
1944
+ ]);
1945
+ var WaitOutputSchema = exports_external.object({
1946
+ waitId: exports_external.string().uuid(),
1947
+ mode: exports_external.enum(["time", "event"]),
1948
+ firedAt: exports_external.string().nullable(),
1949
+ payload: exports_external.unknown().optional()
1950
+ });
1951
+
1952
+ class WaitExecutor extends BaseExecutor {
1953
+ type = "wait";
1954
+ mode = "async";
1955
+ configSchema = WaitConfigSchema;
1956
+ outputSchema = WaitOutputSchema;
1957
+ async execute(config, _context, meta) {
1958
+ const { db } = this.deps;
1959
+ const existing = await db.getWaitStateByStepId(meta.stepId);
1960
+ if (existing) {
1961
+ if (existing.status !== "pending") {
1962
+ const nextPort = computeNextPort(existing.mode, existing.status);
1963
+ return {
1964
+ status: "success",
1965
+ output: {
1966
+ waitId: existing.id,
1967
+ mode: existing.mode,
1968
+ firedAt: existing.resolvedAt,
1969
+ payload: existing.firedPayload ?? undefined
1970
+ },
1971
+ nextPort
1972
+ };
1973
+ }
1974
+ return {
1975
+ status: "success",
1976
+ async: true,
1977
+ waitFor: "wait.fired",
1978
+ correlationId: existing.id
1979
+ };
1980
+ }
1981
+ if (config.mode === "time") {
1982
+ const waitId2 = crypto.randomUUID();
1983
+ const wakeUpAt = new Date(Date.now() + config.durationMs).toISOString();
1984
+ await db.createWaitState({
1985
+ id: waitId2,
1986
+ workflowRunId: meta.runId,
1987
+ workflowRunStepId: meta.stepId,
1988
+ mode: "time",
1989
+ wakeUpAt
1990
+ });
1991
+ return {
1992
+ status: "success",
1993
+ async: true,
1994
+ waitFor: "wait.fired",
1995
+ correlationId: waitId2
1996
+ };
1997
+ }
1998
+ if (typeof config.filter === "string") {
1999
+ compileStringFilter(config.filter);
2000
+ }
2001
+ const waitId = crypto.randomUUID();
2002
+ const expiresAt = config.timeoutMs ? new Date(Date.now() + config.timeoutMs).toISOString() : null;
2003
+ await db.createWaitState({
2004
+ id: waitId,
2005
+ workflowRunId: meta.runId,
2006
+ workflowRunStepId: meta.stepId,
2007
+ mode: "event",
2008
+ eventName: config.eventName,
2009
+ eventFilter: config.filter ?? null,
2010
+ expiresAt,
2011
+ scope: config.scope
2012
+ });
2013
+ subscribeWaitToBus(waitId, config.eventName);
2014
+ return {
2015
+ status: "success",
2016
+ async: true,
2017
+ waitFor: "wait.fired",
2018
+ correlationId: waitId
2019
+ };
2020
+ }
2021
+ }
2022
+ function computeNextPort(mode, status) {
2023
+ if (mode === "time")
2024
+ return "default";
2025
+ return status === "timeout" ? "timeout" : "event";
2026
+ }
2027
+
2028
+ // src/workflows/task-step-routing.ts
2029
+ init_db();
2030
+ init_types();
2031
+ async function isTaskBoundToStep(taskId, stepId) {
2032
+ const task = await getTaskById(taskId);
2033
+ return task?.workflowRunStepId === stepId;
2034
+ }
2035
+ async function failStepAndRunIfWaiting(stepId, runId, reason, ownerTaskId) {
2036
+ const now = new Date().toISOString();
2037
+ return await getDbClient().transaction(async () => {
2038
+ const current = await getWorkflowRunStep(stepId);
2039
+ if (!current || current.status !== "waiting")
2040
+ return false;
2041
+ if (ownerTaskId && !await isTaskBoundToStep(ownerTaskId, stepId))
2042
+ return false;
2043
+ await updateWorkflowRunStep(stepId, {
2044
+ status: "failed",
2045
+ error: reason,
2046
+ finishedAt: now
2047
+ });
2048
+ await updateWorkflowRun(runId, {
2049
+ status: "failed",
2050
+ error: reason,
2051
+ finishedAt: now
2052
+ });
2053
+ return true;
2054
+ });
2055
+ }
2056
+ async function checkpointPortStepAndResolveSuccessors(def, runId, stepId, nodeId, output, nextPort, ctx) {
2057
+ return await getDbClient().transaction(async () => {
2058
+ const current = await getWorkflowRunStep(stepId);
2059
+ if (!current || current.status !== "waiting")
2060
+ return { claimed: false, successors: [] };
2061
+ await checkpointStep(runId, stepId, nodeId, { output, nextPort }, ctx);
2062
+ await updateWorkflowRun(runId, { status: "running" });
2063
+ return { claimed: true, successors: getSuccessors(def, nodeId, nextPort) };
2064
+ });
2065
+ }
2066
+ async function scheduleTaskStepRetry(def, runId, step, taskId, reason) {
2067
+ const node = def.nodes.find((n) => n.id === step.nodeId);
2068
+ if (!node || node.type !== "agent-task" || !node.retry)
2069
+ return "not-eligible";
2070
+ const parsed = RetryPolicySchema.safeParse(node.retry);
2071
+ if (!parsed.success)
2072
+ return "not-eligible";
2073
+ const policy = parsed.data;
2074
+ return await getDbClient().transaction(async () => {
2075
+ const current = await getWorkflowRunStep(step.id);
2076
+ if (!current || current.status !== "waiting")
2077
+ return "not-claimed";
2078
+ if (!await isTaskBoundToStep(taskId, step.id))
2079
+ return "not-claimed";
2080
+ if (current.retryCount >= policy.maxRetries)
2081
+ return "not-eligible";
2082
+ await detachTaskFromWorkflowRunStep(taskId);
2083
+ await checkpointStepFailure(runId, step.id, reason, current.retryCount, policy);
2084
+ return "scheduled";
2085
+ });
2086
+ }
2087
+ var UNCLAIMED = {
2088
+ claimed: false,
2089
+ foreachChild: false,
2090
+ joined: false,
2091
+ successors: []
2092
+ };
2093
+ async function completeTaskStepAndResolveSuccessors(def, runId, step, output, ctx, failureReason, ownerTaskId) {
2094
+ return await getDbClient().transaction(async () => {
2095
+ const current = await getWorkflowRunStep(step.id);
2096
+ if (!current || current.status !== "waiting")
2097
+ return UNCLAIMED;
2098
+ if (ownerTaskId && !await isTaskBoundToStep(ownerTaskId, step.id))
2099
+ return UNCLAIMED;
2100
+ const foreachParent = resolveForeachParent(def, step.nodeId);
2101
+ if (foreachParent) {
2102
+ await updateWorkflowRunStep(step.id, {
2103
+ status: "completed",
2104
+ output,
2105
+ ...failureReason !== undefined ? { error: failureReason } : {},
2106
+ finishedAt: new Date().toISOString()
2107
+ });
2108
+ const join = await joinForeach(def, runId, step, ctx);
2109
+ await updateWorkflowRun(runId, { status: "running" });
2110
+ return {
2111
+ claimed: true,
2112
+ foreachChild: true,
2113
+ joined: join.joined,
2114
+ successors: join.successors
2115
+ };
2116
+ }
2117
+ await checkpointStep(runId, step.id, step.nodeId, { output }, ctx);
2118
+ await updateWorkflowRun(runId, { status: "running" });
2119
+ return {
2120
+ claimed: true,
2121
+ foreachChild: false,
2122
+ joined: true,
2123
+ successors: getSuccessors(def, step.nodeId)
2124
+ };
2125
+ });
2126
+ }
2127
+
2128
+ // src/workflows/resume.ts
2129
+ function setupWorkflowResumeListener(eventBus, registry) {
2130
+ const onTaskCompleted = async (data) => {
2131
+ try {
2132
+ const event = data;
2133
+ if (!event.workflowRunId || !event.workflowRunStepId)
2134
+ return;
2135
+ await resumeFromTaskCompletion(event, registry);
2136
+ } catch (err) {
2137
+ console.error("[workflows] Resume from task completion failed:", err);
2138
+ }
2139
+ };
2140
+ eventBus.on("task.completed", onTaskCompleted);
2141
+ const onTaskFailed = async (data) => {
2142
+ try {
2143
+ const event = data;
2144
+ if (!event.workflowRunId || !event.workflowRunStepId)
2145
+ return;
2146
+ await handleTaskFailure(event, event.failureReason ?? "Task failed", registry, {
2147
+ retryable: true
2148
+ });
2149
+ } catch (err) {
2150
+ console.error("[workflows] Handle task failure error:", err);
2151
+ }
2152
+ };
2153
+ eventBus.on("task.failed", onTaskFailed);
2154
+ const onTaskCancelled = async (data) => {
2155
+ try {
2156
+ const event = data;
2157
+ if (!event.workflowRunId || !event.workflowRunStepId)
2158
+ return;
2159
+ await handleTaskFailure(event, "Task was cancelled", registry, { retryable: false });
2160
+ } catch (err) {
2161
+ console.error("[workflows] Handle task cancellation error:", err);
2162
+ }
2163
+ };
2164
+ eventBus.on("task.cancelled", onTaskCancelled);
2165
+ const onApprovalResolved = async (data) => {
2166
+ try {
2167
+ const event = data;
2168
+ if (!event.workflowRunId || !event.workflowRunStepId)
2169
+ return;
2170
+ await resumeFromApprovalResolution(event, registry);
2171
+ } catch (err) {
2172
+ console.error("[workflows] Resume from approval resolution failed:", err);
2173
+ }
2174
+ };
2175
+ eventBus.on("approval.resolved", onApprovalResolved);
2176
+ const onChildRunFinished = async (data) => {
2177
+ try {
2178
+ const { parentStepId } = data;
2179
+ if (!parentStepId)
2180
+ return;
2181
+ await resumeFromChildRun(parentStepId, registry);
2182
+ } catch (err) {
2183
+ console.error("[workflows] Resume from child workflow run failed:", err);
2184
+ }
2185
+ };
2186
+ eventBus.on("workflow.child.finished", onChildRunFinished);
2187
+ return () => {
2188
+ eventBus.off("task.completed", onTaskCompleted);
2189
+ eventBus.off("task.failed", onTaskFailed);
2190
+ eventBus.off("task.cancelled", onTaskCancelled);
2191
+ eventBus.off("approval.resolved", onApprovalResolved);
2192
+ eventBus.off("workflow.child.finished", onChildRunFinished);
2193
+ };
2194
+ }
2195
+ async function failClosedOnUnreadableReplay(runId, stepId, resume) {
2196
+ try {
2197
+ await resume();
2198
+ } catch (err) {
2199
+ if (!await failRunOnUnreadableReplay(runId, err, stepId))
2200
+ throw err;
2201
+ }
2202
+ }
2203
+ async function resumeFromTaskCompletion(event, registry) {
2204
+ await failClosedOnUnreadableReplay(event.workflowRunId, event.workflowRunStepId, () => resumeFromTaskCompletionUnguarded(event, registry));
2205
+ }
2206
+ async function resumeFromTaskCompletionUnguarded(event, registry) {
2207
+ const run = await getWorkflowRun(event.workflowRunId);
2208
+ if (!run || run.status !== "waiting" && run.status !== "running")
2209
+ return;
2210
+ const step = await getWorkflowRunStep(event.workflowRunStepId);
2211
+ if (!step || step.status !== "waiting")
2212
+ return;
2213
+ if (await isStaleTaskEvent(step.id, event))
2214
+ return;
2215
+ const workflow = await getWorkflow(run.workflowId);
2216
+ if (!workflow)
2217
+ return;
2218
+ const ctx = run.context ?? {};
2219
+ let taskOutput = event.output;
2220
+ if (event.output) {
2221
+ try {
2222
+ const parsed = JSON.parse(event.output);
2223
+ if (typeof parsed === "object" && parsed !== null) {
2224
+ taskOutput = parsed;
2225
+ }
2226
+ } catch {}
2227
+ }
2228
+ const stepOutput = { taskId: event.taskId, taskOutput };
2229
+ const routing = await completeTaskStepAndResolveSuccessors(workflow.definition, run.id, step, stepOutput, ctx);
2230
+ if (!routing.claimed)
2231
+ return;
2232
+ const successors = routing.successors;
2233
+ if (successors.length > 0) {
2234
+ const secretKeys = getSecretInputKeys(workflow.input);
2235
+ await walkGraph(workflow.definition, run.id, ctx, successors, registry, workflow.id, secretKeys);
2236
+ } else {
2237
+ await finalizeOrWait(run.id);
2238
+ }
2239
+ }
2240
+ async function finalizeOrWait(runId) {
2241
+ await getDbClient().transaction(async () => {
2242
+ const steps = await getWorkflowRunStepsByRunId(runId);
2243
+ if (hasRunningStep(steps)) {
2244
+ const run = await getWorkflowRun(runId);
2245
+ if (run?.status === "waiting")
2246
+ await updateWorkflowRun(runId, { status: "running" });
2247
+ return;
2248
+ }
2249
+ const hasWaiting = steps.some((s) => s.status === "waiting" || s.status === "failed" && s.nextRetryAt != null);
2250
+ if (hasWaiting) {
2251
+ await updateWorkflowRun(runId, { status: "waiting" });
2252
+ } else {
2253
+ await updateWorkflowRun(runId, {
2254
+ status: "completed",
2255
+ finishedAt: new Date().toISOString()
2256
+ });
2257
+ }
2258
+ });
2259
+ }
2260
+ async function handleTaskFailure(event, reason, registry, options) {
2261
+ await failClosedOnUnreadableReplay(event.workflowRunId, event.workflowRunStepId, () => handleTaskFailureUnguarded(event, reason, registry, options));
2262
+ }
2263
+ async function handleTaskFailureUnguarded(event, reason, registry, options) {
2264
+ const run = await getWorkflowRun(event.workflowRunId);
2265
+ if (!run || run.status !== "waiting" && run.status !== "running")
2266
+ return;
2267
+ const step = await getWorkflowRunStep(event.workflowRunStepId);
2268
+ if (!step || step.status !== "waiting")
2269
+ return;
2270
+ if (await isStaleTaskEvent(step.id, event))
2271
+ return;
2272
+ const workflow = await getWorkflow(run.workflowId);
2273
+ if (!workflow)
2274
+ return;
2275
+ if (options.retryable) {
2276
+ const retry = await scheduleTaskStepRetry(workflow.definition, run.id, step, event.taskId, reason);
2277
+ if (retry === "scheduled") {
2278
+ console.log(`[workflows] Task ${event.taskId} failed; step ${step.nodeId} of run ${run.id} queued for retry ${step.retryCount + 1}`);
2279
+ return;
2280
+ }
2281
+ if (retry === "not-claimed")
2282
+ return;
2283
+ }
2284
+ const onFailure = workflow.definition.onNodeFailure ?? "fail";
2285
+ if (onFailure === "fail") {
2286
+ await markRunFailed(event, reason);
2287
+ return;
2288
+ }
2289
+ const ctx = run.context ?? {};
2290
+ const stepOutput = {
2291
+ taskId: event.taskId,
2292
+ taskOutput: `${FAILED_TASK_OUTPUT_PREFIX} ${reason}] This node failed or was cancelled.`
2293
+ };
2294
+ const routing = await completeTaskStepAndResolveSuccessors(workflow.definition, run.id, step, stepOutput, ctx, reason);
2295
+ if (!routing.claimed)
2296
+ return;
2297
+ const successors = routing.successors;
2298
+ if (successors.length > 0) {
2299
+ const secretKeys = getSecretInputKeys(workflow.input);
2300
+ await walkGraph(workflow.definition, run.id, ctx, successors, registry, workflow.id, secretKeys);
2301
+ } else {
2302
+ await finalizeOrWait(run.id);
2303
+ }
2304
+ }
2305
+ async function isStaleTaskEvent(stepId, event) {
2306
+ if (!event.taskId)
2307
+ return false;
2308
+ const boundTask = await getTaskByWorkflowRunStepId(stepId);
2309
+ return boundTask != null && boundTask.id !== event.taskId;
2310
+ }
2311
+ async function markRunFailed(event, reason) {
2312
+ await failStepAndRunIfWaiting(event.workflowRunStepId, event.workflowRunId, reason);
2313
+ }
2314
+ async function retryFailedRun(runId, registry) {
2315
+ const run = await getWorkflowRun(runId);
2316
+ if (!run || run.status !== "failed")
2317
+ throw new Error("Run is not in failed state");
2318
+ const workflow = await getWorkflow(run.workflowId);
2319
+ if (!workflow)
2320
+ throw new Error("Workflow not found");
2321
+ const steps = await getWorkflowRunStepsByRunId(runId);
2322
+ const failedStep = steps.find((s) => s.status === "failed");
2323
+ if (!failedStep)
2324
+ throw new Error("No failed step found");
2325
+ const completedNodeIds = new Set(await getCompletedStepNodeIds(runId));
2326
+ const notReady = await findWorkflowReadinessProblems({ nodes: workflow.definition.nodes.filter((node) => !completedNodeIds.has(node.id)) }, registry);
2327
+ if (notReady.length > 0) {
2328
+ throw new Error(`Retry not started, run left failed: ${formatReadinessProblems(notReady)}`);
2329
+ }
2330
+ const { activeEdges } = await loadCompletedStepRouting(workflow.definition, runId, completedNodeIds);
2331
+ const foreachParent = resolveForeachParent(workflow.definition, failedStep.nodeId);
2332
+ const failedNode = foreachParent ?? workflow.definition.nodes.find((n) => n.id === failedStep.nodeId);
2333
+ if (!failedNode)
2334
+ throw new Error(`Node ${failedStep.nodeId} not found in workflow definition`);
2335
+ const hasStructuralPredecessor = workflow.definition.nodes.some((node) => node.next && getNextTargets(node.next).includes(failedNode.id));
2336
+ const hasActivePredecessor = [...activeEdges].some((edge) => edge.endsWith(`→${failedNode.id}`));
2337
+ const shouldRetryFailedNode = foreachParent != null || !hasStructuralPredecessor || hasActivePredecessor;
2338
+ const ctx = run.context ?? {};
2339
+ const claimed = await getDbClient().transaction(async () => {
2340
+ const current = await getWorkflowRun(runId);
2341
+ if (!current || current.status !== "failed")
2342
+ return false;
2343
+ await updateWorkflowRunStep(failedStep.id, {
2344
+ status: shouldRetryFailedNode ? "pending" : "cancelled",
2345
+ error: shouldRetryFailedNode ? null : "Skipped on retry because its branch was not active"
2346
+ });
2347
+ await updateWorkflowRun(runId, { status: "running", error: null, context: ctx });
2348
+ return true;
2349
+ });
2350
+ if (!claimed)
2351
+ throw new Error("Run is not in failed state");
2352
+ const liveNodeIds = new Set(steps.filter((s) => s.status === "running" || s.status === "waiting").map((s) => s.nodeId));
2353
+ const readyNodes = findReadyNodes(workflow.definition, completedNodeIds, activeEdges).filter((n) => n.id === failedNode.id || !liveNodeIds.has(n.id));
2354
+ const nodesToRun = !shouldRetryFailedNode || readyNodes.some((n) => n.id === failedNode.id) ? readyNodes : [failedNode, ...readyNodes];
2355
+ const secretKeys = getSecretInputKeys(workflow.input);
2356
+ await walkGraph(workflow.definition, runId, ctx, nodesToRun, registry, workflow.id, secretKeys);
2357
+ }
2358
+ async function cancelWorkflowRunRows(runId, cancelReason) {
2359
+ const terminalStatuses = ["completed", "failed", "cancelled", "skipped"];
2360
+ const now = new Date().toISOString();
2361
+ return await getDbClient().transaction(async () => {
2362
+ const current = await getWorkflowRun(runId);
2363
+ if (!current || terminalStatuses.includes(current.status))
2364
+ return false;
2365
+ const steps = await getWorkflowRunStepsByRunId(runId);
2366
+ for (const step of steps) {
2367
+ if (terminalStatuses.includes(step.status))
2368
+ continue;
2369
+ const task = await getTaskByWorkflowRunStepId(step.id);
2370
+ if (task) {
2371
+ await cancelTask(task.id, cancelReason);
2372
+ }
2373
+ await updateWorkflowRunStep(step.id, {
2374
+ status: "cancelled",
2375
+ error: cancelReason,
2376
+ finishedAt: now
2377
+ });
2378
+ }
2379
+ await cancelPendingApprovalRequestsForRun(runId, cancelReason);
2380
+ await updateWorkflowRun(runId, {
2381
+ status: "cancelled",
2382
+ error: cancelReason,
2383
+ finishedAt: now
2384
+ });
2385
+ return true;
2386
+ });
2387
+ }
2388
+ async function cancelWorkflowRun(runId, reason) {
2389
+ const run = await getWorkflowRun(runId);
2390
+ if (!run)
2391
+ throw new Error("Workflow run not found");
2392
+ const terminalStatuses = ["completed", "failed", "cancelled", "skipped"];
2393
+ if (terminalStatuses.includes(run.status) && run.status !== "cancelled") {
2394
+ throw new Error(`Cannot cancel run in '${run.status}' state`);
2395
+ }
2396
+ const cancelReason = reason ?? "Cancelled by user";
2397
+ const applied = await cancelWorkflowRunRows(runId, cancelReason);
2398
+ const cancelledApprovals = await listCancelledApprovalRequestsForRun(runId);
2399
+ const latestRun = await getWorkflowRun(runId);
2400
+ if (!applied && latestRun?.status !== "cancelled") {
2401
+ throw new Error(`Cannot cancel run in '${latestRun?.status ?? "missing"}' state`);
2402
+ }
2403
+ await postApprovalCancellationUpdates(cancelledApprovals, applied ? cancelReason : latestRun?.error ?? cancelReason);
2404
+ }
2405
+ async function cancelWorkflowRunStep(stepId, reason = "Cancelled by user", slackClient) {
2406
+ const now = new Date().toISOString();
2407
+ let persistedReason = reason;
2408
+ await getDbClient().transaction(async () => {
2409
+ const step = await getWorkflowRunStep(stepId);
2410
+ if (!step)
2411
+ throw new Error("Workflow run step not found");
2412
+ if (step.nodeType !== "human-in-the-loop") {
2413
+ throw new Error("Only human-in-the-loop steps have an approval cancellation lifecycle");
2414
+ }
2415
+ if (["completed", "failed", "skipped"].includes(step.status)) {
2416
+ throw new Error(`Cannot cancel step in '${step.status}' state`);
2417
+ }
2418
+ if (step.status === "cancelled") {
2419
+ persistedReason = step.error ?? reason;
2420
+ return;
2421
+ }
2422
+ const task = await getTaskByWorkflowRunStepId(stepId);
2423
+ if (task)
2424
+ await cancelTask(task.id, reason);
2425
+ await updateWorkflowRunStep(stepId, {
2426
+ status: "cancelled",
2427
+ error: reason,
2428
+ finishedAt: now
2429
+ });
2430
+ });
2431
+ const approvals = await listCancelledApprovalRequestsForStep(stepId);
2432
+ await postApprovalCancellationUpdates(approvals, persistedReason, slackClient);
2433
+ }
2434
+ async function resumeFromApprovalResolution(event, registry) {
2435
+ await failClosedOnUnreadableReplay(event.workflowRunId, event.workflowRunStepId, () => resumeFromApprovalResolutionUnguarded(event, registry));
2436
+ }
2437
+ async function resumeFromApprovalResolutionUnguarded(event, registry) {
2438
+ const run = await getWorkflowRun(event.workflowRunId);
2439
+ if (!run || run.status !== "waiting" && run.status !== "running")
2440
+ return;
2441
+ const step = await getWorkflowRunStep(event.workflowRunStepId);
2442
+ if (!step || step.status !== "waiting")
2443
+ return;
2444
+ const workflow = await getWorkflow(run.workflowId);
2445
+ if (!workflow)
2446
+ return;
2447
+ if (event.status === "cancelled") {
2448
+ console.warn(`[workflows] approval ${event.requestId} is cancelled; step ${event.workflowRunStepId} stays waiting for the run cancel path`);
2449
+ return;
2450
+ }
2451
+ const ctx = run.context ?? {};
2452
+ const { output: stepOutput, nextPort } = shapeApprovalResolution(registry, workflow.definition, step.nodeId, step.output, { requestId: event.requestId, status: event.status, responses: event.responses });
2453
+ const routing = await checkpointPortStepAndResolveSuccessors(workflow.definition, run.id, step.id, step.nodeId, stepOutput, nextPort, ctx);
2454
+ if (!routing.claimed)
2455
+ return;
2456
+ const successors = routing.successors;
2457
+ if (successors.length > 0) {
2458
+ const secretKeys = getSecretInputKeys(workflow.input);
2459
+ await walkGraph(workflow.definition, run.id, ctx, successors, registry, workflow.id, secretKeys);
2460
+ } else {
2461
+ await finalizeOrWait(run.id);
2462
+ }
2463
+ }
2464
+ async function resumeWaitState(waitId, status, payload, registry) {
2465
+ const cappedPayload = capPayload(payload);
2466
+ const result = await resolveWaitState(waitId, { status, firedPayload: cappedPayload });
2467
+ if (!result.updated || !result.row)
2468
+ return;
2469
+ const waitRow = result.row;
2470
+ await failClosedOnUnreadableReplay(waitRow.workflowRunId, waitRow.workflowRunStepId, () => resumeClaimedWait(waitRow, status, cappedPayload, registry));
2471
+ }
2472
+ async function resumeClaimedWait(waitRow, status, cappedPayload, registry) {
2473
+ const run = await getWorkflowRun(waitRow.workflowRunId);
2474
+ if (!run || run.status !== "waiting" && run.status !== "running")
2475
+ return;
2476
+ const step = await getWorkflowRunStep(waitRow.workflowRunStepId);
2477
+ if (!step || step.status !== "waiting")
2478
+ return;
2479
+ const workflow = await getWorkflow(run.workflowId);
2480
+ if (!workflow)
2481
+ return;
2482
+ const nextPort = computeNextPort(waitRow.mode, status);
2483
+ const ctx = run.context ?? {};
2484
+ const stepOutput = {
2485
+ waitId: waitRow.id,
2486
+ mode: waitRow.mode,
2487
+ firedAt: waitRow.resolvedAt,
2488
+ payload: cappedPayload === undefined ? undefined : cappedPayload
2489
+ };
2490
+ const routing = await checkpointPortStepAndResolveSuccessors(workflow.definition, run.id, step.id, step.nodeId, stepOutput, nextPort, ctx);
2491
+ if (!routing.claimed)
2492
+ return;
2493
+ if (waitRow.mode === "event" && waitRow.eventName) {
2494
+ pruneWaitFromBus(waitRow.id, waitRow.eventName);
2495
+ }
2496
+ const successors = routing.successors;
2497
+ if (successors.length > 0) {
2498
+ const secretKeys = getSecretInputKeys(workflow.input);
2499
+ await walkGraph(workflow.definition, run.id, ctx, successors, registry, workflow.id, secretKeys);
2500
+ } else {
2501
+ await finalizeOrWait(run.id);
2502
+ }
2503
+ }
2504
+ async function resumeFromChildRun(parentStepId, registry) {
2505
+ const step = await getWorkflowRunStep(parentStepId);
2506
+ if (!step || step.status !== "waiting" || step.nodeType !== "sub-workflow")
2507
+ return false;
2508
+ const childId = await getChildWorkflowRunId(parentStepId);
2509
+ const child = childId ? await getWorkflowRun(childId) : null;
2510
+ const outcome = child ? childRunOutcome(child) : { error: `Child workflow run of step ${parentStepId} was deleted` };
2511
+ if (!outcome)
2512
+ return false;
2513
+ let claimed = false;
2514
+ await failClosedOnUnreadableReplay(step.runId, step.id, async () => {
2515
+ const run = await getWorkflowRun(step.runId);
2516
+ if (!run || run.status !== "waiting" && run.status !== "running")
2517
+ return;
2518
+ const workflow = await getWorkflow(run.workflowId);
2519
+ if (!workflow)
2520
+ return;
2521
+ if ("error" in outcome) {
2522
+ claimed = await failStepAndRunIfWaiting(step.id, run.id, outcome.error);
2523
+ return;
2524
+ }
2525
+ const ctx = run.context ?? {};
2526
+ const routing = await checkpointPortStepAndResolveSuccessors(workflow.definition, run.id, step.id, step.nodeId, outcome.output, "success", ctx);
2527
+ if (!routing.claimed)
2528
+ return;
2529
+ claimed = true;
2530
+ if (routing.successors.length > 0) {
2531
+ const secretKeys = getSecretInputKeys(workflow.input);
2532
+ await walkGraph(workflow.definition, run.id, ctx, routing.successors, registry, workflow.id, secretKeys);
2533
+ } else {
2534
+ await finalizeOrWait(run.id);
2535
+ }
2536
+ });
2537
+ return claimed;
2538
+ }
2539
+ var FIRED_PAYLOAD_BYTE_CAP = 64 * 1024;
2540
+ function capPayload(payload) {
2541
+ if (payload === undefined || payload === null)
2542
+ return payload;
2543
+ let encoded;
2544
+ try {
2545
+ encoded = JSON.stringify(payload);
2546
+ } catch {
2547
+ return { truncated: true, reason: "non-serializable" };
2548
+ }
2549
+ if (encoded.length <= FIRED_PAYLOAD_BYTE_CAP) {
2550
+ return payload;
2551
+ }
2552
+ const summary = encoded.slice(0, 1024);
2553
+ return {
2554
+ truncated: true,
2555
+ originalSize: encoded.length,
2556
+ summary
2557
+ };
2558
+ }
2559
+ var waitsByEvent = new Map;
2560
+ var listenersByEvent = new Map;
2561
+ var busRegistry = null;
2562
+ async function initWaitBusSubscriptions(registry) {
2563
+ busRegistry = registry;
2564
+ const pendingNames = await collectPendingEventNames();
2565
+ for (const name of pendingNames) {
2566
+ const pending = await getPendingWaitsByEvent(name);
2567
+ for (const w of pending) {
2568
+ registerWait(w.id, name);
2569
+ }
2570
+ }
2571
+ }
2572
+ async function collectPendingEventNames() {
2573
+ return new Set(await getPendingEventWaitNames());
2574
+ }
2575
+ function subscribeWaitToBus(waitId, eventName) {
2576
+ registerWait(waitId, eventName);
2577
+ }
2578
+ function registerWait(waitId, eventName) {
2579
+ let set = waitsByEvent.get(eventName);
2580
+ if (!set) {
2581
+ set = new Set;
2582
+ waitsByEvent.set(eventName, set);
2583
+ }
2584
+ set.add(waitId);
2585
+ if (!listenersByEvent.has(eventName)) {
2586
+ const listener = (data) => {
2587
+ processBusEvent(eventName, data).catch((err) => {
2588
+ console.error(`[workflows] Wait bus listener failed for event=${eventName}:`, scrubSecrets(err instanceof Error ? err.message : String(err)));
2589
+ });
2590
+ };
2591
+ listenersByEvent.set(eventName, listener);
2592
+ workflowEventBus.on(eventName, listener);
2593
+ }
2594
+ }
2595
+ function pruneWaitFromBus(waitId, eventName) {
2596
+ const set = waitsByEvent.get(eventName);
2597
+ if (!set)
2598
+ return;
2599
+ set.delete(waitId);
2600
+ if (set.size === 0) {
2601
+ waitsByEvent.delete(eventName);
2602
+ const listener = listenersByEvent.get(eventName);
2603
+ if (listener) {
2604
+ workflowEventBus.off(eventName, listener);
2605
+ listenersByEvent.delete(eventName);
2606
+ }
2607
+ }
2608
+ }
2609
+ async function processBusEvent(eventName, payload) {
2610
+ const set = waitsByEvent.get(eventName);
2611
+ if (!set || set.size === 0)
2612
+ return;
2613
+ if (!busRegistry)
2614
+ return;
2615
+ const waitIds = [...set];
2616
+ for (const waitId of waitIds) {
2617
+ try {
2618
+ const row = await getWaitStateById(waitId);
2619
+ if (!row || row.status !== "pending") {
2620
+ set.delete(waitId);
2621
+ continue;
2622
+ }
2623
+ if (row.eventScope === "run") {
2624
+ if (!isPayloadInRun(payload, row.workflowRunId))
2625
+ continue;
2626
+ }
2627
+ const ok = await matchesFilter(payload, row.eventFilter ?? undefined);
2628
+ if (!ok)
2629
+ continue;
2630
+ await resumeWaitState(waitId, "fired", payload, busRegistry);
2631
+ } catch (err) {
2632
+ console.error(`[workflows] Wait bus listener failed for wait=${waitId} event=${eventName}:`, err);
2633
+ }
2634
+ }
2635
+ if (set.size === 0) {
2636
+ waitsByEvent.delete(eventName);
2637
+ const listener = listenersByEvent.get(eventName);
2638
+ if (listener) {
2639
+ workflowEventBus.off(eventName, listener);
2640
+ listenersByEvent.delete(eventName);
2641
+ }
2642
+ }
2643
+ }
2644
+ function isPayloadInRun(payload, runId) {
2645
+ if (typeof payload !== "object" || payload === null)
2646
+ return false;
2647
+ const rec = payload;
2648
+ return rec._runId === runId || rec.workflowRunId === runId;
2649
+ }
2650
+ function _resetWaitBusSubscriptionsForTests() {
2651
+ for (const [name, listener] of listenersByEvent.entries()) {
2652
+ workflowEventBus.off(name, listener);
2653
+ }
2654
+ listenersByEvent.clear();
2655
+ waitsByEvent.clear();
2656
+ busRegistry = null;
2657
+ }
2658
+
2659
+ export { notifyAutomationPreflightFailure, automationIntegrationFixUrl, isNeedsSetupFailure, preflightAutomation, renderAutomationTokens, getAutomationSetupStates, schedulePreflightInput, listEnabledAutomationPreflightInputs, recordSchedulePreflightFailure, checkpointStep, checkpointStepFailure, checkpointStepWaiting, FOREACH_TERMINAL_STEP_STATUSES, parseSyntheticNodeId, buildForeachAggregate, loadCompletedStepRouting, resolveInputValue, getSecretInputKeys, validateJsonSchema, findJsonSchemaShapeErrors, getMaxWorkflowStepsPerRun, workflowSaveWarnings, withSaveWarnings, runStepValidation, shapeApprovalResolution, FAILED_TASK_OUTPUT_PREFIX, SubWorkflowExecutor, WaitExecutor, failStepAndRunIfWaiting, checkpointPortStepAndResolveSuccessors, scheduleTaskStepRetry, completeTaskStepAndResolveSuccessors, setupWorkflowResumeListener, finalizeOrWait, retryFailedRun, cancelWorkflowRunRows, cancelWorkflowRun, cancelWorkflowRunStep, resumeWaitState, resumeFromChildRun, initWaitBusSubscriptions, subscribeWaitToBus, _resetWaitBusSubscriptionsForTests, TriggerSchemaError, startWorkflowExecution, failRunOnUnreadableReplay, isWorkflowRunActive, holdWorkflowRun, walkGraph, rehydrateCompletedStepOutputs, findReadyNodes, buildNodeInterpolationCtx, interpolateNodeConfig, scriptBodyInterpolationError };