@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,196 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003) background-tasks storage seam.
3
+ //
4
+ // Cloudflare's adapter owns the D1 schemas. Flowsafe subclasses its workflow and
5
+ // background-task domains to add the guarantees core's global domains do not
6
+ // provide: serialized partial workflow updates inside one DO, tenant-filtered
7
+ // task access and recovery, and deletion of the unsalted internal workflow
8
+ // snapshot before its task row. `createBackgroundTaskD1Domains` composes the two
9
+ // subclasses as one inseparable execution configuration.
10
+ import { BackgroundTasksStorageD1, WorkflowsStorageD1, } from '@mastra/cloudflare-d1';
11
+ import { mergeWorkflowStepResult, } from '@mastra/core/storage';
12
+ import { assertMintableTenantId, tenantOwnsSaltedId, } from '../do-runner/index.js';
13
+ export { BACKGROUND_TASK_TTL_PURGE_TABLES, purgeExpiredBackgroundTasks, } from '../do-runner/index.js';
14
+ /**
15
+ * The D1 background-tasks storage domain the manager persists to, reached
16
+ * through the manager's OWN access path — `mastra.getStorage()` then
17
+ * `getStore('backgroundTasks')`, BOTH async, so this awaits (the CI-M-003-001
18
+ * "getStorage() is async — await it" note). Fail-closed with a clear message
19
+ * when a host wired a Mastra with no storage, or a storage adapter that does not
20
+ * implement the `backgroundTasks` domain, rather than surfacing core's terser
21
+ * "Background tasks storage is not available" only once the first task
22
+ * dispatches.
23
+ */
24
+ export async function backgroundTasksStore(mastra) {
25
+ const storage = mastra.getStorage();
26
+ if (!storage) {
27
+ throw new Error('background-tasks: the hosting Mastra has no storage configured — background tasks need a D1 (or equivalent) composite store');
28
+ }
29
+ const store = await storage.getStore('backgroundTasks');
30
+ if (!store) {
31
+ throw new Error("background-tasks: the storage adapter does not implement the 'backgroundTasks' domain (use @mastra/cloudflare-d1, which ships BackgroundTasksStorageD1)");
32
+ }
33
+ return store;
34
+ }
35
+ export const SERIALIZED_WORKFLOWS_D1 = Symbol('flowsafe.serializedWorkflowsD1');
36
+ /** Serialized D1 workflow updates for one single-tenant DO owner. */
37
+ export class DurableObjectWorkflowsStorageD1 extends WorkflowsStorageD1 {
38
+ [SERIALIZED_WORKFLOWS_D1] = true;
39
+ #tails = new Map();
40
+ supportsConcurrentUpdates() {
41
+ return true;
42
+ }
43
+ #locked(workflowName, runId, work) {
44
+ const key = `${workflowName}\0${runId}`;
45
+ const previous = this.#tails.get(key) ?? Promise.resolve();
46
+ const current = previous.then(work, work);
47
+ const settled = current.then(() => undefined, () => undefined);
48
+ this.#tails.set(key, settled);
49
+ return current.finally(() => {
50
+ if (this.#tails.get(key) === settled)
51
+ this.#tails.delete(key);
52
+ });
53
+ }
54
+ #persistUnlocked(args) {
55
+ return super.persistWorkflowSnapshot(args);
56
+ }
57
+ persistWorkflowSnapshot(args) {
58
+ return this.#locked(args.workflowName, args.runId, () => this.#persistUnlocked(args));
59
+ }
60
+ updateWorkflowResults(args) {
61
+ return this.#locked(args.workflowName, args.runId, async () => {
62
+ const run = await super.getWorkflowRunById({
63
+ workflowName: args.workflowName,
64
+ runId: args.runId,
65
+ });
66
+ if (!run)
67
+ return {};
68
+ const snapshot = typeof run.snapshot === 'string'
69
+ ? JSON.parse(run.snapshot)
70
+ : run.snapshot;
71
+ const context = mergeWorkflowStepResult({
72
+ snapshot,
73
+ stepId: args.stepId,
74
+ result: args.result,
75
+ requestContext: args.requestContext,
76
+ });
77
+ await this.#persistUnlocked({
78
+ workflowName: args.workflowName,
79
+ runId: args.runId,
80
+ resourceId: run.resourceId,
81
+ snapshot,
82
+ });
83
+ return context;
84
+ });
85
+ }
86
+ updateWorkflowState(args) {
87
+ return this.#locked(args.workflowName, args.runId, async () => {
88
+ const run = await super.getWorkflowRunById({
89
+ workflowName: args.workflowName,
90
+ runId: args.runId,
91
+ });
92
+ if (!run)
93
+ return undefined;
94
+ const current = typeof run.snapshot === 'string'
95
+ ? JSON.parse(run.snapshot)
96
+ : run.snapshot;
97
+ const snapshot = { ...current, ...args.opts };
98
+ await this.#persistUnlocked({
99
+ workflowName: args.workflowName,
100
+ runId: args.runId,
101
+ resourceId: run.resourceId,
102
+ snapshot,
103
+ });
104
+ return snapshot;
105
+ });
106
+ }
107
+ }
108
+ export const TENANT_SCOPED_BACKGROUND_TASKS_D1 = Symbol('flowsafe.tenantScopedBackgroundTasksD1');
109
+ /** Tenant-bound D1 task domain used by one background-task manager DO. */
110
+ export class TenantScopedBackgroundTasksStorageD1 extends BackgroundTasksStorageD1 {
111
+ [TENANT_SCOPED_BACKGROUND_TASKS_D1] = true;
112
+ tenantId;
113
+ #workflows;
114
+ constructor(config, options) {
115
+ super(config);
116
+ assertMintableTenantId(options.tenantId, 'backgroundTasks');
117
+ this.tenantId = options.tenantId;
118
+ this.#workflows = options.workflows;
119
+ }
120
+ #ownsRun(runId) {
121
+ return tenantOwnsSaltedId(this.tenantId, runId);
122
+ }
123
+ async createTask(task) {
124
+ if (!this.#ownsRun(task.runId)) {
125
+ throw new Error(`background-tasks: parent run '${task.runId}' is not owned by tenant '${this.tenantId}'`);
126
+ }
127
+ await super.createTask(task);
128
+ }
129
+ async getTask(taskId) {
130
+ const task = await super.getTask(taskId);
131
+ return task && this.#ownsRun(task.runId) ? task : null;
132
+ }
133
+ async updateTask(taskId, update) {
134
+ if (!(await this.getTask(taskId))) {
135
+ throw new Error(`background-tasks: task '${taskId}' is not owned by this tenant`);
136
+ }
137
+ await super.updateTask(taskId, update);
138
+ }
139
+ async listTasks(filter) {
140
+ if (filter.runId !== undefined && !this.#ownsRun(filter.runId)) {
141
+ return { tasks: [], total: 0 };
142
+ }
143
+ const { page, perPage, resourceId, ...unpaged } = filter;
144
+ const all = await super.listTasks(unpaged);
145
+ const owned = all.tasks.filter((task) => this.#ownsRun(task.runId) &&
146
+ (resourceId === undefined || task.resourceId === resourceId));
147
+ if (perPage === undefined)
148
+ return { tasks: owned, total: owned.length };
149
+ const start = (page ?? 0) * perPage;
150
+ return {
151
+ tasks: owned.slice(start, start + perPage),
152
+ total: owned.length,
153
+ };
154
+ }
155
+ async deleteTask(taskId) {
156
+ const task = await this.getTask(taskId);
157
+ if (!task)
158
+ return;
159
+ await this.#workflows.deleteWorkflowRunById({
160
+ workflowName: '__background-task',
161
+ runId: task.id,
162
+ });
163
+ await super.deleteTask(taskId);
164
+ }
165
+ async deleteTasks(filter) {
166
+ const { tasks } = await this.listTasks({
167
+ ...filter,
168
+ page: undefined,
169
+ perPage: undefined,
170
+ });
171
+ for (const task of tasks)
172
+ await this.deleteTask(task.id);
173
+ }
174
+ async getRunningCount() {
175
+ return (await this.listTasks({ status: 'running' })).total;
176
+ }
177
+ async getRunningCountByAgent(agentId) {
178
+ return (await this.listTasks({ status: 'running', agentId })).total;
179
+ }
180
+ }
181
+ /** Coupled workflow/task overrides for one tenant background-task DO. */
182
+ export function createBackgroundTaskD1Domains(options) {
183
+ const config = {
184
+ binding: options.binding,
185
+ ...(options.tablePrefix !== undefined
186
+ ? { tablePrefix: options.tablePrefix }
187
+ : {}),
188
+ };
189
+ const workflows = new DurableObjectWorkflowsStorageD1(config);
190
+ const backgroundTasks = new TenantScopedBackgroundTasksStorageD1(config, {
191
+ tenantId: options.tenantId,
192
+ workflows,
193
+ });
194
+ return { workflows, backgroundTasks };
195
+ }
196
+ //# sourceMappingURL=d1-storage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1-storage.js","sourceRoot":"","sources":["../../src/background-tasks/d1-storage.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,iDAAiD;AACjD,EAAE;AACF,iFAAiF;AACjF,6EAA6E;AAC7E,8EAA8E;AAC9E,2EAA2E;AAC3E,iFAAiF;AACjF,yDAAyD;AAGzD,OAAO,EACL,wBAAwB,EAExB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAQ/B,OAAO,EAGL,uBAAuB,GAExB,MAAM,sBAAsB,CAAC;AAG9B,OAAO,EACL,sBAAsB,EAEtB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAM/B,OAAO,EACL,gCAAgC,EAChC,2BAA2B,GAC5B,MAAM,uBAAuB,CAAC;AAE/B;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,MAAc;IAEd,MAAM,OAAO,GAAG,MAAM,CAAC,UAAU,EAAE,CAAC;IACpC,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,6HAA6H,CAC9H,CAAC;IACJ,CAAC;IACD,MAA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,IAAI,KAAK;YAAE,MAAM,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC3D,CAAC;IAEQ,KAAK,CAAC,eAAe;QAC5B,OAAO,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IAC7D,CAAC;IAEQ,KAAK,CAAC,sBAAsB,CAAC,OAAe;QACnD,OAAO,CAAC,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;IACtE,CAAC;CACF;AAQD,yEAAyE;AACzE,MAAM,UAAU,6BAA6B,CAC3C,OAA6C;IAE7C,MAAM,MAAM,GAAmB;QAC7B,OAAO,EAAE,OAAO,CAAC,OAAgC;QACjD,GAAG,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS;YACnC,CAAC,CAAC,EAAE,WAAW,EAAE,OAAO,CAAC,WAAW,EAAE;YACtC,CAAC,CAAC,EAAE,CAAC;KACR,CAAC;IACF,MAAM,SAAS,GAAG,IAAI,+BAA+B,CAAC,MAAM,CAAC,CAAC;IAC9D,MAAM,eAAe,GAAG,IAAI,oCAAoC,CAAC,MAAM,EAAE;QACvE,QAAQ,EAAE,OAAO,CAAC,QAAQ;QAC1B,SAAS;KACV,CAAC,CAAC;IACH,OAAO,EAAE,SAAS,EAAE,eAAe,EAAE,CAAC;AACxC,CAAC"}
@@ -0,0 +1,82 @@
1
+ import { BackgroundTaskManager, type BackgroundTaskManagerConfig, type ToolExecutor } from '@mastra/core/background-tasks';
2
+ import type { Mastra } from '@mastra/core/mastra';
3
+ import type { HostPubSub } from '../do-runner/index.js';
4
+ export interface BackgroundTaskHostOptions {
5
+ /**
6
+ * The DO's Mastra — must carry a storage adapter whose
7
+ * `getStore('backgroundTasks')` resolves (D1Store does). The manager reads
8
+ * every task through it.
9
+ */
10
+ mastra: Mastra;
11
+ /**
12
+ * The DO's ONE raw pubsub instance (DL-001, `createHostPubSub()`). Pass this
13
+ * same object to `new Mastra({ pubsub })`; Mastra 1.50 exposes a proxy from
14
+ * its public `pubsub` getter, so that getter is not the constructor identity.
15
+ * The manager both publishes dispatch events and subscribes the worker
16
+ * callback on the raw instance, and inside a DO one isolate serializes
17
+ * publisher and subscriber, so an in-process `EventEmitterPubSub` is exactly
18
+ * right (no cross-process bus). A host that streams lifecycle events to its
19
+ * hub also passes this same raw instance to `init()`.
20
+ */
21
+ pubsub: HostPubSub;
22
+ /**
23
+ * Static tool executors, keyed by tool name, RE-REGISTERED at every boot so a
24
+ * task recovered on a fresh DO instance (post-eviction) resolves its executor
25
+ * by name (DL-015). Tools are static — their executor closures are safe to
26
+ * rebuild deterministically at boot, unlike per-task closures which core
27
+ * documents are "never serialized".
28
+ */
29
+ executors: Record<string, ToolExecutor>;
30
+ /**
31
+ * Manager config (core `BackgroundTaskManagerConfig` minus `enabled`, which is
32
+ * forced on): concurrency, backpressure ('queue'|'reject'|'fallback-sync'),
33
+ * timeouts, retries, and `cleanup` TTLs. Numeric values are validated before
34
+ * constructing core's manager: concurrency/retry delays/TTLs/throttle are
35
+ * nonnegative, timeout/cleanup intervals are positive, and all integer
36
+ * quantities must be safe integers. Omitted => core defaults.
37
+ */
38
+ manager?: Omit<BackgroundTaskManagerConfig, 'enabled'>;
39
+ /**
40
+ * Enable real evented-worker execution for one tenant DO. Omit to preserve
41
+ * the persistence/recovery-only behavior.
42
+ */
43
+ execution?: {
44
+ tenantId: string;
45
+ };
46
+ }
47
+ /**
48
+ * A BackgroundTaskManager bound to a hosting DO's Mastra + pubsub, with the
49
+ * boot/alarm lifecycle that makes DO eviction survivable. The hosting DO owns
50
+ * alarm arming (it needs `ctx.storage.setAlarm`); this class owns the manager
51
+ * wiring, the recovery-firing `boot()`, and the alarm `cleanup()` duty. The raw
52
+ * manager is reachable as `.manager` for the tenant-bound routes to wrap — never
53
+ * expose it directly over HTTP (DL-014).
54
+ */
55
+ export declare class BackgroundTaskHost {
56
+ #private;
57
+ readonly manager: BackgroundTaskManager;
58
+ constructor(options: BackgroundTaskHostOptions);
59
+ /**
60
+ * DO-boot wiring (DL-015). Fail-fast if the backgroundTasks storage domain is
61
+ * missing, re-register the static executors, start execution-mode workflow
62
+ * workers, THEN call `init(pubsub)` — whose internal `recoverStaleTasks()`
63
+ * re-drives any task the evicted instance left mid-flight. Executors and the
64
+ * workflow subscriber both go in BEFORE recovery publishes work. A failed
65
+ * startup unwinds attempted components in reverse order. Memoized per
66
+ * instance: `init` is itself idempotent (initPromise), and `boot()` from both
67
+ * `fetch()` and `alarm()` must not double-register.
68
+ */
69
+ boot(): Promise<void>;
70
+ /**
71
+ * DO-alarm duty: ensure the DO is booted (a FRESH post-eviction instance
72
+ * recovers HERE, since the alarm is what woke it — see the recovery seam
73
+ * above), then run the manager's TTL cleanup. The hosting DO re-arms the alarm
74
+ * after this returns. Cleanup is core's own `cleanup()` — the belt to the
75
+ * storage-layer `purgeExpiredBackgroundTasks` cron braces (that one needs no
76
+ * live manager); running both is harmless (each only deletes rows past the
77
+ * TTL).
78
+ */
79
+ onAlarm(): Promise<void>;
80
+ shutdown(): Promise<void>;
81
+ }
82
+ //# sourceMappingURL=host.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.d.ts","sourceRoot":"","sources":["../../src/background-tasks/host.ts"],"names":[],"mappings":"AAwCA,OAAO,EACL,qBAAqB,EACrB,KAAK,2BAA2B,EAChC,KAAK,YAAY,EAClB,MAAM,+BAA+B,CAAC;AACvC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAaxD,MAAM,WAAW,yBAAyB;IACxC;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IACf;;;;;;;;;OASG;IACH,MAAM,EAAE,UAAU,CAAC;IACnB;;;;;;OAMG;IACH,SAAS,EAAE,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IACxC;;;;;;;OAOG;IACH,OAAO,CAAC,EAAE,IAAI,CAAC,2BAA2B,EAAE,SAAS,CAAC,CAAC;IACvD;;;OAGG;IACH,SAAS,CAAC,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CAClC;AAkFD;;;;;;;GAOG;AACH,qBAAa,kBAAkB;;IAC7B,QAAQ,CAAC,OAAO,EAAE,qBAAqB,CAAC;gBAY5B,OAAO,EAAE,yBAAyB;IAe9C;;;;;;;;;OASG;IACH,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IA8FrB;;;;;;;;OAQG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IA4CxB,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAWhC"}
@@ -0,0 +1,275 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003): host a Mastra BackgroundTaskManager on a Durable Object, and
3
+ // survive DO eviction BY CONSTRUCTION (DL-015).
4
+ //
5
+ // THE RECOVERY SEAM (spike B-S2, pinned against @mastra/core 1.50.0 dist —
6
+ // validation finding R-002). `recoverStaleTasks()` and `handleResume` are
7
+ // PRIVATE and `getStorage()` is async, so the alarm CANNOT call
8
+ // `recoverStaleTasks()` directly. But it does not need to: the PUBLIC async
9
+ // `manager.init(pubsub)` fires `recoverStaleTasks()` internally (manager.d.ts:21
10
+ // -> chunk .init -> `await this.recoverStaleTasks()`), guarded by its own
11
+ // initPromise so it runs once per manager INSTANCE. A DO evicted mid-task leaves
12
+ // its task row 'running'/'pending' in D1; when the DO is next instantiated (a
13
+ // FRESH manager), `boot()` re-registers the static tool executors, starts the
14
+ // workflow workers, and only then calls `init(pubsub)`. Init's recovery resets a
15
+ // stranded 'running' task (maxRetries > 0) to 'pending' and re-dispatches it;
16
+ // starting workers first guarantees that the workflow event published by that
17
+ // dispatch has a subscriber. Its workflow step resolves the executor by tool
18
+ // name via the re-registered static registry (the cross-process path core ships
19
+ // `registerStaticExecutor` for). The DO ALARM is what WAKES an evicted DO so
20
+ // this happens without waiting for a request. No private method is ever called;
21
+ // the seam is `registerStaticExecutor` + `startWorkers()` + `init(pubsub)`, all
22
+ // public.
23
+ //
24
+ // v1 policy (DL-005/P8): connectors are foreground-only, so approval-carrying
25
+ // tools never enter this suspend/resume topology. Background suspend/resume
26
+ // stays available for NON-gated tools (e.g. a long research tool awaiting an
27
+ // external webhook); such a task's resume mints no capability.
28
+ //
29
+ // Execution is opt-in. The host accepts it only with the serialized D1 workflow
30
+ // adapter and a task domain bound to the same tenant. One DO isolate owns that
31
+ // manager and both domains, so core's tenant-blind recovery sees only that
32
+ // tenant's rows. `boot()` then starts Mastra's public evented workers on the
33
+ // raw pubsub instance the caller passed to Mastra. Persistence-only hosts retain
34
+ // the earlier warning.
35
+ //
36
+ // Core still keys an internal `__background-task` workflow by the unsalted task
37
+ // ID. The tenant-scoped store, TTL purge, and offboarding paths therefore delete
38
+ // the internal snapshot before deleting the task row that supplies its tenant
39
+ // association.
40
+ import { BackgroundTaskManager, } from '@mastra/core/background-tasks';
41
+ import { finiteNonnegativeNumber, nonnegativeSafeInteger, positiveSafeInteger, } from '../numeric-config.js';
42
+ import { backgroundTasksStore, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, } from './d1-storage.js';
43
+ function validateManagerConfig(config) {
44
+ if (!config)
45
+ return;
46
+ if (config.globalConcurrency !== undefined) {
47
+ nonnegativeSafeInteger(config.globalConcurrency, 'backgroundTasks.manager.globalConcurrency');
48
+ }
49
+ if (config.perAgentConcurrency !== undefined) {
50
+ nonnegativeSafeInteger(config.perAgentConcurrency, 'backgroundTasks.manager.perAgentConcurrency');
51
+ }
52
+ if (config.defaultTimeoutMs !== undefined) {
53
+ positiveSafeInteger(config.defaultTimeoutMs, 'backgroundTasks.manager.defaultTimeoutMs');
54
+ }
55
+ if (config.progressThrottleMs !== undefined) {
56
+ nonnegativeSafeInteger(config.progressThrottleMs, 'backgroundTasks.manager.progressThrottleMs');
57
+ }
58
+ if (config.waitTimeoutMs !== undefined) {
59
+ positiveSafeInteger(config.waitTimeoutMs, 'backgroundTasks.manager.waitTimeoutMs');
60
+ }
61
+ const retries = config.defaultRetries;
62
+ if (retries?.maxRetries !== undefined) {
63
+ nonnegativeSafeInteger(retries.maxRetries, 'backgroundTasks.manager.defaultRetries.maxRetries');
64
+ }
65
+ if (retries?.retryDelayMs !== undefined) {
66
+ nonnegativeSafeInteger(retries.retryDelayMs, 'backgroundTasks.manager.defaultRetries.retryDelayMs');
67
+ }
68
+ if (retries?.maxRetryDelayMs !== undefined) {
69
+ nonnegativeSafeInteger(retries.maxRetryDelayMs, 'backgroundTasks.manager.defaultRetries.maxRetryDelayMs');
70
+ }
71
+ if (retries?.backoffMultiplier !== undefined) {
72
+ finiteNonnegativeNumber(retries.backoffMultiplier, 'backgroundTasks.manager.defaultRetries.backoffMultiplier');
73
+ }
74
+ const cleanup = config.cleanup;
75
+ if (cleanup?.completedTtlMs !== undefined) {
76
+ nonnegativeSafeInteger(cleanup.completedTtlMs, 'backgroundTasks.manager.cleanup.completedTtlMs');
77
+ }
78
+ if (cleanup?.failedTtlMs !== undefined) {
79
+ nonnegativeSafeInteger(cleanup.failedTtlMs, 'backgroundTasks.manager.cleanup.failedTtlMs');
80
+ }
81
+ if (cleanup?.cleanupIntervalMs !== undefined) {
82
+ positiveSafeInteger(cleanup.cleanupIntervalMs, 'backgroundTasks.manager.cleanup.cleanupIntervalMs');
83
+ }
84
+ }
85
+ /**
86
+ * A BackgroundTaskManager bound to a hosting DO's Mastra + pubsub, with the
87
+ * boot/alarm lifecycle that makes DO eviction survivable. The hosting DO owns
88
+ * alarm arming (it needs `ctx.storage.setAlarm`); this class owns the manager
89
+ * wiring, the recovery-firing `boot()`, and the alarm `cleanup()` duty. The raw
90
+ * manager is reachable as `.manager` for the tenant-bound routes to wrap — never
91
+ * expose it directly over HTTP (DL-014).
92
+ */
93
+ export class BackgroundTaskHost {
94
+ manager;
95
+ #mastra;
96
+ #pubsub;
97
+ #executors;
98
+ #execution;
99
+ #booted;
100
+ #bootSettled = false;
101
+ #managerNeedsShutdown = false;
102
+ #workersNeedStop = false;
103
+ #shutdownRequested = false;
104
+ #shutdown;
105
+ constructor(options) {
106
+ validateManagerConfig(options.manager);
107
+ this.#mastra = options.mastra;
108
+ this.#pubsub = options.pubsub;
109
+ this.#executors = options.executors;
110
+ this.#execution = options.execution;
111
+ this.manager = new BackgroundTaskManager({
112
+ enabled: true,
113
+ ...options.manager,
114
+ });
115
+ // Must precede init(): the manager reads its Mastra for storage, the
116
+ // internal background-task workflow registration, and id generation.
117
+ this.manager.__registerMastra(options.mastra);
118
+ }
119
+ /**
120
+ * DO-boot wiring (DL-015). Fail-fast if the backgroundTasks storage domain is
121
+ * missing, re-register the static executors, start execution-mode workflow
122
+ * workers, THEN call `init(pubsub)` — whose internal `recoverStaleTasks()`
123
+ * re-drives any task the evicted instance left mid-flight. Executors and the
124
+ * workflow subscriber both go in BEFORE recovery publishes work. A failed
125
+ * startup unwinds attempted components in reverse order. Memoized per
126
+ * instance: `init` is itself idempotent (initPromise), and `boot()` from both
127
+ * `fetch()` and `alarm()` must not double-register.
128
+ */
129
+ boot() {
130
+ if (this.#shutdownRequested) {
131
+ return Promise.reject(new Error('background-tasks: host is shutting down'));
132
+ }
133
+ if (!this.#booted) {
134
+ this.#booted = this.#doBoot().finally(() => {
135
+ this.#bootSettled = true;
136
+ });
137
+ }
138
+ return this.#booted;
139
+ }
140
+ async #doBoot() {
141
+ // Fail-fast with a clear message before any dispatch could surface core's
142
+ // terser error deep in a lifecycle callback.
143
+ const tasks = await backgroundTasksStore(this.#mastra);
144
+ // Execution mode validates every required ownership and concurrency seam.
145
+ if (this.#execution) {
146
+ const workflows = await this.#mastra.getStorage()?.getStore('workflows');
147
+ if (!workflows ||
148
+ workflows[SERIALIZED_WORKFLOWS_D1] !== true) {
149
+ throw new Error('background-tasks: execution requires DurableObjectWorkflowsStorageD1');
150
+ }
151
+ const tenantTasks = tasks;
152
+ if (tenantTasks[TENANT_SCOPED_BACKGROUND_TASKS_D1] !== true ||
153
+ tenantTasks.tenantId !== this.#execution.tenantId) {
154
+ throw new Error('background-tasks: execution requires a task store branded for the same tenant');
155
+ }
156
+ }
157
+ else {
158
+ await this.#warnIfBodiesCannotExecute();
159
+ }
160
+ for (const [toolName, executor] of Object.entries(this.#executors)) {
161
+ this.manager.registerStaticExecutor(toolName, executor);
162
+ }
163
+ try {
164
+ if (this.#execution) {
165
+ this.#workersNeedStop = true;
166
+ await this.#mastra.startWorkers();
167
+ }
168
+ this.#managerNeedsShutdown = true;
169
+ await this.manager.init(this.#pubsub);
170
+ }
171
+ catch (primary) {
172
+ const cleanupErrors = [];
173
+ if (this.#managerNeedsShutdown) {
174
+ try {
175
+ await this.manager.shutdown();
176
+ this.#managerNeedsShutdown = false;
177
+ }
178
+ catch (error) {
179
+ cleanupErrors.push(error);
180
+ }
181
+ }
182
+ if (this.#workersNeedStop) {
183
+ try {
184
+ await this.#mastra.stopWorkers();
185
+ this.#workersNeedStop = false;
186
+ }
187
+ catch (error) {
188
+ cleanupErrors.push(error);
189
+ }
190
+ }
191
+ if (cleanupErrors.length === 0)
192
+ throw primary;
193
+ throw new AggregateError([primary, ...cleanupErrors], 'background-tasks: boot failed and cleanup also failed', { cause: primary });
194
+ }
195
+ }
196
+ async #warnIfBodiesCannotExecute() {
197
+ const workflows = await this.#mastra.getStorage()?.getStore('workflows');
198
+ // Optional-chained: a store that predates the capability method reads as
199
+ // "cannot" (fail loud, never silently assume support).
200
+ const supports = workflows?.supportsConcurrentUpdates?.() ?? false;
201
+ if (!supports) {
202
+ console.warn('background-tasks: persistence-only mode cannot execute task bodies because the workflows domain does not support concurrent updates; configure createBackgroundTaskD1Domains and execution.tenantId on one single-tenant Durable Object to enable execution');
203
+ }
204
+ }
205
+ /**
206
+ * DO-alarm duty: ensure the DO is booted (a FRESH post-eviction instance
207
+ * recovers HERE, since the alarm is what woke it — see the recovery seam
208
+ * above), then run the manager's TTL cleanup. The hosting DO re-arms the alarm
209
+ * after this returns. Cleanup is core's own `cleanup()` — the belt to the
210
+ * storage-layer `purgeExpiredBackgroundTasks` cron braces (that one needs no
211
+ * live manager); running both is harmless (each only deletes rows past the
212
+ * TTL).
213
+ */
214
+ async onAlarm() {
215
+ await this.boot();
216
+ await this.manager.cleanup();
217
+ }
218
+ /**
219
+ * Graceful teardown. Stop the manager first: its shutdown flag rejects new
220
+ * enqueues synchronously before the workflow consumers disappear. Worker
221
+ * teardown is still attempted if manager teardown fails.
222
+ */
223
+ async #doShutdown() {
224
+ if (this.#booted && !this.#bootSettled) {
225
+ try {
226
+ await this.#booted;
227
+ }
228
+ catch {
229
+ // #doBoot already unwound every component it managed to stop. Any
230
+ // component whose cleanup failed remains flagged for the retry below.
231
+ }
232
+ }
233
+ const errors = [];
234
+ if (this.#managerNeedsShutdown) {
235
+ try {
236
+ await this.manager.shutdown();
237
+ this.#managerNeedsShutdown = false;
238
+ }
239
+ catch (error) {
240
+ errors.push(error);
241
+ }
242
+ }
243
+ if (this.#workersNeedStop) {
244
+ try {
245
+ await this.#mastra.stopWorkers();
246
+ this.#workersNeedStop = false;
247
+ }
248
+ catch (error) {
249
+ errors.push(error);
250
+ }
251
+ }
252
+ if (errors.length === 1)
253
+ throw errors[0];
254
+ if (errors.length > 1) {
255
+ throw new AggregateError(errors, 'background-tasks: shutdown failed', {
256
+ cause: errors[0],
257
+ });
258
+ }
259
+ }
260
+ async shutdown() {
261
+ this.#shutdownRequested = true;
262
+ if (this.#shutdown)
263
+ return this.#shutdown;
264
+ const pending = this.#doShutdown();
265
+ this.#shutdown = pending;
266
+ try {
267
+ await pending;
268
+ }
269
+ finally {
270
+ if (this.#shutdown === pending)
271
+ this.#shutdown = undefined;
272
+ }
273
+ }
274
+ }
275
+ //# sourceMappingURL=host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"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C;QACzC,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,MAAM,IAAI,cAAc,CAAC,MAAM,EAAE,mCAAmC,EAAE;gBACpE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;aACjB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,KAAK,CAAC,QAAQ;QACZ,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC;QAC/B,IAAI,IAAI,CAAC,SAAS;YAAE,OAAO,IAAI,CAAC,SAAS,CAAC;QAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACnC,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC;QACzB,IAAI,CAAC;YACH,MAAM,OAAO,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,IAAI,IAAI,CAAC,SAAS,KAAK,OAAO;gBAAE,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC7D,CAAC;IACH,CAAC;CACF"}
@@ -0,0 +1,7 @@
1
+ export type { CreateBackgroundTaskD1DomainsOptions, PurgeExpiredBackgroundTasksOptions, PurgeExpiredBackgroundTasksResult, } from './d1-storage.js';
2
+ export { BACKGROUND_TASK_TTL_PURGE_TABLES, backgroundTasksStore, createBackgroundTaskD1Domains, DurableObjectWorkflowsStorageD1, purgeExpiredBackgroundTasks, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, TenantScopedBackgroundTasksStorageD1, } from './d1-storage.js';
3
+ export type { BackgroundTaskHostOptions } from './host.js';
4
+ export { BackgroundTaskHost } from './host.js';
5
+ export type { BackgroundTaskRouter, BackgroundTaskRoutesOptions, } from './routes.js';
6
+ export { createBackgroundTaskRoutes } from './routes.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/background-tasks/index.ts"],"names":[],"mappings":"AAOA,YAAY,EACV,oCAAoC,EACpC,kCAAkC,EAClC,iCAAiC,GAClC,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,gCAAgC,EAChC,oBAAoB,EACpB,6BAA6B,EAC7B,+BAA+B,EAC/B,2BAA2B,EAC3B,uBAAuB,EACvB,iCAAiC,EACjC,oCAAoC,GACrC,MAAM,iBAAiB,CAAC;AACzB,YAAY,EAAE,yBAAyB,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAC/C,YAAY,EACV,oBAAoB,EACpB,2BAA2B,GAC5B,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,10 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Track B (M-003) — background tasks. Subpath-only (`@proofoftech/flowsafe/
3
+ // background-tasks`), like agent-runner: host-side wiring a consumer opts into,
4
+ // not part of the root barrel. The tenant-range purge coverage + the completedAt
5
+ // TTL cleanup live in do-runner (coupled there to the schema guard) and are
6
+ // re-exported here for a single import surface.
7
+ export { BACKGROUND_TASK_TTL_PURGE_TABLES, backgroundTasksStore, createBackgroundTaskD1Domains, DurableObjectWorkflowsStorageD1, purgeExpiredBackgroundTasks, SERIALIZED_WORKFLOWS_D1, TENANT_SCOPED_BACKGROUND_TASKS_D1, TenantScopedBackgroundTasksStorageD1, } from './d1-storage.js';
8
+ export { BackgroundTaskHost } from './host.js';
9
+ export { createBackgroundTaskRoutes } from './routes.js';
10
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/background-tasks/index.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,4EAA4E;AAC5E,gFAAgF;AAChF,iFAAiF;AACjF,4EAA4E;AAC5E,gDAAgD;AAOhD,OAAO,EACL,gCAAgC,EAChC,oBAAoB,EACpB,6BAA6B,EAC7B,+BAA+B,EAC/B,2BAA2B,EAC3B,uBAAuB,EACvB,iCAAiC,EACjC,oCAAoC,GACrC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,kBAAkB,EAAE,MAAM,WAAW,CAAC;AAK/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,aAAa,CAAC"}
@@ -0,0 +1,15 @@
1
+ import type { BackgroundTaskManager } from '@mastra/core/background-tasks';
2
+ export interface BackgroundTaskRoutesOptions {
3
+ /** The manager to read through — WRAPPED, never exposed over the wire. */
4
+ manager: BackgroundTaskManager;
5
+ /** Route prefix. Default '/background-tasks'. */
6
+ basePath?: string;
7
+ }
8
+ /**
9
+ * A router `(request, tenantId) => Response | null`. `null` means the path is
10
+ * not one of ours (the DO falls through). `tenantId` is the DO's own asserted
11
+ * tenant — never read from the request.
12
+ */
13
+ export type BackgroundTaskRouter = (request: Request, tenantId: string) => Promise<Response | null>;
14
+ export declare function createBackgroundTaskRoutes(options: BackgroundTaskRoutesOptions): BackgroundTaskRouter;
15
+ //# sourceMappingURL=routes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.d.ts","sourceRoot":"","sources":["../../src/background-tasks/routes.ts"],"names":[],"mappings":"AAmBA,OAAO,KAAK,EACV,qBAAqB,EAEtB,MAAM,+BAA+B,CAAC;AAKvC,MAAM,WAAW,2BAA2B;IAC1C,0EAA0E;IAC1E,OAAO,EAAE,qBAAqB,CAAC;IAC/B,iDAAiD;IACjD,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,OAAO,EAChB,QAAQ,EAAE,MAAM,KACb,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAsD9B,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,2BAA2B,GACnC,oBAAoB,CAkDtB"}