@proofoftech/flowsafe 0.3.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 (296) hide show
  1. package/CHANGELOG.md +336 -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/contract.d.ts +29 -0
  15. package/dist/approval-api/contract.d.ts.map +1 -1
  16. package/dist/approval-api/d1-store.d.ts.map +1 -1
  17. package/dist/approval-api/d1-store.js +112 -18
  18. package/dist/approval-api/d1-store.js.map +1 -1
  19. package/dist/approval-api/grants.d.ts +1 -1
  20. package/dist/approval-api/grants.d.ts.map +1 -1
  21. package/dist/approval-api/grants.js +8 -32
  22. package/dist/approval-api/grants.js.map +1 -1
  23. package/dist/approval-api/index.d.ts +2 -2
  24. package/dist/approval-api/index.d.ts.map +1 -1
  25. package/dist/approval-api/index.js.map +1 -1
  26. package/dist/approval-api/router.d.ts +1 -1
  27. package/dist/approval-api/router.d.ts.map +1 -1
  28. package/dist/approval-api/router.js +1 -0
  29. package/dist/approval-api/router.js.map +1 -1
  30. package/dist/approval-api/service.d.ts +24 -3
  31. package/dist/approval-api/service.d.ts.map +1 -1
  32. package/dist/approval-api/service.js +116 -1
  33. package/dist/approval-api/service.js.map +1 -1
  34. package/dist/approval-api/store.d.ts +29 -6
  35. package/dist/approval-api/store.d.ts.map +1 -1
  36. package/dist/approval-api/store.js +62 -2
  37. package/dist/approval-api/store.js.map +1 -1
  38. package/dist/approval-api/tenant-context.d.ts.map +1 -1
  39. package/dist/approval-api/tenant-context.js +17 -1
  40. package/dist/approval-api/tenant-context.js.map +1 -1
  41. package/dist/approval-api/tenant-store.d.ts.map +1 -1
  42. package/dist/approval-api/tenant-store.js +8 -2
  43. package/dist/approval-api/tenant-store.js.map +1 -1
  44. package/dist/approval-api/types.d.ts +19 -0
  45. package/dist/approval-api/types.d.ts.map +1 -1
  46. package/dist/approval-api/types.js +16 -0
  47. package/dist/approval-api/types.js.map +1 -1
  48. package/dist/approval-ui/App.d.ts +9 -1
  49. package/dist/approval-ui/App.d.ts.map +1 -1
  50. package/dist/approval-ui/App.js +10 -5
  51. package/dist/approval-ui/App.js.map +1 -1
  52. package/dist/approval-ui/DetailView.d.ts +4 -1
  53. package/dist/approval-ui/DetailView.d.ts.map +1 -1
  54. package/dist/approval-ui/DetailView.js +2 -2
  55. package/dist/approval-ui/DetailView.js.map +1 -1
  56. package/dist/approval-ui/QueueView.d.ts +7 -1
  57. package/dist/approval-ui/QueueView.d.ts.map +1 -1
  58. package/dist/approval-ui/QueueView.js +8 -3
  59. package/dist/approval-ui/QueueView.js.map +1 -1
  60. package/dist/approval-ui/client.d.ts +19 -0
  61. package/dist/approval-ui/client.d.ts.map +1 -1
  62. package/dist/approval-ui/client.js +29 -1
  63. package/dist/approval-ui/client.js.map +1 -1
  64. package/dist/approval-ui/components.d.ts +20 -0
  65. package/dist/approval-ui/components.d.ts.map +1 -1
  66. package/dist/approval-ui/components.js +2 -0
  67. package/dist/approval-ui/components.js.map +1 -1
  68. package/dist/approval-ui/index.d.ts +4 -2
  69. package/dist/approval-ui/index.d.ts.map +1 -1
  70. package/dist/approval-ui/index.js +3 -0
  71. package/dist/approval-ui/index.js.map +1 -1
  72. package/dist/approval-ui/stream.d.ts +142 -0
  73. package/dist/approval-ui/stream.d.ts.map +1 -0
  74. package/dist/approval-ui/stream.js +136 -0
  75. package/dist/approval-ui/stream.js.map +1 -0
  76. package/dist/approval-ui/use-approval-dashboard.d.ts +74 -1
  77. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -1
  78. package/dist/approval-ui/use-approval-dashboard.js +307 -7
  79. package/dist/approval-ui/use-approval-dashboard.js.map +1 -1
  80. package/dist/approval-ui/use-web-socket-transport.d.ts +10 -0
  81. package/dist/approval-ui/use-web-socket-transport.d.ts.map +1 -0
  82. package/dist/approval-ui/use-web-socket-transport.js +46 -0
  83. package/dist/approval-ui/use-web-socket-transport.js.map +1 -0
  84. package/dist/background-tasks/d1-storage.d.ts +66 -0
  85. package/dist/background-tasks/d1-storage.d.ts.map +1 -0
  86. package/dist/background-tasks/d1-storage.js +196 -0
  87. package/dist/background-tasks/d1-storage.js.map +1 -0
  88. package/dist/background-tasks/host.d.ts +82 -0
  89. package/dist/background-tasks/host.d.ts.map +1 -0
  90. package/dist/background-tasks/host.js +275 -0
  91. package/dist/background-tasks/host.js.map +1 -0
  92. package/dist/background-tasks/index.d.ts +7 -0
  93. package/dist/background-tasks/index.d.ts.map +1 -0
  94. package/dist/background-tasks/index.js +10 -0
  95. package/dist/background-tasks/index.js.map +1 -0
  96. package/dist/background-tasks/routes.d.ts +15 -0
  97. package/dist/background-tasks/routes.d.ts.map +1 -0
  98. package/dist/background-tasks/routes.js +144 -0
  99. package/dist/background-tasks/routes.js.map +1 -0
  100. package/dist/do-runner/cf-types.d.ts +70 -2
  101. package/dist/do-runner/cf-types.d.ts.map +1 -1
  102. package/dist/do-runner/cf-types.js +30 -1
  103. package/dist/do-runner/cf-types.js.map +1 -1
  104. package/dist/do-runner/d1-storage.d.ts +343 -2
  105. package/dist/do-runner/d1-storage.d.ts.map +1 -1
  106. package/dist/do-runner/d1-storage.js +566 -13
  107. package/dist/do-runner/d1-storage.js.map +1 -1
  108. package/dist/do-runner/do-error-response.d.ts +29 -0
  109. package/dist/do-runner/do-error-response.d.ts.map +1 -0
  110. package/dist/do-runner/do-error-response.js +73 -0
  111. package/dist/do-runner/do-error-response.js.map +1 -0
  112. package/dist/do-runner/durable-object.d.ts +5 -2
  113. package/dist/do-runner/durable-object.d.ts.map +1 -1
  114. package/dist/do-runner/durable-object.js +87 -20
  115. package/dist/do-runner/durable-object.js.map +1 -1
  116. package/dist/do-runner/hub-do.d.ts +55 -0
  117. package/dist/do-runner/hub-do.d.ts.map +1 -0
  118. package/dist/do-runner/hub-do.js +197 -0
  119. package/dist/do-runner/hub-do.js.map +1 -0
  120. package/dist/do-runner/index.d.ts +12 -4
  121. package/dist/do-runner/index.d.ts.map +1 -1
  122. package/dist/do-runner/index.js +9 -2
  123. package/dist/do-runner/index.js.map +1 -1
  124. package/dist/do-runner/init.d.ts +20 -0
  125. package/dist/do-runner/init.d.ts.map +1 -1
  126. package/dist/do-runner/init.js +12 -1
  127. package/dist/do-runner/init.js.map +1 -1
  128. package/dist/do-runner/path-safe-id.js +1 -1
  129. package/dist/do-runner/path-safe-id.js.map +1 -1
  130. package/dist/do-runner/pubsub.d.ts +18 -0
  131. package/dist/do-runner/pubsub.d.ts.map +1 -0
  132. package/dist/do-runner/pubsub.js +42 -0
  133. package/dist/do-runner/pubsub.js.map +1 -0
  134. package/dist/do-runner/runtime.d.ts +24 -0
  135. package/dist/do-runner/runtime.d.ts.map +1 -1
  136. package/dist/do-runner/runtime.js +29 -2
  137. package/dist/do-runner/runtime.js.map +1 -1
  138. package/dist/do-runner/thread-do.d.ts +74 -0
  139. package/dist/do-runner/thread-do.d.ts.map +1 -0
  140. package/dist/do-runner/thread-do.js +156 -0
  141. package/dist/do-runner/thread-do.js.map +1 -0
  142. package/dist/do-runner/thread-header.d.ts +16 -0
  143. package/dist/do-runner/thread-header.d.ts.map +1 -0
  144. package/dist/do-runner/thread-header.js +24 -0
  145. package/dist/do-runner/thread-header.js.map +1 -0
  146. package/dist/goals/index.d.ts +2 -0
  147. package/dist/goals/index.d.ts.map +1 -0
  148. package/dist/goals/index.js +7 -0
  149. package/dist/goals/index.js.map +1 -0
  150. package/dist/goals/objective-routes.d.ts +87 -0
  151. package/dist/goals/objective-routes.d.ts.map +1 -0
  152. package/dist/goals/objective-routes.js +375 -0
  153. package/dist/goals/objective-routes.js.map +1 -0
  154. package/dist/host-kit/approval-bridge.d.ts +24 -4
  155. package/dist/host-kit/approval-bridge.d.ts.map +1 -1
  156. package/dist/host-kit/approval-bridge.js +32 -10
  157. package/dist/host-kit/approval-bridge.js.map +1 -1
  158. package/dist/host-kit/env-vars.d.ts +20 -0
  159. package/dist/host-kit/env-vars.d.ts.map +1 -1
  160. package/dist/host-kit/env-vars.js +30 -0
  161. package/dist/host-kit/env-vars.js.map +1 -1
  162. package/dist/host-kit/flowsafe-worker.d.ts +134 -5
  163. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  164. package/dist/host-kit/flowsafe-worker.js +283 -47
  165. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  166. package/dist/host-kit/host-approval-service.d.ts +20 -1
  167. package/dist/host-kit/host-approval-service.d.ts.map +1 -1
  168. package/dist/host-kit/host-approval-service.js +15 -0
  169. package/dist/host-kit/host-approval-service.js.map +1 -1
  170. package/dist/host-kit/hub-topology.d.ts +35 -0
  171. package/dist/host-kit/hub-topology.d.ts.map +1 -0
  172. package/dist/host-kit/hub-topology.js +32 -0
  173. package/dist/host-kit/hub-topology.js.map +1 -0
  174. package/dist/host-kit/index.d.ts +8 -1
  175. package/dist/host-kit/index.d.ts.map +1 -1
  176. package/dist/host-kit/index.js +10 -0
  177. package/dist/host-kit/index.js.map +1 -1
  178. package/dist/host-kit/memory-boundary.d.ts +64 -0
  179. package/dist/host-kit/memory-boundary.d.ts.map +1 -0
  180. package/dist/host-kit/memory-boundary.js +109 -0
  181. package/dist/host-kit/memory-boundary.js.map +1 -0
  182. package/dist/host-kit/route-path.d.ts +17 -0
  183. package/dist/host-kit/route-path.d.ts.map +1 -0
  184. package/dist/host-kit/route-path.js +35 -0
  185. package/dist/host-kit/route-path.js.map +1 -0
  186. package/dist/host-kit/stream-router.d.ts +22 -0
  187. package/dist/host-kit/stream-router.d.ts.map +1 -0
  188. package/dist/host-kit/stream-router.js +191 -0
  189. package/dist/host-kit/stream-router.js.map +1 -0
  190. package/dist/host-kit/stream-ticket.d.ts +55 -0
  191. package/dist/host-kit/stream-ticket.d.ts.map +1 -0
  192. package/dist/host-kit/stream-ticket.js +156 -0
  193. package/dist/host-kit/stream-ticket.js.map +1 -0
  194. package/dist/host-kit/tenant-registry.js +1 -1
  195. package/dist/host-kit/tenant-registry.js.map +1 -1
  196. package/dist/host-kit/thread-topology.d.ts +44 -0
  197. package/dist/host-kit/thread-topology.d.ts.map +1 -0
  198. package/dist/host-kit/thread-topology.js +76 -0
  199. package/dist/host-kit/thread-topology.js.map +1 -0
  200. package/dist/index.d.ts +3 -3
  201. package/dist/index.d.ts.map +1 -1
  202. package/dist/index.js +1 -1
  203. package/dist/index.js.map +1 -1
  204. package/dist/internal-error-response.d.ts +3 -0
  205. package/dist/internal-error-response.d.ts.map +1 -0
  206. package/dist/internal-error-response.js +20 -0
  207. package/dist/internal-error-response.js.map +1 -0
  208. package/dist/numeric-config.d.ts +4 -0
  209. package/dist/numeric-config.d.ts.map +1 -0
  210. package/dist/numeric-config.js +23 -0
  211. package/dist/numeric-config.js.map +1 -0
  212. package/dist/schedules/index.d.ts +5 -0
  213. package/dist/schedules/index.d.ts.map +1 -0
  214. package/dist/schedules/index.js +13 -0
  215. package/dist/schedules/index.js.map +1 -0
  216. package/dist/schedules/router.d.ts +66 -0
  217. package/dist/schedules/router.d.ts.map +1 -0
  218. package/dist/schedules/router.js +827 -0
  219. package/dist/schedules/router.js.map +1 -0
  220. package/dist/schedules/schedules-d1.d.ts +30 -0
  221. package/dist/schedules/schedules-d1.d.ts.map +1 -0
  222. package/dist/schedules/schedules-d1.js +374 -0
  223. package/dist/schedules/schedules-d1.js.map +1 -0
  224. package/dist/schedules/storage.d.ts +11 -0
  225. package/dist/schedules/storage.d.ts.map +1 -0
  226. package/dist/schedules/storage.js +34 -0
  227. package/dist/schedules/storage.js.map +1 -0
  228. package/dist/schedules/tick.d.ts +131 -0
  229. package/dist/schedules/tick.d.ts.map +1 -0
  230. package/dist/schedules/tick.js +598 -0
  231. package/dist/schedules/tick.js.map +1 -0
  232. package/dist/signal-providers/delivery.d.ts +24 -0
  233. package/dist/signal-providers/delivery.d.ts.map +1 -0
  234. package/dist/signal-providers/delivery.js +62 -0
  235. package/dist/signal-providers/delivery.js.map +1 -0
  236. package/dist/signal-providers/github-provider.d.ts +33 -0
  237. package/dist/signal-providers/github-provider.d.ts.map +1 -0
  238. package/dist/signal-providers/github-provider.js +116 -0
  239. package/dist/signal-providers/github-provider.js.map +1 -0
  240. package/dist/signal-providers/host-do.d.ts +79 -0
  241. package/dist/signal-providers/host-do.d.ts.map +1 -0
  242. package/dist/signal-providers/host-do.js +216 -0
  243. package/dist/signal-providers/host-do.js.map +1 -0
  244. package/dist/signal-providers/index.d.ts +7 -0
  245. package/dist/signal-providers/index.d.ts.map +1 -0
  246. package/dist/signal-providers/index.js +19 -0
  247. package/dist/signal-providers/index.js.map +1 -0
  248. package/dist/signal-providers/provider.d.ts +92 -0
  249. package/dist/signal-providers/provider.d.ts.map +1 -0
  250. package/dist/signal-providers/provider.js +87 -0
  251. package/dist/signal-providers/provider.js.map +1 -0
  252. package/dist/signal-providers/subscription-d1.d.ts +88 -0
  253. package/dist/signal-providers/subscription-d1.d.ts.map +1 -0
  254. package/dist/signal-providers/subscription-d1.js +259 -0
  255. package/dist/signal-providers/subscription-d1.js.map +1 -0
  256. package/dist/signal-providers/webhook-route.d.ts +88 -0
  257. package/dist/signal-providers/webhook-route.d.ts.map +1 -0
  258. package/dist/signal-providers/webhook-route.js +391 -0
  259. package/dist/signal-providers/webhook-route.js.map +1 -0
  260. package/dist/signals/client.d.ts +72 -0
  261. package/dist/signals/client.d.ts.map +1 -0
  262. package/dist/signals/client.js +87 -0
  263. package/dist/signals/client.js.map +1 -0
  264. package/dist/signals/d1-shared.d.ts +43 -0
  265. package/dist/signals/d1-shared.d.ts.map +1 -0
  266. package/dist/signals/d1-shared.js +46 -0
  267. package/dist/signals/d1-shared.js.map +1 -0
  268. package/dist/signals/index.d.ts +9 -0
  269. package/dist/signals/index.d.ts.map +1 -0
  270. package/dist/signals/index.js +15 -0
  271. package/dist/signals/index.js.map +1 -0
  272. package/dist/signals/notification-dispatch.d.ts +52 -0
  273. package/dist/signals/notification-dispatch.d.ts.map +1 -0
  274. package/dist/signals/notification-dispatch.js +198 -0
  275. package/dist/signals/notification-dispatch.js.map +1 -0
  276. package/dist/signals/notifications-d1.d.ts +28 -0
  277. package/dist/signals/notifications-d1.d.ts.map +1 -0
  278. package/dist/signals/notifications-d1.js +704 -0
  279. package/dist/signals/notifications-d1.js.map +1 -0
  280. package/dist/signals/router.d.ts +73 -0
  281. package/dist/signals/router.d.ts.map +1 -0
  282. package/dist/signals/router.js +240 -0
  283. package/dist/signals/router.js.map +1 -0
  284. package/dist/signals/storage.d.ts +11 -0
  285. package/dist/signals/storage.d.ts.map +1 -0
  286. package/dist/signals/storage.js +27 -0
  287. package/dist/signals/storage.js.map +1 -0
  288. package/dist/signals/thread-do-routes.d.ts +82 -0
  289. package/dist/signals/thread-do-routes.d.ts.map +1 -0
  290. package/dist/signals/thread-do-routes.js +660 -0
  291. package/dist/signals/thread-do-routes.js.map +1 -0
  292. package/dist/signals/thread-state-d1.d.ts +22 -0
  293. package/dist/signals/thread-state-d1.d.ts.map +1 -0
  294. package/dist/signals/thread-state-d1.js +83 -0
  295. package/dist/signals/thread-state-d1.js.map +1 -0
  296. package/package.json +11 -2
@@ -18,6 +18,36 @@ export function numberVar(raw, fallback, name, options = {}) {
18
18
  }
19
19
  return value;
20
20
  }
21
+ /**
22
+ * A number var that GATES whether a duty runs at all, rather than tuning one
23
+ * that runs regardless. Absent or empty => undefined, silently (the operator
24
+ * named nothing). Invalid => undefined AND a config-error line.
25
+ *
26
+ * The polarity argument is `boolVar`'s, not `numberVar`'s, and the difference
27
+ * is which direction is unsafe. `numberVar` falls back so maintenance keeps
28
+ * running on a typo'd var — correct when the duty runs either way and the
29
+ * number only tunes it (RUN_RETENTION_DAYS). Here the value decides whether an
30
+ * IRREVERSIBLE delete happens at all, so a fallback would not preserve behavior,
31
+ * it would INVENT it — and invent a threshold the caller has already decided it
32
+ * cannot pick on the operator's behalf. Never expiring is recoverable; deleting
33
+ * a tenant's conversations because a var was mistyped is not.
34
+ *
35
+ * The empty-string case is not hypothetical: `''` is what an unset CI/CD
36
+ * variable interpolates to and what a blank wrangler `vars` entry produces, and
37
+ * `numberVar` already reads it as unset — so a caller gating on
38
+ * `raw !== undefined` would silently enable the duty at the fallback value.
39
+ */
40
+ export function optionalNumberVar(raw, name, options = {}) {
41
+ if (raw === undefined || raw === '')
42
+ return undefined;
43
+ const value = Number(raw);
44
+ const belowFloor = options.allowZero ? value < 0 : value <= 0;
45
+ if (!Number.isFinite(value) || belowFloor) {
46
+ console.error(JSON.stringify({ type: 'config-error', var: name, raw, skipped: true }));
47
+ return undefined;
48
+ }
49
+ return value;
50
+ }
21
51
  const TRUTHY = new Set(['true', '1', 'yes', 'on']);
22
52
  const FALSY = new Set(['false', '0', 'no', 'off']);
23
53
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"env-vars.js","sourceRoot":"","sources":["../../src/host-kit/env-vars.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,yEAAyE;AACzE,yEAAyE;AACzE,2EAA2E;AAC3E,yEAAyE;AACzE,4EAA4E;AAC5E,sCAAsC;AActC,MAAM,UAAU,SAAS,CACvB,GAAuB,EACvB,QAAgB,EAChB,IAAY,EACZ,UAA4B,EAAE;IAE9B,IAAI,GAAG,KAAK,SAAS,IAAI,GAAG,KAAK,EAAE;QAAE,OAAO,QAAQ,CAAC;IACrD,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IAC1B,MAAM,UAAU,GAAG,OA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AAG,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IACnC,MAAM,MAAM,GAAG,KAAK;SACjB,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;SAC5B,MAAM,CAAC,OAAO,CAAC,CAAC;IACnB,MAAM,KAAK,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC;IACnE,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE,CAAC;QACzD,OAAO,CAAC,KAAK,CACX,IAAI,CAAC,SAAS,CAAC;YACb,IAAI,EAAE,cAAc;YACpB,GAAG,EAAE,IAAI;YACT,GAAG;YACH,SAAS,EAAE,KAAK;SACjB,CAAC,CACH,CAAC;QACF,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,CAAC;AACnB,CAAC"}
@@ -1,7 +1,8 @@
1
1
  import type { ApprovalAuditEvent, ApprovalDatabase, ApprovalNotificationSink, TenantResolver } from '../approval-api/index.js';
2
2
  import type { AuditMessageBatch, AuditQueue } from '../audit-export/index.js';
3
- import type { SnapshotDatabase } from '../do-runner/index.js';
3
+ import type { SnapshotDatabase, TenantArtifactPurger } from '../do-runner/index.js';
4
4
  import { type DoRunTopology, type RunnerNamespaceLike } from './do-run-topology.js';
5
+ import { type HubNamespaceLike } from './hub-topology.js';
5
6
  import type { TokenVerifier } from './verifier.js';
6
7
  import type { WorkflowMeta } from './workflow-meta.js';
7
8
  /** The ExecutionContext subset the composer needs (structural, like the rest of host-kit). */
@@ -18,6 +19,15 @@ export interface FlowsafeWorkerEnv {
18
19
  DB: ApprovalDatabase & SnapshotDatabase;
19
20
  /** The runner DO namespace createDoRunTopology drives. */
20
21
  RUNNER: RunnerNamespaceLike;
22
+ /**
23
+ * Optional per-tenant hub DO namespace for live streaming (DL-009/DL-019).
24
+ * Present together with STREAM_TICKET_SECRET => the composer mounts the stream
25
+ * stage and fans approval mutations out to the tenant hub; either absent =>
26
+ * streaming stays unmounted and the client remains poll-only.
27
+ */
28
+ HUB?: HubNamespaceLike;
29
+ /** Dedicated stream-ticket signing secret (DL-019). Absent => no streaming. */
30
+ STREAM_TICKET_SECRET?: string;
21
31
  /** Default SLA seconds for new approvals (var; default 14400 = 4h). */
22
32
  APPROVAL_SLA_SECONDS?: string;
23
33
  /**
@@ -31,11 +41,58 @@ export interface FlowsafeWorkerEnv {
31
41
  RUN_RETENTION_DAYS?: string;
32
42
  /** Cron purges DECIDED approval records older than this (var; default 30; 0 = immediately). */
33
43
  APPROVAL_RETENTION_DAYS?: string;
44
+ /**
45
+ * Agent-memory thread TTL in days (var; docs/agent-memory-tenancy.md item 7):
46
+ * the purge cron deletes threads untouched for longer than this, with their
47
+ * messages. UNSET, EMPTY, or INVALID => the duty does not run and no thread
48
+ * ever expires — the opt-in default, because a thread is a conversation a host
49
+ * means to keep, not a terminal run snapshot that is finished by definition.
50
+ * There is no safe number to pick on an operator's behalf here, so anything
51
+ * short of a number the operator actually named is answered by NOT deleting
52
+ * (a config-error line marks the invalid case). Unlike RUN_RETENTION_DAYS this
53
+ * var decides whether an irreversible delete happens at all, so it does not
54
+ * take numberVar's fallback — see optionalNumberVar in env-vars.ts.
55
+ */
56
+ THREAD_RETENTION_DAYS?: string;
57
+ /**
58
+ * Track C agent-inbox TTL in days (var). The purge cron reaps TERMINAL
59
+ * `mastra_notifications` rows past this age (pending rows are never reaped —
60
+ * one may await a future deliverAt). UNSET/EMPTY/INVALID => the duty does not
61
+ * run and no notification ever expires (opt-in, like THREAD_RETENTION_DAYS —
62
+ * a durable inbox is meant to be readable until the host says otherwise).
63
+ */
64
+ NOTIFICATION_RETENTION_DAYS?: string;
65
+ /**
66
+ * Track C thread-state TTL in days (var). The purge cron reaps
67
+ * `mastra_thread_state` rows (state-signal lanes + goals) untouched for longer
68
+ * than this. UNSET/EMPTY/INVALID => the duty does not run (opt-in; an active
69
+ * goal bumps updatedAt so it never ages out).
70
+ */
71
+ THREAD_STATE_RETENTION_DAYS?: string;
72
+ /**
73
+ * Track D schedule-trigger history TTL in days (var). The purge cron reaps
74
+ * `mastra_schedule_triggers` rows past this age by their `actualFireAt`.
75
+ * UNSET/EMPTY/INVALID => the duty does not run (opt-in; a schedule's fire
76
+ * history is inspectable until the host sets a window). The schedule rows
77
+ * themselves are standing config — never TTL'd, reaped only at offboarding.
78
+ */
79
+ SCHEDULE_TRIGGER_RETENTION_DAYS?: string;
34
80
  /** Optional audit export: queue producer binding + SIEM collector config. */
35
81
  AUDIT_QUEUE?: AuditQueue<ApprovalAuditEvent>;
36
82
  SIEM_ENDPOINT?: string;
37
83
  SIEM_AUTH_HEADER?: string;
38
84
  }
85
+ /**
86
+ * Track B background-task TTL cleanup config, surfaced through
87
+ * FlowsafeWorkerConfig (DL-003). Mirrors core BackgroundTaskManager.cleanup's
88
+ * two windows.
89
+ */
90
+ export interface BackgroundTasksCleanupConfig {
91
+ /** Completed rows past this age expire. Default 3_600_000 (1h). */
92
+ completedTtlMs?: number;
93
+ /** Failed / cancelled / timed_out rows past this age expire. Default 86_400_000 (24h). */
94
+ failedTtlMs?: number;
95
+ }
39
96
  export interface FlowsafeWorkerConfig<Env extends FlowsafeWorkerEnv> {
40
97
  /** The catalog createRunRouter serves and gates (hosts pass their metas). */
41
98
  workflows: ReadonlyArray<WorkflowMeta>;
@@ -53,14 +110,20 @@ export interface FlowsafeWorkerConfig<Env extends FlowsafeWorkerEnv> {
53
110
  */
54
111
  buildVerifier: (env: Env) => TokenVerifier;
55
112
  /**
56
- * The two cron expressions scheduled() dispatches on. Keep byte-equal to
57
- * wrangler.jsonc's `triggers.crons`; an unrecognized expression runs BOTH
58
- * duties sequentially and logs a config-error (availability of both beats
59
- * purity on a misconfig).
113
+ * The cron expressions scheduled() dispatches on. `sweep` + `purge` are
114
+ * required and must never share an invocation. `tick` is OPTIONAL (Track D
115
+ * schedules): when set AND `scheduleTick` is provided, the schedule tick runs
116
+ * on it as its OWN failure-isolated invocation (a runaway fire pass gets its
117
+ * own CPU budget, the same rationale that keeps sweep and purge apart). Keep
118
+ * these byte-equal to wrangler.jsonc's `triggers.crons`; an unrecognized
119
+ * expression runs the sweep + purge duties sequentially and logs a
120
+ * config-error (availability beats purity on a misconfig). Absent `tick` ⇒ no
121
+ * schedule-tick invocation, byte-identical.
60
122
  */
61
123
  crons: {
62
124
  sweep: string;
63
125
  purge: string;
126
+ tick?: string;
64
127
  };
65
128
  /**
66
129
  * Deployment-specific routes tried AFTER /healthz and BEFORE the approval
@@ -85,6 +148,72 @@ export interface FlowsafeWorkerConfig<Env extends FlowsafeWorkerEnv> {
85
148
  * (transports usually need secrets); undefined = no notifications.
86
149
  */
87
150
  notify?: (env: Env) => ApprovalNotificationSink | undefined;
151
+ /**
152
+ * When set, the retention purge (runPurgeMaintenance -> the built-in
153
+ * purgeExpiredWorkflowRuns) deletes each expired run's R2 artifacts WITH its
154
+ * snapshot row. The snapshot row is the only enumerable record of a run's
155
+ * artifact keys (R2 keys lead with workflowId — there is no run-level listing
156
+ * without it), so a retention purge without this pairing strands the run's
157
+ * artifacts beyond even purgeTenant's reach. Pass the same TenantArtifactPurger
158
+ * (an R2ArtifactStore) purgeTenant gets; undefined keeps the byte-identical
159
+ * row-only purge. NOT via extraPurgeDuties — that hook runs AFTER the rows are
160
+ * deleted, when the keys are already unenumerable.
161
+ */
162
+ artifactStore?: TenantArtifactPurger;
163
+ /**
164
+ * Opt-in background-task TTL cleanup (Track B). When present, the purge cron
165
+ * reaps terminal `mastra_background_tasks` rows past the TTL as its OWN
166
+ * failure-isolated duty — the storage-layer belt to a hosting DO's manager
167
+ * cleanup (which needs the DO alive). Absent => no duty, byte-identical
168
+ * (background tasks are opt-in). NOT via extraPurgeDuties: this needs its own
169
+ * try/catch and its own log fields, like every sibling purge duty.
170
+ */
171
+ backgroundTasks?: BackgroundTasksCleanupConfig;
172
+ /**
173
+ * Opt-in Track C signal ingestion stage (P6, DL-006). The host builds its
174
+ * `createSignalRouter` (which needs its per-thread DO namespace via
175
+ * createThreadTopology, plus its audit/rate/allowlist config) and returns it
176
+ * here, closed over the request's resolved TenantResolver; the composer mounts
177
+ * it after preRoutes, ahead of approvals/runs (its `/api/threads/*` routes
178
+ * don't overlap). INJECTED rather than built here because createSignalRouter
179
+ * lives in `signals/`, which imports host-kit — host-kit importing it back
180
+ * would cycle. Absent (or returns undefined) => no signal stage, byte-identical.
181
+ */
182
+ buildSignalRouter?: (resolve: TenantResolver, env: Env) => ((request: Request) => Promise<Response | null>) | undefined;
183
+ /**
184
+ * Opt-in Track F goal objective stage (P6-lite, DL-018). Mirrors
185
+ * buildSignalRouter: the host builds its `createObjectiveRouter` (which needs
186
+ * the thread-state store from its D1 domains, plus its audit/maxRuns config)
187
+ * and returns it here, closed over the request's resolved TenantResolver; the
188
+ * composer mounts it after the signal stage. Both live under `/api/threads/*`
189
+ * but do not overlap — goals use the `/goal` segment, signals the channel
190
+ * segments. INJECTED rather than built here because createObjectiveRouter lives
191
+ * in `goals/`, which imports host-kit — host-kit importing it back would cycle.
192
+ * Absent (or returns undefined) ⇒ no goal stage, byte-identical.
193
+ */
194
+ buildObjectiveRouter?: (resolve: TenantResolver, env: Env) => ((request: Request) => Promise<Response | null>) | undefined;
195
+ /**
196
+ * Opt-in Track D schedule CRUD facade (DL-013). Mirrors buildSignalRouter/
197
+ * buildObjectiveRouter: the host builds its `createScheduleRouter` (which needs
198
+ * the schedules store from its D1 domains + its audit/cap config) and returns it
199
+ * here, closed over the request's resolved TenantResolver; the composer mounts it
200
+ * after the goal stage. Its `/api/schedules/*` routes don't overlap the others.
201
+ * INJECTED (not built here, typed structurally) because createScheduleRouter
202
+ * lives in `schedules/`, which transitively imports host-kit — importing it back
203
+ * would cycle. Absent (or returns undefined) ⇒ no schedule surface, byte-identical.
204
+ */
205
+ buildScheduleRouter?: (resolve: TenantResolver, env: Env) => ((request: Request) => Promise<Response | null>) | undefined;
206
+ /**
207
+ * Opt-in Track D schedule tick (DL-012). The host builds its `createScheduleTick`
208
+ * (which needs the schedules store, its run-start seam — topology.start — and
209
+ * the run-cap + audit config) and returns the closure here. The composer runs
210
+ * it on the `crons.tick` cron as its OWN failure-isolated duty (own try/catch,
211
+ * own `schedule-tick` log line). INJECTED (not built here, structurally typed as
212
+ * `() => Promise<unknown>`) because createScheduleTick lives in `schedules/`,
213
+ * which transitively imports host-kit — host-kit importing it back would cycle.
214
+ * Absent (or `crons.tick` unset) ⇒ no tick invocation, byte-identical.
215
+ */
216
+ scheduleTick?: (env: Env) => (() => Promise<unknown>) | undefined;
88
217
  /**
89
218
  * Extra purge-cron duties (e.g. the showcase's demo-tenant reaper). The
90
219
  * returned fields fold into the ONE combined `{type:'maintenance'}` log
@@ -1 +1 @@
1
- {"version":3,"file":"flowsafe-worker.d.ts","sourceRoot":"","sources":["../../src/host-kit/flowsafe-worker.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EACV,kBAAkB,EAClB,gBAAgB,EAChB,wBAAwB,EAExB,cAAc,EACf,MAAM,0BAA0B,CAAC;AAMlC,OAAO,KAAK,EAAE,iBAAiB,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAE9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uBAAuB,CAAC;AAG9D,OAAO,EAEL,KAAK,aAAa,EAClB,KAAK,mBAAmB,EACzB,MAAM,sBAAsB,CAAC;AAW9B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAEvD,8FAA8F;AAC9F,MAAM,WAAW,qBAAqB;IACpC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CAC5C;AAED;;;;GAI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O,CAAC,CAAC,CAAC;CACvC;AAED,iFAAiF;AACjF,MAAM,WAAW,cAAc,CAAC,GAAG,SAAS,iBAAiB;IAC3D,KAAK,CACH,OAAO,EAAE,OAAO,EAChB,GAAG,EAAE,GAAG,EACR,GAAG,EAAE,qBAAqB,GACzB,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrB,SAAS,CACP,UAAU,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,EAC5B,GAAG,EAAE,GAAG,EACR,GAAG,EAAE,qBAAqB,GACzB,OAAO,CAAC,IAAI,CAAC,CAAC;IACjB,KAAK,CAAC,KAAK,EAAE,iBAAiB,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACnE;AASD,wBAAgB,oBAAoB,CAAC,GAAG,SAAS,iBAAiB,EAChE,MAAM,EAAE,oBAAoB,CAAC,GAAG,CAAC,GAChC,cAAc,CAAC,GAAG,CAAC,CA+erB"}
@@ -14,12 +14,14 @@
14
14
  // imports @cloudflare/workers-types.
15
15
  import { APPROVAL_ROLES, createApprovalRouter, createTenantResolver, } from '../approval-api/index.js';
16
16
  import { createAuditQueueHandler } from '../audit-export/index.js';
17
- import { purgeExpiredWorkflowRuns } from '../do-runner/index.js';
17
+ import { purgeExpiredBackgroundTasks, purgeExpiredNotifications, purgeExpiredScheduleTriggers, purgeExpiredThreadState, purgeExpiredThreads, purgeExpiredWorkflowRuns, } from '../do-runner/index.js';
18
18
  import { bearerActorAuthenticator } from './bearer-auth.js';
19
19
  import { createDoRunTopology, } from './do-run-topology.js';
20
- import { numberVar, selfDecisionPolicyVar } from './env-vars.js';
20
+ import { numberVar, optionalNumberVar, selfDecisionPolicyVar, } from './env-vars.js';
21
21
  import { approvalStoreFactoryFor, buildHostApprovalService, maintenanceActor, reconcileApprovalsOnStatusDetached, runApprovalRetentionPurge, runSlaSweepMaintenance, } from './host-approval-service.js';
22
+ import { createHubTopology } from './hub-topology.js';
22
23
  import { createRunRouter } from './run-router.js';
24
+ import { createStreamRouter } from './stream-router.js';
23
25
  function json(payload, status = 200) {
24
26
  return new Response(JSON.stringify(payload), {
25
27
  status,
@@ -30,7 +32,7 @@ export function createFlowsafeWorker(config) {
30
32
  // AUTHENTICATE FIRST, then construct (INV-2): the resolver binds the
31
33
  // approval store to the verified actor's tenant before any service exists —
32
34
  // there is no pre-auth store for a rushed fix to reach.
33
- const buildResolve = (env, topology, waitUntil, notify, selfDecision) => {
35
+ const buildResolve = (env, topology, waitUntil, notify, selfDecision, stream) => {
34
36
  const base = createTenantResolver({
35
37
  authenticate: bearerActorAuthenticator(config.buildVerifier(env)),
36
38
  storeFactory: approvalStoreFactoryFor(env.DB),
@@ -43,6 +45,10 @@ export function createFlowsafeWorker(config) {
43
45
  queue: env.AUDIT_QUEUE,
44
46
  waitUntil,
45
47
  notify,
48
+ // Fetch-scope hub fan-out: every request-path mutation reaches the
49
+ // tenant hub, kept alive by ctx.waitUntil (DL-020). Undefined when no
50
+ // HUB is bound, so a non-streaming host is byte-identical to before.
51
+ stream,
46
52
  allowSelfDecision: selfDecision,
47
53
  }),
48
54
  // The resolver's canSelfDecide display hint reads the SAME policy the
@@ -85,6 +91,10 @@ export function createFlowsafeWorker(config) {
85
91
  60 *
86
92
  60 *
87
93
  1000,
94
+ // Pairs each expired run's R2 artifacts with its snapshot-row deletion
95
+ // (artifacts BEFORE the row — the row is the only record of their keys).
96
+ // Undefined on hosts that wire no R2, so the purge stays byte-identical.
97
+ artifactStore: config.artifactStore,
88
98
  });
89
99
  }
90
100
  catch (error) {
@@ -103,6 +113,113 @@ export function createFlowsafeWorker(config) {
103
113
  retentionDays: env.APPROVAL_RETENTION_DAYS,
104
114
  cron,
105
115
  });
116
+ // Agent-memory thread TTL, opt-in (docs/agent-memory-tenancy.md item 7).
117
+ // Its OWN try/catch, like every sibling duty above and below: isolating one
118
+ // loop while a sibling shares its failure is a defect this codebase has
119
+ // already shipped once — a wedged thread purge must cost the run-snapshot
120
+ // purge, the approval purge, and the extra duties nothing.
121
+ let threadsPurged;
122
+ let threadMessagesPurged;
123
+ // optionalNumberVar, not numberVar: this var GATES the duty rather than
124
+ // tuning it, so unset/empty/garbage must all mean "do not delete" — never a
125
+ // silent fallback threshold (see its contract in env-vars.ts).
126
+ // allowZero: THREAD_RETENTION_DAYS=0 means "expire idle threads now", the
127
+ // same operator intent RUN_RETENTION_DAYS=0 states.
128
+ const threadRetentionDays = optionalNumberVar(env.THREAD_RETENTION_DAYS, 'THREAD_RETENTION_DAYS', { allowZero: true });
129
+ if (threadRetentionDays !== undefined) {
130
+ try {
131
+ const purgedThreads = await purgeExpiredThreads(env.DB, {
132
+ ttlMs: threadRetentionDays * 24 * 60 * 60 * 1000,
133
+ });
134
+ threadsPurged = purgedThreads.threads;
135
+ threadMessagesPurged = purgedThreads.messages;
136
+ }
137
+ catch (error) {
138
+ console.error(JSON.stringify({
139
+ type: 'maintenance-error',
140
+ surface: 'thread-retention-purge',
141
+ cron,
142
+ error: String(error),
143
+ }));
144
+ }
145
+ }
146
+ // Background-task TTL cleanup (Track B, opt-in). Its OWN try/catch, like
147
+ // every sibling duty: a wedged background-task purge must cost the
148
+ // run-snapshot, approval, and thread purges nothing.
149
+ let backgroundTasksPurged;
150
+ if (config.backgroundTasks) {
151
+ try {
152
+ backgroundTasksPurged = await purgeExpiredBackgroundTasks(env.DB, {
153
+ completedTtlMs: config.backgroundTasks.completedTtlMs,
154
+ failedTtlMs: config.backgroundTasks.failedTtlMs,
155
+ });
156
+ }
157
+ catch (error) {
158
+ console.error(JSON.stringify({
159
+ type: 'maintenance-error',
160
+ surface: 'background-task-purge',
161
+ cron,
162
+ error: String(error),
163
+ }));
164
+ }
165
+ }
166
+ // Track C notification TTL (opt-in). Its OWN try/catch, like every sibling
167
+ // duty. optionalNumberVar (GATES the duty; unset/garbage => do not delete).
168
+ let notificationsPurged;
169
+ const notificationRetentionDays = optionalNumberVar(env.NOTIFICATION_RETENTION_DAYS, 'NOTIFICATION_RETENTION_DAYS', { allowZero: true });
170
+ if (notificationRetentionDays !== undefined) {
171
+ try {
172
+ notificationsPurged = await purgeExpiredNotifications(env.DB, {
173
+ ttlMs: notificationRetentionDays * 24 * 60 * 60 * 1000,
174
+ });
175
+ }
176
+ catch (error) {
177
+ console.error(JSON.stringify({
178
+ type: 'maintenance-error',
179
+ surface: 'notification-purge',
180
+ cron,
181
+ error: String(error),
182
+ }));
183
+ }
184
+ }
185
+ // Track C thread-state TTL (opt-in). Same isolation + opt-in posture.
186
+ let threadStatePurged;
187
+ const threadStateRetentionDays = optionalNumberVar(env.THREAD_STATE_RETENTION_DAYS, 'THREAD_STATE_RETENTION_DAYS', { allowZero: true });
188
+ if (threadStateRetentionDays !== undefined) {
189
+ try {
190
+ threadStatePurged = await purgeExpiredThreadState(env.DB, {
191
+ ttlMs: threadStateRetentionDays * 24 * 60 * 60 * 1000,
192
+ });
193
+ }
194
+ catch (error) {
195
+ console.error(JSON.stringify({
196
+ type: 'maintenance-error',
197
+ surface: 'thread-state-purge',
198
+ cron,
199
+ error: String(error),
200
+ }));
201
+ }
202
+ }
203
+ // Track D schedule-trigger history TTL (opt-in). Same isolation + opt-in
204
+ // posture. Only the fire HISTORY expires; schedule config rows are reaped
205
+ // only at offboarding (purgeTenant).
206
+ let scheduleTriggersPurged;
207
+ const scheduleTriggerRetentionDays = optionalNumberVar(env.SCHEDULE_TRIGGER_RETENTION_DAYS, 'SCHEDULE_TRIGGER_RETENTION_DAYS', { allowZero: true });
208
+ if (scheduleTriggerRetentionDays !== undefined) {
209
+ try {
210
+ scheduleTriggersPurged = await purgeExpiredScheduleTriggers(env.DB, {
211
+ ttlMs: scheduleTriggerRetentionDays * 24 * 60 * 60 * 1000,
212
+ });
213
+ }
214
+ catch (error) {
215
+ console.error(JSON.stringify({
216
+ type: 'maintenance-error',
217
+ surface: 'schedule-trigger-purge',
218
+ cron,
219
+ error: String(error),
220
+ }));
221
+ }
222
+ }
106
223
  let extra = {};
107
224
  if (config.extraPurgeDuties) {
108
225
  try {
@@ -122,67 +239,186 @@ export function createFlowsafeWorker(config) {
122
239
  cron,
123
240
  purged,
124
241
  approvalsPurged,
242
+ threadsPurged,
243
+ threadMessagesPurged,
244
+ backgroundTasksCompletedPurged: backgroundTasksPurged?.completed,
245
+ backgroundTasksFailedPurged: backgroundTasksPurged?.failed,
246
+ notificationsPurged,
247
+ threadStatePurged,
248
+ scheduleTriggersPurged,
125
249
  ...extra,
126
250
  }));
127
251
  }
252
+ // Track D schedule tick — its OWN failure-isolated duty (own try/catch, own log
253
+ // line), run on the `crons.tick` invocation. A wedged fire pass must cost the
254
+ // sweep + purge nothing, and vice versa (the two-cron isolation rationale).
255
+ async function runScheduleTickDuty(env, cron) {
256
+ const tick = config.scheduleTick?.(env);
257
+ if (!tick) {
258
+ // The tick cron fired but no scheduleTick builder is wired — a misconfig.
259
+ // Do NOT fall through to sweep/purge (this invocation is the tick's).
260
+ console.error(JSON.stringify({
261
+ type: 'config-error',
262
+ var: 'crons.tick',
263
+ cron,
264
+ reason: 'tick cron fired but no scheduleTick builder is configured',
265
+ }));
266
+ return;
267
+ }
268
+ try {
269
+ const result = await tick();
270
+ console.log(JSON.stringify({ type: 'schedule-tick', cron, result }));
271
+ }
272
+ catch (error) {
273
+ console.error(JSON.stringify({
274
+ type: 'schedule-tick-error',
275
+ cron,
276
+ error: String(error),
277
+ }));
278
+ }
279
+ }
128
280
  return {
129
281
  async fetch(request, env, ctx) {
130
- const url = new URL(request.url);
131
- if (request.method === 'GET' && url.pathname === '/healthz') {
132
- return json({ ok: true });
133
- }
134
- const waitUntil = (promise) => ctx.waitUntil(promise);
135
- const topology = createDoRunTopology(env.RUNNER);
136
- const notify = config.notify?.(env);
137
- const selfDecision = parseSelfDecision(env);
138
- const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision);
139
- if (config.preRoutes) {
140
- const preResponse = await config.preRoutes(request, env, ctx, {
282
+ try {
283
+ const url = new URL(request.url);
284
+ if (request.method === 'GET' && url.pathname === '/healthz') {
285
+ return json({ ok: true });
286
+ }
287
+ const waitUntil = (promise) => ctx.waitUntil(promise);
288
+ const topology = createDoRunTopology(env.RUNNER);
289
+ const notify = config.notify?.(env);
290
+ const selfDecision = parseSelfDecision(env);
291
+ // Fetch-scope live fan-out sink: present iff a hub is bound (streaming is
292
+ // opt-in, DL-019). Each publish rides ctx.waitUntil (DL-020) and is
293
+ // contained — a failed fan-out logs and never fails the mutation.
294
+ const hub = env.HUB;
295
+ let streamSink;
296
+ if (hub) {
297
+ const hubTopology = createHubTopology(hub);
298
+ streamSink = (event) => waitUntil(hubTopology.publish(event).catch((error) => console.error(JSON.stringify({
299
+ type: 'stream-publish-error',
300
+ reason: error instanceof Error ? error.message : String(error),
301
+ }))));
302
+ }
303
+ const resolve = buildResolve(env, topology, waitUntil, notify, selfDecision, streamSink);
304
+ if (config.preRoutes) {
305
+ const preResponse = await config.preRoutes(request, env, ctx, {
306
+ resolve,
307
+ topology,
308
+ });
309
+ if (preResponse)
310
+ return preResponse;
311
+ }
312
+ // Optional stream stage (DL-015/DL-019): mounted only when BOTH the hub
313
+ // binding and the ticket secret are present. Every route is under
314
+ // /api/stream/, so it composes ahead of the approval router without
315
+ // touching the /api/* run_worker_first entry.
316
+ if (env.HUB && env.STREAM_TICKET_SECRET) {
317
+ const streamResponse = await createStreamRouter({
318
+ resolve,
319
+ ticketSecret: env.STREAM_TICKET_SECRET,
320
+ hub: env.HUB,
321
+ runner: env.RUNNER,
322
+ })(request);
323
+ if (streamResponse)
324
+ return streamResponse;
325
+ }
326
+ // Optional Track C signal stage (P6): the host-built createSignalRouter,
327
+ // closed over THIS request's resolver. `/api/threads/*` — composes ahead
328
+ // of approvals/runs without overlap. Absent seam => unmounted.
329
+ const signalRouter = config.buildSignalRouter?.(resolve, env);
330
+ if (signalRouter) {
331
+ const signalResponse = await signalRouter(request);
332
+ if (signalResponse)
333
+ return signalResponse;
334
+ }
335
+ // Optional Track F goal stage (P6-lite, DL-018): the host-built
336
+ // createObjectiveRouter, closed over THIS request's resolver.
337
+ // `/api/threads/:threadId/goal` — composes after signals (non-overlapping)
338
+ // and ahead of approvals/runs. Absent seam ⇒ unmounted, byte-identical.
339
+ const objectiveRouter = config.buildObjectiveRouter?.(resolve, env);
340
+ if (objectiveRouter) {
341
+ const objectiveResponse = await objectiveRouter(request);
342
+ if (objectiveResponse)
343
+ return objectiveResponse;
344
+ }
345
+ // Optional Track D schedule CRUD stage (DL-013): the host-built
346
+ // createScheduleRouter, closed over THIS request's resolver. `/api/schedules/*`
347
+ // — composes after goals (non-overlapping), ahead of approvals/runs. Absent
348
+ // seam ⇒ unmounted, byte-identical.
349
+ const scheduleRouter = config.buildScheduleRouter?.(resolve, env);
350
+ if (scheduleRouter) {
351
+ const scheduleResponse = await scheduleRouter(request);
352
+ if (scheduleResponse)
353
+ return scheduleResponse;
354
+ }
355
+ const approvalResponse = await createApprovalRouter({ resolve })(request);
356
+ if (approvalResponse)
357
+ return approvalResponse;
358
+ const runResponse = await createRunRouter({
359
+ workflows: config.workflows,
141
360
  resolve,
142
- topology,
143
- });
144
- if (preResponse)
145
- return preResponse;
146
- }
147
- const approvalResponse = await createApprovalRouter({ resolve })(request);
148
- if (approvalResponse)
149
- return approvalResponse;
150
- const runResponse = await createRunRouter({
151
- workflows: config.workflows,
152
- resolve,
153
- systemActorId: config.systemActorId,
154
- start: config.wrapStart
155
- ? config.wrapStart(topology.start, env)
156
- : topology.start,
157
- status: topology.status,
158
- resume: config.wrapResume
159
- ? config.wrapResume(topology.resume, env)
160
- : topology.resume,
161
- // D4 self-healing, waitUntil-detached — the shared wrapper owns the
162
- // detach + reconcile-error logging.
163
- reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemActorId, waitUntil),
164
- })(request);
165
- if (runResponse)
166
- return runResponse;
167
- return json({ error: 'not found' }, 404);
361
+ systemActorId: config.systemActorId,
362
+ start: config.wrapStart
363
+ ? config.wrapStart(topology.start, env)
364
+ : topology.start,
365
+ status: topology.status,
366
+ resume: config.wrapResume
367
+ ? config.wrapResume(topology.resume, env)
368
+ : topology.resume,
369
+ // D4 self-healing, waitUntil-detached — the shared wrapper owns the
370
+ // detach + reconcile-error logging.
371
+ reconcileApprovals: reconcileApprovalsOnStatusDetached(config.systemActorId, waitUntil),
372
+ })(request);
373
+ if (runResponse)
374
+ return runResponse;
375
+ return json({ error: 'not found' }, 404);
376
+ }
377
+ catch (error) {
378
+ // Backstop: a mounted router (or any handler fault) that THROWS before
379
+ // returning a Response — e.g. a future unguarded path decode — is
380
+ // contained as a generic 500 here rather than rejecting out of fetch()
381
+ // as an unhandled promise. Never surface error.message to the client.
382
+ console.error(JSON.stringify({
383
+ type: 'worker-fetch-error',
384
+ reason: error instanceof Error ? error.message : String(error),
385
+ }));
386
+ return json({ error: 'internal error' }, 500);
387
+ }
168
388
  },
169
389
  async scheduled(controller, env, ctx) {
170
390
  // Dispatch on WHICH cron fired; an unrecognized expression (ops edited
171
391
  // wrangler without updating the config) runs both sequentially and
172
392
  // logs — availability of both duties beats purity on a misconfig.
173
- const sweep = () => runSlaSweepMaintenance({
174
- store: approvalStoreFactoryFor(env.DB).system(),
175
- systemActor: maintenanceActor(config.systemActorId),
176
- queue: env.AUDIT_QUEUE,
177
- cron: controller.cron,
178
- notify: config.notify?.(env),
179
- });
393
+ const sweep = () => {
394
+ const hub = env.HUB;
395
+ const hubTopology = hub ? createHubTopology(hub) : undefined;
396
+ return runSlaSweepMaintenance({
397
+ store: approvalStoreFactoryFor(env.DB).system(),
398
+ systemActor: maintenanceActor(config.systemActorId),
399
+ queue: env.AUDIT_QUEUE,
400
+ cron: controller.cron,
401
+ notify: config.notify?.(env),
402
+ // BARE hub-publish thunk, NOT waitUntil-wrapped: a scheduled() handler
403
+ // runs under its own waitUntil, so runSlaSweepMaintenance collects
404
+ // each publish into pendingSends and awaits it via Promise.all (DL-020).
405
+ stream: hubTopology
406
+ ? (event) => hubTopology.publish(event)
407
+ : undefined,
408
+ });
409
+ };
180
410
  if (controller.cron === config.crons.sweep) {
181
411
  ctx.waitUntil(sweep());
182
412
  }
183
413
  else if (controller.cron === config.crons.purge) {
184
414
  ctx.waitUntil(runPurgeMaintenance(env, controller.cron));
185
415
  }
416
+ else if (config.crons.tick !== undefined &&
417
+ controller.cron === config.crons.tick) {
418
+ // Track D: the schedule tick's OWN invocation (opt-in; unset ⇒ this
419
+ // branch is unreachable, byte-identical).
420
+ ctx.waitUntil(runScheduleTickDuty(env, controller.cron));
421
+ }
186
422
  else {
187
423
  console.error(JSON.stringify({
188
424
  type: 'config-error',