@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
@@ -0,0 +1,144 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003): the READ-ONLY, tenant-bound HTTP surface over background
3
+ // tasks (DL-014). Background-task rows carry tenant-prefixed run_id / threadId /
4
+ // resourceId (INV-1 + minted memory ids), but core's `listTasks` / `getTask` /
5
+ // `stream` are NOT tenant-bound — exposing the raw manager would be a
6
+ // cross-tenant existence/content oracle. So this router:
7
+ // - REQUIRES a `runId` or `threadId` filter on list AND stream, and validates
8
+ // its salted prefix against the authenticated tenant (400 if absent, 404 if
9
+ // foreign — no oracle);
10
+ // - loads a task for `getTask` and 404s if its `runId` is not tenant-owned,
11
+ // whether the task is missing or another tenant's (one response, no oracle);
12
+ // - never returns or accepts the raw BackgroundTaskManager.
13
+ //
14
+ // The hosting DO passes the already-authenticated tenant (its own idFromName
15
+ // identity), exactly as the run/thread DOs recover theirs. Mutating the queue
16
+ // (dispatch/cancel/resume) is NOT here: v1 keeps background dispatch server-side
17
+ // (an agent's tool call), and a suspended non-gated task's resume, if ever
18
+ // exposed, is a separate role-gated route that mints no capability (P8).
19
+ import { tenantOwnsSaltedId } from '../do-runner/index.js';
20
+ import { safeDecodeSegment } from '../host-kit/route-path.js';
21
+ function json(payload, status = 200) {
22
+ return new Response(JSON.stringify(payload), {
23
+ status,
24
+ headers: { 'content-type': 'application/json' },
25
+ });
26
+ }
27
+ /**
28
+ * Resolve the tenant-scoped filter (runId XOR threadId) from the query, or a
29
+ * fail-closed Response. Both ids are salted `${tenantId}_...`, so
30
+ * `tenantOwnsSaltedId` is exact for either (INV-3). Absent => 400; foreign =>
31
+ * 404 (no oracle — a foreign id gets the same answer as a nonexistent one).
32
+ */
33
+ function resolveScopedFilter(url, tenantId) {
34
+ const runId = url.searchParams.get('runId') ?? undefined;
35
+ const threadId = url.searchParams.get('threadId') ?? undefined;
36
+ if (runId === undefined && threadId === undefined) {
37
+ return json({
38
+ error: 'a runId or threadId filter is required (background-task queries are tenant-scoped)',
39
+ }, 400);
40
+ }
41
+ const scopeValue = runId ?? threadId;
42
+ if (!tenantOwnsSaltedId(tenantId, scopeValue)) {
43
+ return json({ error: 'not found' }, 404);
44
+ }
45
+ return {
46
+ filter: runId !== undefined ? { runId } : { threadId },
47
+ scopeValue,
48
+ };
49
+ }
50
+ /**
51
+ * The scope-ownership predicate shared by list AND stream (DL-014): a row is in
52
+ * scope iff its runId or threadId equals the validated, tenant-owned scope value
53
+ * the request was filtered by. Defense-in-depth OVER core's own filter — a future
54
+ * regression in core's `listTasks`/`stream` scoping cannot leak a foreign or
55
+ * out-of-scope row past this. One predicate so list and stream can never drift.
56
+ */
57
+ function ownsScope(row, scopeValue) {
58
+ return row.runId === scopeValue || row.threadId === scopeValue;
59
+ }
60
+ export function createBackgroundTaskRoutes(options) {
61
+ const { manager } = options;
62
+ const base = options.basePath ?? '/background-tasks';
63
+ return async (request, tenantId) => {
64
+ if (request.method !== 'GET')
65
+ return null;
66
+ const url = new URL(request.url);
67
+ const path = url.pathname;
68
+ if (path !== base && !path.startsWith(`${base}/`))
69
+ return null;
70
+ // GET {base}/stream — SSE of lifecycle events for one tenant-owned run/thread.
71
+ if (path === `${base}/stream`) {
72
+ const resolved = resolveScopedFilter(url, tenantId);
73
+ if (resolved instanceof Response)
74
+ return resolved;
75
+ return streamResponse(manager, resolved, request.signal);
76
+ }
77
+ // GET {base}/task/:taskId — one task, 404 on missing OR foreign (no oracle).
78
+ if (path.startsWith(`${base}/task/`)) {
79
+ // Malformed percent-encoding in the taskId is not a real task — 404 (the
80
+ // no-oracle response), never a decodeURIComponent throw out of the DO
81
+ // handler (this route is post-auth, but the same fail-shut posture).
82
+ const taskId = safeDecodeSegment(path.slice(`${base}/task/`.length));
83
+ if (taskId === undefined || taskId === '' || taskId.includes('/'))
84
+ return json({ error: 'not found' }, 404);
85
+ const task = await manager.getTask(taskId);
86
+ if (!task || !tenantOwnsSaltedId(tenantId, task.runId)) {
87
+ return json({ error: 'not found' }, 404);
88
+ }
89
+ return json({ task });
90
+ }
91
+ // GET {base} — list, filtered to one tenant-owned run/thread.
92
+ if (path === base) {
93
+ const resolved = resolveScopedFilter(url, tenantId);
94
+ if (resolved instanceof Response)
95
+ return resolved;
96
+ const result = await manager.listTasks(resolved.filter);
97
+ // Per-row parity with the stream guard (DL-014): re-check every returned
98
+ // row against the requested scope, so a future regression in core's
99
+ // listTasks filter cannot leak a foreign or out-of-scope task. `total` is
100
+ // recomputed from the surviving rows — never report a count that includes
101
+ // a row we would not return.
102
+ const tasks = result.tasks.filter((t) => ownsScope(t, resolved.scopeValue));
103
+ return json({ tasks, total: tasks.length });
104
+ }
105
+ return null;
106
+ };
107
+ }
108
+ /**
109
+ * Wrap `manager.stream(options)` (an object-chunk ReadableStream) as an SSE
110
+ * Response. The stream is passed the validated filter so core scopes both its
111
+ * on-connect snapshot and its live events; a second exact-match guard in the
112
+ * transform drops any chunk whose runId/threadId is not the requested one, so a
113
+ * cross-tenant leak is impossible even if core's filter ever loosened
114
+ * (defense-in-depth, DL-014). `abortSignal` is the request's own, so a client
115
+ * disconnect closes the upstream subscription.
116
+ */
117
+ function streamResponse(manager, scoped, abortSignal) {
118
+ const { filter, scopeValue } = scoped;
119
+ const source = manager.stream({ ...filter, abortSignal });
120
+ const encoder = new TextEncoder();
121
+ const guarded = source.pipeThrough(new TransformStream({
122
+ transform(chunk, controller) {
123
+ // Same per-row scope guard the list route applies — one predicate so the
124
+ // two surfaces never drift (DL-014, defense-in-depth over core's filter).
125
+ const payload = typeof chunk.payload === 'object' &&
126
+ chunk.payload !== null &&
127
+ !Array.isArray(chunk.payload)
128
+ ? chunk.payload
129
+ : undefined;
130
+ if (!payload || !ownsScope(payload, scopeValue))
131
+ return;
132
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify(chunk)}\n\n`));
133
+ },
134
+ }));
135
+ return new Response(guarded, {
136
+ status: 200,
137
+ headers: {
138
+ 'content-type': 'text/event-stream',
139
+ 'cache-control': 'no-cache',
140
+ connection: 'keep-alive',
141
+ },
142
+ });
143
+ }
144
+ //# sourceMappingURL=routes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sourceRoot":"","sources":["../../src/background-tasks/routes.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,iFAAiF;AACjF,+EAA+E;AAC/E,sEAAsE;AACtE,yDAAyD;A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AC9B,MAAkD,EAClD,WAAwB;IAExB,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,MAAM,CAAC;IACtC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,EAAE,WAAW,EAAE,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,OAAO,GAAG,MAAM,CAAC,WAAW,CAChC,IAAI,eAAe,CAAsC;QACvD,SAAS,CAAC,KAAK,EAAE,UAAU;YACzB,yEAAyE;YACzE,0EAA0E;YAC1E,MAAM,OAAO,GACX,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ;gBACjC,KAAK,CAAC,OAAO,KAAK,IAAI;gBACtB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC;gBAC3B,CAAC,CAAE,KAAK,CAAC,OAAmC;gBAC5C,CAAC,CAAC,SAAS,CAAC;YAChB,IAAI,CAAC,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,UAAU,CAAC;gBAAE,OAAO;YACxD,UAAU,CAAC,OAAO,CAChB,OAAO,CAAC,MAAM,CAAC,SAAS,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC,CACrD,CAAC;QACJ,CAAC;KACF,CAAC,CACH,CAAC;IACF,OAAO,IAAI,QAAQ,CAAC,OAAO,EAAE;QAC3B,MAAM,EAAE,GAAG;QACX,OAAO,EAAE;YACP,cAAc,EAAE,mBAAmB;YACnC,eAAe,EAAE,UAAU;YAC3B,UAAU,EAAE,YAAY;SACzB;KACF,CAAC,CAAC;AACL,CAAC"}
@@ -1,4 +1,4 @@
1
- import { D1Store } from '@mastra/cloudflare-d1';
1
+ import { MastraCompositeStore, type MastraStorageDomains } from '@mastra/core/storage';
2
2
  import type { D1DatabaseBinding } from './cf-types.js';
3
3
  export interface D1StorageOptions {
4
4
  /** D1 binding from the Worker/DO environment. */
@@ -7,8 +7,17 @@ export interface D1StorageOptions {
7
7
  id?: string;
8
8
  /** Table name prefix (letters, numbers, underscores). */
9
9
  tablePrefix?: string;
10
+ /**
11
+ * Additional storage domains composed OVER the D1Store default (Track C:
12
+ * notifications + thread-state, which @mastra/cloudflare-d1 does not ship, so
13
+ * they are flowsafe-owned D1 impls). Injected rather than imported so this
14
+ * lower layer never depends on `signals/` (which imports do-runner) — build
15
+ * them with `createSignalStorageDomains()` and pass them here. Absent ⇒ the
16
+ * bare D1Store, byte-identical to before this seam existed.
17
+ */
18
+ domains?: MastraStorageDomains;
10
19
  }
11
- export declare function createD1Storage(options: D1StorageOptions): D1Store;
20
+ export declare function createD1Storage(options: D1StorageOptions): MastraCompositeStore;
12
21
  /**
13
22
  * Minimal structural D1 surface the purge uses — same posture as the
14
23
  * approval store: tests back it with node:sqlite, Workers pass env.DB.
@@ -56,6 +65,17 @@ export interface PurgeExpiredRunsOptions {
56
65
  /** Clock override for tests. */
57
66
  now?: () => number;
58
67
  }
68
+ /**
69
+ * The tables `purgeExpiredWorkflowRuns` deletes from under the run TTL — the
70
+ * production anchor the schema guard cross-checks every `run-ttl` retention
71
+ * declaration against (DL-003), the retention-leg analog of
72
+ * TENANT_RANGE_PURGE_TABLES for the offboarding leg. One table, because the run
73
+ * TTL rides a `run_id` range paired with artifact deletion and an app-owned
74
+ * index (its own block below), not the tenant-range map. The guard reads THIS,
75
+ * not a literal copied into the test, so a purge that changes what it targets
76
+ * and a guard that still blesses the old set cannot drift apart silently.
77
+ */
78
+ export declare const RUN_TTL_PURGE_TABLES: readonly string[];
59
79
  /**
60
80
  * Data-retention purge: deletes TERMINAL runs (success/failed/tripwire/
61
81
  * canceled/bailed/skipped) whose updatedAt is older than the TTL from
@@ -68,6 +88,246 @@ export interface PurgeExpiredRunsOptions {
68
88
  * DO alarm) stays with the caller. Returns the number of deleted rows.
69
89
  */
70
90
  export declare function purgeExpiredWorkflowRuns(db: SnapshotDatabase, options: PurgeExpiredRunsOptions): Promise<number>;
91
+ export interface PurgeExpiredThreadsOptions {
92
+ /** Threads untouched for longer than this are eligible, with their messages. */
93
+ ttlMs: number;
94
+ /** Must match createD1Storage's tablePrefix. */
95
+ tablePrefix?: string;
96
+ /**
97
+ * Threads processed per call. Default 100 — the shrinking eligible set is the
98
+ * cursor, so a first backlog drains across firings instead of blowing one
99
+ * invocation's budget (same batching rationale as purgeExpiredWorkflowRuns).
100
+ */
101
+ limit?: number;
102
+ /** Clock override for tests. */
103
+ now?: () => number;
104
+ }
105
+ export interface PurgeExpiredThreadsResult {
106
+ threads: number;
107
+ messages: number;
108
+ }
109
+ /**
110
+ * The tables `purgeExpiredThreads` deletes from under the thread TTL — the
111
+ * production anchor the schema guard cross-checks the `thread-ttl` retention
112
+ * declaration against, AND the target set a `cascade` child must appear in to be
113
+ * believed (DL-003). BOTH tables are here because the purge reaps a thread and
114
+ * its messages together: `mastra_threads` by its own `updatedAt`,
115
+ * `mastra_messages` by cascade (a message has no idleness signal of its own — see
116
+ * the purge doc). So the inventory's `mastra_messages: { retention: cascade with
117
+ * mastra_threads }` is only legal because `mastra_messages` is genuinely a delete
118
+ * target here; a cascade naming a parent whose purge never touches the child is
119
+ * the lie the guard now catches.
120
+ */
121
+ export declare const THREAD_TTL_PURGE_TABLES: readonly string[];
122
+ /**
123
+ * Thread-level retention (docs/agent-memory-tenancy.md item 7): deletes agent
124
+ * memory threads whose `updatedAt` is older than the TTL, each with its
125
+ * messages. The terminal-status shape `purgeExpiredWorkflowRuns` uses does not
126
+ * transfer — threads are not per-run and have no status, so there is nothing to
127
+ * prove "finished" about one. Time since last write IS the only signal a thread
128
+ * is done, which is why the TTL keys on `updatedAt` (the D1 memory domain stamps
129
+ * it on every saveThread, so an active conversation never ages out).
130
+ *
131
+ * MESSAGES BEFORE THREADS: a message carries a `createdAt` but no `updatedAt`,
132
+ * so there is no per-message IDLENESS signal — a message's lifetime is its
133
+ * thread's, and its rows are reachable only through it. Deleting a thread first
134
+ * would strand its messages beyond every later firing of this purge (only
135
+ * purgeTenant, at offboarding, still ranges over their salted `thread_id`).
136
+ *
137
+ * EVERY statement re-checks the CURRENT row rather than trusting the SELECT's id
138
+ * list, and that is load-bearing here in a way it is not for
139
+ * purgeExpiredWorkflowRuns (where terminal status is absorbing, so its re-check
140
+ * is belt-and-braces). "Idle" is precisely NOT absorbing — a thread can come
141
+ * back to life mid-purge — and the writer is not atomic either: the memory
142
+ * domain's saveMessages issues its message insert and its `UPDATE mastra_threads
143
+ * SET updatedAt` as two INDEPENDENT calls under one Promise.all, so a send's
144
+ * message can be visible while its thread still reads idle. That TORN state is
145
+ * what each guard answers:
146
+ *
147
+ * - The message DELETE re-reads the thread's current `updatedAt` (subquery) AND
148
+ * bounds itself to `createdAt < cutoff`. The subquery alone would sweep a
149
+ * just-arrived message into the same statement as the genuinely old ones —
150
+ * it keys on the THREAD's staleness, and the bump has not landed — silently
151
+ * destroying the message the user just sent. `createdAt` is the message's own
152
+ * evidence of recency, and the only guard that survives a torn write.
153
+ * - The thread DELETE re-checks `updatedAt < cutoff` AND fires only when `NOT
154
+ * EXISTS` any message for it. Sequence alone cannot carry "messages before
155
+ * threads": a message landing after the message DELETE leaves an idle-looking
156
+ * thread whose row would go out from under it. The NOT EXISTS makes the
157
+ * invariant — never delete a thread a message points at — a property of the
158
+ * statement rather than of timing.
159
+ *
160
+ * Together: a torn or concurrent send at ANY point in the sequence keeps both
161
+ * its message and its thread; the thread's next firing (by then bumped, or by
162
+ * then genuinely idle again) decides its fate on fresh evidence.
163
+ *
164
+ * Residuals, both accepted, neither reachable by a read path: (1) a send landing
165
+ * between the two DELETEs loses the already-expiring history while the thread
166
+ * and the new message survive — strictly better than the deletion that was
167
+ * milliseconds away. (2) A message inserted AFTER its thread's row is already
168
+ * gone is orphaned by the writer, not by this purge; D1 offers no cross-statement
169
+ * transaction through this seam to close it. An orphan is unreachable by recall
170
+ * (nothing lists a thread that does not exist), stays tenant-salted on its
171
+ * `thread_id`, and is reaped by purgeTenant at offboarding — a hygiene cost, not
172
+ * a leak.
173
+ *
174
+ * `mastra_resources` (working memory) is deliberately untouched: a resource is
175
+ * the OWNER's, shared across every thread they have, so one thread aging out
176
+ * says nothing about it. It is reaped at offboarding (purgeTenant).
177
+ *
178
+ * Missing tables read as zero (a deployment with no agent memory never created
179
+ * them). Scheduling stays with the caller — see createFlowsafeWorker's
180
+ * THREAD_RETENTION_DAYS duty.
181
+ */
182
+ export declare function purgeExpiredThreads(db: SnapshotDatabase, options: PurgeExpiredThreadsOptions): Promise<PurgeExpiredThreadsResult>;
183
+ /**
184
+ * The table `purgeExpiredBackgroundTasks` deletes from under the background-task
185
+ * TTL — the production anchor the schema guard cross-checks the
186
+ * `background-task-ttl` retention declaration against (DL-003), the Track B
187
+ * analog of RUN_TTL_PURGE_TABLES. One table: the TTL rides `completedAt` on
188
+ * `mastra_background_tasks` alone, no cascade.
189
+ */
190
+ export declare const BACKGROUND_TASK_TTL_PURGE_TABLES: readonly string[];
191
+ export interface PurgeExpiredBackgroundTasksOptions {
192
+ /**
193
+ * Completed task records untouched for longer than this expire. Default
194
+ * 3_600_000 (1h) — core `BackgroundTaskManager.cleanup`'s `completedTtlMs`.
195
+ */
196
+ completedTtlMs?: number;
197
+ /**
198
+ * Failed / cancelled / timed_out task records older than this expire. Default
199
+ * 86_400_000 (24h) — core's `failedTtlMs`. Kept longer than completed so a
200
+ * failure stays inspectable.
201
+ */
202
+ failedTtlMs?: number;
203
+ /** Must match createD1Storage's tablePrefix. */
204
+ tablePrefix?: string;
205
+ /** Clock override for tests. */
206
+ now?: () => number;
207
+ }
208
+ export interface PurgeExpiredBackgroundTasksResult {
209
+ /** Deleted 'completed' rows. */
210
+ completed: number;
211
+ /** Deleted 'failed' | 'cancelled' | 'timed_out' rows. */
212
+ failed: number;
213
+ }
214
+ /**
215
+ * Background-task TTL cleanup (DL-003 retention leg): deletes terminal task
216
+ * rows from `mastra_background_tasks` once their `completedAt` is older than the
217
+ * TTL, mirroring core `BackgroundTaskManager.cleanup()` at the storage layer so
218
+ * a purge cron can reap them WITHOUT a live manager — the same posture as
219
+ * purgeExpiredWorkflowRuns/purgeExpiredThreads (raw D1 binding, failure-isolated
220
+ * as a cron duty). Two windows, exactly as core: completed rows expire fast
221
+ * (default 1h), failed/cancelled/timed_out slowly (default 24h) so a failure
222
+ * stays inspectable.
223
+ *
224
+ * `completedAt` is stored as ISO-8601 TEXT (`toISOString()`), so lexicographic
225
+ * `<` against an ISO cutoff is a correct timestamp comparison — the same bet the
226
+ * other purges take. `completedAt IS NOT NULL` is load-bearing: a row without a
227
+ * completion stamp cannot be proven old, so it survives (fail safe). Live rows
228
+ * (pending / running / suspended) are never matched — deleting a suspended task
229
+ * mid-flight would strand its resume. A missing table reads as zero (background
230
+ * tasks may never have run). Scheduling stays with the caller.
231
+ */
232
+ export declare function purgeExpiredBackgroundTasks(db: SnapshotDatabase, options?: PurgeExpiredBackgroundTasksOptions): Promise<PurgeExpiredBackgroundTasksResult>;
233
+ /**
234
+ * The table `purgeExpiredNotifications` deletes from under the notification TTL
235
+ * — the anchor the schema guard cross-checks the `notification-ttl` retention
236
+ * declaration against (DL-003), the Track C analog of
237
+ * BACKGROUND_TASK_TTL_PURGE_TABLES.
238
+ */
239
+ export declare const NOTIFICATION_TTL_PURGE_TABLES: readonly string[];
240
+ export interface PurgeExpiredNotificationsOptions {
241
+ /**
242
+ * Resolved (delivered/seen/dismissed/archived/discarded) notifications whose
243
+ * `updatedAt` is older than this expire. PENDING rows are never touched — one
244
+ * may be waiting on a future `deliverAt`, and reaping it would drop a signal
245
+ * the model has not seen. No default: the caller (createFlowsafeWorker's cron)
246
+ * gates this on an opt-in retention window, since a durable inbox is meant to
247
+ * be readable until the host says otherwise.
248
+ */
249
+ ttlMs: number;
250
+ /** Must match createD1Storage's tablePrefix. */
251
+ tablePrefix?: string;
252
+ /** Clock override for tests. */
253
+ now?: () => number;
254
+ }
255
+ /**
256
+ * Notification TTL cleanup (DL-003 retention leg): deletes TERMINAL agent-inbox
257
+ * rows from `mastra_notifications` once their `updatedAt` is older than the TTL,
258
+ * at the storage layer so a cron reaps them without a live agent — the same
259
+ * posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
260
+ * `updatedAt` is ISO-8601 TEXT, so lexicographic `<` is a correct timestamp
261
+ * comparison. A missing table reads as zero (notifications may never have been
262
+ * sent). Scheduling stays with the caller.
263
+ */
264
+ export declare function purgeExpiredNotifications(db: SnapshotDatabase, options: PurgeExpiredNotificationsOptions): Promise<number>;
265
+ /**
266
+ * The table `purgeExpiredThreadState` deletes from under the thread-state TTL —
267
+ * the anchor the schema guard cross-checks the `thread-state-ttl` retention
268
+ * declaration against (DL-003).
269
+ */
270
+ export declare const THREAD_STATE_TTL_PURGE_TABLES: readonly string[];
271
+ export interface PurgeExpiredThreadStateOptions {
272
+ /**
273
+ * Thread-state rows (state-signal lanes + goals) whose `updatedAt` is older
274
+ * than this expire. An actively-updated goal or task lane bumps `updatedAt`
275
+ * on every write, so it never ages out; an abandoned thread's state does. No
276
+ * default (opt-in, like the notification and thread TTLs — durable state is
277
+ * kept until the host sets a window).
278
+ */
279
+ ttlMs: number;
280
+ /** Must match createD1Storage's tablePrefix. */
281
+ tablePrefix?: string;
282
+ /** Clock override for tests. */
283
+ now?: () => number;
284
+ }
285
+ /**
286
+ * Thread-state TTL cleanup (DL-003 retention leg): deletes thread-state rows
287
+ * from `mastra_thread_state` once their `updatedAt` is older than the TTL. Keys
288
+ * on `updatedAt` for the same reason `purgeExpiredThreads` does — thread state
289
+ * has no terminal status, so time-since-last-write is the only "done" signal.
290
+ * ISO-8601 TEXT encoding; missing table reads as zero; scheduling stays with the
291
+ * caller. Independent of the thread TTL (an orphan row is reaped here or at
292
+ * offboarding by purgeTenant), so it self-bounds without touching the delicate
293
+ * messages-before-threads ordering of purgeExpiredThreads.
294
+ */
295
+ export declare function purgeExpiredThreadState(db: SnapshotDatabase, options: PurgeExpiredThreadStateOptions): Promise<number>;
296
+ /**
297
+ * The table `purgeExpiredScheduleTriggers` deletes from under the trigger-row TTL
298
+ * — the anchor the schema guard cross-checks the `schedule-trigger-ttl` retention
299
+ * declaration against (DL-003), the Track D analog of THREAD_STATE_TTL_PURGE_TABLES.
300
+ * Only the trigger HISTORY expires; the schedule rows themselves are standing
301
+ * config (retention 'none', reaped at offboarding by purgeTenant).
302
+ */
303
+ export declare const SCHEDULE_TRIGGER_TTL_PURGE_TABLES: readonly string[];
304
+ export interface PurgeExpiredScheduleTriggersOptions {
305
+ /**
306
+ * Trigger-history rows whose `actualFireAt` is older than this expire. No
307
+ * default (opt-in, like the notification/thread-state TTLs): a schedule's fire
308
+ * history is inspectable until the host sets a window.
309
+ */
310
+ ttlMs: number;
311
+ /** Must match createD1Storage's tablePrefix. */
312
+ tablePrefix?: string;
313
+ /** Clock override for tests. */
314
+ now?: () => number;
315
+ }
316
+ /**
317
+ * Schedule-trigger TTL cleanup (DL-003 retention leg): deletes trigger-history
318
+ * rows from `mastra_schedule_triggers` once their `actualFireAt` is older than the
319
+ * TTL, at the storage layer so a cron reaps them without a live tick — the same
320
+ * posture as the other purges (raw D1 binding, failure-isolated as a cron duty).
321
+ *
322
+ * `actualFireAt` is stored as INTEGER ms-epoch (core types
323
+ * `ScheduleTrigger.actualFireAt` as `number`, unlike the ISO-TEXT timestamp
324
+ * columns the other domains use), so the comparison is a NUMERIC `<` against a
325
+ * numeric cutoff — a correct timestamp comparison over integers. A missing table
326
+ * reads as zero (schedules may never have fired). Scheduling stays with the
327
+ * caller. Deleting trigger history never touches a live schedule (its own row is
328
+ * in `mastra_schedules`), so there is no ordering constraint.
329
+ */
330
+ export declare function purgeExpiredScheduleTriggers(db: SnapshotDatabase, options: PurgeExpiredScheduleTriggersOptions): Promise<number>;
71
331
  /**
72
332
  * Additive, app-owned index for the tenant range predicate. It couples us to
73
333
  * Mastra's snapshot column name (`run_id`, snake_case — its timestamps are
@@ -98,9 +358,90 @@ export interface PurgeTenantResult {
98
358
  messages: number;
99
359
  /** Agent-memory rows: salted resource ids (working memory). */
100
360
  resources: number;
361
+ /** Track B: background-task rows, ranged over their INV-1 salted `run_id`. */
362
+ backgroundTasks: number;
363
+ /** Track C: agent-inbox rows, ranged over their salted `thread_id`. */
364
+ notifications: number;
365
+ /** Track C: thread-state rows (state lanes + goals), ranged over `thread_id`. */
366
+ threadState: number;
367
+ /** Track D: schedule rows, METADATA-filtered on their `metadata.tenantId`. */
368
+ schedules: number;
369
+ /** Track D: schedule-trigger rows, METADATA-filtered on their `metadata.tenantId`. */
370
+ scheduleTriggers: number;
101
371
  approvals: number;
372
+ /** Track E: signal-subscription rows, by the `tenant_id` column (the approvals leg). */
373
+ subscriptions: number;
102
374
  artifacts: number;
103
375
  }
376
+ /**
377
+ * The `PurgeTenantResult` field a range-purged table reports into. A track
378
+ * adopting a new `mastra_*` domain (notifications, thread-state, background
379
+ * tasks, schedules) adds its counter HERE, its row to
380
+ * TENANT_RANGE_PURGE_TABLES, and its field to PurgeTenantResult — all in the
381
+ * SAME change (DL-003). The union is what makes that mechanical rather than
382
+ * remembered: a counter with no result field fails the pin below, and a result
383
+ * field with no counter fails the `memory` initializer in purgeTenant.
384
+ */
385
+ export type TenantRangePurgeCounter = 'threads' | 'messages' | 'resources' | 'backgroundTasks' | 'notifications' | 'threadState';
386
+ /** One table purgeTenant reaps by the INV-3 `[tid_, tid\x60)` range predicate. */
387
+ export interface TenantRangePurgeTable {
388
+ /** The PurgeTenantResult field this table's deleted-row count lands in. */
389
+ counter: TenantRangePurgeCounter;
390
+ /** Unprefixed table name; purgeTenant applies the host's tablePrefix. */
391
+ table: string;
392
+ /**
393
+ * The tenant-salted column the range rides. Thread-keyed tables use their
394
+ * `thread_id` (a minted `${tenantId}_${uuid}`); row-keyed tables use their own
395
+ * salted `id`. Any column whose values are salted ids works — that is the
396
+ * whole reason the ids are salted at mint (docs/agent-memory-tenancy.md).
397
+ */
398
+ column: string;
399
+ }
400
+ /**
401
+ * The tenant-range purge inventory — EXTENSIBLE by construction (DL-003): each
402
+ * later track appends its adopted table here instead of editing purgeTenant's
403
+ * body, so adoption is one additive row plus the counter/result pair the types
404
+ * force alongside it. Ordering is not load-bearing (the deletes run
405
+ * concurrently; see purgeTenant).
406
+ *
407
+ * `mastra_workflow_snapshot` is deliberately absent: it rides the same range but
408
+ * over `run_id`, paired with artifact deletion and an app-owned index, so it
409
+ * keeps its own block. `mastra_background_tasks` (Track B) rides the range over
410
+ * its own `run_id` — the originating run's INV-1 salted id, always present on a
411
+ * task row — without artifacts or an app index, so it lives here. Tables no
412
+ * feature writes yet (`mastra_scorers`) are absent because nothing salts their
413
+ * ids yet — the schema-guard's inventory pin is what forces that decision when a
414
+ * track adopts one.
415
+ */
416
+ export declare const TENANT_RANGE_PURGE_TABLES: readonly TenantRangePurgeTable[];
417
+ /**
418
+ * The `PurgeTenantResult` field a METADATA-filtered table reports into. Track D's
419
+ * schedule rows key on slugified ids (`agent_<slug>`/`schedule_<slug>`), NOT
420
+ * tenant-salted ids, so the `[tid_, tid\x60)` range predicate cannot reach them —
421
+ * the tenant lives in `metadata.tenantId` (DL-013). This is the second
422
+ * offboarding KIND alongside the range counter: a track adopting a metadata-keyed
423
+ * domain adds its counter HERE, its row to TENANT_METADATA_PURGE_TABLES, and its
424
+ * PurgeTenantResult field, all in the SAME change (DL-003), pinned the same way.
425
+ */
426
+ export type TenantMetadataPurgeCounter = 'schedules' | 'scheduleTriggers';
427
+ /** One table purgeTenant reaps by `json_extract(metadata, '$.tenantId') = ?`. */
428
+ export interface TenantMetadataPurgeTable {
429
+ /** The PurgeTenantResult field this table's deleted-row count lands in. */
430
+ counter: TenantMetadataPurgeCounter;
431
+ /** Unprefixed table name; purgeTenant applies the host's tablePrefix. */
432
+ table: string;
433
+ }
434
+ /**
435
+ * The metadata-filtered purge inventory (DL-003) — the offboarding coverage for
436
+ * tables whose tenant is a JSON `metadata.tenantId` (stamped by the schedules
437
+ * facade at create + the tick on every trigger), not a salted id column. Both
438
+ * Track D tables are here: schedule rows and their trigger history. The DELETE is
439
+ * `WHERE json_extract(metadata, '$.tenantId') = ?` (the same SQLite json_extract
440
+ * the run-snapshot purge already uses on `snapshot`), so a NULL/absent metadata
441
+ * never matches — every row our facade/tick writes carries it, so this reaps them
442
+ * all. Ordering is not load-bearing (deletes run concurrently; see purgeTenant).
443
+ */
444
+ export declare const TENANT_METADATA_PURGE_TABLES: readonly TenantMetadataPurgeTable[];
104
445
  /**
105
446
  * Complete tenant offboarding: reaps EVERY tenant-keyed store — snapshot
106
447
  * rows of ANY status (a tenant's suspended-and-abandoned runs are never
@@ -1 +1 @@
1
- {"version":3,"file":"d1-storage.d.ts","sourceRoot":"","sources":["../../src/do-runner/d1-storage.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,OAAO,EAAE,MAAM,uBAAuB,CAAC;AAEhD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAGvD,MAAM,WAAW,gBAAgB;IAC/B,iDAAiD;IACjD,OAAO,EAAE,iBAAiB,CAAC;IAC3B,gDAAgD;IAChD,EAAE,CAAC,EAAE,MAAM,CAAC;IACZ,yDAAyD;IACzD,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,wBAAgB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAYlE;AAcD;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,iBAAiB,CAAC;CAC3C;AAED,MAAM,WAAW,iBAAiB;IAChC,IAAI,CAAC,GAAG,MAAM,EAAE,OAAO,EAAE,GAAG,iBAAiB,CAAC;IAC9C,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IACxB,GAAG,CAAC,CAAC,GAAG,OAAO,KAAK,OAAO,CAAC;QAAE,OAAO,EAAE,CAAC,EAAE,CAAA;KAAE,CAAC,CAAC;CAC/C;AAED,qFAAqF;AACrF,MAAM,WAAW,oBAAoB;IACnC,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,KA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