@xyne/workflow-sdk 3.2.54 → 3.2.56

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 (172) hide show
  1. package/dist/agents/agent-step.d.ts +30 -15
  2. package/dist/agents/agent-step.d.ts.map +1 -1
  3. package/dist/agents/agent-step.js +15 -5
  4. package/dist/agents/agent-step.js.map +1 -1
  5. package/dist/agents/citation-resolve.js +1 -1
  6. package/dist/agents/citation-resolve.js.map +1 -1
  7. package/dist/agents/contract.d.ts +16 -8
  8. package/dist/agents/contract.d.ts.map +1 -1
  9. package/dist/agents/host-agent-step.d.ts +20 -10
  10. package/dist/agents/host-agent-step.d.ts.map +1 -1
  11. package/dist/agents/host-agent-step.js +7 -3
  12. package/dist/agents/host-agent-step.js.map +1 -1
  13. package/dist/agents/provider.d.ts +2 -2
  14. package/dist/agents/tool-types.d.ts +13 -2
  15. package/dist/agents/tool-types.d.ts.map +1 -1
  16. package/dist/client/workflow-client.js +1 -1
  17. package/dist/client/workflow-client.js.map +1 -1
  18. package/dist/common/attachment.d.ts +24 -7
  19. package/dist/common/attachment.d.ts.map +1 -1
  20. package/dist/common/attachment.js +34 -7
  21. package/dist/common/attachment.js.map +1 -1
  22. package/dist/common/multipart-values.d.ts +21 -0
  23. package/dist/common/multipart-values.d.ts.map +1 -0
  24. package/dist/common/multipart-values.js +63 -0
  25. package/dist/common/multipart-values.js.map +1 -0
  26. package/dist/completion/address.d.ts +27 -0
  27. package/dist/completion/address.d.ts.map +1 -0
  28. package/dist/completion/address.js +62 -0
  29. package/dist/completion/address.js.map +1 -0
  30. package/dist/completion/attach.d.ts +20 -0
  31. package/dist/completion/attach.d.ts.map +1 -0
  32. package/dist/completion/attach.js +37 -0
  33. package/dist/completion/attach.js.map +1 -0
  34. package/dist/completion/index.d.ts +6 -0
  35. package/dist/completion/index.d.ts.map +1 -0
  36. package/dist/completion/index.js +4 -0
  37. package/dist/completion/index.js.map +1 -0
  38. package/dist/completion/types.d.ts +109 -0
  39. package/dist/completion/types.d.ts.map +1 -0
  40. package/dist/completion/types.js +35 -0
  41. package/dist/completion/types.js.map +1 -0
  42. package/dist/connectors/builtin/builtin-connector.d.ts.map +1 -1
  43. package/dist/connectors/builtin/builtin-connector.js +6 -2
  44. package/dist/connectors/builtin/builtin-connector.js.map +1 -1
  45. package/dist/connectors/builtin/steps/code.step.d.ts +20 -10
  46. package/dist/connectors/builtin/steps/code.step.d.ts.map +1 -1
  47. package/dist/connectors/builtin/steps/code.step.js +14 -7
  48. package/dist/connectors/builtin/steps/code.step.js.map +1 -1
  49. package/dist/connectors/builtin/steps/cycle.step.d.ts +36 -7
  50. package/dist/connectors/builtin/steps/cycle.step.d.ts.map +1 -1
  51. package/dist/connectors/builtin/steps/cycle.step.js +84 -6
  52. package/dist/connectors/builtin/steps/cycle.step.js.map +1 -1
  53. package/dist/connectors/builtin/steps/delay.step.d.ts +49 -0
  54. package/dist/connectors/builtin/steps/delay.step.d.ts.map +1 -0
  55. package/dist/connectors/builtin/steps/delay.step.js +40 -0
  56. package/dist/connectors/builtin/steps/delay.step.js.map +1 -0
  57. package/dist/connectors/builtin/steps/http-request.step.d.ts +100 -50
  58. package/dist/connectors/builtin/steps/http-request.step.d.ts.map +1 -1
  59. package/dist/connectors/builtin/steps/http-request.step.js +14 -15
  60. package/dist/connectors/builtin/steps/http-request.step.js.map +1 -1
  61. package/dist/connectors/builtin/steps/map.step.d.ts.map +1 -1
  62. package/dist/connectors/builtin/steps/map.step.js +9 -2
  63. package/dist/connectors/builtin/steps/map.step.js.map +1 -1
  64. package/dist/connectors/builtin/steps/multipart-body.d.ts +23 -0
  65. package/dist/connectors/builtin/steps/multipart-body.d.ts.map +1 -0
  66. package/dist/connectors/builtin/steps/multipart-body.js +40 -0
  67. package/dist/connectors/builtin/steps/multipart-body.js.map +1 -0
  68. package/dist/connectors/builtin/steps/parallel.step.d.ts.map +1 -1
  69. package/dist/connectors/builtin/steps/parallel.step.js +9 -2
  70. package/dist/connectors/builtin/steps/parallel.step.js.map +1 -1
  71. package/dist/connectors/builtin/steps/wait-for-api-call.step.d.ts +80 -0
  72. package/dist/connectors/builtin/steps/wait-for-api-call.step.d.ts.map +1 -0
  73. package/dist/connectors/builtin/steps/wait-for-api-call.step.js +104 -0
  74. package/dist/connectors/builtin/steps/wait-for-api-call.step.js.map +1 -0
  75. package/dist/connectors/builtin/steps/wait-for-human.step.d.ts +1057 -0
  76. package/dist/connectors/builtin/steps/wait-for-human.step.d.ts.map +1 -0
  77. package/dist/connectors/builtin/steps/wait-for-human.step.js +222 -0
  78. package/dist/connectors/builtin/steps/wait-for-human.step.js.map +1 -0
  79. package/dist/connectors/builtin/steps/wait-for-webhook.step.d.ts +80 -0
  80. package/dist/connectors/builtin/steps/wait-for-webhook.step.d.ts.map +1 -0
  81. package/dist/connectors/builtin/steps/wait-for-webhook.step.js +104 -0
  82. package/dist/connectors/builtin/steps/wait-for-webhook.step.js.map +1 -0
  83. package/dist/connectors/builtin/steps/wait.step.d.ts +10 -35
  84. package/dist/connectors/builtin/steps/wait.step.d.ts.map +1 -1
  85. package/dist/connectors/builtin/steps/wait.step.js +11 -57
  86. package/dist/connectors/builtin/steps/wait.step.js.map +1 -1
  87. package/dist/conversational-flow/create.d.ts +2 -1
  88. package/dist/conversational-flow/create.d.ts.map +1 -1
  89. package/dist/conversational-flow/create.js +2 -2
  90. package/dist/conversational-flow/create.js.map +1 -1
  91. package/dist/conversational-flow/edit/build.js +1 -1
  92. package/dist/conversational-flow/edit/build.js.map +1 -1
  93. package/dist/conversational-flow/edit/questions.d.ts +35 -0
  94. package/dist/conversational-flow/edit/questions.d.ts.map +1 -0
  95. package/dist/conversational-flow/edit/questions.js +188 -0
  96. package/dist/conversational-flow/edit/questions.js.map +1 -0
  97. package/dist/conversational-flow/questions.d.ts +32 -0
  98. package/dist/conversational-flow/questions.d.ts.map +1 -0
  99. package/dist/conversational-flow/questions.js +122 -0
  100. package/dist/conversational-flow/questions.js.map +1 -0
  101. package/dist/engine/config-validator.d.ts.map +1 -1
  102. package/dist/engine/config-validator.js +29 -0
  103. package/dist/engine/config-validator.js.map +1 -1
  104. package/dist/engine/pause-step.d.ts +21 -4
  105. package/dist/engine/pause-step.d.ts.map +1 -1
  106. package/dist/engine/pause-step.js +11 -2
  107. package/dist/engine/pause-step.js.map +1 -1
  108. package/dist/engine/read-config.d.ts +12 -0
  109. package/dist/engine/read-config.d.ts.map +1 -0
  110. package/dist/engine/read-config.js +50 -0
  111. package/dist/engine/read-config.js.map +1 -0
  112. package/dist/engine/workflow-executor.d.ts.map +1 -1
  113. package/dist/engine/workflow-executor.js +38 -56
  114. package/dist/engine/workflow-executor.js.map +1 -1
  115. package/dist/index.d.ts +14 -6
  116. package/dist/index.d.ts.map +1 -1
  117. package/dist/index.js +6 -2
  118. package/dist/index.js.map +1 -1
  119. package/dist/persistence/in-memory-adapter.d.ts +3 -18
  120. package/dist/persistence/in-memory-adapter.d.ts.map +1 -1
  121. package/dist/persistence/in-memory-adapter.js +9 -61
  122. package/dist/persistence/in-memory-adapter.js.map +1 -1
  123. package/dist/persistence/types.d.ts +29 -58
  124. package/dist/persistence/types.d.ts.map +1 -1
  125. package/dist/router/approval-context.d.ts +1 -1
  126. package/dist/router/approval-context.d.ts.map +1 -1
  127. package/dist/router/approval-context.js +3 -3
  128. package/dist/router/approval-context.js.map +1 -1
  129. package/dist/router/types.d.ts +18 -7
  130. package/dist/router/types.d.ts.map +1 -1
  131. package/dist/router/workflow-router.d.ts.map +1 -1
  132. package/dist/router/workflow-router.js +164 -123
  133. package/dist/router/workflow-router.js.map +1 -1
  134. package/dist/runtime/workflow-runtime.d.ts +40 -45
  135. package/dist/runtime/workflow-runtime.d.ts.map +1 -1
  136. package/dist/runtime/workflow-runtime.js +188 -123
  137. package/dist/runtime/workflow-runtime.js.map +1 -1
  138. package/dist/steps/base-step.d.ts +11 -10
  139. package/dist/steps/base-step.d.ts.map +1 -1
  140. package/dist/steps/base-step.js.map +1 -1
  141. package/dist/storage/files.d.ts +39 -0
  142. package/dist/storage/files.d.ts.map +1 -0
  143. package/dist/storage/files.js +75 -0
  144. package/dist/storage/files.js.map +1 -0
  145. package/dist/storage/in-memory-adapter.d.ts +15 -8
  146. package/dist/storage/in-memory-adapter.d.ts.map +1 -1
  147. package/dist/storage/in-memory-adapter.js +36 -18
  148. package/dist/storage/in-memory-adapter.js.map +1 -1
  149. package/dist/storage/types.d.ts +36 -26
  150. package/dist/storage/types.d.ts.map +1 -1
  151. package/dist/storage/types.js +5 -6
  152. package/dist/storage/types.js.map +1 -1
  153. package/dist/testing/mock-step-context.d.ts +7 -2
  154. package/dist/testing/mock-step-context.d.ts.map +1 -1
  155. package/dist/testing/mock-step-context.js +2 -1
  156. package/dist/testing/mock-step-context.js.map +1 -1
  157. package/dist/testing/test-connector.d.ts +1 -1
  158. package/dist/testing/test-connector.js +1 -1
  159. package/dist/types/index.d.ts +2 -2
  160. package/dist/types/index.d.ts.map +1 -1
  161. package/dist/types/index.js +1 -1
  162. package/dist/types/index.js.map +1 -1
  163. package/dist/types/known-types.d.ts +51 -1
  164. package/dist/types/known-types.d.ts.map +1 -1
  165. package/dist/types/known-types.js +54 -1
  166. package/dist/types/known-types.js.map +1 -1
  167. package/dist/types/pause-state.d.ts +0 -8
  168. package/dist/types/pause-state.d.ts.map +1 -1
  169. package/dist/types/pause-state.js.map +1 -1
  170. package/dist/types/workflow-variable.d.ts +20 -10
  171. package/dist/types/workflow-variable.d.ts.map +1 -1
  172. package/package.json +1 -1
@@ -18,6 +18,10 @@ import { WorkflowStatus } from '../types/status.js';
18
18
  import { approvalGate } from '../util/approval-gate.js';
19
19
  import { ConfigValidator } from '../engine/config-validator.js';
20
20
  import { literalValues } from '../util/literal-values.js';
21
+ import { readWorkflowConfig } from '../engine/read-config.js';
22
+ import { collectStepIds, resolveGate } from '../completion/address.js';
23
+ import { attachDeliveryFiles } from '../completion/attach.js';
24
+ import { coerceTextFields } from '../common/multipart-values.js';
21
25
  import { resolvePage } from './paging.js';
22
26
  import { validateTriggerPayload } from '../common/validate-payload.js';
23
27
  import { AccessDeniedError, ResourceNotFoundError } from '../authz/default.js';
@@ -59,11 +63,6 @@ const noopLogger = {
59
63
  warn: () => { },
60
64
  error: () => { },
61
65
  };
62
- function generateSecret() {
63
- const bytes = new Uint8Array(24);
64
- crypto.getRandomValues(bytes);
65
- return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
66
- }
67
66
  /** The trigger's author-supplied input schema, when it has one. */
68
67
  function inputSchemaOf(config) {
69
68
  const inputSchema = (config.trigger.config ?? {})['inputSchema'];
@@ -71,8 +70,19 @@ function inputSchemaOf(config) {
71
70
  ? inputSchema
72
71
  : undefined;
73
72
  }
74
- function parseWorkflowConfig(raw) {
75
- return JSON.parse(raw ?? '{}');
73
+ /**
74
+ * The author's declared shape, checked the same way a manual trigger's input
75
+ * is — required fields and attachment invariants, not a deep type check. A
76
+ * sender that gets this back learns what it sent wrong instead of the run
77
+ * carrying on with a field that is not there.
78
+ */
79
+ function checkAgainstContract(contract, payload) {
80
+ if (contract === undefined || contract === null || typeof contract !== 'object')
81
+ return [];
82
+ if (payload === null || typeof payload !== 'object' || Array.isArray(payload)) {
83
+ return [{ path: '', message: 'Expected a JSON object' }];
84
+ }
85
+ return validateTriggerPayload(contract, payload);
76
86
  }
77
87
  /** The author-given name out of the metadata column, if it has one. */
78
88
  function parseWorkflowName(raw) {
@@ -326,7 +336,7 @@ export class WorkflowRuntime {
326
336
  async activateWorkflow(ctx, workflowId, opts) {
327
337
  // Guard up front, before any external side-effects (webhook/scheduler).
328
338
  const { record, permittedActions } = await this.authorizedWorkflow(ctx, workflowId, 'workflow:activate');
329
- const gate = this.gateFor(parseWorkflowConfig(record.config));
339
+ const gate = this.gateFor(readWorkflowConfig(record.config));
330
340
  // A caller who may approve is approving by activating — otherwise an admin
331
341
  // toggling their own workflow would queue a review of their own work.
332
342
  // Strict four-eyes is the authorizer's to impose: withhold
@@ -463,7 +473,7 @@ export class WorkflowRuntime {
463
473
  }
464
474
  async activateInternal(ctx, workflow) {
465
475
  const workflowId = workflow.id;
466
- const config = parseWorkflowConfig(workflow.config);
476
+ const config = readWorkflowConfig(workflow.config);
467
477
  const activateAttributes = workflow.attributes;
468
478
  // A configuration naming things that do not exist, or that its author may
469
479
  // not use, fails here — beside the credential check below and for the same
@@ -501,7 +511,7 @@ export class WorkflowRuntime {
501
511
  throw new Error(`Workflow ${workflowId} not found`);
502
512
  }
503
513
  await this.require(ctx, 'workflow:activate', this.workflowRef(workflow));
504
- const config = parseWorkflowConfig(workflow.config);
514
+ const config = readWorkflowConfig(workflow.config);
505
515
  // Falls through rather than returning early on an unregistered trigger type:
506
516
  // the call still succeeded, and every successful call must leave by the same
507
517
  // door so that none of them can quietly skip the notification below.
@@ -518,42 +528,6 @@ export class WorkflowRuntime {
518
528
  this.publishWorkflowChange(workflowId, 'deactivated', opts?.origin);
519
529
  }
520
530
  // ─── Workflow callback secret ───
521
- /**
522
- * Lazy-allocate the workflow's stable wait-callback secret. Idempotent —
523
- * if a secret already exists, returns the existing record.
524
- *
525
- * Host calls this when saving a workflow that uses wait-step webhook
526
- * mode, then surfaces the URL in the UI so the author can paste it into
527
- * the external system's configuration.
528
- */
529
- async ensureWorkflowCallback(workflowId) {
530
- const existing = await this.persistence.getWorkflowCallback(workflowId);
531
- if (existing)
532
- return existing;
533
- const record = {
534
- workflowId,
535
- secret: generateSecret(),
536
- createdAt: new Date(),
537
- };
538
- await this.persistence.storeWorkflowCallback(record);
539
- return record;
540
- }
541
- /**
542
- * Rotate the workflow's wait-callback secret. The old URL stops working
543
- * immediately. Author has to update external configurations.
544
- */
545
- async rotateWorkflowCallback(workflowId) {
546
- return this.persistence.rotateWorkflowCallback(workflowId, generateSecret());
547
- }
548
- /**
549
- * Build the wait-callback URL template the author should paste into
550
- * their external system. `{executionId}` is the placeholder the HTTP
551
- * step substitutes via `{{ runtime.executionId }}`.
552
- */
553
- buildWaitCallbackUrl(secret, executionId) {
554
- const base = `${this.baseUrl}/wait/callback/${secret}`;
555
- return executionId ? `${base}/${executionId}` : `${base}/{executionId}`;
556
- }
557
531
  // ─── Trigger Firing ───
558
532
  /**
559
533
  * Dispatch a domain event to every active workflow watching for it.
@@ -575,7 +549,7 @@ export class WorkflowRuntime {
575
549
  ...(event.occurredAt !== undefined ? { occurredAt: event.occurredAt } : {}),
576
550
  };
577
551
  for (const workflow of workflows) {
578
- const config = parseWorkflowConfig(workflow.config);
552
+ const config = readWorkflowConfig(workflow.config);
579
553
  if (!this.connectors.hasTrigger(config.trigger.type))
580
554
  continue;
581
555
  const trigger = this.connectors.getTrigger(config.trigger.type);
@@ -623,7 +597,7 @@ export class WorkflowRuntime {
623
597
  const workflow = await this.persistence.getWorkflow(workflowId);
624
598
  if (!workflow || workflow.status !== 'ACTIVE')
625
599
  return notFound;
626
- const config = parseWorkflowConfig(workflow.config);
600
+ const config = readWorkflowConfig(workflow.config);
627
601
  const trigger = this.connectors.findTrigger(config.trigger.type)?.trigger;
628
602
  if (!(trigger instanceof WebhookTrigger))
629
603
  return notFound;
@@ -685,52 +659,6 @@ export class WorkflowRuntime {
685
659
  executionIds,
686
660
  };
687
661
  }
688
- /**
689
- * Handle an incoming wait-callback at `POST /wait/callback/<secret>/<executionId>`.
690
- *
691
- * The `secret` is the workflow's stable callback secret (generated at
692
- * workflow create). The `executionId` is the in-flight execution that
693
- * paused on a wait-webhook step — the workflow's HTTP step interpolated
694
- * it into the URL it gave the external system via
695
- * `{{ runtime.executionId }}`.
696
- *
697
- * Validation:
698
- * 1. Secret resolves to a workflow (404 on miss, same hash-map security
699
- * as trigger webhooks — wrong/unknown secrets are indistinguishable).
700
- * 2. Execution exists, is EXTERNAL_WAIT, and belongs to that workflow
701
- * (404 otherwise; same 404 so attackers can't probe for valid
702
- * execution IDs by guessing).
703
- *
704
- * On success, the callback body becomes the resume payload and the
705
- * execution is re-enqueued. The wait step's `onResume` sees it as
706
- * `resumeData`.
707
- */
708
- async handleWaitCallback(secret, executionId, body) {
709
- const callback = await this.persistence.getWorkflowCallbackBySecret(secret);
710
- if (!callback) {
711
- return { status: 404, body: { error: 'Wait callback not found' } };
712
- }
713
- const exec = await this.persistence.getExecution(executionId);
714
- if (!exec ||
715
- exec.workflowId !== callback.workflowId ||
716
- exec.status !== 'EXTERNAL_WAIT') {
717
- // Either the execution is wrong workflow, terminal, or unknown. Same
718
- // 404 either way — don't leak which case.
719
- return { status: 404, body: { error: 'Wait callback not found' } };
720
- }
721
- // Wrap the caller's body as a structured resume payload. Objects pass
722
- // through; primitives get wrapped under `{ body }` so step code always
723
- // sees a record.
724
- const data = body && typeof body === 'object' && !Array.isArray(body)
725
- ? body
726
- : { body };
727
- // System path: the unguessable secret in the URL is the authorization —
728
- // there is no caller to ask the authorizer about.
729
- await this.resumeInternal(executionId, {
730
- data: { action: 'approve', data },
731
- });
732
- return { status: 202, body: { received: true, executionId } };
733
- }
734
662
  /**
735
663
  * Fire a workflow manually via API.
736
664
  *
@@ -753,7 +681,7 @@ export class WorkflowRuntime {
753
681
  throw new Error(`Cannot run workflow ${workflowId}: it is awaiting approval. ` +
754
682
  `Deactivate it to keep editing and testing, or wait for a decision.`);
755
683
  }
756
- const config = parseWorkflowConfig(workflow.config);
684
+ const config = readWorkflowConfig(workflow.config);
757
685
  const triggerCfg = (config.trigger.config ?? {});
758
686
  const inputSchema = triggerCfg['inputSchema'];
759
687
  const errors = validateTriggerPayload(inputSchema, payload);
@@ -814,7 +742,7 @@ export class WorkflowRuntime {
814
742
  const workflow = await this.persistence.getWorkflow(workflowId);
815
743
  if (!workflow)
816
744
  throw new ResourceNotFoundError('Workflow', workflowId);
817
- const config = parseWorkflowConfig(workflow.config);
745
+ const config = readWorkflowConfig(workflow.config);
818
746
  const trigger = this.connectors.findTrigger(config.trigger.type)?.trigger;
819
747
  if (!(trigger instanceof ApiTrigger)) {
820
748
  throw new Error(`Workflow ${workflowId} does not use an API trigger`);
@@ -831,7 +759,7 @@ export class WorkflowRuntime {
831
759
  throw new Error(`Workflow ${workflowId} not found`);
832
760
  }
833
761
  await this.require(ctx, 'workflow:run', this.workflowRef(workflow));
834
- return inputSchemaOf(parseWorkflowConfig(workflow.config));
762
+ return inputSchemaOf(readWorkflowConfig(workflow.config));
835
763
  }
836
764
  /**
837
765
  * Resume a paused execution. Guards `execution:approve`, then does the work.
@@ -908,9 +836,10 @@ export class WorkflowRuntime {
908
836
  });
909
837
  }
910
838
  else {
911
- // No identifiable gate record yet — fall back to the global slot. The
912
- // executor routes it to the sole gate at run time (back-compat).
913
- await this.persistence.persistResumePayload(executionId, input.data);
839
+ // Addressing is per node now, so there is nowhere for an answer with no
840
+ // gate to go. Say so rather than park it in a slot that may later be
841
+ // applied to whichever gate happens to be the only one open.
842
+ throw new Error(`Execution ${executionId} has no open gate to resume`);
914
843
  }
915
844
  }
916
845
  // Keep status as EXTERNAL_WAIT — the executor detects this as a resume and
@@ -919,6 +848,117 @@ export class WorkflowRuntime {
919
848
  await this.queue.enqueue({ executionId, singletonKey: executionId });
920
849
  this.log.info(`execution ${executionId} resume enqueued`);
921
850
  }
851
+ /**
852
+ * Apply what an external system reported to the node that is waiting for it.
853
+ *
854
+ * The counterpart of {@link handleWebhook} for a run already under way: the
855
+ * host authenticates the caller however it likes, mounts whatever route it
856
+ * likes, and calls this. The SDK names no URL and checks no credential — what
857
+ * it owns is finding the gate, refusing a stale or repeated answer, and
858
+ * checking the body against the contract the author declared.
859
+ *
860
+ * No caller to authorize, by construction: a delivery carries no principal,
861
+ * so the host's middleware is the authorization and this is the system path.
862
+ * Answers with a {@link DeliveryOutcome} rather than throwing, because the
863
+ * sender has to decide from it whether to retry, stop, or fix its body.
864
+ */
865
+ async deliver(address, delivery) {
866
+ // The host streamed any files into storage while parsing the request, so
867
+ // they exist before this method can judge them. Anything but `applied`
868
+ // therefore hands them back — in one place, because there are six ways to
869
+ // decline and forgetting one leaks a blob per occurrence.
870
+ const outcome = await this.decideDelivery(address, delivery);
871
+ if (outcome.kind !== 'applied')
872
+ await this.discardDelivered(address, delivery);
873
+ return outcome;
874
+ }
875
+ /**
876
+ * Give back the files of a delivery that was not applied.
877
+ *
878
+ * The run's scope is looked up here rather than threaded out of the decision,
879
+ * because this only runs when there are files to reclaim — a declined
880
+ * delivery that carried none returns before asking, so the ordinary path
881
+ * costs nothing. When the run cannot be found there is no scope to pass, and
882
+ * the adapter falls back to validating the key alone, which is the right
883
+ * answer: nobody can say whose it was.
884
+ *
885
+ * Best-effort by contract: a storage failure here must not turn a clean
886
+ * `invalid` into a server error. A host that wants certainty sweeps for
887
+ * objects no run references.
888
+ */
889
+ async discardDelivered(address, delivery) {
890
+ const files = delivery.files;
891
+ if (!this.storage || !files || files.length === 0)
892
+ return;
893
+ const storage = this.storage;
894
+ const scope = await this.scopeOfExecution(address.executionId);
895
+ await Promise.all(files.map((f) => storage.delete(f.attachment, scope).catch((err) => {
896
+ this.log.warn(`could not discard ${f.attachment.name} after a declined delivery: ${String(err)}`);
897
+ })));
898
+ }
899
+ /** The tenant a run acts as, or undefined when the run is unknown. */
900
+ async scopeOfExecution(executionId) {
901
+ const exec = await this.persistence.getExecution(executionId);
902
+ if (!exec)
903
+ return undefined;
904
+ const workflow = await this.persistence.getWorkflow(exec.workflowId);
905
+ return workflow?.attributes;
906
+ }
907
+ async decideDelivery(address, delivery) {
908
+ const exec = await this.persistence.getExecution(address.executionId);
909
+ if (!exec)
910
+ return { kind: 'unknown' };
911
+ const workflow = await this.persistence.getWorkflow(exec.workflowId);
912
+ if (!workflow)
913
+ return { kind: 'unknown' };
914
+ const rows = await this.persistence.getStepRows(address.executionId);
915
+ const known = collectStepIds(readWorkflowConfig(workflow.config));
916
+ const resolved = resolveGate(address, exec.status, rows, known);
917
+ if (resolved.kind === 'outcome')
918
+ return resolved.outcome;
919
+ const row = resolved.row;
920
+ const data = row.data ? JSON.parse(row.data) : {};
921
+ // A gate that re-parks keeps the attempt it is on; an answer to the one
922
+ // before would otherwise be applied as if it were current.
923
+ const fence = data['fence'];
924
+ if (address.fence !== undefined && fence !== undefined && fence !== address.fence) {
925
+ return { kind: 'ignored', reason: 'superseded' };
926
+ }
927
+ // A gate takes one answer. The same delivery arriving twice is the sender
928
+ // retrying; a different one is a second answer, and neither replaces the
929
+ // first.
930
+ const already = data['delivery'];
931
+ if (already !== undefined || data['resumePayload'] !== undefined) {
932
+ const repeat = delivery.deliveryId !== undefined && already?.deliveryId === delivery.deliveryId;
933
+ return { kind: 'ignored', reason: repeat ? 'duplicate' : 'already_answered' };
934
+ }
935
+ // References merge straight in — there are no bytes here to move. A text
936
+ // field is re-read against the contract first, because multipart delivers
937
+ // every field as a string whatever the contract says it is.
938
+ const contract = data['contract'];
939
+ const coerced = delivery.encoding === 'multipart'
940
+ ? coerceTextFields(delivery.payload, contract)
941
+ : delivery.payload;
942
+ const payload = attachDeliveryFiles(coerced, delivery.files ?? [], contract);
943
+ const issues = checkAgainstContract(contract, payload);
944
+ if (issues.length > 0)
945
+ return { kind: 'invalid', issues };
946
+ data['delivery'] = {
947
+ payload,
948
+ receivedAt: new Date().toISOString(),
949
+ ...(delivery.deliveryId !== undefined ? { deliveryId: delivery.deliveryId } : {}),
950
+ };
951
+ await this.persistence.upsertStep(address.executionId, row.stepName, {
952
+ status: row.status,
953
+ executorType: row.executorType,
954
+ data: JSON.stringify(data),
955
+ attributes: workflow.attributes,
956
+ ...(row.category !== undefined ? { category: row.category } : {}),
957
+ });
958
+ await this.queue.enqueue({ executionId: address.executionId, singletonKey: address.executionId });
959
+ this.log.info(`delivery applied to ${address.executionId} at ${row.stepName}`);
960
+ return { kind: 'applied', nodePath: row.stepName };
961
+ }
922
962
  /**
923
963
  * Rerun a workflow from a specific step, using the source execution's
924
964
  * cached outputs for all prior steps. Creates a new execution.
@@ -964,7 +1004,7 @@ export class WorkflowRuntime {
964
1004
  const page = await this.persistence.listPendingWorkflows(filter, resolvePage(params));
965
1005
  const rows = await this.project(ctx, page.items, (wf) => this.workflowRef(wf));
966
1006
  const items = rows.map((wf) => {
967
- const config = parseWorkflowConfig(wf.config);
1007
+ const config = readWorkflowConfig(wf.config);
968
1008
  const name = parseWorkflowName(wf.metadata);
969
1009
  return {
970
1010
  workflowId: wf.id,
@@ -1439,6 +1479,32 @@ export class WorkflowRuntime {
1439
1479
  * workflowQueue.process((job) => runtime.processJob(job.data.executionId));
1440
1480
  * ```
1441
1481
  */
1482
+ /**
1483
+ * What the open gates of a parked run are waiting for: whether any already
1484
+ * has its answer, and the earliest clock among them.
1485
+ */
1486
+ async readGates(executionId) {
1487
+ const rows = await this.persistence.getStepRows(executionId);
1488
+ let answered = false;
1489
+ let wakeAt;
1490
+ for (const row of rows) {
1491
+ if ((row.status !== 'EXTERNAL_WAIT' && row.status !== 'REVIEW_WAIT') || !row.data)
1492
+ continue;
1493
+ let data;
1494
+ try {
1495
+ data = JSON.parse(row.data);
1496
+ }
1497
+ catch {
1498
+ continue;
1499
+ }
1500
+ if (data['resumePayload'] !== undefined || data['delivery'] !== undefined)
1501
+ answered = true;
1502
+ const at = typeof data['wakeAt'] === 'string' ? Date.parse(data['wakeAt']) : Number.NaN;
1503
+ if (!Number.isNaN(at) && (wakeAt === undefined || at < wakeAt))
1504
+ wakeAt = at;
1505
+ }
1506
+ return { answered, wakeAt };
1507
+ }
1442
1508
  async processJob(executionId) {
1443
1509
  const exec = await this.persistence.getExecution(executionId);
1444
1510
  if (!exec)
@@ -1466,26 +1532,25 @@ export class WorkflowRuntime {
1466
1532
  if (owner)
1467
1533
  this.publishRunChange(owner, executionId, final.status);
1468
1534
  if (final.status === 'EXTERNAL_WAIT') {
1469
- // Liveness (level-triggered): if a resume payload was routed to a gate
1470
- // *during* this pass — after the walk had already read that node's
1471
- // record — the gate is still EXTERNAL_WAIT but its record now carries an
1472
- // unconsumed `resumePayload`. Re-enqueue once so the next pass applies
1473
- // it. Consume-once (the walk marks the gate COMPLETED) prevents loops.
1474
- const rows = await this.persistence.getStepRows(executionId);
1475
- const hasUnconsumedGate = rows.some((r) => {
1476
- if ((r.status !== 'EXTERNAL_WAIT' && r.status !== 'REVIEW_WAIT') || !r.data) {
1477
- return false;
1478
- }
1479
- try {
1480
- return JSON.parse(r.data)['resumePayload'] !== undefined;
1481
- }
1482
- catch {
1483
- return false;
1484
- }
1485
- });
1486
- if (hasUnconsumedGate) {
1535
+ const gates = await this.readGates(executionId);
1536
+ // Liveness (level-triggered): an answer routed to a gate *during* this
1537
+ // pass, after the walk had read that node, leaves the gate parked with
1538
+ // an unconsumed one. Re-enqueue once so the next pass applies it;
1539
+ // consume-once (the walk marks the gate COMPLETED) prevents a loop.
1540
+ if (gates.answered) {
1487
1541
  await this.queue.enqueue({ executionId, singletonKey: executionId });
1488
- this.log.info(`execution ${executionId} re-enqueued (gate payload arrived mid-pass)`);
1542
+ this.log.info(`execution ${executionId} re-enqueued (answer arrived mid-pass)`);
1543
+ }
1544
+ else if (gates.wakeAt !== undefined) {
1545
+ // A gate's own clock — a delay, or an API call's deadline. The queue's
1546
+ // delay IS the timer; nothing sweeps. A pass that fires on a gate
1547
+ // which has since been answered simply re-parks, costing one walk.
1548
+ await this.queue.enqueue({
1549
+ executionId,
1550
+ singletonKey: executionId,
1551
+ delay: Math.max(0, gates.wakeAt - Date.now()),
1552
+ });
1553
+ this.log.info(`execution ${executionId} waking at ${new Date(gates.wakeAt).toISOString()}`);
1489
1554
  }
1490
1555
  return { status: 'paused', reason: 'Step requested pause' };
1491
1556
  }
@@ -1523,7 +1588,7 @@ export class WorkflowRuntime {
1523
1588
  const workflow = await this.persistence.getWorkflow(workflowId);
1524
1589
  if (!workflow || workflow.status !== 'ACTIVE')
1525
1590
  return null;
1526
- const config = parseWorkflowConfig(workflow.config);
1591
+ const config = readWorkflowConfig(workflow.config);
1527
1592
  if (!this.connectors.hasTrigger(config.trigger.type))
1528
1593
  return null;
1529
1594
  const trigger = this.connectors.getTrigger(config.trigger.type);
@@ -1734,7 +1799,7 @@ export class WorkflowRuntime {
1734
1799
  });
1735
1800
  return { kind: 'deferred', reason: `not due until ${exec.fireAt?.toISOString() ?? 'its fire time'}` };
1736
1801
  }
1737
- const config = parseWorkflowConfig(workflow.config);
1802
+ const config = readWorkflowConfig(workflow.config);
1738
1803
  if (!this.connectors.hasTrigger(config.trigger.type)) {
1739
1804
  return this.endScheduled(exec.id, 'CANCELLED', `trigger "${config.trigger.type}" is no longer registered`);
1740
1805
  }
@@ -1849,7 +1914,7 @@ export class WorkflowRuntime {
1849
1914
  // exist yet. The executor stamps the real one on every run.
1850
1915
  execution: { id: '' },
1851
1916
  steps: {},
1852
- vars: projectVariables(parseWorkflowConfig(workflow.config).variables),
1917
+ vars: projectVariables(readWorkflowConfig(workflow.config).variables),
1853
1918
  };
1854
1919
  }
1855
1920
  async createAndEnqueue(workflow, triggerPayload, opts) {