@proofoftech/flowsafe 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +135 -0
  2. package/README.md +59 -9
  3. package/dist/agent-host/thread-host.d.ts.map +1 -1
  4. package/dist/agent-host/thread-host.js +26 -2
  5. package/dist/agent-host/thread-host.js.map +1 -1
  6. package/dist/agent-runner/durable-agent-runner.d.ts +13 -19
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  8. package/dist/agent-runner/durable-agent-runner.js +551 -372
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  10. package/dist/approval-api/retention.d.ts.map +1 -1
  11. package/dist/approval-api/retention.js +6 -5
  12. package/dist/approval-api/retention.js.map +1 -1
  13. package/dist/approval-api/service.js +4 -4
  14. package/dist/approval-api/service.js.map +1 -1
  15. package/dist/approval-ui/use-approval-dashboard.js +6 -6
  16. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  17. package/dist/background-tasks/d1-storage.d.ts.map +1 -1
  18. package/dist/background-tasks/d1-storage.js +7 -5
  19. package/dist/background-tasks/d1-storage.js.map +1 -1
  20. package/dist/background-tasks/host.d.ts.map +1 -1
  21. package/dist/background-tasks/host.js +27 -38
  22. package/dist/background-tasks/host.js.map +1 -1
  23. package/dist/do-runner/cause-chain.d.ts +5 -0
  24. package/dist/do-runner/cause-chain.d.ts.map +1 -1
  25. package/dist/do-runner/cause-chain.js +12 -0
  26. package/dist/do-runner/cause-chain.js.map +1 -1
  27. package/dist/do-runner/cf-types.d.ts +3 -0
  28. package/dist/do-runner/cf-types.d.ts.map +1 -1
  29. package/dist/do-runner/cf-types.js.map +1 -1
  30. package/dist/do-runner/constants.d.ts +1 -1
  31. package/dist/do-runner/constants.d.ts.map +1 -1
  32. package/dist/do-runner/constants.js +1 -1
  33. package/dist/do-runner/constants.js.map +1 -1
  34. package/dist/do-runner/core-events-nonce.d.ts +2 -0
  35. package/dist/do-runner/core-events-nonce.d.ts.map +1 -0
  36. package/dist/do-runner/core-events-nonce.js +16 -0
  37. package/dist/do-runner/core-events-nonce.js.map +1 -0
  38. package/dist/do-runner/d1-storage.js +1 -9
  39. package/dist/do-runner/d1-storage.js.map +1 -1
  40. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  41. package/dist/do-runner/do-error-response.js +2 -1
  42. package/dist/do-runner/do-error-response.js.map +1 -1
  43. package/dist/do-runner/durable-object.d.ts +34 -2
  44. package/dist/do-runner/durable-object.d.ts.map +1 -1
  45. package/dist/do-runner/durable-object.js +447 -53
  46. package/dist/do-runner/durable-object.js.map +1 -1
  47. package/dist/do-runner/fenced-workflow-capability.d.ts +51 -0
  48. package/dist/do-runner/fenced-workflow-capability.d.ts.map +1 -1
  49. package/dist/do-runner/fenced-workflows-d1.d.ts +5 -1
  50. package/dist/do-runner/fenced-workflows-d1.d.ts.map +1 -1
  51. package/dist/do-runner/fenced-workflows-d1.js +236 -48
  52. package/dist/do-runner/fenced-workflows-d1.js.map +1 -1
  53. package/dist/do-runner/index.d.ts +2 -2
  54. package/dist/do-runner/index.d.ts.map +1 -1
  55. package/dist/do-runner/index.js +2 -2
  56. package/dist/do-runner/index.js.map +1 -1
  57. package/dist/do-runner/init.d.ts +2 -3
  58. package/dist/do-runner/init.d.ts.map +1 -1
  59. package/dist/do-runner/init.js.map +1 -1
  60. package/dist/do-runner/memory-id.js +1 -1
  61. package/dist/do-runner/memory-id.js.map +1 -1
  62. package/dist/do-runner/pubsub.d.ts +6 -2
  63. package/dist/do-runner/pubsub.d.ts.map +1 -1
  64. package/dist/do-runner/pubsub.js +12 -22
  65. package/dist/do-runner/pubsub.js.map +1 -1
  66. package/dist/do-runner/run-lifecycle.d.ts +42 -2
  67. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  68. package/dist/do-runner/run-lifecycle.js +57 -1
  69. package/dist/do-runner/run-lifecycle.js.map +1 -1
  70. package/dist/do-runner/run-terminal-state.d.ts +2 -0
  71. package/dist/do-runner/run-terminal-state.d.ts.map +1 -1
  72. package/dist/do-runner/run-terminal-state.js +4 -0
  73. package/dist/do-runner/run-terminal-state.js.map +1 -1
  74. package/dist/do-runner/runtime.d.ts +87 -17
  75. package/dist/do-runner/runtime.d.ts.map +1 -1
  76. package/dist/do-runner/runtime.js +455 -155
  77. package/dist/do-runner/runtime.js.map +1 -1
  78. package/dist/do-runner/suspension-deadline.d.ts +25 -17
  79. package/dist/do-runner/suspension-deadline.d.ts.map +1 -1
  80. package/dist/do-runner/suspension-deadline.js +44 -21
  81. package/dist/do-runner/suspension-deadline.js.map +1 -1
  82. package/dist/do-runner/workflow-snapshot-row.d.ts +6 -0
  83. package/dist/do-runner/workflow-snapshot-row.d.ts.map +1 -1
  84. package/dist/do-runner/workflow-snapshot-row.js +17 -0
  85. package/dist/do-runner/workflow-snapshot-row.js.map +1 -1
  86. package/dist/host-kit/approval-bridge.d.ts +25 -9
  87. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  88. package/dist/host-kit/approval-bridge.js +72 -15
  89. package/dist/host-kit/approval-bridge.js.map +1 -1
  90. package/dist/host-kit/do-response.d.ts.map +1 -1
  91. package/dist/host-kit/do-response.js +7 -1
  92. package/dist/host-kit/do-response.js.map +1 -1
  93. package/dist/host-kit/flowsafe-worker.d.ts +2 -1
  94. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  95. package/dist/host-kit/flowsafe-worker.js +4 -2
  96. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  97. package/dist/host-kit/run-router.d.ts +4 -1
  98. package/dist/host-kit/run-router.d.ts.map +1 -1
  99. package/dist/host-kit/run-router.js +3 -2
  100. package/dist/host-kit/run-router.js.map +1 -1
  101. package/dist/schedules/schedules-d1.d.ts +1 -0
  102. package/dist/schedules/schedules-d1.d.ts.map +1 -1
  103. package/dist/schedules/schedules-d1.js +35 -22
  104. package/dist/schedules/schedules-d1.js.map +1 -1
  105. package/dist/schedules/tick.d.ts +17 -2
  106. package/dist/schedules/tick.d.ts.map +1 -1
  107. package/dist/schedules/tick.js +63 -44
  108. package/dist/schedules/tick.js.map +1 -1
  109. package/dist/signals/d1-shared.js +1 -1
  110. package/dist/signals/d1-shared.js.map +1 -1
  111. package/dist/signals/thread-do-routes.d.ts +8 -1
  112. package/dist/signals/thread-do-routes.d.ts.map +1 -1
  113. package/dist/signals/thread-do-routes.js +40 -44
  114. package/dist/signals/thread-do-routes.js.map +1 -1
  115. package/package.json +10 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,140 @@
1
1
  # @proofoftech/flowsafe
2
2
 
3
+ ## 0.25.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e50aaa6: The agent thread host's start recovery now waits, as `DurableObjectRunner`'s does, until a pending agent start's run row has gone six minutes without a write before it repairs the start as `StartOutcomeUnknown`, and it stamps the repair so the settled-row guard refuses a later write from that start's leg. Before this change the host repaired a pending start about a minute after admission whether or not its leg was still running, and that leg's later writes overwrote the repair. A dead agent start now reads `StartOutcomeUnknown` about six to seven minutes after its last touch. Until then the thread stays blocked, the run's status and terminate routes and a schedule dispatch status read answer `503 RUN_START_PENDING`, and a keyed start replay answers `409 IDEMPOTENT_START_UNRESOLVABLE`, or `503 IDEMPOTENT_START_PENDING` while the start is live in the thread object's current isolate. Keep re-probing an agent start for at least seven minutes after its last activity before you choose a fresh key. When the start route sees its own leg fail in the object, it still repairs at once. A pending start no longer fails the thread object's alarm: recovery keeps its journal and wake, logs an `agent-start-recovery-pending` line, and goes on with the other journals.
8
+
9
+ Two cases repair a start whose leg is still running on another instance:
10
+
11
+ - A deploy from a version earlier than 0.25.0 leaves outgoing agent legs that do not touch their row. If one goes more than six minutes without a write, the thread object repairs and stamps it. From 0.24.x the settled-row guard refuses the outgoing leg's final write. From a version earlier than 0.24.0 the leg writes without the guard, so its write can land over the repair after the journal and ownership are gone; drain agent starts before such a deploy.
12
+ - A leg whose touches fail to reach D1 for six minutes, for example during a D1 outage, is repaired and stamped. A later touch that reaches D1 aborts the leg; otherwise the settled-row guard refuses its next write. A leg in the thread object's current isolate is never repaired.
13
+
14
+ - 9c66e63: A leg whose run another Durable Object instance has settled is now aborted within about 30 seconds instead of ending at its next workflow write. The liveness touch a running leg makes every 30 seconds on `FencedWorkflowsStorageD1` storage now reports whether its run row is settled: terminated, timed out, interrupted, or repaired by start recovery. When it is, the runtime aborts the leg's Mastra run: the engine starts no further step, the step in flight sees its `abortSignal` aborted, and the leg's next write is refused as before. A step that calls external services should pass its `abortSignal` to them so the call in flight stops; a step that ignores it runs to completion. Mastra re-runs a step with `retries` that throws after the abort, so such a step should check `abortSignal.aborted` before its side effects and throw `MastraNonRetryableError` (from `@mastra/core/error`) once it is aborted. A call the abort cuts mid-flight may already have taken effect, and its abort error does not show whether it did. A run whose stored snapshot SQLite cannot parse, for example one nested past its JSON depth limit, is neither guarded nor reported settled, so its leg is not aborted. The touch no longer moves `updatedAt` on a settled row.
15
+
16
+ The touch moved from `DurableObjectRunner` into `RunnerRuntime.start()` and `resume()`, so durable-agent legs on the agent thread host, and legs an in-process driver runs through a shared `RunnerRuntime`, now touch their run row as well. `FencedWorkflowAdmissionCapability.touchRun` may resolve `'live'`, `'settled'` or `'absent'`; a custom capability that resolves nothing keeps working and reports no settlement, so its legs are not aborted. A capability reports `'settled'` only when its storage refuses the aborted leg's later writes over that row. Legs running a flowsafe version without this change are not aborted.
17
+
18
+ On a durable agent the abort also reaches the model call and the tool calls in flight, on start and resumed legs, and a terminate that the agent's own thread object handles cuts them too. A caller's `abortSignal` still aborts a start leg. A tool should pass the `abortSignal` it receives to its own I/O, and a tool that retries after an error should check `abortSignal.aborted` first, because a cut call's error does not always show that an abort cut it. With the matching Breakwater patch, a keyed connector call cut this way keeps its idempotency key reserved until stale takeover or operator recovery, and a call with the same key meanwhile is refused with `IDEMPOTENCY_CONFLICT`; earlier Breakwater releases free the key.
19
+
20
+ - fdda499: After every suspension-deadline resume, the run object now attempts to close an approval still open for the suspension that resume ended, whether the run then ended or suspended at another step. Before this change such a record stayed open and the SLA sweep escalated it; a reviewer could still decide it, but the decision resumed nothing. When the run has ended, every open approval of the run is closed, because none of them can be decided usefully. The close is one best-effort attempt. A failed read or hook, an eviction between the resume and the reconcile, a resume that throws after its result was saved, or a host status read that files from a summary taken before the resume leaves the record open, and the SLA sweep escalates it as before. Only suspensions a timeout resume ends after the upgrade are covered: a record left open earlier stays open, including one left open by an instance still running the earlier version.
21
+
22
+ `DurableObjectRunLifecycleHooks.reconcileApprovals` receives the ended suspension as an optional third argument, `{ step, suspendedAt, resumeCount }`, and is now called after a timeout resume whatever the run's status, so a custom implementation must accept a summary that is not suspended. An implementation honours the argument by superseding each open record whose step, `suspendedAt` and `resumeCount` equal it exactly, counting an absent `resumeCount` as 0. `createFlowsafeRunnerLifecycle()` reconciles as before, then supersedes each open record bound to exactly that suspension, or every open record of a run that has ended. A hook that ignores the third argument leaves such a record open, as before, and now also receives summaries of finished runs.
23
+
24
+ ### Patch Changes
25
+
26
+ - 9e35407: `DurableObjectWorkflowsStorageD1.updateWorkflowState`, the workflow domain `createBackgroundTaskD1Domains()` composes, now applies `expectedStatus` as the compare-and-set guard `@mastra/core` defines: when the stored snapshot's status does not match, the update writes nothing and resolves `undefined`, and the guard is never stored in the snapshot. Before this change the domain ignored the guard and stored it. Because the domain reports concurrent-update support, Mastra relies on that guard to let only one of two concurrent resumes of a suspended run claim it; without it both could proceed.
27
+ - 9e35407: `FencedWorkflowsStorageD1`'s `replaceSnapshot` capability member refuses a replacement whose `snapshot` is not a JSON object or whose `updatedAt` is not an ISO-8601 time in `Date.prototype.toISOString()` form, and writes nothing. Run retention compares the stored `updatedAt` with its cutoff as text, so any other form, including a valid time without milliseconds, can keep a run from being purged on time, and text that is not a time also makes every later settlement read of that run fail as unreadable.
28
+ - 4c673b4: A durable-agent leg resumed through `resumeViaRuntime()` now enforces the total time budget of its run. Before this change the resumed leg ran with no total budget, so a tool or model call that held past it was never aborted. The leg arms the `modelSettings.timeout.totalMs` the run's start call set, else the one in the agent's default options when the run started (or the current default when the start resolved none), and the budget starts again on each resumed leg. When it elapses, the leg's model and tool calls in flight see their `abortSignal` aborted with a `MastraTimeoutError` whose `timeoutType` is `'total'`, and `resumeViaRuntime()` resolves with `status: 'success'` and `result.stepResult.reason: 'error'`. A host that treats the resumed leg's success as completion of the approved action must check that reason. A start leg whose budget elapses ends its run the same way, but its `streamUntilPersisted()` rejects with the `MastraTimeoutError`. A settlement or terminate abort of the leg still reaches those calls with its own reason.
29
+ - 12e9df9: A terminate, and a run-deadline timeout from the maintenance sweep, now write their cancellation intent and terminal record without overwriting progress a leg wrote since they read the run, on `FencedWorkflowsStorageD1` storage. Before this change both writes replaced the run's row without checking that it was still the one they read, so a leg's write that landed between the read and the write was lost: a run that completed in that window could be recorded `cancelled` or `timed_out` without its result. The intent now changes only the run's lifecycle and timestamp, and only while the run's status and lifecycle revision are the ones it read, so a leg's step progress cannot make it miss and a leg in the same Durable Object still takes the cancellation however often it writes. The terminal record is a compare-and-set against the exact row it read. A write that finds the row changed reads the run again and decides from what it finds: a run that completed before the intent landed keeps its result and the request answers `409`. A write that finds the row changed on five attempts in a row answers `503`; retry the request. On `FencedWorkflowsStorageD1` that happens only while a leg on another instance writes continuously. `FencedWorkflowAdmissionCapability` gains an optional `patchRunLifecycle` member for the intent write. Storage that provides `replaceSnapshot` but not `patchRunLifecycle` writes the intent with the exact-row compare-and-set, and a leg in its own object that keeps writing then makes the request answer `503` without stopping the leg; retry it. Storage with neither keeps the unconditional write.
30
+
31
+ ## 0.24.0
32
+
33
+ ### Minor Changes
34
+
35
+ - b96f8dd: Breaking: Guarded durable calls refuse more call-level options. `stream()`, `streamUntilPersisted()`, `generate()`, and `prepare()` on a wrapped Breakwater guarded agent refuse, with a `TypeError`, the call-level options that would change what the guarded agent fixes at construction: tools, hooks, processors, scorers, instructions and system or context messages, step preparation, delegation and sub-agent versions, chunk callbacks and stream transforms, per-step saving, and an own `__proto__` property. See the [durable call-option restrictions](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/durable-agents.md#durable-call-options) for the list. `maxSteps`, `toolChoice`, and `disableBackgroundTasks` are accepted only with the guarded agent's own values. `memory` accepts only the thread and resource on these entries and on `resumeViaRuntime()`, and the wrapper forwards a frozen copy. The wrapper's constructor throws when the guarded agent's default options carry a refused option, lack `maxSteps`, `toolChoice`, or `disableBackgroundTasks`, or set `disableBackgroundTasks` to anything but `true`.
36
+
37
+ Security: Before this change, host code that passed such an option to a guarded durable call could bypass the guarded agent's input or output policies, tool set, or memory configuration: for example, a per-call client tool whose mapped result the input policies never read, a call-level output processor list that replaced the output policies, or a working-memory template added to the system prompt. The check closes these per-call routes; the documented limits of durable results for guarded agents are unchanged. The check reads option values as data; the restrictions page names what it leaves to host code.
38
+
39
+ Migration: Configure tools, instructions, memory, processors, hooks, and scorers on the guarded agent, not per call. Pass `maxSteps`, `toolChoice`, and `disableBackgroundTasks` only with the agent's own values, or omit them. Flowsafe's thread host, signal routes, and schedules pass none of the refused options.
40
+
41
+ - 21df7fb: A `DurableObjectRunner` run whose execution leg stops mid-step no longer stays `running`. A start, resume or suspension-deadline leg can stop this way when the platform ends the Durable Object invocation, for example about 15 minutes after the client disconnected. While a leg runs, it sets its run row's `updatedAt` in D1 every 30 seconds without writing the snapshot. Once the row has gone six minutes without a write, the run's own object settles the run on its next wake, with a compare-and-set against the row it read silent. The run becomes `failed` with `errorEnvelope: { code: 'INTERRUPTED', message }`, and its idempotent-start reservation is settled. A retry of the same key returns that result instead of `503 persisted start is not readable`. Flowsafe never re-executes the interrupted step, because it may already have had external effects. A run with a recorded cancellation or timeout completes that transition, with its cleanup, instead.
42
+
43
+ A deploy does not interrupt a leg: the outgoing instance keeps running it, and its touches keep the run from being settled. A Workers runtime update gives in-flight requests at most 30 seconds, so it interrupts a longer leg. A wake no longer queues behind a leg that is still executing in the object. A leg frame older than two hours is reset with `ctx.abort()`, which releases the locks of a promise the platform stopped without settling. A leg that a client keeps connected for longer than two hours is reset the same way.
44
+
45
+ Settlement needs the `FencedWorkflowsStorageD1` workflow domain that `createD1Storage()` composes. A live leg whose touches fail to reach D1 for six minutes is settled while it runs, and its next workflow write is refused. A run on other storage, including Mastra's own D1 workflow storage, or one whose leg ran on a flowsafe version before this one, is not settled automatically; `POST /runs/:workflowId/:runId/terminate` ends it.
46
+
47
+ `RunTerminalErrorEnvelope.code` and `RunSummary.errorEnvelope.code` gain `'INTERRUPTED'`. Code that switches exhaustively on the code needs a branch for it. `FencedWorkflowAdmissionCapability` gains optional `touchRun` and `replaceSnapshot`; a custom capability without both never settles a run automatically.
48
+
49
+ Each step must finish within one invocation. Split long work into steps, and wait in a suspension with a deadline rather than in an in-memory polling loop.
50
+
51
+ - 9feb010: Require `@mastra/core` `1.73.0` exactly and `@proofoftech/breakwater` `>=0.17.0 <1.0.0` when used. Pin the D1 storage dependency to `@mastra/cloudflare-d1` `1.4.0`.
52
+
53
+ Breaking: Guarded durable calls refuse call-level `errorProcessors`, accepted in 0.23, alongside the existing structured-output restriction. See the [durable call-option restrictions](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/durable-agents.md#durable-call-options).
54
+
55
+ Breaking: When a state read falls back to Mastra's in-memory run, `status()` and the run status, dispatch-status and stream routes report that run's lifecycle status, `suspended` with no suspended paths or `running`, instead of `pending`. The fallback state remains marked `isFromInMemory`; authoritative reads used by resume, deadline and terminate paths still refuse it.
56
+
57
+ Core 1.73.0's `@mastra/core/events` entry calls `crypto.randomUUID()` while it loads, which Cloudflare Workers refuse during startup. Flowsafe's do-runner supplies that value before the entry loads, so Workers that build their pub/sub from `createHostPubSub()` start. A Worker whose bundle evaluates `@mastra/core/events` before Flowsafe's do-runner fails at startup with `Disallowed operation called within global scope`, for example a Worker importing `CachingPubSub` or `withCaching` from that entry, since import sorters order `@mastra/*` before `@proofoftech/*`. On core 1.73.0, such a Worker should not import `@mastra/core/events` itself.
58
+
59
+ Storage initialization (`init()`) automatically adds `ownerId` and `leaseExpiresAt` to `mastra_background_tasks` with additive `ALTER TABLE … ADD COLUMN` statements. No manual migration is needed. Mastra's background-task manager claims and renews task leases, skips live leases during recovery, reclaims running tasks with expired or absent leases, and clears leases on suspension. Flowsafe continues applying the `resourceId` filter omitted by the D1 adapter's `listTasks`.
60
+
61
+ Guarded agents inherit Breakwater's [input policy coverage](https://github.com/ProofOfTechOrg/anchorage/blob/main/packages/breakwater/README.md#input-policy-coverage), [input policies and memory](https://github.com/ProofOfTechOrg/anchorage/blob/main/packages/breakwater/README.md#input-policies-and-memory), [application processor rules](https://github.com/ProofOfTechOrg/anchorage/blob/main/packages/breakwater/README.md#application-processors), and [streaming rules](https://github.com/ProofOfTechOrg/anchorage/blob/main/packages/breakwater/README.md#understand-streaming-hold-back).
62
+
63
+ Migration: Upgrade `@mastra/core` to `1.73.0`, `@mastra/cloudflare-d1` to `1.4.0`, and `@proofoftech/breakwater` to `>=0.17.0 <1.0.0` when used. Remove call-level `errorProcessors` from guarded durable calls. Build the bus with `createHostPubSub()` and do not import `@mastra/core/events` in Worker code on core 1.73.0.
64
+
65
+ - 3d5bd5b: A threaded schedule fire that the thread refuses permanently is recorded as `failed` with the refusal's message, and the schedule keeps firing. The trigger and audit carry the reason `dispatch-refused`. This covers an invalid dispatch or host input, an agent that does not allow the scheduled automation, and no matching thread binding or claimed dispatch. A 403 from a host automation policy fails that fire, not the schedule. Conflicts, server errors and other failures keep being retried. Fires already waiting in `deferred` close the same way on their next retry.
66
+
67
+ A permission-requiring agent whose `resolvePrincipalPermissions` throws, rejects or returns malformed output refuses the entry with 503 `permission resolution unavailable` instead of 403 `forbidden`. Automated callers, including the schedule tick, retry it. Human callers of agent starts receive this status too. A missing resolver or unsatisfied permissions still answer 403.
68
+
69
+ A fire refused because its thread binding does not exist yet is lost and is visible in trigger history.
70
+
71
+ Signal routes answer a request the thread refuses as malformed, including host input refusals, with 400 `{ "error": "bad request" }` instead of 502 `{ "error": "internal error" }`. Public signal callers receive this response too.
72
+
73
+ In `D1SchedulesStorage`, permanently refused fires no longer hold schedule deletion open while they wait for retries. A custom store decides its own deletion handling.
74
+
75
+ Migration: The required `failDeferredTrigger` member on `ScheduleTickStore` is a breaking interface change. If you supply a custom store, implement this signature:
76
+
77
+ ```typescript
78
+ failDeferredTrigger(
79
+ id: string,
80
+ scheduleId: string,
81
+ error: string,
82
+ metadata: Record<string, unknown>,
83
+ ): Promise<boolean>;
84
+ ```
85
+
86
+ Merge `metadata` into the stored metadata, as `touchDeferredTrigger` does. Record the failure only while the trigger is still `deferred`, and resolve `true` when a row changes or `false` otherwise. Leave a trigger whose target already settled a receipt, or that another tick resolved, unchanged.
87
+
88
+ A custom `signalAgent` seam must throw an error with the thread route's status in a numeric `status` property, as `ScheduleTickSignalAgent` documents. An adapter that reaches the route through another hop must not report that hop's own status as a refusal. A seam that throws without a status keeps every refusal retrying.
89
+
90
+ - 4d0fe16: `FencedWorkflowsStorageD1` refuses to overwrite a settled run row. A row is settled once its run lifecycle records a terminal transition (terminate or timeout), an interruption, or a start-recovery repair. A workflow snapshot write over such a row lands only when it advances the lifecycle revision and keeps those records; any other write throws the new `RunSettledConflictError`, which the run routes answer with 409. This fixes a defect in earlier releases. When a deploy left a run's leg executing on the outgoing Durable Object instance, a terminate or timeout on the new instance did not stop that leg: it went on running the run's remaining steps, with their external effects, and its writes replaced the terminal record. The cancelled or timed-out run could end `success`, `failed`, `running` or `suspended`, and a run left `suspended` could be resumed after its cancellation. Now the leg's next write is refused and the leg stops there.
91
+
92
+ The guard applies on a D1 binding with `batch()`, where unscoped persistence is now one conditional upsert that writes the same columns as `@mastra/cloudflare-d1`. Standalone client and REST configurations keep the adapter's write and have no guard. Code that rewrites a settled row through `persistWorkflowSnapshot` without advancing its lifecycle revision is refused. Legs running a flowsafe version without the guard still overwrite: during this upgrade, after a rollback, and in a mixed-version deploy. A refused leg stops at its next write; a workflow whose `shouldPersistSnapshot` skips `running` writes nothing between steps, so its steps run until that write. A durable agent persists nothing between tool calls by default, so a terminated agent's leg on an outgoing instance keeps calling tools until it suspends or finishes, and that write is refused. The agent thread host's start recovery does not stamp its repair, so a durable-agent leg that outlives it still overwrites it.
93
+
94
+ A `DurableObjectRunner` start whose leg stopped before its first write is now repaired as `StartOutcomeUnknown` only once its row has gone six minutes without a write, about six to seven minutes after it stopped instead of about one minute, unless the start route sees its own leg fail in the object. The repair stamps the run lifecycle so the guard refuses that leg's later writes; the run's summary is unchanged. `InitialTerminalizationRequest` gains an optional `markOutcomeUnknown`.
95
+
96
+ - 65f7715: A `DurableObjectRunner` workflow step can wait without an approval. It suspends with `SUSPENSION_TIMER_PAYLOAD_KEY` (`'flowsafe.timer'`, exported from `@proofoftech/flowsafe/do-runner/constants` and `@proofoftech/flowsafe/do-runner`) set to `true` beside its `flowsafe.deadlineMs`, and the run's Durable Object resumes it with the timeout envelope when the deadline expires. A run that must outlast one Durable Object invocation waits this way between steps.
97
+
98
+ The run object lists such steps in the new `RunSummary.suspensionTimers` on its start, resume, status, dispatch-status and protected-replay responses. It lists a step only when the current suspension derives an armable deadline for it, the marker is exactly `true`, the entry has not been abandoned, and an alarm is scheduled. `queueApprovalForSuspension` files nothing for a listed step, and `reconcileApprovalsForSummary` supersedes its stale open records without filing a new one. Every other case files an ordinary approval, so a timer step accepts an approval decision's `{ approved, comment?, decidedBy? }` as well as the timeout envelope and re-checks its wait condition on every resume. During a rollout, a timer step gets an ordinary approval wherever a Worker or run object without this change handles the run. Reconciliation supersedes that record once the step has suspended again.
99
+
100
+ The run object files the approvals of a run it leaves suspended with no host request behind it, from its alarm: after a timeout resume (a timer that waits again, the gate after it, or a deadline gate that suspends again, whose expired approval is superseded and filed afresh, notifying reviewers), after it abandons a timer, after its alarm recovers a start, and after it finds a stopped leg's run suspended. `DurableObjectRunLifecycleHooks` gains an optional `reconcileApprovals(workflowId, summary)`, which `createFlowsafeRunnerLifecycle()` fills with `reconcileApprovalsForSummary`. It is best effort; a failure is logged as `reconcile-error`, and a host status read with approval reconciliation, as `createFlowsafeWorker` does, files what it missed. Hooks without the member, and a timer abandoned after 24 hours of unreadable run state, leave those approvals to that host read. An approval open for a suspension that a timeout resume ended stays open.
101
+
102
+ A suspension-deadline resume now keeps the run's recorded `requestedBy` and `requestedByKind` instead of recording `SUSPENSION_DEADLINE_PRINCIPAL_ID` with kind `system`, so separation of duties applies to the gate after a timeout as it would without the timeout. A legacy requester without a kind is kept with kind `human`. The reserved principal is recorded only for a run without a requester, and a run whose recorded requester is already the reserved principal keeps it. A step that recognized a timeout resume by that principal id should test its resume data with `isSuspensionTimeoutResumeData` instead; a `RunSummary` no longer shows that a timeout advanced the run.
103
+
104
+ A step declaring a Zod `suspendSchema` must declare `flowsafe.timer` as well as `flowsafe.deadlineMs`, or use a loose object; a schema that strips the marker files an approval on every wait.
105
+
106
+ `DurableKeyValueStorage` gains an optional `getAlarm`. A storage without it lists no timer steps, so their approvals are filed.
107
+
108
+ ### Patch Changes
109
+
110
+ - 5b467f2: A registered agent start whose caller Breakwater's RBAC gate refuses during preparation is refused with status 403 before the runtime starts and creates no run. An automated fire the agent's RBAC gate refuses now records `failed` instead of a run that did nothing. A created signal the gate refuses for a missing actor is preserved even when Mastra's isolate-wide run registry evicts the start's entry.
111
+
112
+ Security: Before this change, if Mastra's isolate-wide run registry evicted the start's entry between preparation and the first step, the loop called the model for the refused caller on the thread's history and returned its output.
113
+
114
+ No migration is needed.
115
+
116
+ - 3b5b0ad: A guarded `resumeViaRuntime()` whose memory does not resolve is refused before registry installation, observation, or the resumed step. The run stays suspended and can be redriven once memory resolves. A failure while Breakwater resolves the memory processors, including a memory processor lookup error or function-valued memory that resolves a title-enabled `Memory` there, stops the audited `breakwater-memory` step with `input processor failed` and one `agent.input.processor` error event; the resume rejects with `Durable agent registry rehydration denied: input processor failed`. If durable preparation's first memory lookup throws or resolves a title-enabled `Memory`, the resume rejects with that error, including the title `TypeError`, and writes no audit event.
117
+
118
+ Security: Before this change, such a resume ran the approved tool and failed only at the next model step. A leg with no further model step finished and saved through the memory.
119
+
120
+ No migration is needed.
121
+
122
+ - 5b467f2: A run resumed through `resumeViaRuntime()` that suspends at another approval keeps blocking its thread until that approval is decided, even while an output processor has not processed or drops the approval. Under the default cache, the resumed observer starts from the current stream position without replaying earlier legs' events. Earlier resumed legs' thread registrations complete when the run ends or a resume fails after rehydration; the wrapper then publishes a terminal error.
123
+
124
+ Availability: Before this change, the thread was released while the run awaited approval. Signals to the thread were refused as blocked, or a host without a durable blocking check could start a second run.
125
+
126
+ No migration is needed.
127
+
128
+ - aa48c2c: When you set `canPersistSchedule`, its answer governs persistence for every threaded schedule fire in place of `canPersist`'s answer. This includes a wake that falls back to persistence during a deployment drain, under a run cap, or without a start seam. Delivered signals whose schedule persistence is denied carry the persistence-forbidden marker, preventing the runner from persisting them after the run ends. For those fires, `canPersist` is not called, so a throwing `canPersist` no longer fails them and hosts see fewer `canPersist` calls.
129
+
130
+ An authorized schedule wake with memory available persists, instead of being discarded, when a drain keeps it from starting a run. A fire that `canPersistSchedule` refuses is never persisted through a wake fallback, even when `canPersist` allows the system principal.
131
+
132
+ A throwing `canPersistSchedule` fails every fire on which it is consulted, including wake and deliver targets, and the schedule tick retries the fire.
133
+
134
+ - 049971f: Message, signal, notification-dispatch, and schedule routes now re-read the thread's blocking run when they wake. If that run ends while the route checks authorization or content, the idle thread wakes instead of answering `blocked`. A schedule fire no longer settles a permanent `blocked`/`skipped` receipt in that case.
135
+
136
+ This matters for hosts whose `resolveBlockingRun` answer can change while the route holds `serializeDispatch`, such as a host whose start returns while the run keeps executing. Hosts that execute a run's steps under the dispatch lock see no change. Each wake that found a blocking run makes one more `resolveBlockingRun` call, per send in a notification dispatch batch. No migration is required.
137
+
3
138
  ## 0.23.0
4
139
 
5
140
  ### Minor Changes
package/README.md CHANGED
@@ -9,7 +9,7 @@ Flowsafe runs Mastra workflows and agents through Cloudflare Durable Objects, st
9
9
  ## Install
10
10
 
11
11
  ```bash
12
- npm install @mastra/core@1.67.0 @proofoftech/flowsafe
12
+ npm install @mastra/core@1.73.0 @proofoftech/flowsafe
13
13
  ```
14
14
 
15
15
  Install `@proofoftech/breakwater` when resumed steps call approval-protected connectors:
@@ -18,6 +18,8 @@ Install `@proofoftech/breakwater` when resumed steps call approval-protected con
18
18
  npm install @proofoftech/breakwater
19
19
  ```
20
20
 
21
+ Guarded durable calls follow the [durable call-option restrictions](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/durable-agents.md#durable-call-options).
22
+
21
23
  Install React and React DOM only when you import `@proofoftech/flowsafe/approval-ui`.
22
24
 
23
25
  Compatibility:
@@ -25,9 +27,9 @@ Compatibility:
25
27
  - Node.js 22.13.0 or later (engine range `>=22.13.0`)
26
28
  - ESM only
27
29
  - TypeScript `moduleResolution: "NodeNext"`, `"Node16"`, or `"Bundler"`
28
- - `@mastra/core` `1.67.0`
30
+ - `@mastra/core` `1.73.0`
29
31
  - `react` and `react-dom` `>=18 <20` (React 18 or 19) for the optional approval UI
30
- - `@proofoftech/breakwater` `>=0.16.0 <1.0.0` when used
32
+ - `@proofoftech/breakwater` `>=0.17.0 <1.0.0` when used
31
33
  - host-provided Wrangler `>=4.118 <5` for the optional `flowsafe-provision` CLI
32
34
 
33
35
  ## Choose an export
@@ -103,7 +105,9 @@ export class AppRunner extends DurableObjectRunner<Env> {
103
105
  }
104
106
  ```
105
107
 
106
- `init()` creates D1-backed Mastra storage from the conventional `DB` binding unless you inject storage. Workflow definitions use the same `createWorkflow()` and `createStep()` shape as Mastra. Flowsafe pins `@mastra/cloudflare-d1` 1.3.2 because the shipped D1 storage is written against that release's domain surface: it subclasses the adapter's background-tasks domain to apply the `TaskFilter.resourceId` predicate the adapter accepts but omits from its SQL builder, and hand-writes the schedules, notifications, and thread-state domains the adapter does not ship at all. `D1StorageOptions.domains` accepts host-supplied `workflowDefinitions` and `knowledge` domains, which have no D1-backed defaults. The pin also holds the adapter on its `@cloudflare/workers-types` v4 peer, which is the major Flowsafe still builds against.
108
+ `init()` creates D1-backed Mastra storage from the conventional `DB` binding unless you inject storage. Workflow definitions use the same `createWorkflow()` and `createStep()` shape as Mastra. Flowsafe pins `@mastra/cloudflare-d1` `1.4.0` because the shipped D1 storage is written against that release's domain surface: it subclasses the adapter's background-tasks domain to apply the `TaskFilter.resourceId` predicate the adapter accepts but omits from its SQL builder, and hand-writes the schedules, notifications, and thread-state domains the adapter does not ship at all. `D1StorageOptions.domains` accepts host-supplied `workflowDefinitions` and `knowledge` domains, which have no D1-backed defaults. The pin also holds the adapter on its `@cloudflare/workers-types` v4 peer, which is the major Flowsafe still builds against.
109
+
110
+ Storage initialization (`init()`) adds `ownerId` and `leaseExpiresAt` to `mastra_background_tasks` with additive `ALTER TABLE … ADD COLUMN` statements. No manual migration is needed. Mastra's background-task manager claims tasks with a lease, renews it while running, skips live leases during recovery, and clears the lease on suspension. Recovery reclaims running tasks with expired or absent leases. Flowsafe continues applying the `resourceId` filter that the D1 adapter's `listTasks` omits.
107
111
 
108
112
  If the deployment uses a table prefix, pass one shared constant to storage and host maintenance:
109
113
 
@@ -150,11 +154,26 @@ The composed host mounts `POST /runs/:workflowId/:runId/terminate`. It transitio
150
154
  }
151
155
  ```
152
156
 
153
- Termination is idempotent. A retry by the same trusted principal returns the persisted terminal summary after ownership cleanup. An unrelated principal receives the same opaque `404` as any inaccessible run. A disputed economic settlement returns `409` with `reason.code` set to `DISPUTED_SETTLEMENT` before the runtime cancels active work.
157
+ Termination is idempotent. A retry by the same trusted principal returns the persisted terminal summary after ownership cleanup. An unrelated principal receives the same opaque `404` as any inaccessible run. A disputed economic settlement returns `409` with `reason.code` set to `DISPUTED_SETTLEMENT` before the runtime cancels active work. On `FencedWorkflowsStorageD1` storage, a run that completes before a terminate records its intent keeps its result and the terminate answers `409`. After the intent is recorded, a leg in the same object that completes is recorded as cancelled, while a leg on another instance that completes keeps its result and the terminate answers `409`. A terminate that keeps losing to a leg writing on another instance answers `503` and can be retried.
158
+
159
+ A run whose execution leg stops mid-step, because the platform ended the Durable Object invocation, does not stay `running`. A running leg marks its run row in D1 every 30 seconds. Once the row has gone six minutes without a write, the run's own object settles it on its next wake, and it never re-executes the interrupted step:
160
+
161
+ ```json
162
+ {
163
+ "status": "failed",
164
+ "error": "Run execution stopped mid-step before a durable outcome was recorded; external effects may have occurred. This run will not be automatically re-executed.",
165
+ "errorEnvelope": {
166
+ "code": "INTERRUPTED",
167
+ "message": "Run execution stopped mid-step before a durable outcome was recorded; external effects may have occurred. This run will not be automatically re-executed."
168
+ }
169
+ }
170
+ ```
171
+
172
+ A run with a recorded cancellation or timeout completes that transition instead. A deploy does not interrupt a leg: the outgoing instance keeps running it, and its touches keep the run from being settled. When another instance terminates, times out or otherwise settles a run whose leg is still running, that leg's next touch aborts it: no further step starts, and the step in flight sees its `abortSignal` aborted. Pass a step's `abortSignal` to the external calls it makes so they stop too; a call the abort cuts mid-flight may already have taken effect, and its abort error does not show whether it did. Mastra re-runs a step with `retries` that throws after the abort, so such a step should check `abortSignal.aborted` before its side effects and throw `MastraNonRetryableError` (from `@mastra/core/error`) once it is aborted. A Workers runtime update gives in-flight requests at most 30 seconds, so it interrupts a longer leg. Without a connected client, a Durable Object invocation lasts about 15 minutes, so each step must finish within one. Split long work into steps, and [wait without an approval](#wait-without-an-approval) rather than in an in-memory polling loop. Settlement needs the `FencedWorkflowsStorageD1` workflow domain that `createD1Storage()` composes; terminate a stranded run on other storage. See [interrupted legs](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/do-runner-design.md#interrupted-legs).
154
173
 
155
174
  Economic settlement projections are trusted internal `StartRunOptions.economicOperations` and `ResumeRunOptions.economicOperations` inputs. The host fixes the projection at an execution-leg boundary before that leg becomes cancellable. Public start and resume bodies cannot set it, and Flowsafe does not expose a dynamic mid-leg update API.
156
175
 
157
- The terminal snapshot commits before lifecycle cleanup. Cleanup abandons open approvals, discards an executing agent-schedule receipt, releases run ownership, and then records completion. A crash between those steps reuses the terminal snapshot as its retry anchor. Hosts that compose the run route must override `DurableObjectRunner.runLifecycle()`; use `createFlowsafeRunnerLifecycle()` so approval cleanup uses the same approval service and separation-of-duties configuration as the Worker.
176
+ The terminal snapshot commits before lifecycle cleanup. Cleanup abandons open approvals, discards an executing agent-schedule receipt, releases run ownership, and then records completion. A crash between those steps reuses the terminal snapshot as its retry anchor. Hosts that compose the run route must override `DurableObjectRunner.runLifecycle()`; use `createFlowsafeRunnerLifecycle()` so approval cleanup, and the approvals the run object files from its alarm, use the same approval service and separation-of-duties configuration as the Worker.
158
177
 
159
178
  `POST /runs` and the resume body accept an optional nonnegative `deadlineMs`. Resume replaces the prior deadline relative to the accepted resume leg. `RunSummary.deadlineAt` exposes the persisted epoch-millisecond deadline. The independent deadline maintenance duty sends a compare-and-swap request to the owner Durable Object and transitions each expired run once:
160
179
 
@@ -202,9 +221,9 @@ const gate = createStep({
202
221
  });
203
222
  ```
204
223
 
205
- Use `isArmableSuspensionDeadlineMs(value)` to validate relative milliseconds against the runner's safe-integer and inclusive duration bounds. Import it, those duration bounds and the reserved payload keys from `@proofoftech/flowsafe/do-runner/constants` to avoid loading the runner graph; the per-run cap `MAX_SUSPENSION_DEADLINES_PER_RUN` comes from `@proofoftech/flowsafe/do-runner`. A step declaring a Zod `suspendSchema` must declare the reserved field or use a loose object, because Mastra replaces the suspend payload with parsed output. Its `resumeSchema` must accept the timeout envelope as well as the signal shape.
224
+ Use `isArmableSuspensionDeadlineMs(value)` to validate relative milliseconds against the runner's safe-integer and inclusive duration bounds. Import it, those duration bounds and the reserved payload keys from `@proofoftech/flowsafe/do-runner/constants` to avoid loading the runner graph; the per-run cap `MAX_SUSPENSION_DEADLINES_PER_RUN` comes from `@proofoftech/flowsafe/do-runner`. A step declaring a Zod `suspendSchema` must declare the reserved fields it sets, the timer marker included, or use a loose object, because Mastra replaces the suspend payload with parsed output. Its `resumeSchema` must accept the timeout envelope as well as the signal shape.
206
225
 
207
- For workflow tests, import `suspensionTimeoutResumeData` from `@proofoftech/flowsafe/do-runner/testing` and call it with `{ step, deadlineAt }` and an expiry time. It returns the alarm's envelope shape; `isSuspensionTimeoutResumeData` checks that shape without authenticating its origin. Public resume requests containing the reserved key are rejected. Alarm resumes record system provenance and do not grant approval.
226
+ For workflow tests, import `suspensionTimeoutResumeData` from `@proofoftech/flowsafe/do-runner/testing` and call it with `{ step, deadlineAt }` and an expiry time. It returns the alarm's envelope shape; `isSuspensionTimeoutResumeData` checks that shape without authenticating its origin. Public resume requests containing the reserved key are rejected. An alarm resume keeps the run's recorded requester, so separation of duties applies to the next gate as it would without the timeout, and it grants no approval.
208
227
 
209
228
  Import `suspensionDeadlinesOf` from `@proofoftech/flowsafe/do-runner` to inspect a `RunSummary`. It returns derived entries and rejected requests without scheduling a wake or mutating the summary. See the [acceptance rules](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/do-runner-design.md#inspect-and-test-suspension-deadlines).
210
229
 
@@ -212,6 +231,37 @@ Only a top-level suspended step can arm a deadline. A step suspended inside a ne
212
231
 
213
232
  Wake precision is the Durable Object alarm's, and there is no maintenance-sweep backstop for it, so treat a suspension deadline as best-effort near its due time. Run-level `deadlineMs` remains the swept mechanism. `MAX_SUSPENSION_DEADLINES_PER_RUN` caps how many deadlines one run arms; the stored record, its parser, and the wake arithmetic stay inside the run's Durable Object, because nothing outside it can act on that state safely. Suspension deadlines apply to `DurableObjectRunner`-hosted workflow runs; durable agents keep their own resume path.
214
233
 
234
+ #### Wait without an approval
235
+
236
+ A step that only waits, such as a poll between attempts, suspends as a timer: it sets `SUSPENSION_TIMER_PAYLOAD_KEY` to `true` beside its deadline. The run's Durable Object resumes the step when the deadline expires, lists the step in `RunSummary.suspensionTimers`, and the approval bridges file no approval for it. A run that must outlast one Durable Object invocation, about 15 minutes without a connected client, waits this way between steps.
237
+
238
+ ```ts
239
+ import {
240
+ SUSPENSION_DEADLINE_PAYLOAD_KEY,
241
+ SUSPENSION_TIMER_PAYLOAD_KEY,
242
+ } from '@proofoftech/flowsafe/do-runner/constants';
243
+
244
+ const poll = createStep({
245
+ id: 'poll',
246
+ inputSchema: z.object({ jobId: z.string() }),
247
+ outputSchema: z.object({ jobId: z.string() }),
248
+ execute: async ({ inputData, suspend }) => {
249
+ // Checked on every resume, whatever resumed the step.
250
+ if (!(await jobFinished(inputData.jobId))) {
251
+ return suspend({
252
+ [SUSPENSION_TIMER_PAYLOAD_KEY]: true,
253
+ [SUSPENSION_DEADLINE_PAYLOAD_KEY]: 60_000,
254
+ });
255
+ }
256
+ return { jobId: inputData.jobId };
257
+ },
258
+ });
259
+ ```
260
+
261
+ A timer can still receive an approval: the run object lists a step only while it can vouch for the wake, and every other case files an ordinary approval (see [timer suspensions](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/do-runner-design.md#timer-suspensions)). So a timer step accepts an approval decision's `{ approved, comment?, decidedBy? }` as well as the timeout envelope, in its `resumeSchema` and its branch, and re-checks its wait condition on every resume rather than treating any resume as permission to proceed. The run object files the approvals a timer leaves to a person through the `reconcileApprovals` hook that `createFlowsafeRunnerLifecycle()` fills; see [approvals the run object files](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/do-runner-design.md#approvals-the-run-object-files) for when it files and what it leaves to a host status read. After every timeout resume it also attempts to close an approval still open for the suspension that resume ended.
262
+
263
+ The marker lives in the step's suspend payload, so a step that spreads untrusted data into that payload can make a gate wait without an approval for up to the deadline. A `foreach` with `concurrency` above 1 reports one payload for its suspended iterations, so one iteration's marker applies to the batch.
264
+
215
265
  Read the [Durable Object runner design](https://github.com/ProofOfTechOrg/anchorage/blob/main/docs/do-runner-design.md) for the suspension fence, the stored record, and the failure modes.
216
266
 
217
267
  ### REST surface
@@ -326,7 +376,7 @@ Use `GET /admin/inventory` while the fence remains `draining`. A drain is proven
326
376
 
327
377
  The host mints opaque, path-safe run and thread ids. `RunnerRuntime.start()` requires a host-owned run id and has no generation fallback. The id scopes the snapshot, Durable Object, approval lookup, stream address, and artifact path, but it carries no customer identity.
328
378
 
329
- Callers that need exactly-once start behavior supply an `idempotencyKey`, never a run ID. The key is available on `POST /runs`, trusted agent-host starts, and `streamUntilPersisted()`. A retry returns the same persisted run. `IDEMPOTENT_START_PENDING` includes `pendingSince`; re-probe the point-in-time `IDEMPOTENT_START_UNRESOLVABLE` result before acting. A key remains valid until its reservation-retention horizon expires.
379
+ Callers that need exactly-once start behavior supply an `idempotencyKey`, never a run ID. The key is available on `POST /runs`, trusted agent-host starts, and `streamUntilPersisted()`. A retry returns the same persisted run. `IDEMPOTENT_START_PENDING` includes `pendingSince`; re-probe the point-in-time `IDEMPOTENT_START_UNRESOLVABLE` result before acting. For an agent start, keep re-probing for at least seven minutes after its last activity before choosing a fresh key: until the thread object repairs a start whose leg stopped or runs on another instance, its replay answers `IDEMPOTENT_START_UNRESOLVABLE`. A key remains valid until its reservation-retention horizon expires.
330
380
 
331
381
  ### Pass application context at start
332
382
 
@@ -1 +1 @@
1
- {"version":3,"file":"thread-host.d.ts","sourceRoot":"","sources":["../../src/agent-host/thread-host.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAWjE,OAAO,EAGL,KAAK,cAAc,EAQnB,KAAK,oBAAoB,EACzB,KAAK,2BAA2B,EAIjC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,KAAK,iBAAiB,EAEtB,KAAK,eAAe,EAEpB,KAAK,kBAAkB,EAIvB,KAAK,iCAAiC,EAIvC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,KAAK,2BAA2B,EAGjC,MAAM,8BAA8B,CAAC;AAUtC,OAAO,EAGL,KAAK,sBAAsB,EAC3B,KAAK,UAAU,EAIf,KAAK,mBAAmB,EAExB,KAAK,WAAW,EACjB,MAAM,uBAAuB,CAAC;AAO/B,OAAO,EAEL,KAAK,SAAS,EACf,MAAM,oCAAoC,CAAC;AAK5C,OAAO,EAEL,KAAK,uBAAuB,EAE7B,MAAM,4CAA4C,CAAC;AAgBpD,OAAO,KAAK,EACV,WAAW,EAEX,gBAAgB,EAEhB,2BAA2B,EAE5B,MA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AK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,OAAO,CAAC,CAAC;IACpB,KAAK,CACH,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE,qBAAqB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC7B,iBAAiB,CACf,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE;QACL,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,SAAS,EAAE,cAAc,CAAC;KAC3B,GACA,OAAO,CAAC,gBAAgB,CAAC,CAAC;IAC7B;;;;OAIG;IACH,WAAW,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,GAAG,SAAS,CAAC,CAAC;IACvE,uEAAuE;IACvE,sBAAsB,CACpB,KAAK,EAAE,WAAW,EAClB,KAAK,EAAE;QAAE,OAAO,EAAE,MAAM,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,GAC5D,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC,CAAC;IACnC,gBAAgB,CAAC,KAAK,EAAE,wBAAwB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACjE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;CACvE;AAiTD,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,sBAAsB,GAC9B,eAAe,CA80EjB"}
@@ -8,7 +8,7 @@ import { AgentRunSelectorMismatchError, } from '../agent-runner/durable-agent-ru
8
8
  import { AGENT_ENTRY_PATHS, AGENT_RUN_STORAGE_KEY_PREFIX, bindAgentThread, createFlowsafeDurableAgent, deleteAgentRunRecord, deleteAgentThreadBinding, readAgentRunRecord, readAgentThreadBinding, writeAgentRunRecord, } from '../agent-runner/index.js';
9
9
  import { canonicalResourceOwner, principalActor, principalAuditFields, principalOwner, RUN_START_ROLES, samePrincipal, } from '../approval-api/index.js';
10
10
  import { assertExecutionPrincipal, isExecutionPrincipalId, } from '../approval-api/principal.js';
11
- import { ExecutionFenceUnreadableError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeRunExecutionIdentity, RunStartPendingError, } from '../do-runner/execution-admission.js';
11
+ import { ExecutionFenceUnreadableError, isRunStartPendingError, normalizeD1RunExecutionIdentity, normalizeMutationEpoch, normalizeRunExecutionIdentity, RunStartPendingError, } from '../do-runner/execution-admission.js';
12
12
  import { DoStatusError, isPathSafeId, resolveScheduleStartOwner, resourceIdFromKey, SUSPENSION_TIMEOUT_RESUME_KEY, } from '../do-runner/index.js';
13
13
  import { isDefinitiveInitialAdmissionRefusal } from '../do-runner/initial-admission-refusal.js';
14
14
  import { mastraRegistryEntries } from '../do-runner/mastra-registry.js';
@@ -116,6 +116,7 @@ function providerOptions(value) {
116
116
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
117
117
  throw new AgentHostRequestError(400, 'providerOptions must be an object');
118
118
  }
119
+ // The closed provider-options check validates this snapshot's namespaces and keys before use; the model provider validates the values when it parses its options.
119
120
  return structuredClone(value);
120
121
  }
121
122
  function record(value) {
@@ -438,6 +439,11 @@ export function createThreadAgentHost(options) {
438
439
  });
439
440
  if (!module)
440
441
  throw new AgentHostRequestError(404, 'agent not found');
442
+ // A resolver failure is an operational fault, not a denial; a retryable
443
+ // status lets automated callers retry.
444
+ if (decision === 'error') {
445
+ throw new AgentHostRequestError(503, 'permission resolution unavailable');
446
+ }
441
447
  if (!granted)
442
448
  throw new AgentHostRequestError(403, 'forbidden');
443
449
  return { current, module, principalPermissions };
@@ -1059,6 +1065,10 @@ export function createThreadAgentHost(options) {
1059
1065
  owner: principalOwner(stored.runRecord.principal),
1060
1066
  threaded: stored.threaded,
1061
1067
  },
1068
+ // Agent legs touch their row while they run.
1069
+ startLeg: ownFrame !== undefined && unwoundExecutions.has(ownFrame)
1070
+ ? 'unwound'
1071
+ : 'touched',
1062
1072
  });
1063
1073
  }
1064
1074
  else {
@@ -1191,7 +1201,21 @@ export function createThreadAgentHost(options) {
1191
1201
  prefix: AGENT_OWNER_RECOVERY_PREFIX,
1192
1202
  });
1193
1203
  for (const [key, stored] of pending) {
1194
- await recoverOwner(scope, key, stored);
1204
+ try {
1205
+ await recoverOwner(scope, key, stored);
1206
+ }
1207
+ catch (error) {
1208
+ // A start whose leg may still run, or whose row has not gone
1209
+ // silent, settled nothing: its journal and the wake stay for a
1210
+ // later alarm, and the other journals are still recovered.
1211
+ if (!isRunStartPendingError(error))
1212
+ throw error;
1213
+ console.error(JSON.stringify({
1214
+ type: 'agent-start-recovery-pending',
1215
+ threadId: scope.threadId,
1216
+ runId: stored.runId,
1217
+ }));
1218
+ }
1195
1219
  }
1196
1220
  await withRecoveryLock(async () => {
1197
1221
  const remaining = await storage.list({