@proofoftech/flowsafe 0.22.0 → 0.23.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.
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // RunnerRuntime hosts Mastra workflow execution against injected storage.
3
- // It is deliberately environment-free: the Durable Object shell feeds it
3
+ // It is environment-free: the Durable Object shell feeds it
4
4
  // D1-backed storage; tests feed it InMemoryStore. Durability comes from
5
5
  // Mastra's own snapshot persistence — createRun() writes the initial
6
6
  // snapshot, the engine persists after each step boundary, and resume()
@@ -58,9 +58,8 @@ export class RunNotSuspendedError extends Error {
58
58
  * An authoritative run-state read did not succeed, so nothing that read
59
59
  * returned is evidence about the run. One cause is Mastra answering from its
60
60
  * in-memory fallback instead of from storage — what comes back then describes
61
- * the Run object this isolate happens to hold rather than what is persisted —
62
- * and the run object's alarm raises it for any other failed read too, carrying
63
- * the underlying fault as `cause`. Distinct from UnknownRunError: the run may
61
+ * the Run object this isolate happens to hold rather than what is persisted.
62
+ * Distinct from UnknownRunError: the run may
64
63
  * well exist and be suspended — nothing about it could be READ. The message
65
64
  * therefore names no cause: it is minted where the read failed, not where the
66
65
  * reason is known.
@@ -90,14 +89,10 @@ export class InvalidRunRequestError extends Error {
90
89
  this.name = 'InvalidRunRequestError';
91
90
  }
92
91
  }
93
- // PATH_SAFE_ID_PATTERN validates runId and workflowId (full rationale lives on
94
- // the leaf module). runId is validated at start() (client input →
95
- // InvalidRunRequestError); workflowId is developer-controlled and validated at
96
- // register() (programming error → plain Error).
97
92
  // Core surfaces input/resume-schema violations and wrong-step selections as
98
93
  // untyped Errors. Message matching is brittle, so it is scoped to choosing
99
94
  // the HTTP-facing error class only; anything unmatched propagates unchanged
100
- // (a 500 at the DO boundary, same as before classification existed).
95
+ // (a 500 at the DO boundary).
101
96
  const CLIENT_ERROR_MARKERS = [
102
97
  'Invalid input',
103
98
  'Invalid resume data',
@@ -229,7 +224,7 @@ function resolveResumeStep(step, state) {
229
224
  }
230
225
  // The live attempt for a step. Repeated steps (foreach) store an array of
231
226
  // attempts, so the current suspension/resume is the latest; a single-run step
232
- // stores one entry. Shared by the suspendedAt/resumedAt/suspendPayload readers.
227
+ // stores one entry.
233
228
  function latestAttempt(steps, stepKey) {
234
229
  const entry = steps?.[stepKey];
235
230
  return Array.isArray(entry) ? entry[entry.length - 1] : entry;
@@ -248,15 +243,13 @@ function resumedAtOf(steps, stepKey) {
248
243
  return latestAttempt(steps, stepKey)?.resumedAt;
249
244
  }
250
245
  /**
251
- * One home for the per-step projection convention behind every RunSummary map
252
- * (suspendedAt / resumedAt / resumeCount / suspendPayload): collect
246
+ * One home for the per-step projection convention: collect
253
247
  * `stepKey -> value` over the suspended step keys, projecting an empty result
254
248
  * as undefined so JSON summaries omit the field. The accumulator is
255
249
  * null-prototype because step keys are author-chosen strings: on a plain
256
250
  * object literal a step named '__proto__' would route into the
257
251
  * Object.prototype setter and silently vanish (or, for an object-valued
258
- * payload, rewire the accumulator's prototype) — the same hazard
259
- * snapshot provenance stores [stepKey, count] pairs to avoid.
252
+ * payload, rewire the accumulator's prototype).
260
253
  */
261
254
  function byStep(suspendedKeys, lookup) {
262
255
  const map = Object.create(null);
@@ -586,9 +579,8 @@ export class RunnerRuntime {
586
579
  #terminalAbortIntents = new Map();
587
580
  #lifecycleLocks = new Map();
588
581
  // The host DO's pubsub identity (RunnerRuntimeOptions.pubsub), threaded into
589
- // both createRun sites below so a configured host publishes and
590
- // replays on ONE shared feed. Undefined ⇒ core defaults a fresh emitter per
591
- // run ⇒ byte-identical to before this seam existed.
582
+ // createRun so a configured host publishes and replays on ONE shared feed.
583
+ // Undefined ⇒ core defaults a fresh emitter per run.
592
584
  #pubsub;
593
585
  #executionFence;
594
586
  #startIdempotency;
@@ -604,10 +596,7 @@ export class RunnerRuntime {
604
596
  /**
605
597
  * The deployment execution fence this runtime enforces, or undefined when
606
598
  * the host built an unfenced runtime. Exposed so the surfaces ABOVE the
607
- * runtime — the run object's routes, the thread DO's signal routes — gate on
608
- * the same store rather than constructing a second one, and so
609
- * DurableObjectRunner can assert that a runtime built against a bound
610
- * database is never fence-less.
599
+ * runtime gate on the same store rather than constructing a second one.
611
600
  */
612
601
  get executionFence() {
613
602
  return this.#executionFence;
@@ -671,7 +660,7 @@ export class RunnerRuntime {
671
660
  throw new Error('RunnerRuntime: register all workflows before the first run — the Mastra instance is frozen once runs start');
672
661
  }
673
662
  if (!isPathSafeId(workflow.id)) {
674
- throw new Error(`RunnerRuntime: workflow id '${workflow.id}' must be URL-path-safe (letters, digits, '.', '_', '~', '-'; 1-200 chars) — it feeds the DO name join and the /runs/:workflowId/:runId path`);
663
+ throw new Error(`RunnerRuntime: workflow id '${workflow.id}' must be URL-path-safe — it feeds the DO name join and the /runs/:workflowId/:runId path`);
675
664
  }
676
665
  if (this.#workflows.has(workflow.id)) {
677
666
  throw new Error(`RunnerRuntime: duplicate workflow id '${workflow.id}'`);
@@ -819,10 +808,10 @@ export class RunnerRuntime {
819
808
  const originalCached = workflow.runs.get(runId);
820
809
  let provenance;
821
810
  try {
822
- const existing = await workflow.getWorkflowRunById(runId);
811
+ const existing = await this.#getWorkflow(workflowId).getWorkflowRunById(runId);
823
812
  if (existing || originalCached)
824
813
  throw new RunAlreadyExistsError(workflowId, runId, existing?.status ?? 'pending');
825
- const source = await this.#captureWorkflowStorage(workflow);
814
+ const source = await this.#captureWorkflowStorage(workflowId);
826
815
  active.source = source;
827
816
  provenance = {
828
817
  version: 2,
@@ -876,7 +865,7 @@ export class RunnerRuntime {
876
865
  onInitialWriteAttempt: () => {
877
866
  candidate = workflow.runs.get(runId);
878
867
  },
879
- }, () => workflow.createRun({ runId, pubsub: this.#pubsub }));
868
+ }, () => this.#createRun(workflowId, runId));
880
869
  if (!admitted?.witness ||
881
870
  !sameExecution(admitted.witness.execution, d1Execution))
882
871
  throw new RunStateUnreadableError(workflowId, runId);
@@ -895,7 +884,7 @@ export class RunnerRuntime {
895
884
  ...capturedExecution,
896
885
  ...startIdentity,
897
886
  });
898
- run = await workflow.createRun({ runId, pubsub: this.#pubsub });
887
+ run = await this.#createRun(workflowId, runId);
899
888
  }
900
889
  active.run = run;
901
890
  engineEntered = true;
@@ -928,7 +917,7 @@ export class RunnerRuntime {
928
917
  await this.#startIdempotency.releaseReservation(claim);
929
918
  }
930
919
  if (engineEntered && provenance && !outcomeReadStarted) {
931
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
920
+ const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
932
921
  if (recovered)
933
922
  return recovered;
934
923
  }
@@ -951,7 +940,7 @@ export class RunnerRuntime {
951
940
  * loads it and re-enters the engine at the suspended step.
952
941
  */
953
942
  async resume(workflowId, runId, options = {}) {
954
- const workflow = this.#getWorkflow(workflowId);
943
+ this.#getWorkflow(workflowId);
955
944
  const proof = await this.#assertResumeFence(workflowId, runId);
956
945
  return this.#withRunLock(workflowId, runId, async () => {
957
946
  const activeKey = this.#runKey(workflowId, runId);
@@ -963,9 +952,9 @@ export class RunnerRuntime {
963
952
  let engineEntered = false;
964
953
  let outcomeReadStarted = false;
965
954
  try {
966
- const source = await this.#captureWorkflowStorage(workflow);
955
+ const source = await this.#captureWorkflowStorage(workflowId);
967
956
  active.source = source;
968
- const state = await this.#workflowState(workflow, runId, true);
957
+ const state = await this.#workflowState(workflowId, runId, true);
969
958
  if (!state)
970
959
  throw new UnknownRunError(workflowId, runId);
971
960
  if (state.isFromInMemory)
@@ -998,7 +987,7 @@ export class RunnerRuntime {
998
987
  await options.prepareExecution(new RequestContext(Object.entries(values)));
999
988
  await this.#withLifecycleLock(workflowId, runId, check);
1000
989
  }
1001
- const run = await workflow.createRun({ runId, pubsub: this.#pubsub });
990
+ const run = await this.#createRun(workflowId, runId);
1002
991
  const { executionPromise } = await this.#withLifecycleLock(workflowId, runId, async () => {
1003
992
  await check();
1004
993
  active.run = run;
@@ -1024,7 +1013,7 @@ export class RunnerRuntime {
1024
1013
  }
1025
1014
  catch (error) {
1026
1015
  if (engineEntered && provenance && !outcomeReadStarted) {
1027
- const recovered = await this.#summaryForAttempt(workflow, runId, provenance);
1016
+ const recovered = await this.#summaryForAttempt(workflowId, runId, provenance);
1028
1017
  if (recovered)
1029
1018
  return recovered;
1030
1019
  }
@@ -1049,7 +1038,7 @@ export class RunnerRuntime {
1049
1038
  this.#getWorkflow(workflowId);
1050
1039
  const prepared = await this.#withLifecycleLock(workflowId, runId, async () => {
1051
1040
  const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source ??
1052
- (await this.#captureWorkflowStorage(this.#getWorkflow(workflowId)));
1041
+ (await this.#captureWorkflowStorage(workflowId));
1053
1042
  const state = await source.load.call(source.workflows, {
1054
1043
  workflowName: workflowId,
1055
1044
  runId,
@@ -1156,7 +1145,7 @@ export class RunnerRuntime {
1156
1145
  async #transitionTerminal(workflowId, runId, status, now, cas, replayPrincipals, replayingPrincipal) {
1157
1146
  this.#getWorkflow(workflowId);
1158
1147
  return this.#withRunLock(workflowId, runId, async () => {
1159
- const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
1148
+ const source = await this.#captureWorkflowStorage(workflowId);
1160
1149
  const state = await source.load.call(source.workflows, {
1161
1150
  workflowName: workflowId,
1162
1151
  runId,
@@ -1252,7 +1241,7 @@ export class RunnerRuntime {
1252
1241
  async completeTerminalCleanup(workflowId, runId, expectedRevision, now = Date.now()) {
1253
1242
  this.#getWorkflow(workflowId);
1254
1243
  return this.#withRunLock(workflowId, runId, async () => {
1255
- const source = await this.#captureWorkflowStorage(this.#getWorkflow(workflowId));
1244
+ const source = await this.#captureWorkflowStorage(workflowId);
1256
1245
  const state = await source.load.call(source.workflows, {
1257
1246
  workflowName: workflowId,
1258
1247
  runId,
@@ -1294,8 +1283,7 @@ export class RunnerRuntime {
1294
1283
  * that did not reach storage.
1295
1284
  */
1296
1285
  async status(workflowId, runId) {
1297
- const workflow = this.#getWorkflow(workflowId);
1298
- const state = await this.#workflowState(workflow, runId);
1286
+ const state = await this.#workflowState(workflowId, runId);
1299
1287
  if (!state)
1300
1288
  return null;
1301
1289
  return this.#summaryFromState(runId, state);
@@ -1315,12 +1303,11 @@ export class RunnerRuntime {
1315
1303
  * that did not reach storage. `null` still means the read SUCCEEDED and
1316
1304
  * found nothing.
1317
1305
  *
1318
- * Both status readers refuse a valid v2 pending row before lifecycle
1319
- * projection; it has no durable execution outcome yet.
1306
+ * A valid v2 pending row is refused before lifecycle projection; it has no
1307
+ * durable execution outcome yet.
1320
1308
  */
1321
1309
  async authoritativeStatus(workflowId, runId) {
1322
- const workflow = this.#getWorkflow(workflowId);
1323
- const state = await this.#workflowState(workflow, runId);
1310
+ const state = await this.#workflowState(workflowId, runId);
1324
1311
  if (!state)
1325
1312
  return null;
1326
1313
  if (state.isFromInMemory === true) {
@@ -1335,10 +1322,9 @@ export class RunnerRuntime {
1335
1322
  throw new RunStateUnreadableError(workflowId, runId);
1336
1323
  return state;
1337
1324
  }
1338
- async #captureWorkflowStorage(workflow) {
1339
- const workflows = await workflow.mastra
1340
- ?.getStorage()
1341
- ?.getStore('workflows');
1325
+ async #captureWorkflowStorage(workflowId) {
1326
+ this.#getWorkflow(workflowId);
1327
+ const workflows = await this.#mastra?.getStorage()?.getStore('workflows');
1342
1328
  if (!workflows)
1343
1329
  throw new Error('workflow storage is unavailable');
1344
1330
  const methods = {
@@ -1384,9 +1370,9 @@ export class RunnerRuntime {
1384
1370
  throw new InvalidRunRequestError('workflowId is malformed');
1385
1371
  if (!isPathSafeId(runId))
1386
1372
  throw new InvalidRunRequestError('runId is malformed');
1387
- const workflow = this.#getWorkflow(workflowId);
1373
+ this.#getWorkflow(workflowId);
1388
1374
  try {
1389
- const source = await this.#captureWorkflowStorage(workflow);
1375
+ const source = await this.#captureWorkflowStorage(workflowId);
1390
1376
  return {
1391
1377
  source,
1392
1378
  state: await this.#readStartState(source, workflowId, runId),
@@ -1584,12 +1570,12 @@ export class RunnerRuntime {
1584
1570
  if (claim && !this.#startIdempotency)
1585
1571
  throw new ExecutionFenceUnreadableError('run start recovery is unresolved');
1586
1572
  const { workflowId, runId } = execution;
1587
- const workflow = this.#getWorkflow(workflowId);
1573
+ this.#getWorkflow(workflowId);
1588
1574
  return this.#withRunLock(workflowId, runId, () => this.#withLifecycleLock(workflowId, runId, async () => {
1589
1575
  try {
1590
1576
  if (this.isRunActive(workflowId, runId))
1591
1577
  throw new Error('run owner is not quiescent');
1592
- const source = await this.#captureWorkflowStorage(workflow);
1578
+ const source = await this.#captureWorkflowStorage(workflowId);
1593
1579
  if (this.isRunActive(workflowId, runId) ||
1594
1580
  (await Reflect.apply(isOwnerQuiescent, undefined, [])) !== true ||
1595
1581
  this.isRunActive(workflowId, runId))
@@ -1689,9 +1675,8 @@ export class RunnerRuntime {
1689
1675
  // only ever deny downstream (fail closed), so loud propagation is safe.
1690
1676
  //
1691
1677
  // Every leg — provider or not — carries a base context minting the
1692
- // workflow-scope key (breakwater's crossWorkflowIsolation reads it): the
1693
- // runtime is the trusted authority for "which workflow is executing", so
1694
- // the scope is never client-suppliable. Provider values are partitioned into
1678
+ // workflow-scope key: the runtime is the trusted authority for "which
1679
+ // workflow is executing", so the scope is never client-suppliable. Provider values are partitioned into
1695
1680
  // stored application context, capabilities, and trusted identity so every
1696
1681
  // layer has an explicit order and a provider cannot replace runtime scope.
1697
1682
  async #requestContextFor(workflowId, runId, leg, provenance, storedRequestContext, lifecycle) {
@@ -1706,13 +1691,8 @@ export class RunnerRuntime {
1706
1691
  base[RUN_LIFECYCLE_CONTEXT_KEY] = lifecycle;
1707
1692
  }
1708
1693
  // No isolation scope is minted here: a deployment serves exactly one
1709
- // organization, so breakwater's connector idempotency and rate-limit keys
1710
- // are deployment-wide by construction. Budget partitioning within a
1711
- // deployment stays available
1712
- // through breakwater's crossWorkflowIsolation, which reads the workflow
1713
- // scope minted above. The isolation-scope context key remains RESERVED —
1714
- // orderedRequestContext drops it from provider values — so a provider can
1715
- // never mint a scope that desyncs from the execution identity below.
1694
+ // organization. The isolation-scope context key is RESERVED, so a provider
1695
+ // can never mint a scope that desyncs from the execution identity below.
1716
1696
  if (leg.kind === 'start') {
1717
1697
  base[BREAKWATER_CONNECTOR_EXECUTION_KEY] = {
1718
1698
  kind: 'start',
@@ -1814,8 +1794,8 @@ export class RunnerRuntime {
1814
1794
  lifecycle,
1815
1795
  };
1816
1796
  }
1817
- #workflowState(workflow, runId, withNestedWorkflows = false) {
1818
- return workflow.getWorkflowRunById(runId, {
1797
+ #workflowState(workflowId, runId, withNestedWorkflows = false) {
1798
+ return this.#getWorkflow(workflowId).getWorkflowRunById(runId, {
1819
1799
  fields: RUN_STATE_FIELDS,
1820
1800
  withNestedWorkflows,
1821
1801
  });
@@ -1845,7 +1825,7 @@ export class RunnerRuntime {
1845
1825
  await this.settleStartExecution(selected);
1846
1826
  return selected.summary;
1847
1827
  }
1848
- const state = await this.#workflowState(this.#getWorkflow(workflowId), runId);
1828
+ const state = await this.#workflowState(workflowId, runId);
1849
1829
  if (!state)
1850
1830
  throw new UnknownRunError(workflowId, runId);
1851
1831
  return this.#summaryFromState(runId, state);
@@ -1856,22 +1836,22 @@ export class RunnerRuntime {
1856
1836
  throw new RunStartPendingError();
1857
1837
  return summarizeState(runId, state, provenance ? new Map(provenance.resumeCounts) : undefined, provenance?.requestedBy, provenance?.requestedByKind);
1858
1838
  }
1859
- async #summaryForAttempt(workflow, runId, expected) {
1839
+ async #summaryForAttempt(workflowId, runId, expected) {
1860
1840
  try {
1861
1841
  if (expected.version === 2) {
1862
- const source = this.#activeRuns.get(this.#runKey(workflow.id, runId))?.source;
1842
+ const source = this.#activeRuns.get(this.#runKey(workflowId, runId))?.source;
1863
1843
  if (!source)
1864
1844
  return undefined;
1865
1845
  const state = await this.#completedStartState(source, {
1866
1846
  tablePrefix: source.tablePrefix,
1867
- workflowId: workflow.id,
1847
+ workflowId,
1868
1848
  runId,
1869
1849
  startToken: expected.startToken,
1870
1850
  }, expected);
1871
1851
  await this.#settleStartReservation(state);
1872
1852
  return state.summary;
1873
1853
  }
1874
- const persisted = await this.#workflowState(workflow, runId);
1854
+ const persisted = await this.#workflowState(workflowId, runId);
1875
1855
  if (!persisted ||
1876
1856
  persisted.isFromInMemory ||
1877
1857
  persisted.status === 'pending')
@@ -1962,8 +1942,21 @@ export class RunnerRuntime {
1962
1942
  const workflow = this.#workflows.get(workflowId);
1963
1943
  if (!workflow)
1964
1944
  throw new UnknownWorkflowError(workflowId);
1945
+ // Run-state reads and run creation go through the workflow's own Mastra,
1946
+ // so a workflow another Mastra registered would reach that Mastra's storage.
1947
+ // Another Mastra can register the object during any await, so callers look
1948
+ // the workflow up again where they reach storage, not only at entry.
1949
+ if (workflow.mastra !== this.#mastra) {
1950
+ throw new Error(`RunnerRuntime: workflow '${workflowId}' is not registered on this runtime's Mastra — another runtime or Mastra has registered the same workflow object`);
1951
+ }
1965
1952
  return workflow;
1966
1953
  }
1954
+ #createRun(workflowId, runId) {
1955
+ return this.#getWorkflow(workflowId).createRun({
1956
+ runId,
1957
+ pubsub: this.#pubsub,
1958
+ });
1959
+ }
1967
1960
  #ensureMastra() {
1968
1961
  if (this.#mastra)
1969
1962
  return;
@@ -1983,8 +1976,8 @@ export class RunnerRuntime {
1983
1976
  // alone. The same caller-supplied runId under two workflows are DISTINCT
1984
1977
  // persisted runs (Mastra snapshots key on workflowName+runId) and must never
1985
1978
  // share a per-run FIFO entry. Composing the key in ONE place keeps every
1986
- // per-run map keyed identically, so a future map cannot reintroduce a
1987
- // runId-only key and cross workflow boundaries.
1979
+ // per-run map keyed identically, so no map can key by runId alone and cross
1980
+ // workflow boundaries.
1988
1981
  // This is the exact string the DO name join produces
1989
1982
  // (idFromName(`${workflowId}:${runId}`)); PATH_SAFE_ID_PATTERN excludes ':'
1990
1983
  // from both ids, so the join is unambiguous.