@powerhousedao/reactor-workflow 6.2.3-dev.84 → 6.2.3-dev.86

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.
package/README.md CHANGED
@@ -55,7 +55,7 @@ rather than restated here.
55
55
  Its `base64` is computed on first read, as upstream's getter is, so a piece
56
56
  that only reads `data` holds one copy of the file. A `streaming: true` FILE
57
57
  prop gets upstream's `ApStreamingFile` instead: `{ filename, extension,
58
- size, body }`, with `body` read from the staged file or the network.
58
+ size, body }`, with `body` read from the staged file or the network.
59
59
  - **Prop validation**, from the same place. Before an action's `run()` or any
60
60
  trigger hook but `onDisable`, a prop left unset takes its `defaultValue` and
61
61
  the coerced values go through the engine's `validateProperty`. A failure is
@@ -156,7 +156,7 @@ the sweeps and the supervisor are per process.
156
156
  with nobody running them. This is only for a host that never composed: one
157
157
  that lost the lease after composing stays without workflows until restart.
158
158
  - **The default owner is stable**: `<hostname>/<fingerprint of the journal's
159
- storage location>`. So one deployment slot restarting re-claims its OWN lease
159
+ storage location>`. So one deployment slot restarting re-claims its OWN lease
160
160
  once the killed process's heartbeat is stale (40s) rather than waiting out
161
161
  the whole TTL. A genuine second replica still differs
162
162
  by hostname or by the journal it points at. The storage location is hashed,
@@ -324,7 +324,9 @@ action at another version is the same block.
324
324
  ### The core piece
325
325
 
326
326
  The engine's own blocks are the built-in piece `@powerhousedao/piece-core`, in
327
- `src/pieces/core/`. Its actions are `branch` and `assert`; its triggers are
327
+ `src/pieces/core/`. Its actions are `branch`, `assert`, `delay`,
328
+ `approval` ("Request approval"), `stop` ("Stop run") and `waitForWebhook`
329
+ ("Respond and wait for webhook"); its triggers are
328
330
  `manual`, `schedule` and `webhook`. It is written with `createPiece`,
329
331
  `createAction` and `createTrigger`, and its version is this package's version.
330
332
 
@@ -339,6 +341,33 @@ The engine's own blocks are the built-in piece `@powerhousedao/piece-core`, in
339
341
  - `branch` and `assert` run through `ActivepiecesBlockExecutor` like any piece
340
342
  action, with the same resolution and journaling. `branch` leaves on `true`
341
343
  or `false` by its result.
344
+ - `delay` ("Delay for" an amount and unit, or "Delay until" a date) suspends
345
+ the run on a `DELAY` waitpoint and outputs `{ resumedAt }`; a time already
346
+ past does not wait. `approval` suspends it on a WEBHOOK waitpoint of kind
347
+ `approval` (title, Markdown details rendered when the run pauses, labels,
348
+ when a reason is required, approver DIDs, an optional expiry) and outputs
349
+ `{ approved, reason, decidedBy, decidedAt }` from the editor's decision
350
+ (`decidedAt` is when it was decided, not when the run resumed). It
351
+ gets no resume URL: a waiting step stops the leg, so no later step could send
352
+ one. To email a link, use Activepieces' approval pieces (Gmail's "Request
353
+ approval in email", or Create Approval Links then Wait for Approval). Both
354
+ throw in a single-step test, and both leave on `next`.
355
+ - `stop` ends the run `SUCCEEDED` without running the steps after it, through
356
+ the same path as `ctx.run.stop`. Its optional response (`responseType`
357
+ `json`, `raw` or `redirect`; `status`, `headers`, `body`, `text`,
358
+ `redirectUrl`) answers a held request; with none set it answers 200 with
359
+ `{}`, as `run.stop()` does. Its only port is `error`, so the editor offers
360
+ no step after it.
361
+ - `waitForWebhook` is Activepieces' "Respond and Wait for Next Webhook": it
362
+ suspends the run on a WEBHOOK waitpoint of kind `webhook` whose
363
+ `responseToSend` is the configured response (the same props as `stop`)
364
+ with the resume URL in the `x-resume-webhook-url` header and, for a JSON
365
+ object body unless `includeResumeUrl` is off, in a `resumeUrl` field. The
366
+ URL is the plain resume URL; a caller appends `/sync` to hold for the run's
367
+ answer. It outputs `{ resumeUrl }` while waiting and the resuming request's
368
+ `{ body, headers, queryParams }` after. `expiresAfter` and `expiresUnit`
369
+ end the run if nobody calls in time. It needs the host's
370
+ `waitpointBaseUrl`, throws in a single-step test, and leaves on `next`.
342
371
  - The triggers are fed by the host: `reactor/schedule.ts`, `reactor/webhook.ts`
343
372
  and the `fire` mutation. Their hooks are never called.
344
373
  - `manual` takes optional `inputs`, shaped after Activepieces' web form
@@ -430,17 +459,17 @@ at all enforces nothing, but only hand-built definitions lack one: `policy` is
430
459
  non-null in the workflow model since v1, so every workflow document, old or
431
460
  new, carries one.
432
461
 
433
- | Field | Where | Behaviour |
434
- | -------------------------- | ------------------------- | ----------------------------------------------------------------------------------------------------- |
435
- | `concurrency` | `reactor/run-gate.ts` | SINGLETON drops a firing while a run is active; QUEUE serialises; PARALLEL runs concurrently |
436
- | `maxParallelRuns` | `reactor/run-gate.ts` | Bounds PARALLEL; null is unbounded. SINGLETON and QUEUE are 1 by definition |
437
- | `runTimeoutSeconds` | `pieces/engine/coordinator.ts` | A run deadline from FIRING time, checked between steps and bounding every retry wait; expiry ends the run CANCELLED |
438
- | `defaultRetry`, step `retry` | `pieces/engine/retry.ts` | Attempts, backoff, delays and `retryOn`; attempts land on the step's journal row |
439
- | `onFailure` | `reactor/service.ts` | On a trigger's failed run: PARK parks the trigger; NOTIFY logs at error level; IGNORE does nothing. A failed manual run or rerun changes nothing |
440
- | `maxSuspensionDays` | — | **Not enforced**: nothing suspends. Waitpoints, `run.pause` and `generateResumeUrl` all throw |
441
- | `retainRunsDays` | — | **Not enforced** per workflow; `PH_WORKFLOWS_RUN_RETENTION_DAYS` is the journal-wide control |
442
- | `journalAsDocument` | — | **Not enforced**: the journal is relational, and there is no run document model |
443
- | step `idempotencyKeyExpression` | — | **Not enforced**: a fire dedupes on its trigger operation or a trigger item's `_dedupe_key` |
462
+ | Field | Where | Behaviour |
463
+ | ------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
464
+ | `concurrency` | `reactor/run-gate.ts` | SINGLETON drops a firing while a run is active; QUEUE serialises; PARALLEL runs concurrently |
465
+ | `maxParallelRuns` | `reactor/run-gate.ts` | Bounds PARALLEL; null is unbounded. SINGLETON and QUEUE are 1 by definition |
466
+ | `runTimeoutSeconds` | `pieces/engine/coordinator.ts` | A run deadline from FIRING time, checked between steps and bounding every retry wait; expiry ends the run CANCELLED |
467
+ | `defaultRetry`, step `retry` | `pieces/engine/retry.ts` | Attempts, backoff, delays and `retryOn`; attempts land on the step's journal row |
468
+ | `onFailure` | `reactor/service.ts` | On a trigger's failed run: PARK parks the trigger; NOTIFY logs at error level; IGNORE does nothing. A failed manual run or rerun changes nothing |
469
+ | `maxSuspensionDays` | `reactor/waitpoint-poller.ts` | A WEBHOOK waitpoint expires this long after it was created (sooner if its block says so); expiry of the one the run waits on ends the run CANCELLED with `WaitpointExpired`. A `DELAY` longer than this is refused when created |
470
+ | `retainRunsDays` | — | **Not enforced** per workflow; `PH_WORKFLOWS_RUN_RETENTION_DAYS` is the journal-wide control |
471
+ | `journalAsDocument` | — | **Not enforced**: the journal is relational, and there is no run document model |
472
+ | step `idempotencyKeyExpression` | — | **Not enforced**: a fire dedupes on its trigger operation or a trigger item's `_dedupe_key` |
444
473
 
445
474
  **Enforcing the policy changes every deployed workflow.** The model's initial
446
475
  values are `concurrency: QUEUE`, `onFailure: PARK` and
@@ -624,26 +653,26 @@ Everything the engine itself reads from the environment is prefixed
624
653
  — that manifest is the published surface a host reads, this table is the
625
654
  explanation behind it.
626
655
 
627
- | Variable | Default | What it sets |
628
- | ------------------------------------- | ------------------ | ----------------------------------------------------------------------------------------- |
629
- | `PH_WORKFLOWS_SECRETS_MASTER_KEY` | generated key file | 64 hex chars (32 bytes) encrypting connection secrets at rest (`reactor/secret-store.ts`) |
630
- | `PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES` | unset | Addresses or CIDRs a piece may reach, widening the default policy (`reactor/lib.ts`) |
631
- | `PH_WORKFLOWS_RUN_CONCURRENCY` | from the host | Most piece children at once (`worker/pool.ts`); unset, sized from the cores and memory, at most 32 |
632
- | `PH_WORKFLOWS_RUN_QUEUE_DEPTH` | `0` | Requests that may wait for a child before new ones are refused; `0` waits without limit |
633
- | `PH_WORKFLOWS_WORKER_MEMORY_MB` | `256` | Each child's V8 heap (`--max-old-space-size`); a child past 80% of it is retired |
634
- | `PH_WORKFLOWS_WORKER_MAX_REQUESTS` | `1000` | Requests a child serves before it is retired |
635
- | `PH_WORKFLOWS_WORKER_MIN` | `1` | Idle children kept warm; `0` lets every idle child exit |
636
- | `PH_WORKFLOWS_TRIGGER_SLOTS` | `1` | Children reserved for trigger hooks |
637
- | `PH_WORKFLOWS_RUNS_IN_FLIGHT` | 8 × the pool | Runs admitted at once across workflows (`reactor/run-dispatcher.ts`) |
638
- | `PH_WORKFLOWS_ADMIT_MAX_ELU` | `0.8` | Main-thread event-loop utilization above which no new run is admitted; one always runs |
639
- | `PH_WORKFLOWS_MAX_QUEUED_FIRINGS` | `100` | Firings of ONE workflow that may wait for its concurrency slot; past it a firing is journaled CANCELLED (`reactor/run-gate.ts`) |
640
- | `PH_WORKFLOWS_POLL_INTERVAL_MS` | `60000` | Cadence for a polling trigger that names none of its own |
641
- | `PH_WORKFLOWS_WEBHOOK_RECONCILE_MS` | `900000` | How often a webhook trigger re-registers with its provider |
642
- | `PH_WORKFLOWS_WEBHOOK_TIMEOUT_MS` | `30000` | How long a sync-mode delivery holds the provider's socket |
643
- | `PH_WORKFLOWS_PIECE_MAX_FILE_BYTES` | `8388608` | File-size ceiling for FILE-property hydration and `ctx.files.write` |
644
- | `PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS` | `10000` | Cap on one call a piece makes of its host; raised to the step's own timeout when that is longer, clipped to the step deadline (`activepieces/context/limits.ts`) |
645
- | `PH_WORKFLOWS_ATTACHMENT_CACHE_BYTES` | `1073741824` | Downloaded attachments kept on disk by content (`engine/attachment-cache.ts`); `0` is off |
646
- | `PH_WORKFLOWS_RUN_RETENTION_DAYS` | `30` | Deletes finished runs older than this many days; `0`/`off` keeps everything (`reactor/run-retention.ts`) |
656
+ | Variable | Default | What it sets |
657
+ | ------------------------------------- | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
658
+ | `PH_WORKFLOWS_SECRETS_MASTER_KEY` | generated key file | 64 hex chars (32 bytes) encrypting connection secrets at rest (`reactor/secret-store.ts`) |
659
+ | `PH_WORKFLOWS_EGRESS_ALLOW_ADDRESSES` | unset | Addresses or CIDRs a piece may reach, widening the default policy (`reactor/lib.ts`) |
660
+ | `PH_WORKFLOWS_RUN_CONCURRENCY` | from the host | Most piece children at once (`worker/pool.ts`); unset, sized from the cores and memory, at most 32 |
661
+ | `PH_WORKFLOWS_RUN_QUEUE_DEPTH` | `0` | Requests that may wait for a child before new ones are refused; `0` waits without limit |
662
+ | `PH_WORKFLOWS_WORKER_MEMORY_MB` | `256` | Each child's V8 heap (`--max-old-space-size`); a child past 80% of it is retired |
663
+ | `PH_WORKFLOWS_WORKER_MAX_REQUESTS` | `1000` | Requests a child serves before it is retired |
664
+ | `PH_WORKFLOWS_WORKER_MIN` | `1` | Idle children kept warm; `0` lets every idle child exit |
665
+ | `PH_WORKFLOWS_TRIGGER_SLOTS` | `1` | Children reserved for trigger hooks |
666
+ | `PH_WORKFLOWS_RUNS_IN_FLIGHT` | 8 × the pool | Runs admitted at once across workflows (`reactor/run-dispatcher.ts`) |
667
+ | `PH_WORKFLOWS_ADMIT_MAX_ELU` | `0.8` | Main-thread event-loop utilization above which no new run is admitted; one always runs |
668
+ | `PH_WORKFLOWS_MAX_QUEUED_FIRINGS` | `100` | Firings of ONE workflow that may wait for its concurrency slot; past it a firing is journaled CANCELLED (`reactor/run-gate.ts`) |
669
+ | `PH_WORKFLOWS_POLL_INTERVAL_MS` | `60000` | Cadence for a polling trigger that names none of its own |
670
+ | `PH_WORKFLOWS_WEBHOOK_RECONCILE_MS` | `900000` | How often a webhook trigger re-registers with its provider |
671
+ | `PH_WORKFLOWS_WEBHOOK_TIMEOUT_MS` | `30000` | How long a sync-mode delivery holds the provider's socket |
672
+ | `PH_WORKFLOWS_PIECE_MAX_FILE_BYTES` | `8388608` | File-size ceiling for FILE-property hydration and `ctx.files.write` |
673
+ | `PH_WORKFLOWS_HOST_CALL_TIMEOUT_MS` | `10000` | Cap on one call a piece makes of its host; raised to the step's own timeout when that is longer, clipped to the step deadline (`activepieces/context/limits.ts`) |
674
+ | `PH_WORKFLOWS_ATTACHMENT_CACHE_BYTES` | `1073741824` | Downloaded attachments kept on disk by content (`engine/attachment-cache.ts`); `0` is off |
675
+ | `PH_WORKFLOWS_RUN_RETENTION_DAYS` | `30` | Deletes finished runs older than this many days; `0`/`off` keeps everything (`reactor/run-retention.ts`) |
647
676
  | `PH_WORKFLOWS_SINGLETON_OWNER` | `<host>/<journal hash>` | Names this process as the workflow singleton's owner; the default is stable per slot, so a restart re-claims once the old heartbeat is stale (`reactor/singleton-lease.ts`) |
648
677
 
649
678
  Each numeric one parses as `Number(raw) || default`: a value that is not a
@@ -832,6 +861,8 @@ step returns. Directories a crashed host left behind are swept at startup.
832
861
  the step's directory under the ceiling. After the step the host ingests each
833
862
  file, hashing and uploading it from disk, and refuses any path the step did
834
863
  not write: outside its directory, a symlink or a hard link.
864
+ `ctx.files.upload` stages the same way, but the host ingests the file during
865
+ the call, over the host-call channel, and returns the ref.
835
866
  - **Who may read.** A run reads the refs its own steps wrote, and the refs its
836
867
  journaled steps already held on a rerun or a step test. Anything else is the
837
868
  host's call (`canReadAttachmentRef`), made against the documents the run was
@@ -928,10 +959,72 @@ releases what an earlier enable registered. The reason reads
928
959
  action's default retry (3 attempts, exponential from 5s) unless the action
929
960
  declares a `defaultRetry`. `continueOnFailure` is ignored.
930
961
  - `test` is never called.
962
+ - `run.canPause` is `true` in a run and `false` in a single-step test, where
963
+ `createWaitpoint`, `waitForWaitpoint` and `run.pause` throw.
964
+ - `createWaitpoint`, `waitForWaitpoint` and the deprecated `run.pause` (both
965
+ pause shapes) suspend the run (#3218): the step and run go `WAITING` and
966
+ the run gives up its worker, its admission slot and its `concurrency`
967
+ slot. A resume goes through admission again, re-runs the waiting step as
968
+ `RESUME` with `resumePayload`, and gets a fresh `runTimeoutSeconds`.
969
+ - A step has at most one live waitpoint, as upstream: a second
970
+ `createWaitpoint` in the step, a retry of it, or a retry of a create whose
971
+ answer was lost gets the same waitpoint and resume URL, already resolved if
972
+ its resume came before the step paused. Once the step resumes, it can wait
973
+ again on a new one. Only the hash of a resume URL's token is stored, so the
974
+ URL is re-issued only within the leg that minted it; a step that would get a
975
+ live waitpoint from an earlier leg fails instead (unreachable today).
976
+ - A waiting run resumes on the waitpoint its step waits on, or on a WEBHOOK
977
+ link a step that succeeded created (Create Approval Links, then Wait for
978
+ Approval), as upstream. When the run starts waiting, the waitpoints of
979
+ steps that failed close `CANCELLED`; when it resumes on such a link, the
980
+ waitpoint its step waited on closes. Only the expiry of the waitpoint it
981
+ waits on ends the run; a link that expires just closes. A resume already
982
+ delivered wins over that expiry.
983
+ - Every end of a run (succeeded, failed, cancelled, expired, or failed by the
984
+ orphan sweep) closes its waitpoints and fails its waiting step. A resume
985
+ URL of a closed waitpoint, or of a run that has ended, answers `gone`, and
986
+ the editor refuses to resolve it.
987
+ - One poller on the singleton owner wakes due `DELAY` waitpoints and expires
988
+ overdue ones, in batches, on a single timer armed for the next due time
989
+ (re-checked at least every five minutes). An expiry and the run it ends are
990
+ one transaction. Each pass also ends, `CANCELLED` with `WaitpointNotLive`,
991
+ a WAITING run whose waitpoint closed without ending it.
992
+ - Not yet: a run left `RUNNING` by a crash after it resumed is failed, not
993
+ resumed (#3224).
994
+ - A run resumed on a definition that was re-published meanwhile rebuilds it
995
+ by replaying the workflow's global operations below the revision it pinned,
996
+ from the latest `UPGRADE_DOCUMENT` snapshot, without denied or undone
997
+ operations. This is not the reactor's own rebuild (keyframes, upgrade
998
+ transitions); when the result does not hash to the pin, the leg fails.
999
+ - A WEBHOOK waitpoint needs the host's `waitpointBaseUrl`; without it
1000
+ `createWaitpoint({ type: "WEBHOOK" })` throws.
1001
+ - A resumed run reads steps journaled before it waited from the journal: a
1002
+ truncated or redacted output is unavailable to later steps, and a document
1003
+ output is its reference, not the document.
931
1004
  - `requireAuth` defaults to `false` in the descriptor; upstream defaults to
932
1005
  `true`.
933
- - `run.stop`, `run.respond`, `run.pause`, waitpoints and `generateResumeUrl`
934
- throw.
1006
+ - `run.respond` and `run.stop` answer the request the run holds: a
1007
+ `responseMode: "sync"` webhook delivery, or a `POST <resumeUrl>/sync` for
1008
+ the leg it resumed. The first answer wins and later ones are ignored; within
1009
+ a step the last of `respond`, `stop` and `waitForWaitpoint` wins, as
1010
+ upstream. The answer goes out when the step returns, with status 200 and
1011
+ body `{}` by default; a string body goes as text, anything else as JSON, and
1012
+ `set-cookie` and framing headers are dropped. The answer is served on the
1013
+ host's origin, so it always carries `x-content-type-options: nosniff` and
1014
+ `content-security-policy: sandbox`, over any the step sets: a step's HTML
1015
+ renders without scripts or the origin's cookies. Unlike upstream, any step may
1016
+ answer, not only one of the trigger's piece. `run.stop` ends the run
1017
+ `SUCCEEDED` and skips the steps after it.
1018
+ - A run that pauses answers the held request with its waitpoint's
1019
+ `responseToSend`; without one, a sync webhook answers 202 with the run's
1020
+ status. A `/sync` resume is held up to `PH_WORKFLOWS_WEBHOOK_TIMEOUT_MS`
1021
+ (504 after), and answered with the run's status when the leg ends or waits
1022
+ without responding. One whose waitpoint closes, or whose run ends, before a
1023
+ leg resumes on it (including a resume that fails to start) answers 409 with
1024
+ the run's status and error.
1025
+ - The deprecated `generateResumeUrl` links to the waitpoint the step's
1026
+ deprecated `run.pause` creates (one link per step). A step that pauses some
1027
+ other way, or that already made a waitpoint, leaves that link dead.
935
1028
  - `connections.get`, `tags`, `server`, `agent` and `flows.list` throw.
936
1029
  - `ctx.store` checks the key length on `put` only; `get` and `delete` of an
937
1030
  over-long key answer as if it were absent.
@@ -943,6 +1036,9 @@ releases what an earlier enable registered. The reason reads
943
1036
 
944
1037
  - Trigger hooks cannot read `attachment://` refs, and a trigger's
945
1038
  `ctx.files.write` returns an inline data URI rather than a ref.
1039
+ - `ctx.files.upload` returns the attachment ref as both `id` and `url`; the
1040
+ `url` is not an HTTP URL. In a trigger hook both are the inline data URI.
1041
+ Without an attachment store an action's call throws.
946
1042
  - A webhook body that is not JSON or form data is decoded as UTF-8 text, so
947
1043
  binary and multipart deliveries are corrupted.
948
1044
  - A step cannot read back a file it wrote: its `apfile://` token only becomes
@@ -989,7 +1085,7 @@ A case this engine is known to fail runs as `it.fails` and names the issue that
989
1085
  fixes it; never edit those files by hand. To regenerate them:
990
1086
 
991
1087
  ```sh
992
- pnpm --filter @powerhousedao/pieces-framework sync-upstream -- --tag 0.91.0 --from <activepieces checkout>
1088
+ pnpm --filter @powerhousedao/pieces-framework sync-upstream -- --tag 0.92.3 --from <activepieces checkout>
993
1089
  ```
994
1090
 
995
1091
  ## Design documents
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
- import { C as PropertySettingDef, E as ReactorTap, F as BlockMatch, I as BlockResolution, L as PieceOrigin, M as EgressPolicy, T as WorkflowRunResult, b as WorkflowTelemetry, f as SecretStat, g as ModelManifestSource, h as IPieceWorker, i as ReplayedStep, k as PieceResolver, l as ConnectionRequest, n as packagePieces, p as SecretStore, r as CORE_PIECE_NAME, s as AttachmentPort, t as PieceRegistry, v as PieceWorkerResult, w as StepExecutionRecord, x as WorkflowTelemetryOptions, y as TELEMETRY_SCOPE } from "./piece-registry-ByALLpvA.js";
1
+ import { C as PropertySettingDef, E as ReactorTap, F as BlockMatch, I as BlockResolution, L as PieceOrigin, M as EgressPolicy, T as WorkflowRunResult, b as WorkflowTelemetry, f as SecretStat, g as ModelManifestSource, h as IPieceWorker, i as ReplayedStep, k as PieceResolver, l as ConnectionRequest, n as packagePieces, p as SecretStore, r as CORE_PIECE_NAME, s as AttachmentPort, t as PieceRegistry, v as PieceWorkerResult, w as StepExecutionRecord, x as WorkflowTelemetryOptions, y as TELEMETRY_SCOPE } from "./piece-registry-C1Pc0hD6.js";
2
2
  import { ActionBase, IndexQueryRequest, IndexQueryResult, TriggerBase } from "@powerhousedao/pieces-framework";
3
3
  import { ILogger, OperationWithContext } from "document-model";
4
4
  import "@powerhousedao/pieces-framework/workflow";
5
5
  import { BlockIdentity, BlockRef } from "@powerhousedao/pieces-framework/block-type";
6
- import "@powerhousedao/workflow/document-models/workflow";
7
6
  import { AttachmentRef, BaseReadModel, DocumentViewDatabase, IConsistencyTracker, IOperationIndex, IReactorClient, IWriteCache, ModelManifestEntry, ReadModelRegistrationStage } from "@powerhousedao/reactor";
7
+ import "@powerhousedao/workflow/document-models/workflow";
8
8
  import { AuthSubject, Principal } from "@powerhousedao/shared/document-model";
9
9
  import { IRelationalDb, IWebhookScope, WebhookField, WebhookHashAlgorithm, WebhookPolicy, WebhookReply, WebhookRequest, WebhookSignatureEncoding } from "@powerhousedao/shared/processors";
10
10
  //#region src/pieces/core/version.d.ts
@@ -197,6 +197,7 @@ interface WorkflowRuntimeHostDeps {
197
197
  modelManifest?(): ModelManifestEntry[];
198
198
  modelEntries?(documentType: string): ModelManifestEntry[];
199
199
  webhooks?: IWebhookScope;
200
+ waitpointBaseUrl?: string;
200
201
  attachments?: AttachmentClientLike;
201
202
  canReadAttachmentRef?(request: AttachmentReadRequest): Promise<boolean>;
202
203
  secrets?: SecretStore;
@@ -19008,10 +19009,43 @@ interface WorkflowParkRow {
19008
19009
  reason: string;
19009
19010
  parked_at: string;
19010
19011
  }
19012
+ interface RunPinRow {
19013
+ definition_hash: string | null;
19014
+ definition_op_index: number | null;
19015
+ definition_scope_hash: string | null;
19016
+ }
19017
+ type NullableColumn<T> = ColumnType<T | null, T | null | undefined, T | null>;
19018
+ interface WaitpointRow {
19019
+ id: string;
19020
+ run_id: string;
19021
+ workflow_id: string;
19022
+ step_id: string;
19023
+ step_key: string;
19024
+ step_path: string;
19025
+ piece_name: string;
19026
+ block_name: string;
19027
+ type: string;
19028
+ kind: string;
19029
+ status: string;
19030
+ token_hash: string | null;
19031
+ created_at: string;
19032
+ resume_at: string | null;
19033
+ expires_at: string | null;
19034
+ resolved_at: string | null;
19035
+ decided_by: string | null;
19036
+ approval: string | null;
19037
+ resume_payload: string | null;
19038
+ response_to_send: string | null;
19039
+ }
19011
19040
  interface WorkflowRuntimeDB {
19012
19041
  run: RunRow & {
19013
19042
  admit_attempts: ColumnType<number, number | undefined, number>;
19043
+ definition_hash: NullableColumn<string>;
19044
+ definition_op_index: NullableColumn<number>;
19045
+ definition_scope_hash: NullableColumn<string>;
19046
+ waiting_on: NullableColumn<string>;
19014
19047
  };
19048
+ waitpoint: WaitpointRow;
19015
19049
  step_execution: StepExecutionRow;
19016
19050
  run_document: RunDocumentRow;
19017
19051
  trigger_state: TriggerStateRow;
@@ -19023,6 +19057,11 @@ interface WorkflowRuntimeDB {
19023
19057
  applied_at: string;
19024
19058
  };
19025
19059
  }
19060
+ interface EndedWait {
19061
+ runId: string;
19062
+ reason: string;
19063
+ closed: string[];
19064
+ }
19026
19065
  interface ErasedRuns {
19027
19066
  runs: number;
19028
19067
  steps: number;
@@ -19066,6 +19105,8 @@ declare class WorkflowRunStore {
19066
19105
  private readonly unmigrated;
19067
19106
  private readonly runsInFlight;
19068
19107
  private readonly journaledSteps;
19108
+ private readonly pausingRuns;
19109
+ private readonly resumedLegs;
19069
19110
  private constructor();
19070
19111
  static create(relationalDb: IRelationalDb): Promise<WorkflowRunStore>;
19071
19112
  hasUnmigratedTriggerState(workflowId: string): boolean;
@@ -19083,7 +19124,8 @@ declare class WorkflowRunStore {
19083
19124
  * passed its `runTimeoutSeconds`. Separate from `failRun` because a
19084
19125
  * CANCELLED run is not rerunnable and must not read as a workflow defect.
19085
19126
  */
19086
- cancelRun(runId: string, reason: string): Promise<void>;
19127
+ cancelRun(runId: string, reason: string): Promise<string[]>;
19128
+ private endLiveRun;
19087
19129
  enqueueRun(options: EnqueueRunOptions): Promise<string>;
19088
19130
  private unmarkOnFailure;
19089
19131
  /**
@@ -19160,13 +19202,17 @@ declare class WorkflowRunStore {
19160
19202
  beginRun(runId: string, details: {
19161
19203
  workflowName: string;
19162
19204
  workflowVersion: number;
19163
- }): Promise<void>;
19205
+ }): Promise<boolean>;
19164
19206
  startRun(options: StartRunOptions): Promise<string>;
19165
19207
  recordStep(runId: string, ordinal: number, step: StepExecutionRecord): Promise<void>;
19166
19208
  private sweepIsNoop;
19167
- finishRun(runId: string, result: WorkflowRunResult, executionOrder?: ReadonlyMap<string, number>): Promise<void>;
19209
+ finishRun(runId: string, result: WorkflowRunResult, executionOrder?: ReadonlyMap<string, number>, pin?: RunPinRow): Promise<{
19210
+ held: boolean;
19211
+ closed: string[];
19212
+ }>;
19168
19213
  private sweepSteps;
19169
- failRun(runId: string, error: string, errorName?: string): Promise<void>;
19214
+ private withRunRow;
19215
+ failRun(runId: string, error: string, errorName?: string): Promise<string[]>;
19170
19216
  listRuns(workflowId?: string | string[], limit?: number, options?: ListRunsOptions): Promise<RunRow[]>;
19171
19217
  getRun(id: string): Promise<RunRow | undefined>;
19172
19218
  getSteps(runId: string): Promise<StepExecutionRow[]>;
@@ -19203,6 +19249,45 @@ declare class WorkflowRunStore {
19203
19249
  recordPollFailure(workflowId: string, error: string, nowIso: string, nextPollAtIso: string, consecutiveFailures: number): Promise<void>;
19204
19250
  claimDedupe(workflowId: string, dedupeKey: string, ttlMs: number, nowIso: string): Promise<boolean>;
19205
19251
  deleteDedupe(workflowId: string): Promise<void>;
19252
+ createWaitpoint(row: WaitpointRow): Promise<{
19253
+ waitpoint: WaitpointRow;
19254
+ created: boolean;
19255
+ }>;
19256
+ getWaitpoint(id: string): Promise<WaitpointRow | undefined>;
19257
+ getWaitpointByTokenHash(tokenHash: string): Promise<WaitpointRow | undefined>;
19258
+ completeWaitpoint(id: string, resolution: {
19259
+ payload: unknown;
19260
+ decidedBy?: string | null;
19261
+ resolvedAt?: string;
19262
+ }): Promise<WaitpointRow | undefined>;
19263
+ claimDueDelayWaitpoints(nowIso: string, limit: number): Promise<WaitpointRow[]>;
19264
+ expireDueWaitpoints(nowIso: string, limit: number): Promise<{
19265
+ expired: WaitpointRow[];
19266
+ ended: EndedWait[];
19267
+ }>;
19268
+ endStrandedWaits(limit: number): Promise<EndedWait[]>;
19269
+ nextExpiry(): Promise<string | undefined>;
19270
+ countWaitingRuns(): Promise<number>;
19271
+ nextDelayDue(): Promise<string | undefined>;
19272
+ hasCompletedWaitpoint(runId: string): Promise<boolean>;
19273
+ heldRunIds(): Promise<string[]>;
19274
+ isRunInFlight(runId: string): boolean;
19275
+ claimWaitingRun(runId: string): Promise<boolean>;
19276
+ returnToWaiting(runId: string): Promise<void>;
19277
+ consumeCompletedWaitpoint(runId: string): Promise<{
19278
+ waitpoint: WaitpointRow;
19279
+ closed: string[];
19280
+ } | undefined>;
19281
+ getRunPin(runId: string): Promise<RunPinRow | undefined>;
19282
+ cancelIdleRun(runId: string, reason: string): Promise<string | undefined>;
19283
+ endWait(runId: string, end: {
19284
+ status: "CANCELLED" | "FAILED";
19285
+ reason: string;
19286
+ errorName: string;
19287
+ waitpoints: "EXPIRED" | "CANCELLED";
19288
+ }): Promise<string[]>;
19289
+ listWaitpointsForRuns(runIds: string[]): Promise<Map<string, WaitpointRow[]>>;
19290
+ listWaitingRuns(workflowId: string | string[] | undefined, limit: number): Promise<RunRow[]>;
19206
19291
  pruneFinishedRuns(cutoffIso: string, batchSize?: number): Promise<number>;
19207
19292
  eraseRunsForDocuments(documentIds: string[]): Promise<ErasedRuns>;
19208
19293
  pruneDedupe(cutoffIso: string): Promise<number>;
@@ -19392,9 +19477,69 @@ declare class TriggerSupervisor {
19392
19477
  private failRefused;
19393
19478
  }
19394
19479
  //#endregion
19480
+ //#region src/reactor/waitpoint-types.d.ts
19481
+ type WaitpointType = "DELAY" | "WEBHOOK";
19482
+ type WaitpointStatus = "PENDING" | "COMPLETED" | "CONSUMED" | "EXPIRED" | "CANCELLED";
19483
+ type WaitpointKind = "approval" | "webhook" | "delay";
19484
+ type ReasonRequiredOn = "none" | "reject" | "both";
19485
+ interface ApprovalRequest {
19486
+ title: string;
19487
+ body: string | null;
19488
+ approveLabel: string;
19489
+ rejectLabel: string;
19490
+ reasonRequiredOn: ReasonRequiredOn;
19491
+ approvers: string[];
19492
+ }
19493
+ interface WaitpointResumePayload {
19494
+ body?: unknown;
19495
+ headers?: Record<string, string>;
19496
+ queryParams?: Record<string, string>;
19497
+ }
19498
+ interface WaitpointDescription {
19499
+ workflowName: string;
19500
+ stepName: string;
19501
+ status: WaitpointStatus;
19502
+ workflowDescription?: string;
19503
+ actionName?: string;
19504
+ waitingSince: string;
19505
+ expiresAt?: string;
19506
+ startedAt?: string;
19507
+ triggerName?: string;
19508
+ }
19509
+ interface WaitpointRecord {
19510
+ id: string;
19511
+ runId: string;
19512
+ workflowId: string;
19513
+ stepId: string;
19514
+ stepKey: string;
19515
+ stepPath: string;
19516
+ pieceName: string;
19517
+ blockName: string;
19518
+ type: WaitpointType;
19519
+ kind: WaitpointKind;
19520
+ status: WaitpointStatus;
19521
+ createdAt: string;
19522
+ resumeAt: string | null;
19523
+ expiresAt: string | null;
19524
+ resolvedAt: string | null;
19525
+ decidedBy: string | null;
19526
+ approval: ApprovalRequest | null;
19527
+ }
19528
+ interface ResolveWaitpointInput {
19529
+ approved: boolean;
19530
+ reason?: string;
19531
+ }
19532
+ interface WaitingRunsArgs {
19533
+ driveId?: string;
19534
+ workflowId?: string;
19535
+ first?: number;
19536
+ }
19537
+ export declare const WAITPOINT_EXPIRED_ERROR_NAME = "WaitpointExpired";
19538
+ export declare const WAITPOINT_NOT_LIVE_ERROR_NAME = "WaitpointNotLive";
19539
+ //#endregion
19395
19540
  //#region src/reactor/service.d.ts
19396
19541
  /** Why a firing was journaled CANCELLED without running, when it was. */
19397
- type FiringRefusal = "parked" | "singleton" | "stale" | "queue-full" | "expired";
19542
+ type FiringRefusal = "parked" | "singleton" | "stale" | "queue-full" | "expired" | "cancelled";
19398
19543
  type PersistedRunResult = WorkflowRunResult & {
19399
19544
  runId: string | null;
19400
19545
  refusal?: FiringRefusal;
@@ -19731,6 +19876,8 @@ export declare class WorkflowRuntimeService {
19731
19876
  private dispatcher;
19732
19877
  fire(workflowId: string, triggerPayload?: unknown, triggerKind?: string, resume?: RunResume, ctx?: WorkflowCaller, enqueuedRunId?: string): Promise<PersistedRunResult>;
19733
19878
  private runFired;
19879
+ private executeLeg;
19880
+ private endUnheldWait;
19734
19881
  private readonly runGate;
19735
19882
  private readonly unsettledFirings;
19736
19883
  private readonly runLimits;
@@ -19747,6 +19894,9 @@ export declare class WorkflowRuntimeService {
19747
19894
  private pollHeld;
19748
19895
  private settleFiring;
19749
19896
  private readonly heldReplies;
19897
+ private readonly runResponders;
19898
+ private readonly queuedReplies;
19899
+ private readonly syncResumes;
19750
19900
  /** Why a trigger's firing of a PARKED workflow is refused; undefined when
19751
19901
  * it is not parked, or when an operator started the run. */
19752
19902
  private parkedFiring;
@@ -19782,6 +19932,63 @@ export declare class WorkflowRuntimeService {
19782
19932
  private applyFailureMode;
19783
19933
  rerun(runId: string, ctx?: WorkflowCaller): Promise<PersistedRunResult>;
19784
19934
  private rereads;
19935
+ private readonly resuming;
19936
+ private readonly definitionHashes;
19937
+ /** Our hash of the runnable definition: computed once per published version. */
19938
+ private definitionHash;
19939
+ private waitpointPort;
19940
+ /** Re-enters a WAITING run that holds a COMPLETED waitpoint, through the
19941
+ * dispatcher. Whoever writes second, the resume or the WAITING, delivers. */
19942
+ private deliverHeld;
19943
+ private answerNotWaiting;
19944
+ private readonly waitpointPoller;
19945
+ private unobserveSuspended?;
19946
+ /** Test hook: one waitpoint poll pass now; a no-op until the supervisor starts. */
19947
+ pollWaitpointsNow(): Promise<void>;
19948
+ private startWaitpointPoller;
19949
+ private stopWaitpointPoller;
19950
+ private answerHeldResumes;
19951
+ private answerClosed;
19952
+ private heldResume;
19953
+ private answerUnresumed;
19954
+ private deliverAllHeld;
19955
+ private resumeRun;
19956
+ private runResumed;
19957
+ private answerShutDown;
19958
+ private resumePolicy;
19959
+ private resumeStopped;
19960
+ private pinnedState;
19961
+ private rebuildWorkflowState;
19962
+ /** Resolves a WEBHOOK waitpoint from the editor, as the calling DID. */
19963
+ resolveWaitpoint(waitpointId: string, input: ResolveWaitpointInput, ctx?: WorkflowCaller): Promise<WaitpointRecord>;
19964
+ /** A POST to a resume URL. Single-use: only a PENDING waitpoint resumes. */
19965
+ resumeWaitpointByToken(token: string, payload: WaitpointResumePayload): Promise<{
19966
+ status: "resumed" | "already" | "gone";
19967
+ }>;
19968
+ /** A POST to a resume URL's `/sync`, held like a sync webhook until the
19969
+ * resumed leg responds, waits, ends, or times out. The first answer wins. */
19970
+ resumeWaitpointByTokenSync(token: string, payload: WaitpointResumePayload, options?: {
19971
+ timeoutMs?: number;
19972
+ }): Promise<{
19973
+ status: "resumed" | "already" | "gone";
19974
+ reply?: WebhookReply;
19975
+ }>;
19976
+ private holdSyncResume;
19977
+ private resumeByToken;
19978
+ /** What a resume URL's confirm page shows. */
19979
+ describeWaitpointByToken(token: string): Promise<WaitpointDescription | undefined>;
19980
+ private workflowStateForPage;
19981
+ private blockDisplayName;
19982
+ /** The waitpoints of one run, for a caller who may read the run. */
19983
+ waitpointsForRun(runId: string, ctx?: WorkflowCaller): Promise<WaitpointRecord[]>;
19984
+ /** WAITING runs this caller may read, oldest first, with their waitpoints. */
19985
+ waitingRuns(args: WaitingRunsArgs, ctx?: WorkflowCaller): Promise<Array<{
19986
+ run: RunRecord;
19987
+ waitpoints: WaitpointRecord[];
19988
+ }>>;
19989
+ /** Cancels a WAITING or PENDING run; its waitpoints stop resuming. */
19990
+ cancelRun(runId: string, ctx?: WorkflowCaller): Promise<RunRecord>;
19991
+ private callerDid;
19785
19992
  testStep(workflowId: string, stepId: string, ctx?: WorkflowCaller, access?: WorkflowAccessOptions): Promise<StepTestResult>;
19786
19993
  private testScope;
19787
19994
  private readReferencedDocuments;
@@ -19791,6 +19998,9 @@ export declare class WorkflowRuntimeService {
19791
19998
  blockResolutions(workflowId: string, ctx?: WorkflowCaller): Promise<BlockResolutionRecord[]>;
19792
19999
  private draftOf;
19793
20000
  }
20001
+ export declare const WORKFLOW_DISABLED_ERROR_NAME = "WorkflowDisabled";
20002
+ export declare const WORKFLOW_PARKED_ERROR_NAME = "WorkflowParked";
20003
+ export declare function waitpointRecord(row: WaitpointRow): WaitpointRecord;
19794
20004
  /** The runtime a host composes: one instance, its lifetime the host's. */
19795
20005
  export declare function createWorkflowRuntime(deps: WorkflowRuntimeHostDeps): WorkflowRuntimeService;
19796
20006
  //#endregion
@@ -19974,6 +20184,6 @@ interface WebhookPayload {
19974
20184
  body: unknown;
19975
20185
  }
19976
20186
  //#endregion
19977
- export { type AcquireSingletonOptions, type AttachmentClientLike, type AttachmentReadRequest, type BlockResolutionRecord, CORE_PIECE_NAME, type ConnectionCheckResult, type ConnectionSummary, type HostIdentity, type OAuthAppClient, type OAuthAppDefinition, type OAuthAppRegistry, type OAuthAppRelay, type OAuthAttemptStatus, type OAuthAttemptView, type OAuthClientKind, type OAuthSignIn, type OAuthStart, type OutputTree, type OutputTreeNode, type PersistedRunResult, PieceRegistry, type PieceStoreRow, type PieceTriggerBinding, type RunPage, type RunRecord, type RunRow, type RunsArgs, type RunsPageArgs, type ScheduleTriggerBinding, type StepExecutionRow, type StepTestResult, TELEMETRY_SCOPE, type TriggerBinding, type TriggerDedupeRow, type TriggerStateRow, type WebhookConfig, type WebhookPayload, type WorkflowAccessOptions, type WorkflowCaller, type WorkflowHealth, type WorkflowHealthReader, type WorkflowRuntimeDB, type WorkflowRuntimeHostDeps, type WorkflowSingletonLease, type WorkflowSingletonLoss, type WorkflowTelemetryOptions, packagePieces };
20187
+ export { type AcquireSingletonOptions, type ApprovalRequest, type AttachmentClientLike, type AttachmentReadRequest, type BlockResolutionRecord, CORE_PIECE_NAME, type ConnectionCheckResult, type ConnectionSummary, type HostIdentity, type OAuthAppClient, type OAuthAppDefinition, type OAuthAppRegistry, type OAuthAppRelay, type OAuthAttemptStatus, type OAuthAttemptView, type OAuthClientKind, type OAuthSignIn, type OAuthStart, type OutputTree, type OutputTreeNode, type PersistedRunResult, PieceRegistry, type PieceStoreRow, type PieceTriggerBinding, type ReasonRequiredOn, type ResolveWaitpointInput, type RunPage, type RunPinRow, type RunRecord, type RunRow, type RunsArgs, type RunsPageArgs, type ScheduleTriggerBinding, type StepExecutionRow, type StepTestResult, TELEMETRY_SCOPE, type TriggerBinding, type TriggerDedupeRow, type TriggerStateRow, type WaitingRunsArgs, type WaitpointDescription, type WaitpointKind, type WaitpointRecord, type WaitpointResumePayload, type WaitpointRow, type WaitpointStatus, type WaitpointType, type WebhookConfig, type WebhookPayload, type WorkflowAccessOptions, type WorkflowCaller, type WorkflowHealth, type WorkflowHealthReader, type WorkflowRuntimeDB, type WorkflowRuntimeHostDeps, type WorkflowSingletonLease, type WorkflowSingletonLoss, type WorkflowTelemetryOptions, packagePieces };
19978
20188
  export {};
19979
20189
  //# sourceMappingURL=index.d.ts.map