@proofoftech/flowsafe 0.4.0 → 0.6.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 (222) hide show
  1. package/CHANGELOG.md +307 -0
  2. package/dist/agent-runner/approval-shapes.d.ts +36 -0
  3. package/dist/agent-runner/approval-shapes.d.ts.map +1 -0
  4. package/dist/agent-runner/approval-shapes.js +101 -0
  5. package/dist/agent-runner/approval-shapes.js.map +1 -0
  6. package/dist/agent-runner/durable-agent-runner.d.ts +154 -0
  7. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -0
  8. package/dist/agent-runner/durable-agent-runner.js +291 -0
  9. package/dist/agent-runner/durable-agent-runner.js.map +1 -0
  10. package/dist/agent-runner/index.d.ts +3 -0
  11. package/dist/agent-runner/index.d.ts.map +1 -0
  12. package/dist/agent-runner/index.js +10 -0
  13. package/dist/agent-runner/index.js.map +1 -0
  14. package/dist/approval-api/d1-store.d.ts.map +1 -1
  15. package/dist/approval-api/d1-store.js +85 -17
  16. package/dist/approval-api/d1-store.js.map +1 -1
  17. package/dist/approval-api/index.d.ts +1 -1
  18. package/dist/approval-api/index.d.ts.map +1 -1
  19. package/dist/approval-api/index.js.map +1 -1
  20. package/dist/approval-api/router.d.ts +1 -1
  21. package/dist/approval-api/router.d.ts.map +1 -1
  22. package/dist/approval-api/router.js +1 -0
  23. package/dist/approval-api/router.js.map +1 -1
  24. package/dist/approval-api/service.d.ts +2 -2
  25. package/dist/approval-api/service.d.ts.map +1 -1
  26. package/dist/approval-api/service.js +15 -1
  27. package/dist/approval-api/service.js.map +1 -1
  28. package/dist/approval-api/store.d.ts +10 -6
  29. package/dist/approval-api/store.d.ts.map +1 -1
  30. package/dist/approval-api/store.js +15 -0
  31. package/dist/approval-api/store.js.map +1 -1
  32. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  33. package/dist/approval-api/tenant-context.js +15 -0
  34. package/dist/approval-api/tenant-context.js.map +1 -1
  35. package/dist/approval-api/types.d.ts +8 -0
  36. package/dist/approval-api/types.d.ts.map +1 -1
  37. package/dist/approval-api/types.js.map +1 -1
  38. package/dist/background-tasks/d1-storage.d.ts +66 -0
  39. package/dist/background-tasks/d1-storage.d.ts.map +1 -0
  40. package/dist/background-tasks/d1-storage.js +196 -0
  41. package/dist/background-tasks/d1-storage.js.map +1 -0
  42. package/dist/background-tasks/host.d.ts +82 -0
  43. package/dist/background-tasks/host.d.ts.map +1 -0
  44. package/dist/background-tasks/host.js +275 -0
  45. package/dist/background-tasks/host.js.map +1 -0
  46. package/dist/background-tasks/index.d.ts +7 -0
  47. package/dist/background-tasks/index.d.ts.map +1 -0
  48. package/dist/background-tasks/index.js +10 -0
  49. package/dist/background-tasks/index.js.map +1 -0
  50. package/dist/background-tasks/routes.d.ts +15 -0
  51. package/dist/background-tasks/routes.d.ts.map +1 -0
  52. package/dist/background-tasks/routes.js +144 -0
  53. package/dist/background-tasks/routes.js.map +1 -0
  54. package/dist/do-runner/d1-storage.d.ts +343 -2
  55. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  56. package/dist/do-runner/d1-storage.js +565 -12
  57. package/dist/do-runner/d1-storage.js.map +1 -1
  58. package/dist/do-runner/do-error-response.d.ts +29 -0
  59. package/dist/do-runner/do-error-response.d.ts.map +1 -0
  60. package/dist/do-runner/do-error-response.js +73 -0
  61. package/dist/do-runner/do-error-response.js.map +1 -0
  62. package/dist/do-runner/durable-object.d.ts +1 -1
  63. package/dist/do-runner/durable-object.d.ts.map +1 -1
  64. package/dist/do-runner/durable-object.js +2 -16
  65. package/dist/do-runner/durable-object.js.map +1 -1
  66. package/dist/do-runner/index.d.ts +9 -3
  67. package/dist/do-runner/index.d.ts.map +1 -1
  68. package/dist/do-runner/index.js +8 -2
  69. package/dist/do-runner/index.js.map +1 -1
  70. package/dist/do-runner/init.d.ts +20 -0
  71. package/dist/do-runner/init.d.ts.map +1 -1
  72. package/dist/do-runner/init.js +12 -1
  73. package/dist/do-runner/init.js.map +1 -1
  74. package/dist/do-runner/pubsub.d.ts +18 -0
  75. package/dist/do-runner/pubsub.d.ts.map +1 -0
  76. package/dist/do-runner/pubsub.js +42 -0
  77. package/dist/do-runner/pubsub.js.map +1 -0
  78. package/dist/do-runner/runtime.d.ts +24 -0
  79. package/dist/do-runner/runtime.d.ts.map +1 -1
  80. package/dist/do-runner/runtime.js +29 -2
  81. package/dist/do-runner/runtime.js.map +1 -1
  82. package/dist/do-runner/thread-do.d.ts +74 -0
  83. package/dist/do-runner/thread-do.d.ts.map +1 -0
  84. package/dist/do-runner/thread-do.js +156 -0
  85. package/dist/do-runner/thread-do.js.map +1 -0
  86. package/dist/do-runner/thread-header.d.ts +16 -0
  87. package/dist/do-runner/thread-header.d.ts.map +1 -0
  88. package/dist/do-runner/thread-header.js +24 -0
  89. package/dist/do-runner/thread-header.js.map +1 -0
  90. package/dist/goals/index.d.ts +2 -0
  91. package/dist/goals/index.d.ts.map +1 -0
  92. package/dist/goals/index.js +7 -0
  93. package/dist/goals/index.js.map +1 -0
  94. package/dist/goals/objective-routes.d.ts +87 -0
  95. package/dist/goals/objective-routes.d.ts.map +1 -0
  96. package/dist/goals/objective-routes.js +375 -0
  97. package/dist/goals/objective-routes.js.map +1 -0
  98. package/dist/host-kit/approval-bridge.d.ts +24 -4
  99. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  100. package/dist/host-kit/approval-bridge.js +32 -10
  101. package/dist/host-kit/approval-bridge.js.map +1 -1
  102. package/dist/host-kit/env-vars.d.ts +20 -0
  103. package/dist/host-kit/env-vars.d.ts.map +1 -1
  104. package/dist/host-kit/env-vars.js +30 -0
  105. package/dist/host-kit/env-vars.js.map +1 -1
  106. package/dist/host-kit/flowsafe-worker.d.ts +111 -4
  107. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  108. package/dist/host-kit/flowsafe-worker.js +253 -63
  109. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  110. package/dist/host-kit/index.d.ts +3 -1
  111. package/dist/host-kit/index.d.ts.map +1 -1
  112. package/dist/host-kit/index.js +7 -0
  113. package/dist/host-kit/index.js.map +1 -1
  114. package/dist/host-kit/memory-boundary.d.ts +64 -0
  115. package/dist/host-kit/memory-boundary.d.ts.map +1 -0
  116. package/dist/host-kit/memory-boundary.js +109 -0
  117. package/dist/host-kit/memory-boundary.js.map +1 -0
  118. package/dist/host-kit/route-path.d.ts +17 -0
  119. package/dist/host-kit/route-path.d.ts.map +1 -0
  120. package/dist/host-kit/route-path.js +35 -0
  121. package/dist/host-kit/route-path.js.map +1 -0
  122. package/dist/host-kit/thread-topology.d.ts +44 -0
  123. package/dist/host-kit/thread-topology.d.ts.map +1 -0
  124. package/dist/host-kit/thread-topology.js +76 -0
  125. package/dist/host-kit/thread-topology.js.map +1 -0
  126. package/dist/index.d.ts +3 -3
  127. package/dist/index.d.ts.map +1 -1
  128. package/dist/index.js +1 -1
  129. package/dist/index.js.map +1 -1
  130. package/dist/internal-error-response.d.ts +3 -0
  131. package/dist/internal-error-response.d.ts.map +1 -0
  132. package/dist/internal-error-response.js +20 -0
  133. package/dist/internal-error-response.js.map +1 -0
  134. package/dist/numeric-config.d.ts +4 -0
  135. package/dist/numeric-config.d.ts.map +1 -0
  136. package/dist/numeric-config.js +23 -0
  137. package/dist/numeric-config.js.map +1 -0
  138. package/dist/schedules/index.d.ts +5 -0
  139. package/dist/schedules/index.d.ts.map +1 -0
  140. package/dist/schedules/index.js +13 -0
  141. package/dist/schedules/index.js.map +1 -0
  142. package/dist/schedules/router.d.ts +66 -0
  143. package/dist/schedules/router.d.ts.map +1 -0
  144. package/dist/schedules/router.js +827 -0
  145. package/dist/schedules/router.js.map +1 -0
  146. package/dist/schedules/schedules-d1.d.ts +30 -0
  147. package/dist/schedules/schedules-d1.d.ts.map +1 -0
  148. package/dist/schedules/schedules-d1.js +374 -0
  149. package/dist/schedules/schedules-d1.js.map +1 -0
  150. package/dist/schedules/storage.d.ts +11 -0
  151. package/dist/schedules/storage.d.ts.map +1 -0
  152. package/dist/schedules/storage.js +34 -0
  153. package/dist/schedules/storage.js.map +1 -0
  154. package/dist/schedules/tick.d.ts +131 -0
  155. package/dist/schedules/tick.d.ts.map +1 -0
  156. package/dist/schedules/tick.js +598 -0
  157. package/dist/schedules/tick.js.map +1 -0
  158. package/dist/signal-providers/delivery.d.ts +24 -0
  159. package/dist/signal-providers/delivery.d.ts.map +1 -0
  160. package/dist/signal-providers/delivery.js +62 -0
  161. package/dist/signal-providers/delivery.js.map +1 -0
  162. package/dist/signal-providers/github-provider.d.ts +33 -0
  163. package/dist/signal-providers/github-provider.d.ts.map +1 -0
  164. package/dist/signal-providers/github-provider.js +116 -0
  165. package/dist/signal-providers/github-provider.js.map +1 -0
  166. package/dist/signal-providers/host-do.d.ts +79 -0
  167. package/dist/signal-providers/host-do.d.ts.map +1 -0
  168. package/dist/signal-providers/host-do.js +216 -0
  169. package/dist/signal-providers/host-do.js.map +1 -0
  170. package/dist/signal-providers/index.d.ts +7 -0
  171. package/dist/signal-providers/index.d.ts.map +1 -0
  172. package/dist/signal-providers/index.js +19 -0
  173. package/dist/signal-providers/index.js.map +1 -0
  174. package/dist/signal-providers/provider.d.ts +92 -0
  175. package/dist/signal-providers/provider.d.ts.map +1 -0
  176. package/dist/signal-providers/provider.js +87 -0
  177. package/dist/signal-providers/provider.js.map +1 -0
  178. package/dist/signal-providers/subscription-d1.d.ts +88 -0
  179. package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
  180. package/dist/signal-providers/subscription-d1.js +259 -0
  181. package/dist/signal-providers/subscription-d1.js.map +1 -0
  182. package/dist/signal-providers/webhook-route.d.ts +88 -0
  183. package/dist/signal-providers/webhook-route.d.ts.map +1 -0
  184. package/dist/signal-providers/webhook-route.js +391 -0
  185. package/dist/signal-providers/webhook-route.js.map +1 -0
  186. package/dist/signals/client.d.ts +72 -0
  187. package/dist/signals/client.d.ts.map +1 -0
  188. package/dist/signals/client.js +87 -0
  189. package/dist/signals/client.js.map +1 -0
  190. package/dist/signals/d1-shared.d.ts +43 -0
  191. package/dist/signals/d1-shared.d.ts.map +1 -0
  192. package/dist/signals/d1-shared.js +46 -0
  193. package/dist/signals/d1-shared.js.map +1 -0
  194. package/dist/signals/index.d.ts +9 -0
  195. package/dist/signals/index.d.ts.map +1 -0
  196. package/dist/signals/index.js +15 -0
  197. package/dist/signals/index.js.map +1 -0
  198. package/dist/signals/notification-dispatch.d.ts +52 -0
  199. package/dist/signals/notification-dispatch.d.ts.map +1 -0
  200. package/dist/signals/notification-dispatch.js +198 -0
  201. package/dist/signals/notification-dispatch.js.map +1 -0
  202. package/dist/signals/notifications-d1.d.ts +28 -0
  203. package/dist/signals/notifications-d1.d.ts.map +1 -0
  204. package/dist/signals/notifications-d1.js +704 -0
  205. package/dist/signals/notifications-d1.js.map +1 -0
  206. package/dist/signals/router.d.ts +73 -0
  207. package/dist/signals/router.d.ts.map +1 -0
  208. package/dist/signals/router.js +240 -0
  209. package/dist/signals/router.js.map +1 -0
  210. package/dist/signals/storage.d.ts +11 -0
  211. package/dist/signals/storage.d.ts.map +1 -0
  212. package/dist/signals/storage.js +27 -0
  213. package/dist/signals/storage.js.map +1 -0
  214. package/dist/signals/thread-do-routes.d.ts +82 -0
  215. package/dist/signals/thread-do-routes.d.ts.map +1 -0
  216. package/dist/signals/thread-do-routes.js +660 -0
  217. package/dist/signals/thread-do-routes.js.map +1 -0
  218. package/dist/signals/thread-state-d1.d.ts +22 -0
  219. package/dist/signals/thread-state-d1.d.ts.map +1 -0
  220. package/dist/signals/thread-state-d1.js +83 -0
  221. package/dist/signals/thread-state-d1.js.map +1 -0
  222. package/package.json +11 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,312 @@
1
1
  # @proofoftech/flowsafe
2
2
 
3
+ ## 0.6.0
4
+
5
+ ### Minor Changes
6
+
7
+ - eca3b6e: Close the durable-agent, agent-schedule, notification-dispatch, and D1 background-task execution residuals with tenant-safe thread routing and eviction-safe approval resume. Harden stored schedule context and core schedule-contract validation; make D1 notification creation preserve explicit-id coalescing, insertion-order targets, rollback-safe atomic migration, and concurrent partial updates; priority-plan summary and individual delivery across state-stable 100-id batches; accept Mastra's raw constructor pubsub with rollback-safe workers and a synchronous enqueue shutdown gate; close failed resume streams; validate public numeric configuration synchronously; preserve nested Mastra background-task SSE events; and require a proven process shutdown before spike restart.
8
+ - d54d2be: Track D — schedules (`@proofoftech/flowsafe/schedules`, additive, opt-in). A new
9
+ subpath ships the D1 schedules domain, a CAS-driven tick we own, and a tenant
10
+ facade — all on the single DO + D1 RunnerRuntime substrate (P1), no new
11
+ `ApprovalRecord` shape or existing signature changed, unconfigured hosts
12
+ byte-identical.
13
+
14
+ - `D1SchedulesStorage` + `createScheduleStorageDomains` — the flowsafe-owned D1
15
+ domain over `mastra_schedules` / `mastra_schedule_triggers` (the
16
+ `@mastra/cloudflare-d1` adapter ships neither), mirroring core's
17
+ `SchedulesStorage` contract incl. the CAS `updateScheduleNextFire`. Composed
18
+ into `createD1Storage` via the injected `domains` seam.
19
+ - `createScheduleTick` — we OWN the tick (DL-012): `listDueSchedules` → CAS claim
20
+ → workflow targets mint a fresh INV-1 runId and fire through the host's
21
+ run-start seam; agent targets are GUARDED OFF (their only public fire path,
22
+ `schedules.run(id)`, enqueues onto core's pubsub worker loop we do not run, so
23
+ firing is a fail-closed audited skip — agent-target execution is deferred). An
24
+ injectable run-cap seam (DL-007) skips a capped tenant while the schedule stays
25
+ healthy. The P4 stored-context barrier strips reserved keys before any leg.
26
+ - `createScheduleRouter` — the tenant facade (DL-013): server-minted ids,
27
+ `metadata.tenantId` stamping, tenant-filtered reads, ownership 404s (no
28
+ oracle), per-tenant count + fire-rate caps, and P4 reserved-key rejection on
29
+ create/update (the whole `breakwater.` namespace + `mastra:goal`).
30
+ - Storage triad (DL-003): both tables register in the schema-guard inventory
31
+ (8 → 10) with a new metadata-filtered `purgeTenant` kind
32
+ (`TENANT_METADATA_PURGE_TABLES`), plus `purgeExpiredScheduleTriggers` for the
33
+ trigger-history TTL. `createFlowsafeWorker` gains an opt-in `scheduleTick` seam
34
+ (its own failure-isolated cron duty) and a `SCHEDULE_TRIGGER_RETENTION_DAYS`
35
+ purge duty.
36
+
37
+ - 0f4f70a: Track E (M-007) — signal providers: a new subpath `@proofoftech/flowsafe/signal-providers`
38
+ (additive, opt-in, subpath-only). Host external-event providers on a Durable
39
+ Object with alarm-driven polling, terminate provider webhooks on the Worker, and
40
+ persist subscriptions in a flowsafe-owned D1 table.
41
+
42
+ - `SignalProviderHost` — a per-tenant provider host DO (`idFromName(tenantId)`)
43
+ whose alarm rehydrates subscriptions from D1 (core's registry is in-memory,
44
+ lost on eviction) and polls each of the tenant's providers with per-provider +
45
+ per-delivery failure isolation, delivering through Track C's thread-DO topology.
46
+ - `D1SubscriptionStoreFactory` — a flowsafe-owned, tenant-columned
47
+ `flowsafe_signal_subscriptions` store mirroring the approval store's INV-2
48
+ posture (`.forTenant()` tenant-bound, `.system().listByResource()` the webhook's
49
+ cross-tenant authority). Registered in `purgeTenant` (`PurgeTenantResult.subscriptions`);
50
+ retention is `none` (standing config reaped only at offboarding).
51
+ - `createWebhookRouter` — webhook ingress that verifies the provider signature
52
+ over the RAW bytes BEFORE parsing, maps the payload to a tenant via the
53
+ subscription ROW only (never the payload), rate-caps per provider+tenant, and
54
+ audits every ingest with a bounded forgery audit. `createSubscriptionRouter` —
55
+ the human-only HTTP subscribe/unsubscribe surface (never exposed as model
56
+ tools; mints no capability).
57
+ - `githubSignalProvider` — a binding-gated GitHub reference provider
58
+ (`X-Hub-Signature-256` verified constant-time via WebCrypto). `createWebhookSignalProvider`
59
+ is the generic path.
60
+
61
+ Also adds a `subscriptions` counter to `PurgeTenantResult` (the DL-003 offboarding
62
+ coverage for the new flowsafe-owned table).
63
+
64
+ - 6c80e92: Track F (M-005) — goals. New subpath-only export `@proofoftech/flowsafe/goals`:
65
+ `createObjectiveRouter`, a role-gated + audited objective HTTP surface
66
+ (set/get/update/clear over `/api/threads/:threadId/goal`) that writes the
67
+ thread-scoped goal record in Track C's `mastra_thread_state` domain
68
+ (`GOAL_STATE_TYPE` 'goal'). The write path is a P6-lite ingestion boundary
69
+ (auth → coarse role → thread-prefix ownership 404 → size cap →
70
+ `assertNoClientMemoryIds` → field allowlist → maxRuns host cap → audit) and
71
+ persists through `@mastra/core`'s own `writeObjective`/`readObjective`/
72
+ `clearObjective`, so a record it writes is byte-identical to what the durable
73
+ goal step reads via `resolveGoalStore` (DL-018 — no thread-DO affinity needed
74
+ for the write). A requested `maxRuns` above the host cap is rejected, not
75
+ clamped (default the core `DEFAULT_GOAL_MAX_RUNS`, 50; DL-007). Goals never mint
76
+ capability (P8) and Track F starts no runs — per-tenant run budgets stay
77
+ enforced at the existing seams. `GOAL_REQUEST_CONTEXT_KEY` ('mastra:goal') is
78
+ reserved with a no-collision pin against the runtime's requestContext base keys.
79
+ Hosts mount the surface opt-in through `createFlowsafeWorker`'s new
80
+ `buildObjectiveRouter` seam; absent config is byte-identical. Additive only — no
81
+ new table, schema-guard, purge, or TTL change (reuses the Track C thread-state
82
+ domain), and no existing signature or `ApprovalRecord` shape changes.
83
+
84
+ ### Patch Changes
85
+
86
+ - 8e3562f: Make approval filing atomic across terminal and open records for the same captured suspension fingerprint, preventing stale reconciliation from filing over a decision.
87
+ - 97cb097: Harden the P6 ingestion routers against a pre-auth malformed-path fault. The
88
+ signal, goal, and schedule routers decoded the threadId/schedule-id path
89
+ segment with bare `decodeURIComponent` before authentication, and
90
+ `createFlowsafeWorker`'s fetch handler did not wrap the router calls — so an
91
+ unauthenticated request with malformed percent-encoding (e.g.
92
+ `POST /api/threads/%/message`) threw a `URIError` out of `fetch()` as a
93
+ per-request 500. The three routers now use a shared `safeDecodeSegment`
94
+ (host-kit) that treats malformed encoding as route-absent (byte-identical to a
95
+ non-matching path), matching the Track E webhook router; the worker fetch
96
+ handler gains a top-level try/catch that contains any handler throw as a
97
+ generic 500 without leaking `error.message`. The same helper closes the whole
98
+ class: the background-tasks read route (post-auth, DO-mounted) adopts it too, so
99
+ a malformed taskId returns the no-oracle 404 instead of throwing. Additive and
100
+ behavior-preserving for all valid paths.
101
+
102
+ ## 0.5.0
103
+
104
+ ### Minor Changes
105
+
106
+ - 281c6d1: Track 0 (substrate for the long-running-agents program): close the agent-memory
107
+ tenancy obligations and add the seams the agent tracks build on. All additive —
108
+ a host that configures none of it is byte-identical.
109
+
110
+ - **Agent-memory host boundary** (`@proofoftech/flowsafe/host-kit`):
111
+ `assertNoClientMemoryIds(body)` rejects (400) any request body naming
112
+ `threadId`/`resourceId` — memory ids are minted server-side from the
113
+ authenticated tenant via `TenantContext.newThreadId()/newResourceId()`, never
114
+ chosen by a client — and `requireOwnedMemoryId(tenant, id)` answers 404 (not
115
+ 403, so no existence oracle) on a foreign id. Every memory-touching route MUST
116
+ call both (the rule the agent-domain routes in later tracks adopt).
117
+ - **Recall-path proof**: core's own `MastraMemory` implementation over the real
118
+ D1 store, two tenants keyed by the SAME business key, pinning that `recall()`,
119
+ `listThreads({filter:{resourceId}})`, and resource-scoped `getWorkingMemory()`
120
+ never cross tenants.
121
+ - **Thread TTL**: `purgeExpiredThreads(db, { ttlMs, limit, tablePrefix })`, wired
122
+ into `createFlowsafeWorker`'s purge cron behind the new `THREAD_RETENTION_DAYS`
123
+ var with its own failure isolation. Keyed on `mastra_threads.updatedAt`
124
+ (threads are not per-run and have no terminal status); messages go with their
125
+ thread and before it; working-memory rows are untouched. Unset by default — no
126
+ thread expires until an operator names a number.
127
+ - **Extensible purge/guard inventory** (`TENANT_RANGE_PURGE_TABLES`,
128
+ `TenantRangePurgeTable`, `TenantRangePurgeCounter`): adopting a `mastra_*`
129
+ domain is now one additive row plus the counter/result pair the types force in
130
+ the same change; the schema guard still trips on any silently added table, and
131
+ its inventory now also forces each table's retention story — where "no TTL"
132
+ demands a written reason, so an absent decision cannot read as "none needed".
133
+ - **Host pubsub identity** (`createHostPubSub`, `HostPubSub`): the seam for one
134
+ in-process `EventEmitterPubSub` per host DO — passed to `init()` (new
135
+ `InitOptions.pubsub`), taken back off `InitResult.pubsub`, and threaded into
136
+ the runtime (new `RunnerRuntimeOptions.pubsub`, readable as
137
+ `RunnerRuntime.pubsub`) so a host reaches it with no host change. Every
138
+ consumer in the isolate then shares one emitter instead of each letting core
139
+ default its own (two such feeds never see each other's events). The identity
140
+ and the seam only: nothing passes it to core's `createRun` yet, so a configured
141
+ pubsub is an identity the host holds, not yet a feed core publishes on. Opt-in;
142
+ absent leaves polling as the fallback.
143
+ - **`ThreadDurableObject`**: per-thread DO base addressed `idFromName(threadId)`
144
+ where the threadId is tenant-minted, so its name carries the tenant like a
145
+ runId. Every request must state its authenticated tenant
146
+ (`THREAD_TENANT_HEADER`) and is asserted against that prefix before the
147
+ subclass's `route()` runs — fail closed (403). Everything else it throws rides
148
+ the shared `doErrorResponse` taxonomy, so a run driven from a thread route
149
+ keeps its 404/409/400 instead of collapsing to a 500.
150
+ - **`createThreadTopology`** (`@proofoftech/flowsafe/host-kit`): the sanctioned
151
+ way to reach a per-thread DO, and the MINTER for the header
152
+ `ThreadDurableObject` verifies. `send`/`forward` refuse (404) a threadId the
153
+ authenticated tenant does not own — before the DO is addressed — and stamp
154
+ `x-flowsafe-tenant` from the resolved `TenantContext`, `forward` OVERWRITING
155
+ whatever a client's own request carried. Mint and verify ship together:
156
+ forwarding a client Request verbatim (the existing hub idiom) would otherwise
157
+ let the client write the very header the thread DO authenticates on.
158
+
159
+ - 4ea35fd: Track A (durable agents): drive Mastra's durable-agent loop through the one
160
+ RunnerRuntime chokepoint so agent legs inherit the substrate's invariants —
161
+ additive and opt-in, no existing signature or `ApprovalRecord` shape changed.
162
+
163
+ - `@proofoftech/flowsafe/agent-runner` (new subpath): `createFlowsafeDurableAgent`
164
+ returns a `DurableAgent` subclass whose `executeWorkflow(runId, workflowInput)`
165
+ calls `runtime.start('durable-agentic-loop', { runId, inputData })` instead of
166
+ the base `createRun + start` (DL-001/DL-010), so INV-1 (server-minted runId),
167
+ the per-leg `requestContextForRun` grant derivation, and the resume ledger
168
+ apply to agent legs. `stream()`/`generate()`/`prepare()` are overridden to
169
+ REQUIRE a caller-minted runId — closing every inherited minting entry point's
170
+ upstream `crypto.randomUUID()` fallback (INV-1: a durable-agent run must carry
171
+ its tenant everywhere it becomes a key). The shared loop workflow is registered on
172
+ the runtime idempotently; the agent's stream pubsub defaults to the runtime's
173
+ identity (one feed per DO). `resume()` stays non-client-facing — resume flows
174
+ only through the approval-decision path (grant-only doctrine, P8).
175
+ - The durable tool-call step hands `tool.execute` the ENGINE-LEG requestContext
176
+ from its step params (spike S1, verified against `@mastra/core` 1.50.0 dist),
177
+ so the `breakwater.approvedConnectors` grant reaches the connector write gate
178
+ with zero extra wiring and a forged/self resume fails closed there.
179
+ - R-003: the record-creation/bridge path parses BOTH durable approval-suspend
180
+ shapes — nested `{ type:'approval', requireToolApproval:{ toolCallId, toolName,
181
+ args } }` and flat `{ type:'approval', toolCallId, toolName, args }` — and
182
+ derives `connectors:[toolName]` (the connector id the write gate checks) so an
183
+ approved agent gate mints exactly that grant. The resume-routing
184
+ `threadId`-capture seam (DL-002) is deferred to Track C, where the thread-DO
185
+ consumes it.
186
+ - `RunnerRuntime` now threads the host pubsub identity into both `createRun`
187
+ sites (`createRun({ runId, pubsub })`); undefined leaves behavior
188
+ byte-identical (polling fallback).
189
+ - The workerd `spike:verify` grows agent-gate scenarios proving the R-003
190
+ round-trip and forged-resume fail-closed on real workerd + D1.
191
+
192
+ - 15d4ec3: Track B (background tasks): the additive, opt-in substrate + defenses for
193
+ Mastra background tasks on the one Durable-Object + D1 chokepoint. No existing
194
+ signature or the `ApprovalRecord` shape changed; hosts stay byte-identical with
195
+ background tasks unconfigured.
196
+
197
+ - **breakwater `_background` model-override defense (DL-005), the ONE breakwater
198
+ change (MINOR).** `createConnector`'s wrapped `execute`/`dryRunExecute` reject
199
+ tool-call args carrying a `_background` field (core `LLMBackgroundOverride`)
200
+ unless the manifest opts in via `permissions.background` — the argv-flag-
201
+ smuggling posture of the agent-cli `buildFlags` defense. `background: true` is
202
+ allowed only on a read-only connector (a write-class opt-in throws at
203
+ construction); v1 keeps write/approval-carrying connectors foreground-only.
204
+ Plus a `backgroundExecution` tool-policy evaluator (deny-by-default for the
205
+ write class) as the defense-in-depth counterpart at the gate loop. Both are
206
+ DEFENSE-IN-DEPTH for DIRECT / NESTED calls, NOT the agent-path guard: on the
207
+ agent path core deletes `_background` from the args before dispatch (schema or
208
+ not), and core's own `resolveBackgroundConfig` baseEnabled gate — a breakwater
209
+ connector sets no background config — already prevents the model from
210
+ backgrounding an ineligible tool, so the breakwater reads see stripped args and
211
+ fire on nothing there. The real write boundary on every path (including inside
212
+ the background executor) is the requestContext grant.
213
+ - **`mastra_background_tasks` adopted into the D1 substrate in ONE change
214
+ (DL-003).** Registered in the schema-guard inventory (coverage `tenant-range`,
215
+ a new `background-task-ttl` retention kind), in `purgeTenant` (ranged over the
216
+ INV-1 salted `run_id`; new `PurgeTenantResult.backgroundTasks`), and given a
217
+ storage-layer TTL cleanup `purgeExpiredBackgroundTasks` (+
218
+ `BACKGROUND_TASK_TTL_PURGE_TABLES`) mirroring core's two-window
219
+ `BackgroundTaskManager.cleanup` so a purge cron reaps terminal rows without a
220
+ live manager. Surfaced through `FlowsafeWorkerConfig.backgroundTasks` as the
221
+ purge cron's own failure-isolated duty (undefined = no duty, byte-identical).
222
+ - **`@proofoftech/flowsafe/background-tasks` (new subpath):** `backgroundTasksStore`
223
+ (the async accessor onto @mastra/cloudflare-d1's `BackgroundTasksStorageD1` —
224
+ the D1 domain the adapter already ships; not reimplemented, per "what NOT to
225
+ build"), `BackgroundTaskHost` (hosts a `BackgroundTaskManager` on a DO with the
226
+ DL-015 boot/alarm lifecycle), and `createBackgroundTaskRoutes` (READ-only,
227
+ tenant-bound by construction, DL-014: list/stream REQUIRE a runId/threadId
228
+ filter and validate its salted prefix; `getTask` 404s a missing OR foreign
229
+ task with no oracle; the raw manager is never exposed).
230
+ - **Recovery seam pinned (R-002, spike B-S2):** DO eviction is survived by
231
+ re-registering the static tool executors and calling the PUBLIC async
232
+ `manager.init(pubsub)` at DO boot — which fires the manager's own (private)
233
+ `recoverStaleTasks()` internally. No private method is ever called.
234
+
235
+ **Known substrate limitation (spike B-S1 findings R-B1/R-B2/R-B3, documented in
236
+ `background-tasks/host.ts`):** durable background-task _execution_ does not yet
237
+ run on the Cloudflare substrate. Core runs task bodies on the _evented_
238
+ execution engine, which refuses to `createRun` unless the workflows store
239
+ reports `supportsConcurrentUpdates()`. `@mastra/cloudflare-d1` returns `false`
240
+ AND leaves `updateWorkflowResults`/`updateWorkflowState` as unimplemented throws
241
+ ("D1 does not support atomic read-modify-write") — so R-B1 is NOT a flag to
242
+ flip: overriding it passes core's gate then throws on the first step-update,
243
+ stranding the task at `running`. The P9 fix is an adapter that _implements_
244
+ atomic partial-updates (the DO's single-threaded lease makes that safe), plus
245
+ `mastra.startWorkers()` to run the evented workers (R-B2 — the two close
246
+ together). A latent tenant-isolation residual (R-B3) rides along: core keys the
247
+ internal `__background-task` run by the UNSALTED `taskId`, so its snapshot row
248
+ escapes tenant offboarding — inert while execution is blocked, but it MUST be
249
+ closed in the same change that enables execution, and a CI guard
250
+ (`background-tasks/d1-storage.test.ts`) fails the instant
251
+ `supportsConcurrentUpdates()` returns true. Persistence, the recovery seam,
252
+ tenant purge + TTL, the read routes, and the `_background` defense all work
253
+ regardless. `BackgroundTaskHost.boot()` warns once so the limitation is loud,
254
+ not a stray async throw.
255
+
256
+ - 4b953d4: Track C (long-running-agents program, M-004): signals, subscriptions, and
257
+ notifications. All additive and opt-in — a host that configures none of it is
258
+ byte-identical.
259
+
260
+ New subpath `@proofoftech/flowsafe/signals`:
261
+
262
+ - **Thread-DO signal routes** (`createThreadSignalRoutes`) — the
263
+ message/queue/signal/state/notification surface hosted on the per-thread DO.
264
+ Each call stamps the DO's one pubsub identity (`scope.init.pubsub`) onto the
265
+ agent so a send drains IN-PROCESS into an active loop: core keys its signal
266
+ registry by the pubsub instance, so affinity needs both the DO isolate
267
+ (idFromName(threadId)) and the shared pubsub — the DL-002 thesis, proven on
268
+ workerd (spike C-S2). An idle-thread WAKE starts a run, so it requires a
269
+ runtime-driven durable agent (`createFlowsafeDurableAgent`, which carries the
270
+ new `RUNTIME_DRIVEN_AGENT` brand from `@proofoftech/flowsafe/agent-runner`) —
271
+ its stream re-enters RunnerRuntime rather than the default engine; a wake
272
+ requested on a plain agent is refused fail-closed (degraded to a durable
273
+ persist), and every allowed wake consults the per-tenant run cap (DL-007). The
274
+ routes drive the public Agent methods only (`agentThreadStreamRuntime` is not
275
+ on core's exports map).
276
+ - **D1 storage domains** — `D1NotificationsStorage` (over `mastra_notifications`,
277
+ mirroring core's InMemory reference incl. coalescing) and
278
+ `D1ThreadStateStorage` (over `mastra_thread_state`, the state-signal lanes and
279
+ the goal record). `@mastra/cloudflare-d1` ships neither, so they are
280
+ flowsafe-owned; `createSignalStorageDomains` composes them into
281
+ `createD1Storage` (which now accepts injected `domains`) so
282
+ `agent.sendNotificationSignal` persists to D1. Both tables are registered in
283
+ the tenant-range offboarding purge (`purgeTenant`), the schema-guard inventory,
284
+ and their own opt-in TTL purges (`purgeExpiredNotifications`,
285
+ `purgeExpiredThreadState`) — the DL-003 triad, in one change. `PurgeTenantResult`
286
+ gains `notifications` + `threadState` counters (a breaking change only for
287
+ callers that build a `PurgeTenantResult` literal).
288
+ - **P6 ingestion trust boundary** (`createSignalRouter`) — every ingest is
289
+ authenticated → role-gated → thread-prefix-ownership-checked (404, no oracle) →
290
+ size-capped → memory-id-refused → attribute-allowlisted → per-tenant rate-capped
291
+ → forwarded via `createThreadTopology` (which overwrites the tenant header, so a
292
+ forged one cannot ride along; cross-tenant sends fail closed at both the topology
293
+ 404 and the DO 403, spike C-S4). Every ingest is audited (`signal.ingest`),
294
+ accepted OR rejected — including the three post-auth denials that read like an
295
+ attack on this channel (the role 403, the cross-tenant thread 404, the
296
+ memory-id 400); pre-auth failures (401 / resolver throw) are not audited. XML
297
+ injection is neutralized by core's `signalToXmlMarkup`, which entity-escapes
298
+ contents and attribute values and re-validates tag/attribute names — a single
299
+ layer over a soft-pinned core, so a C-S5 render test pins it (a core `escapeXml`
300
+ regression fails flowsafe CI); the route adds its own line at ingest —
301
+ `tagName` XML-name validation, the attribute-key allowlist, and the size cap —
302
+ but does not re-escape the contents. Signals never mint capability —
303
+ `sendToolApproval` is not an approval surface (P8).
304
+ - **`SignalClient`** — a DOM-free client in the `ApprovalApiClient` mold.
305
+
306
+ `createFlowsafeWorker` gains an opt-in signal stage (`buildSignalRouter` seam) and
307
+ two opt-in TTL cron duties (`NOTIFICATION_RETENTION_DAYS`,
308
+ `THREAD_STATE_RETENTION_DAYS`).
309
+
3
310
  ## 0.4.0
4
311
 
5
312
  ### Minor Changes
@@ -0,0 +1,36 @@
1
+ /** The suspend-payload `type` discriminator core stamps on an approval gate. */
2
+ export declare const AGENT_APPROVAL_SUSPEND_TYPE = "approval";
3
+ /** The tool-call identity parsed out of an agent approval suspend payload. */
4
+ export interface AgentApprovalSuspend {
5
+ toolCallId?: string;
6
+ toolName?: string;
7
+ args?: Record<string, unknown>;
8
+ }
9
+ /**
10
+ * Parse a durable-agent approval suspend payload — a PER-STEP payload, already
11
+ * unwrapped from RunSummary.suspendPayload's step-keyed map — into its tool-call
12
+ * identity, reading BOTH shapes (R-003): the NESTED `requireToolApproval` object
13
+ * when present, else the FLAT top-level fields.
14
+ *
15
+ * Returns undefined for any payload that is NOT an agent tool-call gate: a
16
+ * non-object, a non-'approval' `type`, or a workflow-step gate that names no
17
+ * tool (it declares its own `connectors` instead — the caller keeps its
18
+ * existing handling for those). Fail-closed: a payload naming no tool at all
19
+ * yields undefined so agentGateConnectors() invents no grant.
20
+ */
21
+ export declare function parseAgentApprovalSuspend(payload: unknown): AgentApprovalSuspend | undefined;
22
+ /**
23
+ * The breakwater connector ids an approved agent gate should grant: the single
24
+ * provider-safe tool id the model called (== the connector id the write gate
25
+ * checks; see the file header's provider-rewrite constraint). Requires
26
+ * BOTH a non-empty `toolName` AND a non-empty `toolCallId` — a real
27
+ * durable-agent gate always carries both (toolCallId is the suspend's
28
+ * `resumeLabel`), so demanding both never rejects a real gate while narrowing
29
+ * the surface where a workflow-step gate COINCIDENTALLY shaped `{type:'approval',
30
+ * toolName}` would mint an unintended grant (a workflow author's own convention
31
+ * is an explicit `connectors` array, which requestedConnectors takes first).
32
+ * Returns [] otherwise, so a decision never invents a grant the suspension did
33
+ * not request (fail-closed).
34
+ */
35
+ export declare function agentGateConnectors(payload: unknown): string[];
36
+ //# sourceMappingURL=approval-shapes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-shapes.d.ts","sourceRoot":"","sources":["../../src/agent-runner/approval-shapes.ts"],"names":[],"mappings":"AA2BA,gFAAgF;AAChF,eAAO,MAAM,2BAA2B,aAAa,CAAC;AAItD,8EAA8E;AAC9E,MAAM,WAAW,oBAAoB;IACnC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAChC;AAYD;;;;;;;;;;;GAWG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,OAAO,GACf,oBAAoB,GAAG,SAAS,CAqBlC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,GAAG,MAAM,EAAE,CAS9D"}
@@ -0,0 +1,101 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Durable-agent approval-suspend shape parsing (validation finding R-003).
3
+ //
4
+ // The durable-agentic-loop's tool-call step suspends for approval in TWO
5
+ // payload shapes, both validated against @mastra/core 1.50.0 dist
6
+ // (agent/durable/index.js):
7
+ //
8
+ // FLAT (pre-exec gate, :3283): { type:'approval', toolCallId, toolName, args }
9
+ // NESTED (mid-exec, :3385): { type:'approval', requireToolApproval:{ toolCallId, toolName, args } }
10
+ //
11
+ // Both carry `resumeLabel: toolCallId` and a `{ approved: boolean }` resume
12
+ // schema. A workflow STEP gate declares its own grants in an explicit
13
+ // `connectors` array; an AGENT gate instead names the tool the model wants to
14
+ // call by its provider-visible `toolName`. For a breakwater connector this must
15
+ // be the SAME provider-safe id (`[A-Za-z0-9_-]+`) the write gate checks.
16
+ // Providers rewrite punctuation-bearing ids such as `salesforce.createContact`
17
+ // before returning a tool call, and that rewrite is not reversible in the
18
+ // suspend payload. Hosts using automatic agent-gate grants must therefore give
19
+ // those connectors provider-safe ids. agentGateConnectors() mints [toolName],
20
+ // and the runtime's approvalGrantProvider derives that exact grant from the
21
+ // APPROVED record on resume.
22
+ //
23
+ // Pure and dependency-free (no @mastra import): it inspects a plain payload
24
+ // object only, so the record-creation/bridge path (host-kit/approval-bridge.ts)
25
+ // can call it without dragging the durable Agent — and therefore @mastra's
26
+ // Node built-ins — into any browser-reachable module.
27
+ /** The suspend-payload `type` discriminator core stamps on an approval gate. */
28
+ export const AGENT_APPROVAL_SUSPEND_TYPE = 'approval';
29
+ const PROVIDER_SAFE_TOOL_NAME = /^[A-Za-z0-9_-]+$/;
30
+ function asRecord(value) {
31
+ return value !== null && typeof value === 'object'
32
+ ? value
33
+ : undefined;
34
+ }
35
+ function asString(value) {
36
+ return typeof value === 'string' ? value : undefined;
37
+ }
38
+ /**
39
+ * Parse a durable-agent approval suspend payload — a PER-STEP payload, already
40
+ * unwrapped from RunSummary.suspendPayload's step-keyed map — into its tool-call
41
+ * identity, reading BOTH shapes (R-003): the NESTED `requireToolApproval` object
42
+ * when present, else the FLAT top-level fields.
43
+ *
44
+ * Returns undefined for any payload that is NOT an agent tool-call gate: a
45
+ * non-object, a non-'approval' `type`, or a workflow-step gate that names no
46
+ * tool (it declares its own `connectors` instead — the caller keeps its
47
+ * existing handling for those). Fail-closed: a payload naming no tool at all
48
+ * yields undefined so agentGateConnectors() invents no grant.
49
+ */
50
+ export function parseAgentApprovalSuspend(payload) {
51
+ const record = asRecord(payload);
52
+ if (record === undefined)
53
+ return undefined;
54
+ if (record.type !== AGENT_APPROVAL_SUSPEND_TYPE)
55
+ return undefined;
56
+ // The two shapes are disjoint: NESTED carries a `requireToolApproval` object
57
+ // (mid-exec) and FLAT carries the fields at top level (pre-exec). Resolve the
58
+ // source as a UNIT — whichever shape is present — rather than field-by-field,
59
+ // so a malformed payload can never produce a mixed-provenance result.
60
+ const source = asRecord(record.requireToolApproval) ?? record;
61
+ const toolCallId = asString(source.toolCallId);
62
+ const toolName = asString(source.toolName);
63
+ const args = asRecord(source.args);
64
+ // An 'approval' payload that names neither a tool nor a call is not an agent
65
+ // tool-call gate we can round-trip — treat it as "not an agent gate" so the
66
+ // caller falls back to its workflow-step handling and no grant is invented.
67
+ if (toolName === undefined && toolCallId === undefined)
68
+ return undefined;
69
+ const parsed = {};
70
+ if (toolCallId !== undefined)
71
+ parsed.toolCallId = toolCallId;
72
+ if (toolName !== undefined)
73
+ parsed.toolName = toolName;
74
+ if (args !== undefined)
75
+ parsed.args = args;
76
+ return parsed;
77
+ }
78
+ /**
79
+ * The breakwater connector ids an approved agent gate should grant: the single
80
+ * provider-safe tool id the model called (== the connector id the write gate
81
+ * checks; see the file header's provider-rewrite constraint). Requires
82
+ * BOTH a non-empty `toolName` AND a non-empty `toolCallId` — a real
83
+ * durable-agent gate always carries both (toolCallId is the suspend's
84
+ * `resumeLabel`), so demanding both never rejects a real gate while narrowing
85
+ * the surface where a workflow-step gate COINCIDENTALLY shaped `{type:'approval',
86
+ * toolName}` would mint an unintended grant (a workflow author's own convention
87
+ * is an explicit `connectors` array, which requestedConnectors takes first).
88
+ * Returns [] otherwise, so a decision never invents a grant the suspension did
89
+ * not request (fail-closed).
90
+ */
91
+ export function agentGateConnectors(payload) {
92
+ const parsed = parseAgentApprovalSuspend(payload);
93
+ return parsed?.toolName !== undefined &&
94
+ parsed.toolName.length > 0 &&
95
+ PROVIDER_SAFE_TOOL_NAME.test(parsed.toolName) &&
96
+ parsed.toolCallId !== undefined &&
97
+ parsed.toolCallId.length > 0
98
+ ? [parsed.toolName]
99
+ : [];
100
+ }
101
+ //# sourceMappingURL=approval-shapes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-shapes.js","sourceRoot":"","sources":["../../src/agent-runner/approval-shapes.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,2EAA2E;AAC3E,EAAE;AACF,yEAAyE;AACzE,kEAAkE;AAClE,4BAA4B;AAC5B,EAAE;AACF,oFAAoF;AACpF,4GAA4G;AAC5G,EAAE;AACF,4EAA4E;AAC5E,sEAAsE;AACtE,8EAA8E;AAC9E,gFAAgF;AAChF,yEAAyE;AACzE,+EAA+E;AAC/E,0EAA0E;AAC1E,+EAA+E;AAC/E,8EAA8E;AAC9E,4EAA4E;AAC5E,6BAA6B;AAC7B,EAAE;AACF,4EAA4E;AAC5E,gFAAgF;AAChF,2EAA2E;AAC3E,sDAAsD;AAEtD,gFAAgF;AAChF,MAAM,CAAC,MAAM,2BAA2B,GAAG,UAAU,CAAC;AAEtD,MAAM,uBAAuB,GAAG,kBAAkB,CAAC;AASnD,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ;QAChD,CAAC,CAAE,KAAiC;QACpC,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAED,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AACvD,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,yBAAyB,CACvC,OAAgB;IAEhB,MAAM,MAAM,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;IACjC,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC3C,IAAI,MAAM,CAAC,IAAI,KAAK,2BAA2B;QAAE,OAAO,SAAS,CAAC;IAClE,6EAA6E;I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 import type { Agent, ToolsInput } from '@mastra/core/agent';
2
+ import { DurableAgent, type DurableAgentConfig, type DurableAgenticWorkflowInput, type DurableAgentStreamOptions } from '@mastra/core/agent/durable';
3
+ import type { Mastra } from '@mastra/core/mastra';
4
+ import { type RunnerRuntime, type RunSummary } from '../do-runner/index.js';
5
+ /**
6
+ * The shared workflow id every durable-agent loop compiles to (core's
7
+ * DurableAgentDefaults.AGENTIC_LOOP). Exposed so hosts and tests can reference
8
+ * the registered id without a magic string.
9
+ */
10
+ export declare const DURABLE_AGENTIC_LOOP_WORKFLOW_ID = "durable-agentic-loop";
11
+ /**
12
+ * Brand marking an agent as RUNTIME-DRIVEN: its inherited signal wake
13
+ * (`agent.stream` under `ifIdle:'wake'`) re-enters the INV-1-guarded
14
+ * {@link FlowsafeDurableAgent.executeWorkflow}, which drives
15
+ * `runtime.start('durable-agentic-loop', …)` rather than the base
16
+ * `createRun + run.start` on the DEFAULT engine. Track C's thread-DO signal
17
+ * routes REQUIRE this brand before honoring an idle wake, because the wake is the
18
+ * one signal path that starts a run: a plain core `Agent` (or a STOCK
19
+ * `DurableAgent`, whose `stream()` mints a tenant-less UUID and whose
20
+ * `executeWorkflow` runs on the default engine) would start a run OUTSIDE
21
+ * RunnerRuntime — a second execution path DL-001 forbids, tenant-unscoped and
22
+ * grant-underivable. Structural (a `unique symbol`-keyed truthy field) so a test
23
+ * double can opt in without constructing a real durable agent.
24
+ *
25
+ * The brand is paired with Track C's host-owned idle-start seam: the thread DO
26
+ * mints the tenant-salted run id and invokes the wrapper directly, avoiding
27
+ * core's tenant-less idle-wake id generation.
28
+ */
29
+ export declare const RUNTIME_DRIVEN_AGENT: unique symbol;
30
+ /**
31
+ * Does this value carry the {@link RUNTIME_DRIVEN_AGENT} brand — i.e. is its
32
+ * signal wake driven through RunnerRuntime rather than the default engine?
33
+ * Takes `unknown` so a caller holding a core `Agent` (whose type has no index
34
+ * for the brand symbol) can check without a cast.
35
+ */
36
+ export declare function isRuntimeDrivenAgent(agent: unknown): boolean;
37
+ /** Options for {@link createFlowsafeDurableAgent}. */
38
+ export interface FlowsafeDurableAgentOptions<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined> {
39
+ /** The Agent to wrap with durable, runtime-driven execution. */
40
+ agent: Agent<TAgentId, TTools, TOutput>;
41
+ /**
42
+ * The RunnerRuntime the loop is driven through (DL-001/DL-010). REQUIRED —
43
+ * this is the whole point of the flowsafe wrapper: executeWorkflow() calls
44
+ * `runtime.start('durable-agentic-loop', ...)` instead of the base
45
+ * `createRun + start`, so INV-1, the per-leg grant context, and the resume
46
+ * ledger apply to agent legs. The loop workflow is registered on this runtime
47
+ * by the factory (idempotently — one shared id serves every durable agent).
48
+ */
49
+ runtime: RunnerRuntime;
50
+ /** Optional id override (defaults to agent.id). */
51
+ id?: TAgentId;
52
+ /** Optional name override (defaults to agent.name). */
53
+ name?: string;
54
+ /** Resumable-stream cache — see createDurableAgent's `cache`. */
55
+ cache?: DurableAgentConfig<TAgentId, TTools, TOutput>['cache'];
56
+ /**
57
+ * PubSub for the agent's own stream events (observe()/onChunk). DEFAULTS to
58
+ * `runtime.pubsub` (the host DO's ONE identity, DL-001) when omitted, so the
59
+ * run's events and the agent's observe()/emitError feed agree without the host
60
+ * wiring it twice — a mismatched pubsub would leave observe() replaying an
61
+ * empty feed. Pass an explicit instance only to override that default.
62
+ */
63
+ pubsub?: DurableAgentConfig<TAgentId, TTools, TOutput>['pubsub'];
64
+ /**
65
+ * Public Mastra thread runtime (`mastra.agentThreadStreamRuntime`). When
66
+ * present, started and rehydrated outputs are registered on the same pubsub
67
+ * identity so active-thread signals join the durable loop.
68
+ */
69
+ threadRuntime?: Mastra['agentThreadStreamRuntime'];
70
+ /** Max steps for the agentic loop (bakes into the shared loop's isTaskComplete step). */
71
+ maxSteps?: number;
72
+ }
73
+ /**
74
+ * A DurableAgent whose loop runs through {@link RunnerRuntime} rather than the
75
+ * base `createRun + run.start`. Construct via {@link createFlowsafeDurableAgent}
76
+ * so the loop workflow is registered on the runtime.
77
+ */
78
+ export declare class FlowsafeDurableAgent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined> extends DurableAgent<TAgentId, TTools, TOutput> {
79
+ #private;
80
+ /**
81
+ * The runtime-driven brand Track C's thread-DO signal wake requires (see
82
+ * {@link RUNTIME_DRIVEN_AGENT}). A `unique symbol` field, so it cannot collide
83
+ * with an inherited property and a plain `Agent` never carries it.
84
+ */
85
+ readonly [RUNTIME_DRIVEN_AGENT] = true;
86
+ constructor(options: FlowsafeDurableAgentOptions<TAgentId, TTools, TOutput>);
87
+ /**
88
+ * Enforce INV-1 before the inherited durable `stream()` runs: without this the
89
+ * optional `options.runId` would let core mint a tenant-less
90
+ * `crypto.randomUUID()` upstream (see {@link FlowsafeDurableAgent.#assertCallerRunId}).
91
+ * A host mints `${tenantId}_${uuid}` and passes it as `options.runId`.
92
+ */
93
+ stream(messages: Parameters<DurableAgent<TAgentId, TTools, TOutput>['stream']>[0], options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['stream']>[1]): Promise<Awaited<ReturnType<DurableAgent<TAgentId, TTools, TOutput>['stream']>>>;
94
+ /**
95
+ * Same INV-1 boundary guard as {@link FlowsafeDurableAgent.stream} — `generate()`
96
+ * re-implements the durable setup and mints its own runId the same way when
97
+ * one is not supplied.
98
+ */
99
+ generate(messages: Parameters<DurableAgent<TAgentId, TTools, TOutput>['generate']>[0], options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['generate']>[1]): Promise<Awaited<ReturnType<DurableAgent<TAgentId, TTools, TOutput>['generate']>>>;
100
+ /**
101
+ * Same INV-1 boundary guard as {@link FlowsafeDurableAgent.stream}. `prepare()`
102
+ * is the third inherited minting entry point: it forwards `options?.runId` into
103
+ * core's `prepareForDurableExecution` (agent/durable/index.js:5980), which mints
104
+ * a tenant-less `crypto.randomUUID()` when it is absent (index.js:589) AND
105
+ * REGISTERS a run under that id (index.js:5984) — so a later
106
+ * `resume(runId)`/`executeWorkflow` sees a bare UUID `PATH_SAFE_ID_PATTERN`
107
+ * already accepts, past every downstream guard. Enforce INV-1 HERE, while
108
+ * "absent" is still visible.
109
+ */
110
+ prepare(messages: Parameters<DurableAgent<TAgentId, TTools, TOutput>['prepare']>[0], options?: Parameters<DurableAgent<TAgentId, TTools, TOutput>['prepare']>[1]): Promise<Awaited<ReturnType<DurableAgent<TAgentId, TTools, TOutput>['prepare']>>>;
111
+ /**
112
+ * Rehydrate a suspended durable-agent run after isolate eviction, restore its
113
+ * active thread registration, then resume through RunnerRuntime so approval
114
+ * grant derivation and the durable resume ledger remain authoritative.
115
+ * Hosts expose this only from their trusted approval-decision topology.
116
+ */
117
+ resumeViaRuntime(options: {
118
+ runId: string;
119
+ step?: string | string[];
120
+ resumeData?: unknown;
121
+ memory?: DurableAgentStreamOptions<TOutput>['memory'];
122
+ }): Promise<RunSummary>;
123
+ /**
124
+ * Drive the durable-agentic-loop through RunnerRuntime instead of the base
125
+ * `createRun + run.start` (DL-010). stream()/generate() have already parked the
126
+ * non-serializables (model/tools/messageList) on the in-process run registry
127
+ * keyed by this runId, so the loop the runtime starts resolves them in-isolate
128
+ * while the runtime mints the per-leg grant context. The runId guard here is
129
+ * defense in depth — the public boundary (stream/generate) already enforced
130
+ * INV-1; this catches any future internal caller.
131
+ */
132
+ protected executeWorkflow(runId: string, workflowInput: DurableAgenticWorkflowInput): Promise<void>;
133
+ }
134
+ /**
135
+ * Wrap an Agent as a {@link FlowsafeDurableAgent} and register its loop workflow
136
+ * on the runtime — the same `runtime.register` path init()'s boundCreateWorkflow
137
+ * uses.
138
+ *
139
+ * Registration is IDEMPOTENT by id: every durable agent compiles to the ONE
140
+ * shared 'durable-agentic-loop' workflow (the `agentId` in each run's input
141
+ * routes to the right agent via the per-run registry), so a second
142
+ * createFlowsafeDurableAgent on a shared runtime must not throw 'duplicate
143
+ * workflow id'. Like init()'s createWorkflow, register() also throws once runs
144
+ * have started (the Mastra instance is frozen) — call this at host setup, before
145
+ * any run.
146
+ *
147
+ * Multi-agent caveat: the shared loop bakes in the FIRST registrant's `maxSteps`
148
+ * (it is compiled into the isTaskComplete step) as the DEFAULT — a per-call
149
+ * `stream(msg, { maxSteps })` still overrides it, so this only bites a
150
+ * second-plus agent that relies on its CONSTRUCTOR budget. Agents needing
151
+ * distinct default step budgets take separate runtimes.
152
+ */
153
+ export declare function createFlowsafeDurableAgent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TOutput = undefined>(options: FlowsafeDurableAgentOptions<TAgentId, TTools, TOutput>): FlowsafeDurableAgent<TAgentId, TTools, TOutput>;
154
+ //# sourceMappingURL=durable-agent-runner.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durable-agent-runner.d.ts","sourceRoot":"","sources":["../../src/agent-runner/durable-agent-runner.ts"],"names":[],"mappings":"AAyDA,OAAO,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EACL,YAAY,EACZ,KAAK,kBAAkB,EACvB,KAAK,2BAA2B,EAChC,KAAK,yBAAyB,EAC/B,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAGlD,OAAO,EAGL,KAAK,aAAa,EAClB,KAAK,UAAU,EAChB,MAAM,uBAAuB,CAAC;AAE/B;;;;GAIG;AACH,eAAO,MAAM,gCAAgC,yBAAyB,CAAC;AAEvE;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,oBAAoB,EAAE,OAAO,MAEzC,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAM5D;AAED,sDAAsD;AACtD,MAAM,WAAW,2BAA2B,CAC1C,QAAQ,SAAS,MAAM,GAAG,MAAM,EAChC,MAAM,SAAS,UAAU,GAAG,UAAU,EACtC,OAAO,GAAG,SAAS;IAEnB,gEAAgE;IAChE,KAAK,EAAE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