@proofoftech/flowsafe 0.1.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 (204) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +202 -0
  3. package/README.md +273 -0
  4. package/dist/approval-api/contract.d.ts +45 -0
  5. package/dist/approval-api/contract.d.ts.map +1 -0
  6. package/dist/approval-api/contract.js +37 -0
  7. package/dist/approval-api/contract.js.map +1 -0
  8. package/dist/approval-api/d1-store.d.ts +52 -0
  9. package/dist/approval-api/d1-store.d.ts.map +1 -0
  10. package/dist/approval-api/d1-store.js +468 -0
  11. package/dist/approval-api/d1-store.js.map +1 -0
  12. package/dist/approval-api/grants.d.ts +52 -0
  13. package/dist/approval-api/grants.d.ts.map +1 -0
  14. package/dist/approval-api/grants.js +200 -0
  15. package/dist/approval-api/grants.js.map +1 -0
  16. package/dist/approval-api/index.d.ts +21 -0
  17. package/dist/approval-api/index.d.ts.map +1 -0
  18. package/dist/approval-api/index.js +18 -0
  19. package/dist/approval-api/index.js.map +1 -0
  20. package/dist/approval-api/retention.d.ts +32 -0
  21. package/dist/approval-api/retention.d.ts.map +1 -0
  22. package/dist/approval-api/retention.js +81 -0
  23. package/dist/approval-api/retention.js.map +1 -0
  24. package/dist/approval-api/router.d.ts +51 -0
  25. package/dist/approval-api/router.d.ts.map +1 -0
  26. package/dist/approval-api/router.js +245 -0
  27. package/dist/approval-api/router.js.map +1 -0
  28. package/dist/approval-api/service.d.ts +134 -0
  29. package/dist/approval-api/service.d.ts.map +1 -0
  30. package/dist/approval-api/service.js +537 -0
  31. package/dist/approval-api/service.js.map +1 -0
  32. package/dist/approval-api/store.d.ts +126 -0
  33. package/dist/approval-api/store.d.ts.map +1 -0
  34. package/dist/approval-api/store.js +189 -0
  35. package/dist/approval-api/store.js.map +1 -0
  36. package/dist/approval-api/tenant-brand.d.ts +35 -0
  37. package/dist/approval-api/tenant-brand.d.ts.map +1 -0
  38. package/dist/approval-api/tenant-brand.js +18 -0
  39. package/dist/approval-api/tenant-brand.js.map +1 -0
  40. package/dist/approval-api/tenant-context.d.ts +44 -0
  41. package/dist/approval-api/tenant-context.d.ts.map +1 -0
  42. package/dist/approval-api/tenant-context.js +49 -0
  43. package/dist/approval-api/tenant-context.js.map +1 -0
  44. package/dist/approval-api/tenant-store.d.ts +36 -0
  45. package/dist/approval-api/tenant-store.d.ts.map +1 -0
  46. package/dist/approval-api/tenant-store.js +122 -0
  47. package/dist/approval-api/tenant-store.js.map +1 -0
  48. package/dist/approval-api/types.d.ts +247 -0
  49. package/dist/approval-api/types.d.ts.map +1 -0
  50. package/dist/approval-api/types.js +157 -0
  51. package/dist/approval-api/types.js.map +1 -0
  52. package/dist/approval-ui/App.d.ts +11 -0
  53. package/dist/approval-ui/App.d.ts.map +1 -0
  54. package/dist/approval-ui/App.js +15 -0
  55. package/dist/approval-ui/App.js.map +1 -0
  56. package/dist/approval-ui/DetailView.d.ts +13 -0
  57. package/dist/approval-ui/DetailView.d.ts.map +1 -0
  58. package/dist/approval-ui/DetailView.js +20 -0
  59. package/dist/approval-ui/DetailView.js.map +1 -0
  60. package/dist/approval-ui/MetricsView.d.ts +7 -0
  61. package/dist/approval-ui/MetricsView.d.ts.map +1 -0
  62. package/dist/approval-ui/MetricsView.js +22 -0
  63. package/dist/approval-ui/MetricsView.js.map +1 -0
  64. package/dist/approval-ui/QueueView.d.ts +11 -0
  65. package/dist/approval-ui/QueueView.d.ts.map +1 -0
  66. package/dist/approval-ui/QueueView.js +59 -0
  67. package/dist/approval-ui/QueueView.js.map +1 -0
  68. package/dist/approval-ui/client.d.ts +34 -0
  69. package/dist/approval-ui/client.d.ts.map +1 -0
  70. package/dist/approval-ui/client.js +103 -0
  71. package/dist/approval-ui/client.js.map +1 -0
  72. package/dist/approval-ui/components.d.ts +125 -0
  73. package/dist/approval-ui/components.d.ts.map +1 -0
  74. package/dist/approval-ui/components.js +54 -0
  75. package/dist/approval-ui/components.js.map +1 -0
  76. package/dist/approval-ui/index.d.ts +21 -0
  77. package/dist/approval-ui/index.d.ts.map +1 -0
  78. package/dist/approval-ui/index.js +21 -0
  79. package/dist/approval-ui/index.js.map +1 -0
  80. package/dist/approval-ui/mount.d.ts +23 -0
  81. package/dist/approval-ui/mount.d.ts.map +1 -0
  82. package/dist/approval-ui/mount.js +17 -0
  83. package/dist/approval-ui/mount.js.map +1 -0
  84. package/dist/approval-ui/tips.d.ts +32 -0
  85. package/dist/approval-ui/tips.d.ts.map +1 -0
  86. package/dist/approval-ui/tips.js +32 -0
  87. package/dist/approval-ui/tips.js.map +1 -0
  88. package/dist/approval-ui/use-approval-dashboard.d.ts +70 -0
  89. package/dist/approval-ui/use-approval-dashboard.d.ts.map +1 -0
  90. package/dist/approval-ui/use-approval-dashboard.js +148 -0
  91. package/dist/approval-ui/use-approval-dashboard.js.map +1 -0
  92. package/dist/approval-ui/view-model.d.ts +24 -0
  93. package/dist/approval-ui/view-model.d.ts.map +1 -0
  94. package/dist/approval-ui/view-model.js +62 -0
  95. package/dist/approval-ui/view-model.js.map +1 -0
  96. package/dist/artifacts/index.d.ts +123 -0
  97. package/dist/artifacts/index.d.ts.map +1 -0
  98. package/dist/artifacts/index.js +223 -0
  99. package/dist/artifacts/index.js.map +1 -0
  100. package/dist/audit-export/index.d.ts +71 -0
  101. package/dist/audit-export/index.d.ts.map +1 -0
  102. package/dist/audit-export/index.js +124 -0
  103. package/dist/audit-export/index.js.map +1 -0
  104. package/dist/do-runner/breakwater-keys.d.ts +23 -0
  105. package/dist/do-runner/breakwater-keys.d.ts.map +1 -0
  106. package/dist/do-runner/breakwater-keys.js +38 -0
  107. package/dist/do-runner/breakwater-keys.js.map +1 -0
  108. package/dist/do-runner/cf-types.d.ts +26 -0
  109. package/dist/do-runner/cf-types.d.ts.map +1 -0
  110. package/dist/do-runner/cf-types.js +13 -0
  111. package/dist/do-runner/cf-types.js.map +1 -0
  112. package/dist/do-runner/d1-storage.d.ts +128 -0
  113. package/dist/do-runner/d1-storage.d.ts.map +1 -0
  114. package/dist/do-runner/d1-storage.js +287 -0
  115. package/dist/do-runner/d1-storage.js.map +1 -0
  116. package/dist/do-runner/durable-object.d.ts +28 -0
  117. package/dist/do-runner/durable-object.d.ts.map +1 -0
  118. package/dist/do-runner/durable-object.js +164 -0
  119. package/dist/do-runner/durable-object.js.map +1 -0
  120. package/dist/do-runner/index.d.ts +12 -0
  121. package/dist/do-runner/index.d.ts.map +1 -0
  122. package/dist/do-runner/index.js +11 -0
  123. package/dist/do-runner/index.js.map +1 -0
  124. package/dist/do-runner/init.d.ts +38 -0
  125. package/dist/do-runner/init.d.ts.map +1 -0
  126. package/dist/do-runner/init.js +45 -0
  127. package/dist/do-runner/init.js.map +1 -0
  128. package/dist/do-runner/path-safe-id.d.ts +19 -0
  129. package/dist/do-runner/path-safe-id.d.ts.map +1 -0
  130. package/dist/do-runner/path-safe-id.js +70 -0
  131. package/dist/do-runner/path-safe-id.js.map +1 -0
  132. package/dist/do-runner/resume-ledger.d.ts +48 -0
  133. package/dist/do-runner/resume-ledger.d.ts.map +1 -0
  134. package/dist/do-runner/resume-ledger.js +59 -0
  135. package/dist/do-runner/resume-ledger.js.map +1 -0
  136. package/dist/do-runner/runtime.d.ts +161 -0
  137. package/dist/do-runner/runtime.d.ts.map +1 -0
  138. package/dist/do-runner/runtime.js +509 -0
  139. package/dist/do-runner/runtime.js.map +1 -0
  140. package/dist/host-kit/approval-bridge.d.ts +109 -0
  141. package/dist/host-kit/approval-bridge.d.ts.map +1 -0
  142. package/dist/host-kit/approval-bridge.js +262 -0
  143. package/dist/host-kit/approval-bridge.js.map +1 -0
  144. package/dist/host-kit/bearer-auth.d.ts +19 -0
  145. package/dist/host-kit/bearer-auth.d.ts.map +1 -0
  146. package/dist/host-kit/bearer-auth.js +67 -0
  147. package/dist/host-kit/bearer-auth.js.map +1 -0
  148. package/dist/host-kit/do-response.d.ts +13 -0
  149. package/dist/host-kit/do-response.d.ts.map +1 -0
  150. package/dist/host-kit/do-response.js +24 -0
  151. package/dist/host-kit/do-response.js.map +1 -0
  152. package/dist/host-kit/do-run-topology.d.ts +32 -0
  153. package/dist/host-kit/do-run-topology.d.ts.map +1 -0
  154. package/dist/host-kit/do-run-topology.js +39 -0
  155. package/dist/host-kit/do-run-topology.js.map +1 -0
  156. package/dist/host-kit/env-vars.d.ts +26 -0
  157. package/dist/host-kit/env-vars.d.ts.map +1 -0
  158. package/dist/host-kit/env-vars.js +48 -0
  159. package/dist/host-kit/env-vars.js.map +1 -0
  160. package/dist/host-kit/host-approval-service.d.ts +125 -0
  161. package/dist/host-kit/host-approval-service.d.ts.map +1 -0
  162. package/dist/host-kit/host-approval-service.js +187 -0
  163. package/dist/host-kit/host-approval-service.js.map +1 -0
  164. package/dist/host-kit/index.d.ts +18 -0
  165. package/dist/host-kit/index.d.ts.map +1 -0
  166. package/dist/host-kit/index.js +34 -0
  167. package/dist/host-kit/index.js.map +1 -0
  168. package/dist/host-kit/module.d.ts +34 -0
  169. package/dist/host-kit/module.d.ts.map +1 -0
  170. package/dist/host-kit/module.js +17 -0
  171. package/dist/host-kit/module.js.map +1 -0
  172. package/dist/host-kit/registration.d.ts +11 -0
  173. package/dist/host-kit/registration.d.ts.map +1 -0
  174. package/dist/host-kit/registration.js +21 -0
  175. package/dist/host-kit/registration.js.map +1 -0
  176. package/dist/host-kit/run-route-error.d.ts +11 -0
  177. package/dist/host-kit/run-route-error.d.ts.map +1 -0
  178. package/dist/host-kit/run-route-error.js +22 -0
  179. package/dist/host-kit/run-route-error.js.map +1 -0
  180. package/dist/host-kit/run-router.d.ts +60 -0
  181. package/dist/host-kit/run-router.d.ts.map +1 -0
  182. package/dist/host-kit/run-router.js +212 -0
  183. package/dist/host-kit/run-router.js.map +1 -0
  184. package/dist/host-kit/subdomain-check.d.ts +23 -0
  185. package/dist/host-kit/subdomain-check.d.ts.map +1 -0
  186. package/dist/host-kit/subdomain-check.js +60 -0
  187. package/dist/host-kit/subdomain-check.js.map +1 -0
  188. package/dist/host-kit/tenant-registry.d.ts +51 -0
  189. package/dist/host-kit/tenant-registry.d.ts.map +1 -0
  190. package/dist/host-kit/tenant-registry.js +87 -0
  191. package/dist/host-kit/tenant-registry.js.map +1 -0
  192. package/dist/host-kit/verifier.d.ts +63 -0
  193. package/dist/host-kit/verifier.d.ts.map +1 -0
  194. package/dist/host-kit/verifier.js +191 -0
  195. package/dist/host-kit/verifier.js.map +1 -0
  196. package/dist/host-kit/workflow-meta.d.ts +25 -0
  197. package/dist/host-kit/workflow-meta.d.ts.map +1 -0
  198. package/dist/host-kit/workflow-meta.js +12 -0
  199. package/dist/host-kit/workflow-meta.js.map +1 -0
  200. package/dist/index.d.ts +9 -0
  201. package/dist/index.d.ts.map +1 -0
  202. package/dist/index.js +25 -0
  203. package/dist/index.js.map +1 -0
  204. package/package.json +95 -0
@@ -0,0 +1,509 @@
1
+ // RunnerRuntime hosts Mastra workflow execution against injected storage.
2
+ // It is deliberately environment-free: the Durable Object shell feeds it
3
+ // D1-backed storage; tests feed it InMemoryStore. Durability comes from
4
+ // Mastra's own snapshot persistence — createRun() writes the initial
5
+ // snapshot, the engine persists after each step boundary, and resume()
6
+ // loads the snapshot — so a run started in one process resumes in any
7
+ // other process that shares the same database. Persistence only happens
8
+ // for workflows registered on a Mastra instance that has storage (core
9
+ // silently skips it otherwise), which is why this class owns the Mastra
10
+ // instance instead of running standalone workflows.
11
+ //
12
+ // Concurrency: start/resume are serialized per run — keyed by the run's
13
+ // full identity (workflowId + runId) — via an in-instance FIFO lock.
14
+ // Without it, two concurrent resumes both pass the 'suspended' pre-check
15
+ // and the gated step's side effects execute twice — the exact failure an
16
+ // approval product must not have. The lock is per runtime instance;
17
+ // cross-instance serialization comes from routing one DO instance per run
18
+ // (see durable-object.ts).
19
+ import { Mastra } from '@mastra/core/mastra';
20
+ import { RequestContext } from '@mastra/core/request-context';
21
+ import { BREAKWATER_ISOLATION_SCOPE_KEY, BREAKWATER_WORKFLOW_SCOPE_KEY, } from './breakwater-keys.js';
22
+ import { PATH_SAFE_ID_PATTERN, tenantOfRunId } from './path-safe-id.js';
23
+ import { InMemoryResumeLedger } from './resume-ledger.js';
24
+ export class UnknownWorkflowError extends Error {
25
+ constructor(workflowId) {
26
+ super(`unknown workflow '${workflowId}'`);
27
+ this.name = 'UnknownWorkflowError';
28
+ }
29
+ }
30
+ export class UnknownRunError extends Error {
31
+ constructor(workflowId, runId) {
32
+ super(`no run '${runId}' found for workflow '${workflowId}'`);
33
+ this.name = 'UnknownRunError';
34
+ }
35
+ }
36
+ export class RunNotSuspendedError extends Error {
37
+ constructor(workflowId, runId, status) {
38
+ super(`run '${runId}' of workflow '${workflowId}' is '${status}', not 'suspended'`);
39
+ this.name = 'RunNotSuspendedError';
40
+ }
41
+ }
42
+ export class RunAlreadyExistsError extends Error {
43
+ constructor(workflowId, runId, status) {
44
+ super(`run '${runId}' of workflow '${workflowId}' already exists (status '${status}')`);
45
+ this.name = 'RunAlreadyExistsError';
46
+ }
47
+ }
48
+ /** A request the caller can fix: bad input/resume data or step selection. */
49
+ export class InvalidRunRequestError extends Error {
50
+ constructor(message) {
51
+ super(message);
52
+ this.name = 'InvalidRunRequestError';
53
+ }
54
+ }
55
+ // PATH_SAFE_ID_PATTERN validates runId and workflowId (full rationale lives on
56
+ // the leaf module). runId is validated at start() (client input →
57
+ // InvalidRunRequestError); workflowId is developer-controlled and validated at
58
+ // register() (programming error → plain Error).
59
+ // Core surfaces input/resume-schema violations and wrong-step selections as
60
+ // untyped Errors. Message matching is brittle, so it is scoped to choosing
61
+ // the HTTP-facing error class only; anything unmatched propagates unchanged
62
+ // (a 500 at the DO boundary, same as before classification existed).
63
+ const CLIENT_ERROR_MARKERS = [
64
+ 'Invalid input',
65
+ 'Invalid resume data',
66
+ 'was not suspended',
67
+ 'No snapshot found',
68
+ ];
69
+ function asClientError(error) {
70
+ if (!(error instanceof Error))
71
+ return undefined;
72
+ return CLIENT_ERROR_MARKERS.some((marker) => error.message.includes(marker))
73
+ ? new InvalidRunRequestError(error.message)
74
+ : undefined;
75
+ }
76
+ // Failed runs carry the step's thrown error as an Error instance, a string,
77
+ // or — once it crossed an engine/persistence boundary — a serialized
78
+ // { name, message, stack } object; String() on the last reads
79
+ // '[object Object]', so extract the message wherever it lives.
80
+ function errorText(error) {
81
+ if (error instanceof Error)
82
+ return error.message;
83
+ if (typeof error === 'string')
84
+ return error;
85
+ if (error !== null &&
86
+ typeof error === 'object' &&
87
+ 'message' in error &&
88
+ typeof error.message === 'string') {
89
+ return error.message;
90
+ }
91
+ return String(error);
92
+ }
93
+ function summarize(runId, result, counts) {
94
+ switch (result.status) {
95
+ case 'success':
96
+ return { runId, status: result.status, result: result.result };
97
+ case 'failed':
98
+ return {
99
+ runId,
100
+ status: result.status,
101
+ error: errorText(result.error),
102
+ };
103
+ case 'suspended': {
104
+ const summary = {
105
+ runId,
106
+ status: result.status,
107
+ suspended: result.suspended,
108
+ suspendPayload: result.suspendPayload,
109
+ };
110
+ const suspendedKeys = result.suspended.map((path) => path.join('.'));
111
+ const suspendedAt = byStep(suspendedKeys, (key) => suspendedAtOf(result.steps, key));
112
+ if (suspendedAt !== undefined)
113
+ summary.suspendedAt = suspendedAt;
114
+ const resumedAt = byStep(suspendedKeys, (key) => resumedAtOf(result.steps, key));
115
+ if (resumedAt !== undefined)
116
+ summary.resumedAt = resumedAt;
117
+ // resumeCount is runtime-owned (the ledger), NOT read from the snapshot.
118
+ const resumeCount = byStep(suspendedKeys, (key) => counts?.get(key));
119
+ if (resumeCount !== undefined)
120
+ summary.resumeCount = resumeCount;
121
+ return summary;
122
+ }
123
+ case 'tripwire':
124
+ return { runId, status: result.status, error: result.tripwire.reason };
125
+ default:
126
+ return { runId, status: result.status };
127
+ }
128
+ }
129
+ // Storage may hand timestamps back as Date or as a serialized string
130
+ // depending on the adapter's snapshot round-trip; normalize defensively.
131
+ function toIso(value) {
132
+ return value instanceof Date
133
+ ? value.toISOString()
134
+ : new Date(value).toISOString();
135
+ }
136
+ // The resumed step for RunLeg: the caller's selection (dot-joined strings
137
+ // are nested paths, matching suspendedPaths key convention), else the single
138
+ // suspended step from the snapshot, else undefined (ambiguous multi-step
139
+ // resume without a selection — providers treat that as "no step-scoped
140
+ // capabilities", fail closed).
141
+ function resolveResumeStep(step, state) {
142
+ if (Array.isArray(step))
143
+ return [...step];
144
+ if (typeof step === 'string')
145
+ return step.split('.');
146
+ const suspended = Object.keys(state.suspendedPaths ?? {});
147
+ return suspended.length === 1 ? suspended[0]?.split('.') : undefined;
148
+ }
149
+ // The live attempt for a step. Repeated steps (foreach) store an array of
150
+ // attempts, so the current suspension/resume is the latest; a single-run step
151
+ // stores one entry. Shared by the suspendedAt/resumedAt/suspendPayload readers.
152
+ function latestAttempt(steps, stepKey) {
153
+ const entry = steps?.[stepKey];
154
+ return Array.isArray(entry) ? entry[entry.length - 1] : entry;
155
+ }
156
+ /** Epoch-ms suspension time of the step's latest attempt, if recorded. */
157
+ function suspendedAtOf(steps, stepKey) {
158
+ return latestAttempt(steps, stepKey)?.suspendedAt;
159
+ }
160
+ /**
161
+ * Epoch-ms resume time of the step's latest attempt, if recorded. Feeds the
162
+ * INFORMATIONAL RunSummary.resumedAt only — Mastra stamps it solely on a
163
+ * payload-bearing resume, so it is unreliable as a first-vs-re-suspension
164
+ * signal. The grant binding uses `resumeCount` (the runtime ledger) instead.
165
+ */
166
+ function resumedAtOf(steps, stepKey) {
167
+ return latestAttempt(steps, stepKey)?.resumedAt;
168
+ }
169
+ /**
170
+ * One home for the per-step projection convention behind every RunSummary map
171
+ * (suspendedAt / resumedAt / resumeCount / suspendPayload): collect
172
+ * `stepKey -> value` over the suspended step keys, projecting an empty result
173
+ * as undefined so JSON summaries omit the field. The accumulator is
174
+ * null-prototype because step keys are author-chosen strings: on a plain
175
+ * object literal a step named '__proto__' would route into the
176
+ * Object.prototype setter and silently vanish (or, for an object-valued
177
+ * payload, rewire the accumulator's prototype) — the same hazard
178
+ * resume-ledger.ts stores [stepKey, count] pairs to avoid.
179
+ */
180
+ function byStep(suspendedKeys, lookup) {
181
+ const map = Object.create(null);
182
+ let size = 0;
183
+ for (const key of suspendedKeys) {
184
+ const value = lookup(key);
185
+ if (value !== undefined) {
186
+ map[key] = value;
187
+ size += 1;
188
+ }
189
+ }
190
+ return size > 0 ? map : undefined;
191
+ }
192
+ // Projection of the persisted WorkflowState for status(). Unlike summarize()
193
+ // (which shapes a just-finished WorkflowResult), this reads the stored
194
+ // snapshot: suspended paths come from suspendedPaths keys (dot-joined for
195
+ // nested steps) and suspend payloads from per-step results — the same keyed
196
+ // shape start/resume return. A tripwire status carries no reason here (the
197
+ // snapshot does not persist it). When the state is an in-memory approximation
198
+ // (isFromInMemory), steps are empty and timestamps are current-time; the
199
+ // projection truthfully degrades to status-only rather than fabricating
200
+ // detail.
201
+ function summarizeState(runId, state, counts) {
202
+ const summary = {
203
+ runId,
204
+ status: state.status,
205
+ createdAt: toIso(state.createdAt),
206
+ updatedAt: toIso(state.updatedAt),
207
+ };
208
+ if (state.status === 'success') {
209
+ summary.result = state.result;
210
+ }
211
+ else if (state.status === 'failed' && state.error) {
212
+ summary.error = errorText(state.error);
213
+ }
214
+ else if (state.status === 'suspended') {
215
+ const suspendedKeys = Object.keys(state.suspendedPaths ?? {});
216
+ summary.suspended = suspendedKeys.map((key) => key.split('.'));
217
+ const suspendPayload = byStep(suspendedKeys, (key) => latestAttempt(state.steps, key)?.suspendPayload);
218
+ if (suspendPayload !== undefined) {
219
+ summary.suspendPayload = suspendPayload;
220
+ }
221
+ const suspendedAt = byStep(suspendedKeys, (key) => suspendedAtOf(state.steps, key));
222
+ if (suspendedAt !== undefined)
223
+ summary.suspendedAt = suspendedAt;
224
+ const resumedAt = byStep(suspendedKeys, (key) => resumedAtOf(state.steps, key));
225
+ if (resumedAt !== undefined)
226
+ summary.resumedAt = resumedAt;
227
+ const resumeCount = byStep(suspendedKeys, (key) => counts?.get(key));
228
+ if (resumeCount !== undefined)
229
+ summary.resumeCount = resumeCount;
230
+ }
231
+ return summary;
232
+ }
233
+ export class RunnerRuntime {
234
+ #storage;
235
+ #logger;
236
+ #requestContextForRun;
237
+ #workflows = new Map();
238
+ #runLocks = new Map();
239
+ // Per-run resume ledger: #runKey(workflowId, runId) -> (stepKey -> times that
240
+ // step has been resumed). Keyed by the run's FULL identity, never runId alone
241
+ // (see #runKey): a shared caller runId under two workflows are distinct runs.
242
+ // The runtime increments it on every resume (regardless of
243
+ // payload) and projects it as RunSummary.resumeCount / RunLeg.resumeCount —
244
+ // the collision-free grant-binding tie-breaker that Mastra's
245
+ // payload-conditional resumedAt cannot provide.
246
+ //
247
+ // Durability: a lost ledger is fail-closed for grants (leg.resumeCount
248
+ // undefined vs an approval's captured ordinal -> mismatch -> deny, see
249
+ // grants.ts) — never a leak, but an AVAILABILITY bug: the approved action
250
+ // silently no-ops. DO eviction (~70-140s idle), hibernation, and code
251
+ // deploys all wipe in-memory state while ctx.storage survives, so the DO
252
+ // shell adopts a DurableStorageResumeLedger (durable-object.ts); the
253
+ // in-memory default covers node tests and non-DO hosts. Entries are
254
+ // deleted on terminal status below; a resumed-then-abandoned suspended run
255
+ // keeps one small entry until the run is purged.
256
+ #resumeLedger;
257
+ #resumeLedgerExplicit;
258
+ #mastra;
259
+ constructor(options) {
260
+ this.#storage = options.storage;
261
+ this.#logger = options.logger ?? false;
262
+ this.#requestContextForRun = options.requestContextForRun;
263
+ this.#resumeLedgerExplicit = options.resumeLedger !== undefined;
264
+ this.#resumeLedger = options.resumeLedger ?? new InMemoryResumeLedger();
265
+ }
266
+ /**
267
+ * Host-shell seam: replace the DEFAULT in-memory ledger with a durable one.
268
+ * The DO shell calls this with a ctx.storage-backed ledger right after
269
+ * build(), so every DO host gets eviction-proof ordinals without threading
270
+ * a parameter (a forgettable thread is how the durability guarantee rots).
271
+ * A ledger explicitly injected via options wins; adoption is rejected once
272
+ * runs may have consulted the ledger.
273
+ */
274
+ adoptDefaultResumeLedger(ledger) {
275
+ if (this.#mastra) {
276
+ throw new Error('RunnerRuntime: adopt the resume ledger before the first run — ordinals already read from the default ledger would be lost');
277
+ }
278
+ if (this.#resumeLedgerExplicit)
279
+ return;
280
+ this.#resumeLedger = ledger;
281
+ }
282
+ register(workflow) {
283
+ if (this.#mastra) {
284
+ throw new Error('RunnerRuntime: register all workflows before the first run — the Mastra instance is frozen once runs start');
285
+ }
286
+ if (!PATH_SAFE_ID_PATTERN.test(workflow.id)) {
287
+ throw new Error(`RunnerRuntime: workflow id '${workflow.id}' must be URL-path-safe (letters, digits, '.', '_', '~', '-'; 1-200 chars) — it feeds the DO name join and the /runs/:workflowId/:runId path`);
288
+ }
289
+ if (this.#workflows.has(workflow.id)) {
290
+ throw new Error(`RunnerRuntime: duplicate workflow id '${workflow.id}'`);
291
+ }
292
+ this.#workflows.set(workflow.id, workflow);
293
+ }
294
+ workflowIds() {
295
+ return [...this.#workflows.keys()];
296
+ }
297
+ async start(workflowId, options) {
298
+ const workflow = this.#getWorkflow(workflowId);
299
+ // Reject non-path-safe ids at the mint boundary so the runId is unambiguous
300
+ // everywhere it addresses the run (D1 key, DO name, URL path) — see
301
+ // PATH_SAFE_ID_PATTERN. Fail fast, before the lock and any createRun work.
302
+ // The typeof guard is load-bearing, not redundant with the string type:
303
+ // this value can arrive from JSON.parse through an unchecked `as` cast
304
+ // (durable-object.ts readJson), and RegExp.test() coerces its argument to a
305
+ // String — so a numeric runId like 123 would pass the pattern as "123" yet
306
+ // mint a run keyed by the number 123, unreachable by the string "123" the
307
+ // URL path later carries. There is NO generation fallback (INV-1): a
308
+ // missing/null runId is a client error, not a request for one.
309
+ if (typeof options.runId !== 'string' ||
310
+ !PATH_SAFE_ID_PATTERN.test(options.runId)) {
311
+ throw new InvalidRunRequestError("runId is required and must be URL-path-safe (letters, digits, '.', '_', '~', '-'; 1–200 chars)");
312
+ }
313
+ const runId = options.runId;
314
+ return this.#withRunLock(workflowId, runId, async () => {
315
+ // Supplied ids can collide with an existing run; starting it
316
+ // again would re-execute already-executed steps.
317
+ const existing = await workflow.getWorkflowRunById(runId);
318
+ if (existing) {
319
+ throw new RunAlreadyExistsError(workflowId, runId, existing.status);
320
+ }
321
+ // Resolve the leg's context BEFORE createRun: createRun persists the
322
+ // initial snapshot, so a provider failure after it would strand a
323
+ // pending-but-never-started run (a supplied runId would then be locked
324
+ // out by RunAlreadyExistsError on retry). Failing here leaves no state.
325
+ const requestContext = await this.#requestContextFor(workflowId, runId, {
326
+ kind: 'start',
327
+ });
328
+ const run = await workflow.createRun({ runId });
329
+ let result;
330
+ try {
331
+ result = await run.start({
332
+ inputData: options.inputData,
333
+ requestContext,
334
+ });
335
+ }
336
+ catch (error) {
337
+ throw asClientError(error) ?? error;
338
+ }
339
+ return summarize(run.runId, result);
340
+ });
341
+ }
342
+ /**
343
+ * Reattach to a suspended run — the designed fresh-process pattern:
344
+ * createRun({ runId }) does not clobber an existing snapshot; resume()
345
+ * loads it and re-enters the engine at the suspended step.
346
+ */
347
+ async resume(workflowId, runId, options = {}) {
348
+ const workflow = this.#getWorkflow(workflowId);
349
+ return this.#withRunLock(workflowId, runId, async () => {
350
+ const runKey = this.#runKey(workflowId, runId);
351
+ const state = await workflow.getWorkflowRunById(runId);
352
+ if (!state)
353
+ throw new UnknownRunError(workflowId, runId);
354
+ if (state.status !== 'suspended') {
355
+ throw new RunNotSuspendedError(workflowId, runId, state.status);
356
+ }
357
+ // Provider before createRun for symmetry with start(): a resume-time
358
+ // createRun only reattaches (no snapshot write), but failing before it
359
+ // still does the least work and keeps the ordering invariant uniform.
360
+ const step = resolveResumeStep(options.step, state);
361
+ const stepKey = step?.join('.');
362
+ // resumeCount is read BEFORE this resume increments it: it is the count
363
+ // of prior resumes = the ordinal of the CURRENT suspension being resumed
364
+ // (undefined for a first suspension), which the minting approval captured
365
+ // at that suspension. suspendedAt still comes from the snapshot.
366
+ const priorCounts = await this.#resumeLedger.counts(runKey);
367
+ const requestContext = await this.#requestContextFor(workflowId, runId, {
368
+ kind: 'resume',
369
+ step,
370
+ suspendedAt: stepKey !== undefined
371
+ ? suspendedAtOf(state.steps, stepKey)
372
+ : undefined,
373
+ resumeCount: stepKey !== undefined ? priorCounts?.get(stepKey) : undefined,
374
+ });
375
+ const run = await workflow.createRun({ runId });
376
+ let result;
377
+ try {
378
+ result = await run.resume({
379
+ step: options.step,
380
+ resumeData: options.resumeData,
381
+ requestContext,
382
+ });
383
+ }
384
+ catch (error) {
385
+ // The run stayed suspended (resume threw) — do NOT increment; the
386
+ // prior count must persist for a later retry of this same suspension.
387
+ throw asClientError(error) ?? error;
388
+ }
389
+ // Record THIS resume AFTER the leg fingerprint read above and BEFORE
390
+ // summarize: a re-suspension produced by this resume must capture the
391
+ // incremented ordinal so its approval binds to the new suspension.
392
+ // priorCounts rides along so a durable ledger need not re-read what the
393
+ // per-run FIFO lock guarantees unchanged since the read above.
394
+ let counts = priorCounts;
395
+ if (stepKey !== undefined) {
396
+ counts = await this.#resumeLedger.increment(runKey, stepKey, priorCounts ?? new Map());
397
+ }
398
+ const summary = summarize(run.runId, result, counts);
399
+ // Terminal run: drop the ledger (no further suspension can occur).
400
+ if (summary.status !== 'suspended') {
401
+ await this.#resumeLedger.delete(runKey);
402
+ }
403
+ return summary;
404
+ });
405
+ }
406
+ async status(workflowId, runId) {
407
+ const workflow = this.#getWorkflow(workflowId);
408
+ const state = await workflow.getWorkflowRunById(runId);
409
+ if (!state)
410
+ return null;
411
+ // Ledger read only for SUSPENDED runs — the one branch that projects
412
+ // resumeCount (defense in depth: a bridge that ever mints off status()
413
+ // must not see a stale/absent ordinal). Every other status would discard
414
+ // the result, and under the DO shell each read is a billed
415
+ // ctx.storage.get the SPA's polling would pay on every terminal run.
416
+ const counts = state.status === 'suspended'
417
+ ? await this.#resumeLedger.counts(this.#runKey(workflowId, runId))
418
+ : undefined;
419
+ return summarizeState(runId, state, counts);
420
+ }
421
+ // A provider crash propagates (fail loud): silently starting the leg with
422
+ // fewer capabilities than intended would mask the fault. Missing grants can
423
+ // only ever deny downstream (fail closed), so loud propagation is safe.
424
+ //
425
+ // Every leg — provider or not — carries a base context minting the
426
+ // workflow-scope key (breakwater's crossWorkflowIsolation reads it): the
427
+ // runtime is the trusted authority for "which workflow is executing", so
428
+ // the scope is never client-suppliable. Provider values merge OVER the
429
+ // base, so a provider can override the scope deliberately.
430
+ async #requestContextFor(workflowId, runId, leg) {
431
+ const base = {
432
+ [BREAKWATER_WORKFLOW_SCOPE_KEY]: workflowId,
433
+ };
434
+ // Tenant-salted runs (INV-1: `${tenantId}_${uuid}`) also mint the OPAQUE
435
+ // isolation scope, segmenting breakwater's connector idempotency and
436
+ // rate-limit keys per tenant. Server-authoritative like the workflow
437
+ // scope above — the runId was minted from the AUTHENTICATED tenant, so
438
+ // its prefix is trustworthy here.
439
+ //
440
+ // Structural, not flagged: a runId shaped `<inv3-slug>_<rest>` mints a
441
+ // scope. For this repo's hosts that is exactly the tenant (they all mint
442
+ // via TenantContext.newRunId). CONSTRAINT for standalone OSS consumers
443
+ // minting their own runIds: the scope segments breakwater's CROSS-RUN
444
+ // idempotency and rate-limit keys, so one logical account must keep ONE
445
+ // stable pre-`_` prefix (or avoid `_`-prefixed runIds entirely) — ids
446
+ // like `daily_<uuid>` vs `weekly_<uuid>` would split that account's key
447
+ // namespace per prefix, and a cross-run business key ("invoice-2026-07")
448
+ // would fire once per prefix instead of once. Never a cross-tenant leak
449
+ // (splitting only narrows sharing), but a real duplication hazard.
450
+ // Non-matching runIds mint nothing: the single-tenant keys stay
451
+ // byte-identical, and deployments that must never run scope-less enforce
452
+ // that with breakwater's tenantIsolation evaluator (which binds dry-run
453
+ // too, unlike the idempotency path).
454
+ const tenantId = tenantOfRunId(runId);
455
+ if (tenantId !== undefined) {
456
+ base[BREAKWATER_ISOLATION_SCOPE_KEY] = tenantId;
457
+ }
458
+ const values = this.#requestContextForRun
459
+ ? await this.#requestContextForRun(workflowId, runId, leg)
460
+ : undefined;
461
+ return new RequestContext(Object.entries({ ...base, ...values }));
462
+ }
463
+ #getWorkflow(workflowId) {
464
+ this.#ensureMastra();
465
+ const workflow = this.#workflows.get(workflowId);
466
+ if (!workflow)
467
+ throw new UnknownWorkflowError(workflowId);
468
+ return workflow;
469
+ }
470
+ #ensureMastra() {
471
+ if (this.#mastra)
472
+ return;
473
+ this.#mastra = new Mastra({
474
+ workflows: Object.fromEntries(this.#workflows),
475
+ storage: this.#storage,
476
+ logger: this.#logger,
477
+ });
478
+ }
479
+ // The run's full identity as a single map key: workflowId + runId, never runId
480
+ // alone. The same caller-supplied runId under two workflows are DISTINCT
481
+ // persisted runs (Mastra snapshots key on workflowName+runId) and must never
482
+ // share a per-run entry — the FIFO lock OR the resume ledger. Composing the key
483
+ // in ONE place keeps every per-run map keyed identically, so a future per-run
484
+ // map cannot reintroduce a runId-only key (the grant leak the ledger guards).
485
+ // This is the exact string the DO name join produces
486
+ // (idFromName(`${workflowId}:${runId}`)); PATH_SAFE_ID_PATTERN excludes ':'
487
+ // from both ids, so the join is unambiguous.
488
+ #runKey(workflowId, runId) {
489
+ return `${workflowId}:${runId}`;
490
+ }
491
+ // FIFO per-run lock: callers for the same run execute strictly in arrival
492
+ // order; distinct runs do not contend. The map entry is removed when the last
493
+ // waiter settles, so idle runs hold no memory. Keyed by the run's full identity
494
+ // via #runKey (workflowId + runId), not runId alone — the in-process lock
495
+ // granularity thus matches the cross-instance DO routing granularity.
496
+ async #withRunLock(workflowId, runId, fn) {
497
+ const key = this.#runKey(workflowId, runId);
498
+ const prev = this.#runLocks.get(key) ?? Promise.resolve();
499
+ const task = prev.then(fn);
500
+ const tail = task.then(() => undefined, () => undefined);
501
+ this.#runLocks.set(key, tail);
502
+ void tail.then(() => {
503
+ if (this.#runLocks.get(key) === tail)
504
+ this.#runLocks.delete(key);
505
+ });
506
+ return task;
507
+ }
508
+ }
509
+ //# sourceMappingURL=runtime.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../src/do-runner/runtime.ts"],"names":[],"mappings":"AAAA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C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,OAAO,CAAC,OAAO,EAAE,CAAC;QAC1D,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,CACpB,GAAG,EAAE,CAAC,SAAS,EACf,GAAG,EAAE,CAAC,SAAS,CAChB,CAAC;QACF,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,EAAE,IAAI,CAAC,CAAC;QAC9B,KAAK,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE;YAClB,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;gBAAE,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;QACnE,CAAC,CAAC,CAAC;QACH,OAAO,IAAI,CAAC;IACd,CAAC;CACF"}
@@ -0,0 +1,109 @@
1
+ import { type ApprovalActor, type ApprovalAuditSink, type ApprovalDecision, type ApprovalRecord, type ApprovalService, type TenantContext } from '../approval-api/index.js';
2
+ import type { RunSummary } from '../do-runner/index.js';
3
+ /**
4
+ * Resumes a run after a decision. The showcase Worker fetches the run's DO stub;
5
+ * an in-process host uses resumeViaRuntime(runtime). Either way it returns the
6
+ * post-resume RunSummary so the re-queue wrapper can inspect status.
7
+ */
8
+ export type ResumeRunFn = (record: ApprovalRecord, decision: ApprovalDecision) => Promise<RunSummary>;
9
+ /** Steps declare the grants they need in their suspend payload. */
10
+ export declare function requestedConnectors(stepPayload: unknown): string[];
11
+ /**
12
+ * A suspension IS an approval request: queue one record per suspended step
13
+ * path (idempotently — the store's partial unique open-step index collapses
14
+ * duplicates, so re-queuing an already-queued gate is a no-op). EVERY path
15
+ * files: `.parallel()` branches can suspend together
16
+ * (`summary.suspended = [['a'], ['b']]`), and a gate that never reaches the
17
+ * queue can never be decided — its connector then denies on every resume
18
+ * (fail closed) with nothing telling a reviewer why the run is stuck.
19
+ * Capturing each step's (suspendedAt, resumeCount) pair binds its approval to
20
+ * THAT suspension exactly (clock-free grant minting), and each suspend
21
+ * payload's `connectors` declares what a decision should mint.
22
+ *
23
+ * `requestedBy` is the HUMAN who advanced the run to this suspension — the actor
24
+ * who started it, or the reviewer whose decision caused a re-suspension at the
25
+ * next gate. It must NOT be the system actor: the library's self-decision
26
+ * separation-of-duties check compares `requestedBy` to the deciding actor, so
27
+ * attributing every request to the system actor would make that check unfireable.
28
+ * `systemActor` is only the record's creator (needs a create-capable role).
29
+ */
30
+ export declare function queueApprovalForSuspension(service: ApprovalService, workflowId: string, summary: RunSummary, requestedBy: string, systemActor: ApprovalActor): Promise<ApprovalRecord[]>;
31
+ /**
32
+ * Wrap a base resume fn so a run that re-suspends at a LATER gate auto-queues
33
+ * its next approval(s) — the multi-gate flow (product-launch's two gates); every
34
+ * suspended path re-queues, not just the first. The base
35
+ * resume (resumeViaRuntime or a DO-stub fetch) deliberately omits re-queue; this
36
+ * adds it without coupling to the host's resume topology.
37
+ *
38
+ * The reviewer whose decision advanced the run becomes the next gate's
39
+ * `requestedBy`, so they cannot also decide it (SoD across gates). Guard
40
+ * fail-CLOSED: refuse to re-queue without a requester rather than fall back to
41
+ * the system id.
42
+ *
43
+ * `getService` is a thunk because the service references this closure at its own
44
+ * construction (`service = new ApprovalService({ resumeRun: resumeRunWithRequeue(base, () => service, sys) })`);
45
+ * the closure only runs on a later decision, so the reference is resolved by then.
46
+ *
47
+ * `audit` is optional and should be the SAME sink the service itself uses
48
+ * (buildHostApprovalService wires it that way): the base resume above has
49
+ * already durably advanced the run by the time the re-queue below can fail,
50
+ * so a throw here (D4, 2026-07-11 audit) leaves a gate suspended with no
51
+ * approval record and no other signal that happened. reconcileApprovalsForSummary
52
+ * is the recovery; this event is what tells an operator it was needed.
53
+ */
54
+ export declare function resumeRunWithRequeue(base: ResumeRunFn, getService: () => ApprovalService, systemActor: ApprovalActor, audit?: ApprovalAuditSink): ResumeRunFn;
55
+ /**
56
+ * D4 recovery primitive: given a run's suspended RunSummary, heals every
57
+ * CURRENTLY suspended step whose exact (suspendedAt, resumeCount)
58
+ * fingerprint has no approval record of ANY status, then files it fresh.
59
+ * Safe to call on every status() read of a suspended run, rather than only
60
+ * after a confirmed bridge failure, because per step:
61
+ *
62
+ * - any record (any status) already bound to the CURRENT fingerprint means
63
+ * nothing to do — a matching pending/claimed/escalated record makes
64
+ * queueApprovalForSuspension's own idempotent create() a no-op anyway
65
+ * (this skips the round-trip), and a matching DECIDED record means the
66
+ * decision landed but its resume has not (yet, or ever, on the wedge path
67
+ * this exists for) re-queued the next gate — re-filing would double-file
68
+ * a gate correctly waiting on its own resume, the decide -> resume
69
+ * in-flight window;
70
+ * - otherwise, every STALE OPEN record for that step (pending/claimed/
71
+ * escalated, bound to a suspension the step has since moved past —
72
+ * produced e.g. by the raw grant-free resume route re-suspending the step
73
+ * while an earlier request still sits open) is SUPERSEDED first
74
+ * (ApprovalService.supersedeStale: a CAS transition straight to
75
+ * 'rejected', system-attributed, audited as approval.supersede, never
76
+ * through decide() — so it never touches the run) before the fresh file,
77
+ * closing the loop where a stale-but-open record otherwise never heals
78
+ * (every poll re-lists, finds the same open record via the open-step
79
+ * uniqueness index, and re-files nothing). A stale DECIDED record needs
80
+ * no supersede — it is already terminal and excluded from grant
81
+ * derivation by its own (non-'approved', or fingerprint-mismatched)
82
+ * status.
83
+ * - if a supersede loses its CAS (a real decision won the race between the
84
+ * list() above and the supersede), this step is left alone for this
85
+ * round entirely — no fresh file — rather than clobbering or
86
+ * double-filing over a decision that just landed; the next status() read
87
+ * re-evaluates against a fresh summary and a fresh list().
88
+ *
89
+ * Delegates the actual filing to queueApprovalForSuspension against a copy of
90
+ * `summary` narrowed to only the healed paths, so a step with a live or
91
+ * in-flight record is never touched. `requestedBy` on a reconciled record is
92
+ * the SYSTEM actor, not a human: on the re-queue-failure trigger a reviewer
93
+ * DID cause the suspension, but reconcile has only the RunSummary to work
94
+ * from and no reliable way to recover who — so it attributes to the system
95
+ * actor rather than guess (see the SoD note in retention.ts and the
96
+ * operations runbook). That is a deliberate, narrow SoD relaxation on this
97
+ * recovery path only: the gate-A decider MAY legally decide the reconciled
98
+ * gate B, same as the retention-purge recovery path.
99
+ */
100
+ export declare function reconcileApprovalsForSummary(service: ApprovalService, workflowId: string, summary: RunSummary, systemActor: ApprovalActor): Promise<ApprovalRecord[]>;
101
+ /**
102
+ * Adapts reconcileApprovalsForSummary to RunRouterOptions.reconcileApprovals's
103
+ * per-request shape: `tenant.service()`/`tenant.tenantId` only exist once a
104
+ * request resolves, so only the systemActorId (a per-deployment constant) can
105
+ * be bound ahead of time — everything else is read from the tenant the router
106
+ * hands in on each call.
107
+ */
108
+ export declare function reconcileApprovalsOnStatus(systemActorId: string): (tenant: TenantContext, workflowId: string, summary: RunSummary) => Promise<void>;
109
+ //# sourceMappingURL=approval-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approval-bridge.d.ts","sourceRoot":"","sources":["../../src/host-kit/approval-bridge.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,cAAc,EACnB,KAAK,eAAe,EAKpB,KAAK,aAAa,EACnB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,uBAAuB,CAAC;AAExD;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CACxB,MAAM,EAAE,cAAc,EACtB,QAAQ,EAAE,gBAAgB,KACvB,OAAO,CAAC,UAAU,CAAC,CAAC;AAEzB,mEAAmE;AACnE,wBAAgB,mBAAmB,CAAC,WAAW,EAAE,OAAO,GAAG,MAAM,EAAE,CAOlE;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,eAAe,EACxB,UAAU,EAAE,MAAM,EAClB,OAAO,E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