@proofoftech/flowsafe 0.27.0 → 0.30.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 (108) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +4 -0
  3. package/deployment-identity-protocol.mjs +3 -4
  4. package/dist/agent-host/catalog.js +1 -1
  5. package/dist/agent-host/catalog.js.map +1 -1
  6. package/dist/agent-host/index.d.ts +4 -1
  7. package/dist/agent-host/index.d.ts.map +1 -1
  8. package/dist/agent-host/index.js +2 -1
  9. package/dist/agent-host/index.js.map +1 -1
  10. package/dist/agent-host/thread-host.d.ts +18 -0
  11. package/dist/agent-host/thread-host.d.ts.map +1 -1
  12. package/dist/agent-host/thread-host.js +407 -10
  13. package/dist/agent-host/thread-host.js.map +1 -1
  14. package/dist/agent-host/thread-topology.d.ts +83 -0
  15. package/dist/agent-host/thread-topology.d.ts.map +1 -1
  16. package/dist/agent-host/thread-topology.js +202 -1
  17. package/dist/agent-host/thread-topology.js.map +1 -1
  18. package/dist/agent-host/workflow-remote-step-route.d.ts +7 -0
  19. package/dist/agent-host/workflow-remote-step-route.d.ts.map +1 -0
  20. package/dist/agent-host/workflow-remote-step-route.js +148 -0
  21. package/dist/agent-host/workflow-remote-step-route.js.map +1 -0
  22. package/dist/agent-runner/agent-run-state.d.ts +1 -1
  23. package/dist/agent-runner/agent-run-state.d.ts.map +1 -1
  24. package/dist/agent-runner/agent-run-state.js +1 -0
  25. package/dist/agent-runner/agent-run-state.js.map +1 -1
  26. package/dist/agent-runner/durable-agent-runner.d.ts +1 -0
  27. package/dist/agent-runner/durable-agent-runner.d.ts.map +1 -1
  28. package/dist/agent-runner/durable-agent-runner.js +69 -32
  29. package/dist/agent-runner/durable-agent-runner.js.map +1 -1
  30. package/dist/approval-api/types.d.ts +7 -8
  31. package/dist/approval-api/types.d.ts.map +1 -1
  32. package/dist/do-runner/do-error-response.d.ts.map +1 -1
  33. package/dist/do-runner/do-error-response.js +8 -8
  34. package/dist/do-runner/do-error-response.js.map +1 -1
  35. package/dist/do-runner/do-status-error.d.ts +8 -0
  36. package/dist/do-runner/do-status-error.d.ts.map +1 -1
  37. package/dist/do-runner/do-status-error.js +8 -0
  38. package/dist/do-runner/do-status-error.js.map +1 -1
  39. package/dist/do-runner/durable-object.d.ts +2 -0
  40. package/dist/do-runner/durable-object.d.ts.map +1 -1
  41. package/dist/do-runner/durable-object.js +252 -3
  42. package/dist/do-runner/durable-object.js.map +1 -1
  43. package/dist/do-runner/execution-admission.d.ts +2 -0
  44. package/dist/do-runner/execution-admission.d.ts.map +1 -1
  45. package/dist/do-runner/execution-admission.js +12 -2
  46. package/dist/do-runner/execution-admission.js.map +1 -1
  47. package/dist/do-runner/execution-fence.d.ts +1 -1
  48. package/dist/do-runner/index.d.ts +1 -0
  49. package/dist/do-runner/index.d.ts.map +1 -1
  50. package/dist/do-runner/index.js +1 -0
  51. package/dist/do-runner/index.js.map +1 -1
  52. package/dist/do-runner/inventory.d.ts +1 -1
  53. package/dist/do-runner/inventory.d.ts.map +1 -1
  54. package/dist/do-runner/inventory.js +85 -1
  55. package/dist/do-runner/inventory.js.map +1 -1
  56. package/dist/do-runner/remote-step-journal.d.ts +168 -0
  57. package/dist/do-runner/remote-step-journal.d.ts.map +1 -0
  58. package/dist/do-runner/remote-step-journal.js +2089 -0
  59. package/dist/do-runner/remote-step-journal.js.map +1 -0
  60. package/dist/do-runner/run-lifecycle.d.ts +3 -1
  61. package/dist/do-runner/run-lifecycle.d.ts.map +1 -1
  62. package/dist/do-runner/run-lifecycle.js +3 -1
  63. package/dist/do-runner/run-lifecycle.js.map +1 -1
  64. package/dist/do-runner/runtime.d.ts +16 -3
  65. package/dist/do-runner/runtime.d.ts.map +1 -1
  66. package/dist/do-runner/runtime.js +51 -18
  67. package/dist/do-runner/runtime.js.map +1 -1
  68. package/dist/host-kit/do-response.d.ts +19 -1
  69. package/dist/host-kit/do-response.d.ts.map +1 -1
  70. package/dist/host-kit/do-response.js +71 -2
  71. package/dist/host-kit/do-response.js.map +1 -1
  72. package/dist/host-kit/do-run-topology.d.ts +8 -2
  73. package/dist/host-kit/do-run-topology.d.ts.map +1 -1
  74. package/dist/host-kit/do-run-topology.js +26 -1
  75. package/dist/host-kit/do-run-topology.js.map +1 -1
  76. package/dist/host-kit/flowsafe-worker.d.ts +38 -4
  77. package/dist/host-kit/flowsafe-worker.d.ts.map +1 -1
  78. package/dist/host-kit/flowsafe-worker.js +104 -15
  79. package/dist/host-kit/flowsafe-worker.js.map +1 -1
  80. package/dist/host-kit/index.d.ts +5 -5
  81. package/dist/host-kit/index.d.ts.map +1 -1
  82. package/dist/host-kit/index.js +3 -3
  83. package/dist/host-kit/index.js.map +1 -1
  84. package/dist/host-kit/maintenance-capability.js +3 -3
  85. package/dist/host-kit/maintenance-capability.js.map +1 -1
  86. package/dist/host-kit/state-egress.d.ts +34 -6
  87. package/dist/host-kit/state-egress.d.ts.map +1 -1
  88. package/dist/host-kit/state-egress.js +49 -8
  89. package/dist/host-kit/state-egress.js.map +1 -1
  90. package/dist/schedules/tick.d.ts +21 -3
  91. package/dist/schedules/tick.d.ts.map +1 -1
  92. package/dist/schedules/tick.js +54 -7
  93. package/dist/schedules/tick.js.map +1 -1
  94. package/dist/signals/index.d.ts +1 -0
  95. package/dist/signals/index.d.ts.map +1 -1
  96. package/dist/signals/index.js.map +1 -1
  97. package/dist/signals/notification-dispatch.d.ts +2 -64
  98. package/dist/signals/notification-dispatch.d.ts.map +1 -1
  99. package/dist/signals/notification-dispatch.js.map +1 -1
  100. package/dist/signals/notifications-d1.d.ts +91 -2
  101. package/dist/signals/notifications-d1.d.ts.map +1 -1
  102. package/dist/signals/notifications-d1.js +238 -1
  103. package/dist/signals/notifications-d1.js.map +1 -1
  104. package/dist/signals/storage.d.ts +1 -1
  105. package/dist/signals/storage.d.ts.map +1 -1
  106. package/dist/signals/storage.js +3 -3
  107. package/dist/signals/storage.js.map +1 -1
  108. package/package.json +1 -1
@@ -0,0 +1,2089 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { EXECUTION_FENCE_TABLE } from '#deployment-identity-protocol';
3
+ import { assertExecutionPrincipal, } from '../approval-api/principal.js';
4
+ import { D1NotificationsStorage, DEFAULT_NOTIFICATION_OPERATION_RECEIPT_LIMIT, NOTIFICATION_OPERATION_PROJECTION_VERSION, NOTIFICATION_OPERATION_RECEIPTS_TABLE, projectNotificationOperation, } from '../signals/notifications-d1.js';
5
+ import { credentialsMatch } from './deployment-identity.js';
6
+ import { DoStatusError } from './do-status-error.js';
7
+ import { assertMutationEpoch } from './execution-admission.js';
8
+ import { admitsExistingRun, captureExecutionFenceAdmissionSchema, executionFenceAdmissionSql, executionFenceAdmissionValues, } from './execution-fence.js';
9
+ import { isPathSafeId } from './path-safe-id.js';
10
+ import { lifecycleFromRequestContext, RUN_LIFECYCLE_CONTEXT_KEY, } from './run-lifecycle.js';
11
+ import { MASTRA_WORKFLOW_META_KEY } from './suspension-deadline.js';
12
+ import { validateTablePrefix } from './table-prefix.js';
13
+ export const REMOTE_STEP_TABLE = 'flowsafe_remote_step_invocations';
14
+ export const REMOTE_STEP_SCHEMA_TABLE = 'flowsafe_remote_step_schema';
15
+ export const REMOTE_STEP_NOTIFICATION_CURSOR_TABLE = 'flowsafe_remote_step_notification_cursor';
16
+ const REMOTE_STEP_NOTIFICATION_CURSOR_SQL = `CREATE TABLE ${REMOTE_STEP_NOTIFICATION_CURSOR_TABLE} (
17
+ deployment_id TEXT NOT NULL,
18
+ table_prefix TEXT NOT NULL,
19
+ version INTEGER NOT NULL,
20
+ after_invocation_id TEXT NOT NULL,
21
+ PRIMARY KEY (deployment_id, table_prefix)
22
+ )`;
23
+ const REMOTE_STEP_RECOVERY_INDEX = 'flowsafe_remote_step_recovery';
24
+ const REMOTE_STEP_RECOVERY_INDEX_SQL = `CREATE INDEX ${REMOTE_STEP_RECOVERY_INDEX} ON ${REMOTE_STEP_TABLE} (invocation_id) WHERE status IN ('result-retained', 'resuming')`;
25
+ const REMOTE_STEP_AGENT_INDEX = 'flowsafe_remote_step_agent_suspension';
26
+ const REMOTE_STEP_WORKFLOW_INDEX = 'flowsafe_remote_step_workflow_suspension';
27
+ const REMOTE_STEP_AGENT_INDEX_SQL = `CREATE UNIQUE INDEX ${REMOTE_STEP_AGENT_INDEX} ON ${REMOTE_STEP_TABLE} (deployment_id, table_prefix, workflow_id, agent_id, thread_id, resource_id, run_id, step_path, suspended_at, resume_count) WHERE target_kind = 'agent'`;
28
+ const REMOTE_STEP_WORKFLOW_INDEX_SQL = `CREATE UNIQUE INDEX ${REMOTE_STEP_WORKFLOW_INDEX} ON ${REMOTE_STEP_TABLE} (deployment_id, table_prefix, workflow_id, run_id, step_path, suspended_at, resume_count) WHERE target_kind = 'workflow'`;
29
+ const REMOTE_STEP_WRITE_TRIGGER = 'flowsafe_remote_step_write_version';
30
+ const REMOTE_STEP_WRITE_TRIGGER_SQL = `CREATE TRIGGER ${REMOTE_STEP_WRITE_TRIGGER} BEFORE UPDATE ON ${REMOTE_STEP_TABLE} WHEN NEW.write_revision <= OLD.write_revision BEGIN SELECT RAISE(ABORT, 'remote step writer version changed'); END`;
31
+ const REMOTE_STEP_V5_WRITE_TRIGGER_SQL = `CREATE TRIGGER ${REMOTE_STEP_WRITE_TRIGGER} BEFORE UPDATE ON ${REMOTE_STEP_TABLE} WHEN NEW.write_generation <= OLD.write_generation OR NEW.write_revision <= OLD.write_revision BEGIN SELECT RAISE(ABORT, 'remote step writer version changed'); END`;
32
+ const REMOTE_STEP_OPERATION_INDEX = 'flowsafe_remote_step_notification_recovery';
33
+ const REMOTE_STEP_OPERATION_INDEX_SQL = `CREATE INDEX ${REMOTE_STEP_OPERATION_INDEX} ON ${REMOTE_STEP_TABLE} (invocation_id) WHERE operation_state IN ('prepared', 'effect-admitted', 'receipt-recorded', 'resume-admitted', 'unresolved')`;
34
+ const REMOTE_STEP_RESULT_COLUMNS = [
35
+ 'result_json',
36
+ 'result_digest',
37
+ 'quiescence_digest',
38
+ 'executor_quiescent_at',
39
+ ];
40
+ const REMOTE_STEP_SETTLEMENT_COLUMNS = [
41
+ 'resume_lease_owner',
42
+ 'resume_lease_expires_at',
43
+ 'settled_at',
44
+ 'settlement_outcome',
45
+ ];
46
+ const REMOTE_STEP_COLUMNS = [
47
+ 'invocation_id',
48
+ 'principal_json',
49
+ 'start_token',
50
+ 'deployment_id',
51
+ 'table_prefix',
52
+ 'workflow_id',
53
+ 'agent_id',
54
+ 'thread_id',
55
+ 'resource_id',
56
+ 'run_id',
57
+ 'step_path',
58
+ 'suspended_at',
59
+ 'resume_count',
60
+ 'request_json',
61
+ 'deadline_at',
62
+ 'status',
63
+ 'permit_generation',
64
+ 'permit_epoch',
65
+ 'permit_revision',
66
+ 'permit_expires_at',
67
+ 'permit_consumed_at',
68
+ 'permit_digest',
69
+ ...REMOTE_STEP_RESULT_COLUMNS,
70
+ ...REMOTE_STEP_SETTLEMENT_COLUMNS,
71
+ 'target_kind',
72
+ 'suspension_marker',
73
+ 'request_digest',
74
+ 'write_revision',
75
+ ];
76
+ const REMOTE_STEP_V5_COLUMNS = [
77
+ ...REMOTE_STEP_COLUMNS,
78
+ 'write_generation',
79
+ 'operation_key',
80
+ 'operation_id',
81
+ 'notification_id',
82
+ 'notification_request_json',
83
+ 'notification_projection_version',
84
+ 'notification_projection_json',
85
+ 'notification_request_digest',
86
+ 'operation_state',
87
+ 'effect_admitted_at',
88
+ 'receipt_recorded_at',
89
+ 'resume_admitted_at',
90
+ ];
91
+ const REMOTE_STEP_INTEGER_COLUMNS = new Set([
92
+ 'suspended_at',
93
+ 'resume_count',
94
+ 'deadline_at',
95
+ 'permit_generation',
96
+ 'permit_epoch',
97
+ 'permit_revision',
98
+ 'permit_expires_at',
99
+ 'permit_consumed_at',
100
+ 'executor_quiescent_at',
101
+ 'resume_lease_expires_at',
102
+ 'settled_at',
103
+ 'write_revision',
104
+ 'write_generation',
105
+ 'effect_admitted_at',
106
+ 'receipt_recorded_at',
107
+ 'resume_admitted_at',
108
+ ]);
109
+ export const REMOTE_STEP_MARKER = 'flowsafe.remote-step/v1';
110
+ export const WORKFLOW_REMOTE_STEP_MARKER = 'flowsafe.remote-step.workflow/v1';
111
+ export const WORKFLOW_REMOTE_STEP_RESULT_KEY = 'flowsafe.workflowRemoteStepResult';
112
+ export const MAX_REMOTE_STEP_REQUEST_BYTES = 16_384;
113
+ export const MAX_REMOTE_STEP_RESULT_BYTES = 16_384;
114
+ const SHA256_HEX = /^[a-f0-9]{64}$/;
115
+ const RAW_PERMIT = /^[A-Za-z0-9_-]{43}$/;
116
+ function remoteStepTableSql(name, version = 5) {
117
+ return `CREATE TABLE IF NOT EXISTS ${name} (
118
+ invocation_id TEXT PRIMARY KEY,
119
+ principal_json TEXT NOT NULL,
120
+ start_token TEXT NOT NULL,
121
+ deployment_id TEXT NOT NULL,
122
+ table_prefix TEXT NOT NULL,
123
+ workflow_id TEXT NOT NULL,
124
+ agent_id TEXT,
125
+ thread_id TEXT,
126
+ resource_id TEXT,
127
+ run_id TEXT NOT NULL,
128
+ step_path TEXT NOT NULL,
129
+ suspended_at INTEGER NOT NULL,
130
+ resume_count INTEGER NOT NULL,
131
+ request_json TEXT NOT NULL,
132
+ deadline_at INTEGER NOT NULL,
133
+ status TEXT NOT NULL,
134
+ permit_generation INTEGER NOT NULL DEFAULT 0,
135
+ permit_epoch INTEGER,
136
+ permit_revision INTEGER,
137
+ permit_expires_at INTEGER,
138
+ permit_consumed_at INTEGER,
139
+ permit_digest TEXT,
140
+ result_json TEXT,
141
+ result_digest TEXT,
142
+ quiescence_digest TEXT,
143
+ executor_quiescent_at INTEGER,
144
+ resume_lease_owner TEXT,
145
+ resume_lease_expires_at INTEGER,
146
+ settled_at INTEGER,
147
+ settlement_outcome TEXT,
148
+ target_kind TEXT NOT NULL CHECK (target_kind IN ('agent', 'workflow')),
149
+ suspension_marker TEXT NOT NULL,
150
+ request_digest TEXT,
151
+ write_revision INTEGER NOT NULL DEFAULT 0${version === 5
152
+ ? `,
153
+ write_generation INTEGER NOT NULL CHECK (write_generation > 0),
154
+ operation_key TEXT UNIQUE,
155
+ operation_id TEXT,
156
+ notification_id TEXT,
157
+ notification_request_json TEXT,
158
+ notification_projection_version TEXT,
159
+ notification_projection_json TEXT,
160
+ notification_request_digest TEXT,
161
+ operation_state TEXT CHECK (operation_state IN ('prepared', 'effect-admitted', 'receipt-recorded', 'resume-admitted', 'unresolved')),
162
+ effect_admitted_at INTEGER,
163
+ receipt_recorded_at INTEGER,
164
+ resume_admitted_at INTEGER,
165
+ CHECK ((operation_state IS NULL AND operation_key IS NULL AND operation_id IS NULL
166
+ AND notification_id IS NULL AND notification_request_json IS NULL
167
+ AND notification_projection_version IS NULL AND notification_projection_json IS NULL
168
+ AND notification_request_digest IS NULL AND effect_admitted_at IS NULL
169
+ AND receipt_recorded_at IS NULL AND resume_admitted_at IS NULL) OR
170
+ (target_kind = 'agent' AND operation_key IS NOT NULL AND operation_id IS NOT NULL
171
+ AND notification_id IS NOT NULL AND notification_request_json IS NOT NULL
172
+ AND notification_projection_version = 'notification-record-values-v1'
173
+ AND notification_projection_json IS NOT NULL AND notification_request_digest IS NOT NULL))`
174
+ : ''},
175
+ CHECK ((target_kind = 'agent' AND agent_id IS NOT NULL
176
+ AND thread_id IS NOT NULL AND resource_id IS NOT NULL
177
+ AND suspension_marker = '${REMOTE_STEP_MARKER}') OR
178
+ (target_kind = 'workflow' AND agent_id IS NULL
179
+ AND thread_id IS NULL AND resource_id IS NULL
180
+ AND suspension_marker = '${WORKFLOW_REMOTE_STEP_MARKER}'
181
+ AND request_digest IS NOT NULL))
182
+ )`;
183
+ }
184
+ function boundedJsonBytes(value) {
185
+ if (typeof value !== 'string' ||
186
+ new TextEncoder().encode(value).length > MAX_REMOTE_STEP_RESULT_BYTES)
187
+ throw new RemoteStepRefusal(400, 'remote step JSON exceeds its limit');
188
+ try {
189
+ JSON.parse(value);
190
+ }
191
+ catch {
192
+ throw new RemoteStepRefusal(400, 'remote step JSON is malformed');
193
+ }
194
+ }
195
+ function rawDispatchPermit() {
196
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
197
+ let binary = '';
198
+ for (const byte of bytes)
199
+ binary += String.fromCharCode(byte);
200
+ return btoa(binary)
201
+ .replace(/\+/g, '-')
202
+ .replace(/\//g, '_')
203
+ .replace(/=+$/, '');
204
+ }
205
+ async function sha256Hex(value) {
206
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
207
+ return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
208
+ }
209
+ const SNAPSHOT_EXECUTION_OPEN_SQL = `json_valid(snapshot)
210
+ AND json_type(snapshot, '$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}".transitionIntent') IS NULL
211
+ AND json_type(snapshot, '$.requestContext."${RUN_LIFECYCLE_CONTEXT_KEY}".terminal') IS NULL`;
212
+ class RemoteStepRefusal extends DoStatusError {
213
+ status;
214
+ constructor(status, message) {
215
+ super(message);
216
+ this.name = 'RemoteStepRefusal';
217
+ this.status = status;
218
+ }
219
+ }
220
+ function record(value) {
221
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
222
+ ? value
223
+ : undefined;
224
+ }
225
+ function positiveTime(value) {
226
+ return Number.isSafeInteger(value) && value > 0;
227
+ }
228
+ function rowResult(value) {
229
+ const rows = record(value)?.results;
230
+ return Array.isArray(rows) && rows.length === 1
231
+ ? rows[0]
232
+ : undefined;
233
+ }
234
+ function validLifecycle(row) {
235
+ return (Number.isSafeInteger(row.resume_count) &&
236
+ (row.resume_count === -1 || row.resume_count >= 1) &&
237
+ Number.isSafeInteger(row.permit_generation) &&
238
+ row.permit_generation >= 0 &&
239
+ [
240
+ 'pending',
241
+ 'dispatched',
242
+ 'result-retained',
243
+ 'resuming',
244
+ 'settled',
245
+ 'failed',
246
+ ].includes(row.status) &&
247
+ (row.settlement_outcome === null ||
248
+ [
249
+ 'applied',
250
+ 'terminal-not-success',
251
+ 'deadline-expired',
252
+ 'advanced-without-proof',
253
+ ].includes(row.settlement_outcome)) &&
254
+ (row.status !== 'resuming' ||
255
+ (isPathSafeId(row.resume_lease_owner) &&
256
+ positiveTime(row.resume_lease_expires_at) &&
257
+ row.result_json !== null)) &&
258
+ (row.status === 'resuming' ||
259
+ (row.resume_lease_owner === null &&
260
+ row.resume_lease_expires_at === null)) &&
261
+ (row.status !== 'settled' ||
262
+ (row.settlement_outcome === 'applied' &&
263
+ row.result_json !== null &&
264
+ row.result_digest !== null &&
265
+ positiveTime(row.executor_quiescent_at))) &&
266
+ (row.settlement_outcome === null ||
267
+ ((row.status === 'settled' || row.status === 'failed') &&
268
+ positiveTime(row.settled_at))));
269
+ }
270
+ function validPayloadBounds(row) {
271
+ return (typeof row.step_path === 'string' &&
272
+ row.step_path.length <= 1_024 &&
273
+ typeof row.request_json === 'string' &&
274
+ new TextEncoder().encode(row.request_json).length <=
275
+ MAX_REMOTE_STEP_REQUEST_BYTES);
276
+ }
277
+ function validStepPath(value) {
278
+ return (Array.isArray(value) &&
279
+ value.length > 0 &&
280
+ value.every((part) => typeof part === 'string' && part !== ''));
281
+ }
282
+ function decode(row) {
283
+ if (row.target_kind !== 'agent' ||
284
+ row.suspension_marker !== REMOTE_STEP_MARKER ||
285
+ (row.request_digest !== null && !SHA256_HEX.test(row.request_digest)) ||
286
+ !Number.isSafeInteger(row.write_revision) ||
287
+ row.write_revision < 0 ||
288
+ !positiveTime(row.write_generation) ||
289
+ !validPayloadBounds(row) ||
290
+ typeof row.principal_json !== 'string' ||
291
+ !isPathSafeId(row.deployment_id) ||
292
+ !isPathSafeId(row.workflow_id) ||
293
+ !isPathSafeId(row.agent_id) ||
294
+ !isPathSafeId(row.thread_id) ||
295
+ !isPathSafeId(row.resource_id) ||
296
+ !isPathSafeId(row.run_id) ||
297
+ !isPathSafeId(row.start_token))
298
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
299
+ try {
300
+ validateTablePrefix(row.table_prefix);
301
+ }
302
+ catch {
303
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
304
+ }
305
+ let stepPath;
306
+ let request;
307
+ let principal;
308
+ try {
309
+ stepPath = JSON.parse(row.step_path);
310
+ request = JSON.parse(row.request_json);
311
+ principal = assertExecutionPrincipal(JSON.parse(row.principal_json), 'stored remote step principal');
312
+ }
313
+ catch {
314
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
315
+ }
316
+ if (!validStepPath(stepPath) ||
317
+ !isPathSafeId(row.invocation_id) ||
318
+ !positiveTime(row.suspended_at) ||
319
+ !positiveTime(row.deadline_at) ||
320
+ !validLifecycle(row))
321
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
322
+ return {
323
+ invocationId: row.invocation_id,
324
+ principal,
325
+ startToken: row.start_token,
326
+ deploymentId: row.deployment_id,
327
+ tablePrefix: row.table_prefix,
328
+ workflowId: row.workflow_id,
329
+ agentId: row.agent_id,
330
+ threadId: row.thread_id,
331
+ resourceId: row.resource_id,
332
+ runId: row.run_id,
333
+ stepPath,
334
+ suspendedAt: row.suspended_at,
335
+ ...(row.resume_count < 0 ? {} : { resumeCount: row.resume_count }),
336
+ request,
337
+ deadlineAt: row.deadline_at,
338
+ status: row.status,
339
+ permitGeneration: row.permit_generation,
340
+ ...(row.permit_epoch === null ? {} : { permitEpoch: row.permit_epoch }),
341
+ ...(row.permit_revision === null
342
+ ? {}
343
+ : { permitRevision: row.permit_revision }),
344
+ ...(row.permit_expires_at === null
345
+ ? {}
346
+ : { permitExpiresAt: row.permit_expires_at }),
347
+ ...(row.permit_consumed_at === null
348
+ ? {}
349
+ : { permitConsumedAt: row.permit_consumed_at }),
350
+ ...(row.resume_lease_expires_at === null
351
+ ? {}
352
+ : { resumeLeaseExpiresAt: row.resume_lease_expires_at }),
353
+ ...(row.settlement_outcome === null
354
+ ? {}
355
+ : {
356
+ settlementOutcome: row.settlement_outcome,
357
+ }),
358
+ };
359
+ }
360
+ function decodeWorkflow(row) {
361
+ if (row.target_kind !== 'workflow' ||
362
+ row.suspension_marker !== WORKFLOW_REMOTE_STEP_MARKER ||
363
+ row.agent_id !== null ||
364
+ row.thread_id !== null ||
365
+ row.resource_id !== null ||
366
+ !isPathSafeId(row.invocation_id) ||
367
+ !isPathSafeId(row.deployment_id) ||
368
+ !isPathSafeId(row.workflow_id) ||
369
+ !isPathSafeId(row.run_id) ||
370
+ !isPathSafeId(row.start_token) ||
371
+ typeof row.request_digest !== 'string' ||
372
+ !SHA256_HEX.test(row.request_digest) ||
373
+ !Number.isSafeInteger(row.write_revision) ||
374
+ row.write_revision < 0 ||
375
+ !positiveTime(row.write_generation) ||
376
+ !positiveTime(row.suspended_at) ||
377
+ !positiveTime(row.deadline_at) ||
378
+ !validLifecycle(row) ||
379
+ !validPayloadBounds(row))
380
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
381
+ try {
382
+ validateTablePrefix(row.table_prefix);
383
+ const stepPath = JSON.parse(row.step_path);
384
+ const request = JSON.parse(row.request_json);
385
+ const principal = assertExecutionPrincipal(JSON.parse(row.principal_json), 'stored remote step principal');
386
+ if (!validStepPath(stepPath))
387
+ throw new Error('invalid workflow row');
388
+ return {
389
+ targetKind: 'workflow',
390
+ invocationId: row.invocation_id,
391
+ principal,
392
+ startToken: row.start_token,
393
+ deploymentId: row.deployment_id,
394
+ tablePrefix: row.table_prefix,
395
+ workflowId: row.workflow_id,
396
+ runId: row.run_id,
397
+ stepPath,
398
+ suspendedAt: row.suspended_at,
399
+ ...(row.resume_count < 0 ? {} : { resumeCount: row.resume_count }),
400
+ request,
401
+ requestDigest: row.request_digest,
402
+ deadlineAt: row.deadline_at,
403
+ status: row.status,
404
+ permitGeneration: row.permit_generation,
405
+ ...(row.permit_epoch === null ? {} : { permitEpoch: row.permit_epoch }),
406
+ ...(row.permit_revision === null
407
+ ? {}
408
+ : { permitRevision: row.permit_revision }),
409
+ ...(row.permit_expires_at === null
410
+ ? {}
411
+ : { permitExpiresAt: row.permit_expires_at }),
412
+ ...(row.permit_consumed_at === null
413
+ ? {}
414
+ : { permitConsumedAt: row.permit_consumed_at }),
415
+ ...(row.resume_lease_expires_at === null
416
+ ? {}
417
+ : { resumeLeaseExpiresAt: row.resume_lease_expires_at }),
418
+ ...(row.settlement_outcome === null
419
+ ? {}
420
+ : {
421
+ settlementOutcome: row.settlement_outcome,
422
+ }),
423
+ };
424
+ }
425
+ catch {
426
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
427
+ }
428
+ }
429
+ function decodeAny(row) {
430
+ if (row.target_kind === 'agent')
431
+ return decode(row);
432
+ if (row.target_kind === 'workflow')
433
+ return decodeWorkflow(row);
434
+ throw new RemoteStepRefusal(503, 'remote step journal is unreadable');
435
+ }
436
+ function decodeNotificationOperation(row) {
437
+ if (row.operation_state === null) {
438
+ if (row.operation_key !== null ||
439
+ row.operation_id !== null ||
440
+ row.notification_id !== null ||
441
+ row.notification_request_json !== null ||
442
+ row.notification_projection_version !== null ||
443
+ row.notification_projection_json !== null ||
444
+ row.notification_request_digest !== null ||
445
+ row.effect_admitted_at !== null ||
446
+ row.receipt_recorded_at !== null ||
447
+ row.resume_admitted_at !== null)
448
+ throw new RemoteStepRefusal(503, 'remote step operation is unreadable');
449
+ return undefined;
450
+ }
451
+ if (row.target_kind !== 'agent' ||
452
+ !isPathSafeId(row.operation_key) ||
453
+ !isPathSafeId(row.operation_id) ||
454
+ !isPathSafeId(row.notification_id) ||
455
+ typeof row.notification_request_json !== 'string' ||
456
+ typeof row.notification_projection_json !== 'string' ||
457
+ row.notification_projection_version !==
458
+ NOTIFICATION_OPERATION_PROJECTION_VERSION ||
459
+ typeof row.notification_request_digest !== 'string' ||
460
+ !SHA256_HEX.test(row.notification_request_digest) ||
461
+ ![
462
+ 'prepared',
463
+ 'effect-admitted',
464
+ 'receipt-recorded',
465
+ 'resume-admitted',
466
+ 'unresolved',
467
+ ].includes(row.operation_state) ||
468
+ new TextEncoder().encode(row.notification_request_json).length >
469
+ MAX_REMOTE_STEP_REQUEST_BYTES ||
470
+ new TextEncoder().encode(row.notification_projection_json).length >
471
+ MAX_REMOTE_STEP_REQUEST_BYTES ||
472
+ (row.operation_state === 'prepared' &&
473
+ (row.effect_admitted_at !== null ||
474
+ row.receipt_recorded_at !== null ||
475
+ row.resume_admitted_at !== null)) ||
476
+ (row.operation_state !== 'prepared' &&
477
+ !positiveTime(row.effect_admitted_at)) ||
478
+ (row.operation_state === 'effect-admitted' &&
479
+ (row.receipt_recorded_at !== null || row.resume_admitted_at !== null)) ||
480
+ (['receipt-recorded', 'resume-admitted'].includes(row.operation_state) &&
481
+ !positiveTime(row.receipt_recorded_at)) ||
482
+ (row.operation_state === 'receipt-recorded' &&
483
+ row.resume_admitted_at !== null) ||
484
+ (row.operation_state === 'resume-admitted' &&
485
+ !positiveTime(row.resume_admitted_at)))
486
+ throw new RemoteStepRefusal(503, 'remote step operation is unreadable');
487
+ try {
488
+ JSON.parse(row.notification_request_json);
489
+ JSON.parse(row.notification_projection_json);
490
+ }
491
+ catch {
492
+ throw new RemoteStepRefusal(503, 'remote step operation is unreadable');
493
+ }
494
+ return {
495
+ invocationId: row.invocation_id,
496
+ operationId: row.operation_id,
497
+ operationKey: row.operation_key,
498
+ notificationId: row.notification_id,
499
+ requestJson: row.notification_request_json,
500
+ projectionVersion: NOTIFICATION_OPERATION_PROJECTION_VERSION,
501
+ projectionJson: row.notification_projection_json,
502
+ requestDigest: row.notification_request_digest,
503
+ state: row.operation_state,
504
+ ...(row.effect_admitted_at === null
505
+ ? {}
506
+ : { effectAdmittedAt: row.effect_admitted_at }),
507
+ ...(row.receipt_recorded_at === null
508
+ ? {}
509
+ : { receiptRecordedAt: row.receipt_recorded_at }),
510
+ ...(row.resume_admitted_at === null
511
+ ? {}
512
+ : { resumeAdmittedAt: row.resume_admitted_at }),
513
+ };
514
+ }
515
+ function selectedSuspension(summary, allowedToolIds) {
516
+ if (summary.status !== 'suspended')
517
+ throw new RemoteStepRefusal(409, 'run is not suspended');
518
+ const payloads = record(summary.suspendPayload);
519
+ const matches = (summary.suspended ?? []).flatMap((path) => {
520
+ const key = path.join('.');
521
+ const suspended = record(payloads?.[key]);
522
+ const tool = record(suspended?.toolCallSuspended);
523
+ return suspended?.type === 'suspension' &&
524
+ tool?.remoteStep === REMOTE_STEP_MARKER
525
+ ? [{ stepPath: path, key, tool, suspended }]
526
+ : [];
527
+ });
528
+ if (matches.length !== 1)
529
+ throw new RemoteStepRefusal(409, 'remote step suspension is ambiguous');
530
+ const selected = matches[0];
531
+ if (!selected)
532
+ throw new RemoteStepRefusal(409, 'remote step suspension is ambiguous');
533
+ const { stepPath, key, tool, suspended } = selected;
534
+ const suspendedAt = summary.suspendedAt?.[key];
535
+ const resumeCount = summary.resumeCount?.[key];
536
+ if (!positiveTime(suspendedAt) ||
537
+ typeof suspended.toolName !== 'string' ||
538
+ !allowedToolIds.has(suspended.toolName) ||
539
+ typeof suspended.toolCallId !== 'string' ||
540
+ suspended.toolCallId === '' ||
541
+ (resumeCount !== undefined &&
542
+ (!Number.isSafeInteger(resumeCount) || resumeCount < 1)) ||
543
+ !Object.hasOwn(tool, 'request'))
544
+ throw new RemoteStepRefusal(503, 'remote step suspension is unreadable');
545
+ const requestJson = JSON.stringify(tool.request);
546
+ if (typeof requestJson !== 'string' ||
547
+ new TextEncoder().encode(requestJson).length > MAX_REMOTE_STEP_REQUEST_BYTES)
548
+ throw new RemoteStepRefusal(400, 'remote step request exceeds its limit');
549
+ return {
550
+ stepPath,
551
+ suspendedAt,
552
+ ...(resumeCount === undefined ? {} : { resumeCount }),
553
+ requestJson,
554
+ };
555
+ }
556
+ function selectedWorkflowSuspension(summary) {
557
+ if (summary.status !== 'suspended')
558
+ throw new RemoteStepRefusal(409, 'run is not suspended');
559
+ const payloads = record(summary.suspendPayload);
560
+ const matches = (summary.suspended ?? []).flatMap((path) => {
561
+ const key = path.join('.');
562
+ const suspended = record(payloads?.[key]);
563
+ const remoteStep = record(suspended?.remoteStep);
564
+ return suspended?.type === 'suspension' &&
565
+ remoteStep?.marker === WORKFLOW_REMOTE_STEP_MARKER
566
+ ? [{ path, key, remoteStep }]
567
+ : [];
568
+ });
569
+ if (matches.length !== 1)
570
+ throw new RemoteStepRefusal(409, 'remote step suspension is ambiguous');
571
+ const selected = matches[0];
572
+ if (!selected || !Object.hasOwn(selected.remoteStep, 'request'))
573
+ throw new RemoteStepRefusal(503, 'remote step suspension is unreadable');
574
+ const suspendedAt = summary.suspendedAt?.[selected.key];
575
+ const resumeCount = summary.resumeCount?.[selected.key];
576
+ const requestJson = JSON.stringify(selected.remoteStep.request);
577
+ if (!positiveTime(suspendedAt) ||
578
+ (resumeCount !== undefined &&
579
+ (!Number.isSafeInteger(resumeCount) || resumeCount < 1)) ||
580
+ typeof requestJson !== 'string' ||
581
+ new TextEncoder().encode(requestJson).length > MAX_REMOTE_STEP_REQUEST_BYTES)
582
+ throw new RemoteStepRefusal(503, 'remote step suspension is unreadable');
583
+ return {
584
+ stepPath: selected.path,
585
+ suspendedAt,
586
+ ...(resumeCount === undefined ? {} : { resumeCount }),
587
+ requestJson,
588
+ };
589
+ }
590
+ export class RemoteStepJournal {
591
+ #db;
592
+ #fence;
593
+ #runtime;
594
+ #now;
595
+ #deploymentId;
596
+ #tablePrefix;
597
+ #allowedToolIds;
598
+ #verifyCompletion;
599
+ #verifyWorkflowCompletion;
600
+ get deploymentId() {
601
+ return this.#deploymentId;
602
+ }
603
+ get tablePrefix() {
604
+ return this.#tablePrefix;
605
+ }
606
+ notificationStorage(operationReceiptLimit = DEFAULT_NOTIFICATION_OPERATION_RECEIPT_LIMIT) {
607
+ const db = this.#db;
608
+ if (typeof db.batch !== 'function')
609
+ throw new Error('notification operation requires database.batch()');
610
+ return new D1NotificationsStorage(db, this.#tablePrefix, operationReceiptLimit);
611
+ }
612
+ constructor(input) {
613
+ if (!input.fence.usesDatabase(input.db))
614
+ throw new Error('remote step fence uses another database');
615
+ if (!isPathSafeId(input.deploymentId))
616
+ throw new Error('remote step deployment id is malformed');
617
+ validateTablePrefix(input.tablePrefix);
618
+ if (!Array.isArray(input.allowedToolIds) ||
619
+ input.allowedToolIds.length === 0 ||
620
+ input.allowedToolIds.some((id) => !isPathSafeId(id)) ||
621
+ new Set(input.allowedToolIds).size !== input.allowedToolIds.length)
622
+ throw new Error('remote step tool ids are malformed');
623
+ if (typeof input.verifyCompletion !== 'function')
624
+ throw new Error('remote step completion verifier is required');
625
+ this.#db = input.db;
626
+ this.#fence = input.fence;
627
+ this.#runtime = input.runtime;
628
+ this.#deploymentId = input.deploymentId;
629
+ this.#tablePrefix = input.tablePrefix;
630
+ this.#allowedToolIds = new Set(input.allowedToolIds);
631
+ this.#verifyCompletion = input.verifyCompletion;
632
+ this.#verifyWorkflowCompletion = input.verifyWorkflowCompletion;
633
+ this.#now = input.now ?? Date.now;
634
+ }
635
+ async initialize() {
636
+ await this.#db.prepare(remoteStepTableSql(REMOTE_STEP_TABLE)).run();
637
+ await this.#db
638
+ .prepare(`CREATE TABLE IF NOT EXISTS ${REMOTE_STEP_SCHEMA_TABLE} (
639
+ id INTEGER PRIMARY KEY CHECK (id = 1),
640
+ version INTEGER NOT NULL
641
+ )`)
642
+ .run();
643
+ await this.#db
644
+ .prepare(REMOTE_STEP_NOTIFICATION_CURSOR_SQL.replace('CREATE TABLE ', 'CREATE TABLE IF NOT EXISTS '))
645
+ .run();
646
+ const readSchema = async () => {
647
+ const schema = await this.#db
648
+ .prepare(`PRAGMA table_xinfo(${REMOTE_STEP_TABLE})`)
649
+ .all();
650
+ const columns = record(schema)?.results;
651
+ if (!Array.isArray(columns))
652
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
653
+ const samePrefix = (expected, v4 = false, v5 = false) => columns.length === expected.length &&
654
+ columns.every((value, index) => {
655
+ const column = record(value);
656
+ const name = column?.name;
657
+ return (name === expected[index] &&
658
+ column?.type ===
659
+ (REMOTE_STEP_INTEGER_COLUMNS.has(name)
660
+ ? 'INTEGER'
661
+ : 'TEXT') &&
662
+ column?.notnull ===
663
+ ((index > 0 &&
664
+ index <= 16 &&
665
+ !(v4 && index >= 6 && index <= 8)) ||
666
+ ((v4 || v5) &&
667
+ ['target_kind', 'suspension_marker', 'write_revision'].includes(name)) ||
668
+ (v5 && name === 'write_generation')
669
+ ? 1
670
+ : 0) &&
671
+ column?.pk === (index === 0 ? 1 : 0) &&
672
+ column?.hidden === 0 &&
673
+ column?.dflt_value ===
674
+ (name === 'permit_generation' || name === 'write_revision'
675
+ ? '0'
676
+ : null));
677
+ });
678
+ const indexes = record(await this.#db.prepare(`PRAGMA index_list(${REMOTE_STEP_TABLE})`).all())?.results;
679
+ if (!Array.isArray(indexes))
680
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
681
+ const suspensionKey = [
682
+ 'deployment_id',
683
+ 'table_prefix',
684
+ 'workflow_id',
685
+ 'agent_id',
686
+ 'thread_id',
687
+ 'resource_id',
688
+ 'run_id',
689
+ 'step_path',
690
+ 'suspended_at',
691
+ 'resume_count',
692
+ ];
693
+ let uniqueSuspension = false;
694
+ for (const value of indexes) {
695
+ const indexRow = record(value);
696
+ const name = indexRow?.name;
697
+ if (indexRow?.unique !== 1 ||
698
+ indexRow?.origin !== 'u' ||
699
+ indexRow?.partial !== 0 ||
700
+ typeof name !== 'string' ||
701
+ !/^sqlite_autoindex_flowsafe_remote_step_invocations_[1-9][0-9]*$/.test(name))
702
+ continue;
703
+ const details = record(await this.#db.prepare(`PRAGMA index_info('${name}')`).all())?.results;
704
+ if (Array.isArray(details) &&
705
+ details.length === suspensionKey.length &&
706
+ details.every((part, index) => record(part)?.seqno === index &&
707
+ record(part)?.name === suspensionKey[index]))
708
+ uniqueSuspension = true;
709
+ }
710
+ const recoveryIndex = indexes.find((value) => record(value)?.name === REMOTE_STEP_RECOVERY_INDEX);
711
+ const recoveryDefinition = record(await this.#db
712
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
713
+ .bind('index', REMOTE_STEP_RECOVERY_INDEX)
714
+ .all())?.results;
715
+ const validRecoveryIndex = record(recoveryIndex)?.unique === 0 &&
716
+ record(recoveryIndex)?.origin === 'c' &&
717
+ record(recoveryIndex)?.partial === 1 &&
718
+ Array.isArray(recoveryDefinition) &&
719
+ recoveryDefinition.length === 1 &&
720
+ record(recoveryDefinition[0])?.sql === REMOTE_STEP_RECOVERY_INDEX_SQL;
721
+ const validV4Index = async (name, sql) => {
722
+ const entry = indexes.find((value) => record(value)?.name === name);
723
+ const definition = record(await this.#db
724
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
725
+ .bind('index', name)
726
+ .all())?.results;
727
+ return (record(entry)?.unique === 1 &&
728
+ record(entry)?.origin === 'c' &&
729
+ record(entry)?.partial === 1 &&
730
+ Array.isArray(definition) &&
731
+ definition.length === 1 &&
732
+ record(definition[0])?.sql === sql);
733
+ };
734
+ const validV4Table = async () => {
735
+ const tableDefinition = record(await this.#db
736
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
737
+ .bind('table', REMOTE_STEP_TABLE)
738
+ .all())?.results;
739
+ const tableSql = Array.isArray(tableDefinition) && tableDefinition.length === 1
740
+ ? record(tableDefinition[0])?.sql
741
+ : undefined;
742
+ return (typeof tableSql === 'string' &&
743
+ tableSql.includes("target_kind TEXT NOT NULL CHECK (target_kind IN ('agent', 'workflow'))") &&
744
+ tableSql.includes("CHECK ((target_kind = 'agent' AND agent_id IS NOT NULL") &&
745
+ tableSql.includes("(target_kind = 'workflow' AND agent_id IS NULL") &&
746
+ tableSql.includes('write_revision INTEGER NOT NULL DEFAULT 0'));
747
+ };
748
+ const validV4 = async () => {
749
+ const trigger = record(await this.#db
750
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
751
+ .bind('trigger', REMOTE_STEP_WRITE_TRIGGER)
752
+ .all())?.results;
753
+ return ((await validV4Table()) &&
754
+ validRecoveryIndex &&
755
+ (await validV4Index(REMOTE_STEP_AGENT_INDEX, REMOTE_STEP_AGENT_INDEX_SQL)) &&
756
+ (await validV4Index(REMOTE_STEP_WORKFLOW_INDEX, REMOTE_STEP_WORKFLOW_INDEX_SQL)) &&
757
+ Array.isArray(trigger) &&
758
+ trigger.length === 1 &&
759
+ record(trigger[0])?.sql === REMOTE_STEP_WRITE_TRIGGER_SQL);
760
+ };
761
+ const validV5 = async () => {
762
+ const tableDefinition = record(await this.#db
763
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
764
+ .bind('table', REMOTE_STEP_TABLE)
765
+ .all())?.results;
766
+ const tableSql = Array.isArray(tableDefinition)
767
+ ? record(tableDefinition[0])?.sql
768
+ : undefined;
769
+ const operationIndex = indexes.find((value) => record(value)?.name === REMOTE_STEP_OPERATION_INDEX);
770
+ const operationDefinition = record(await this.#db
771
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
772
+ .bind('index', REMOTE_STEP_OPERATION_INDEX)
773
+ .all())?.results;
774
+ const trigger = record(await this.#db
775
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
776
+ .bind('trigger', REMOTE_STEP_WRITE_TRIGGER)
777
+ .all())?.results;
778
+ return (typeof tableSql === 'string' &&
779
+ tableSql.includes('write_generation INTEGER NOT NULL CHECK (write_generation > 0)') &&
780
+ tableSql.includes('operation_key TEXT UNIQUE') &&
781
+ tableSql.includes("CHECK ((target_kind = 'agent' AND agent_id IS NOT NULL") &&
782
+ tableSql.includes("(target_kind = 'workflow' AND agent_id IS NULL") &&
783
+ tableSql.includes("operation_state TEXT CHECK (operation_state IN ('prepared', 'effect-admitted', 'receipt-recorded', 'resume-admitted', 'unresolved'))") &&
784
+ tableSql.includes('CHECK ((operation_state IS NULL AND operation_key IS NULL') &&
785
+ tableSql.includes("(target_kind = 'agent' AND operation_key IS NOT NULL") &&
786
+ validRecoveryIndex &&
787
+ (await validV4Index(REMOTE_STEP_AGENT_INDEX, REMOTE_STEP_AGENT_INDEX_SQL)) &&
788
+ (await validV4Index(REMOTE_STEP_WORKFLOW_INDEX, REMOTE_STEP_WORKFLOW_INDEX_SQL)) &&
789
+ record(operationIndex)?.unique === 0 &&
790
+ record(operationIndex)?.origin === 'c' &&
791
+ record(operationIndex)?.partial === 1 &&
792
+ Array.isArray(operationDefinition) &&
793
+ operationDefinition.length === 1 &&
794
+ record(operationDefinition[0])?.sql ===
795
+ REMOTE_STEP_OPERATION_INDEX_SQL &&
796
+ Array.isArray(trigger) &&
797
+ trigger.length === 1 &&
798
+ record(trigger[0])?.sql === REMOTE_STEP_V5_WRITE_TRIGGER_SQL);
799
+ };
800
+ const versions = await this.#db
801
+ .prepare(`SELECT id, version FROM ${REMOTE_STEP_SCHEMA_TABLE} LIMIT 2`)
802
+ .all();
803
+ const rows = record(versions)?.results;
804
+ if (!Array.isArray(rows) || rows.length > 1)
805
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
806
+ if (rows.length === 1) {
807
+ if (record(rows[0])?.id === 1 && record(rows[0])?.version === 5) {
808
+ if (!samePrefix(REMOTE_STEP_V5_COLUMNS, true, true) ||
809
+ !(await validV5()))
810
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
811
+ return 'current-v5';
812
+ }
813
+ if (record(rows[0])?.id === 1 && record(rows[0])?.version === 4) {
814
+ if (!samePrefix(REMOTE_STEP_COLUMNS, true) || !(await validV4()))
815
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
816
+ return 'current-v4';
817
+ }
818
+ if (record(rows[0])?.id !== 1 ||
819
+ (record(rows[0])?.version !== 3 && record(rows[0])?.version !== 2) ||
820
+ !uniqueSuspension ||
821
+ !samePrefix(record(rows[0])?.version === 3
822
+ ? REMOTE_STEP_COLUMNS.slice(0, -4)
823
+ : REMOTE_STEP_COLUMNS.slice(0, -8)) ||
824
+ (record(rows[0])?.version === 3 && !validRecoveryIndex))
825
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
826
+ return record(rows[0])?.version === 3 ? 'prior-v3' : 'prior-v2';
827
+ }
828
+ if (uniqueSuspension && samePrefix(REMOTE_STEP_COLUMNS.slice(0, -12)))
829
+ return 'prior-v1';
830
+ if (uniqueSuspension && samePrefix(REMOTE_STEP_COLUMNS.slice(0, -8)))
831
+ return 'unversioned-v2';
832
+ if (uniqueSuspension && samePrefix(REMOTE_STEP_COLUMNS.slice(0, -4)))
833
+ return 'unversioned-v3';
834
+ if (samePrefix(REMOTE_STEP_COLUMNS, true) && (await validV4Table()))
835
+ return 'unversioned-v4';
836
+ if (samePrefix(REMOTE_STEP_V5_COLUMNS, true, true)) {
837
+ const definition = record(await this.#db
838
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
839
+ .bind('table', REMOTE_STEP_TABLE)
840
+ .all())?.results;
841
+ const sql = Array.isArray(definition)
842
+ ? record(definition[0])?.sql
843
+ : undefined;
844
+ if (typeof sql === 'string' &&
845
+ sql.includes('write_generation INTEGER NOT NULL CHECK (write_generation > 0)') &&
846
+ sql.includes('operation_key TEXT UNIQUE') &&
847
+ sql.includes("operation_state TEXT CHECK (operation_state IN ('prepared', 'effect-admitted', 'receipt-recorded', 'resume-admitted', 'unresolved'))") &&
848
+ sql.includes('CHECK ((operation_state IS NULL AND operation_key IS NULL') &&
849
+ sql.includes("(target_kind = 'agent' AND operation_key IS NOT NULL") &&
850
+ sql.includes("CHECK ((target_kind = 'agent' AND agent_id IS NOT NULL") &&
851
+ sql.includes("(target_kind = 'workflow' AND agent_id IS NULL"))
852
+ return 'unversioned-v5';
853
+ }
854
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
855
+ };
856
+ const stage = await readSchema();
857
+ if (stage === 'current-v5')
858
+ return;
859
+ if (stage === 'prior-v1' ||
860
+ stage === 'prior-v2' ||
861
+ stage === 'unversioned-v2') {
862
+ const transactional = this.#db;
863
+ if (typeof transactional.batch !== 'function')
864
+ throw new RemoteStepRefusal(503, 'remote step schema upgrade is unavailable');
865
+ try {
866
+ await transactional.batch([
867
+ ...(stage === 'prior-v1' ? REMOTE_STEP_RESULT_COLUMNS : []).map((column) => this.#db.prepare(`ALTER TABLE ${REMOTE_STEP_TABLE} ADD COLUMN ${column} ${column === 'executor_quiescent_at' ? 'INTEGER' : 'TEXT'}`)),
868
+ ...REMOTE_STEP_SETTLEMENT_COLUMNS.map((column) => this.#db.prepare(`ALTER TABLE ${REMOTE_STEP_TABLE} ADD COLUMN ${column} ${REMOTE_STEP_INTEGER_COLUMNS.has(column) ? 'INTEGER' : 'TEXT'}`)),
869
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
870
+ this.#db.prepare(stage === 'prior-v2'
871
+ ? `UPDATE ${REMOTE_STEP_SCHEMA_TABLE} SET version = 3 WHERE id = 1 AND version = 2`
872
+ : `INSERT INTO ${REMOTE_STEP_SCHEMA_TABLE} (id, version) VALUES (1, 3)`),
873
+ ]);
874
+ }
875
+ catch (error) {
876
+ const current = await readSchema();
877
+ if (current !== 'prior-v3' &&
878
+ current !== 'current-v4' &&
879
+ current !== 'current-v5')
880
+ throw error;
881
+ }
882
+ return this.initialize();
883
+ }
884
+ const transactional = this.#db;
885
+ if (typeof transactional.batch !== 'function')
886
+ throw new RemoteStepRefusal(503, 'remote step schema upgrade is unavailable');
887
+ if (stage === 'unversioned-v3') {
888
+ try {
889
+ await transactional.batch([
890
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
891
+ this.#db.prepare(`INSERT INTO ${REMOTE_STEP_SCHEMA_TABLE} (id, version) VALUES (1, 3)`),
892
+ ]);
893
+ }
894
+ catch (error) {
895
+ if ((await readSchema()) !== 'prior-v3')
896
+ throw error;
897
+ }
898
+ return this.initialize();
899
+ }
900
+ if (stage === 'prior-v3') {
901
+ const replacement = `${REMOTE_STEP_TABLE}_v4`;
902
+ try {
903
+ await transactional.batch([
904
+ this.#db.prepare(remoteStepTableSql(replacement, 4)),
905
+ this.#db.prepare(`INSERT INTO ${replacement} (${REMOTE_STEP_COLUMNS.join(', ')})
906
+ SELECT ${REMOTE_STEP_COLUMNS.slice(0, -4).join(', ')}, 'agent', '${REMOTE_STEP_MARKER}', NULL, 0 FROM ${REMOTE_STEP_TABLE}`),
907
+ this.#db.prepare(`DROP TABLE ${REMOTE_STEP_TABLE}`),
908
+ this.#db.prepare(`ALTER TABLE ${replacement} RENAME TO ${REMOTE_STEP_TABLE}`),
909
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
910
+ this.#db.prepare(REMOTE_STEP_AGENT_INDEX_SQL),
911
+ this.#db.prepare(REMOTE_STEP_WORKFLOW_INDEX_SQL),
912
+ this.#db.prepare(REMOTE_STEP_WRITE_TRIGGER_SQL),
913
+ this.#db.prepare(`UPDATE ${REMOTE_STEP_SCHEMA_TABLE} SET version = 4 WHERE id = 1 AND version = 3`),
914
+ ]);
915
+ }
916
+ catch (error) {
917
+ if (!['current-v4', 'current-v5'].includes(await readSchema()))
918
+ throw error;
919
+ }
920
+ return this.initialize();
921
+ }
922
+ if (stage === 'unversioned-v4') {
923
+ try {
924
+ await transactional.batch([
925
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
926
+ this.#db.prepare(REMOTE_STEP_AGENT_INDEX_SQL),
927
+ this.#db.prepare(REMOTE_STEP_WORKFLOW_INDEX_SQL),
928
+ this.#db.prepare(REMOTE_STEP_WRITE_TRIGGER_SQL),
929
+ this.#db.prepare(`INSERT INTO ${REMOTE_STEP_SCHEMA_TABLE} (id, version) VALUES (1, 4)`),
930
+ ]);
931
+ }
932
+ catch (error) {
933
+ if (!['current-v4', 'current-v5'].includes(await readSchema()))
934
+ throw error;
935
+ }
936
+ return this.initialize();
937
+ }
938
+ if (stage === 'current-v4') {
939
+ const replacement = `${REMOTE_STEP_TABLE}_v5`;
940
+ try {
941
+ await transactional.batch([
942
+ this.#db.prepare(remoteStepTableSql(replacement)),
943
+ this.#db.prepare(`INSERT INTO ${replacement} (${REMOTE_STEP_V5_COLUMNS.join(', ')})
944
+ SELECT ${REMOTE_STEP_COLUMNS.join(', ')}, 1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
945
+ FROM ${REMOTE_STEP_TABLE}`),
946
+ this.#db.prepare(`DROP TABLE ${REMOTE_STEP_TABLE}`),
947
+ this.#db.prepare(`ALTER TABLE ${replacement} RENAME TO ${REMOTE_STEP_TABLE}`),
948
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
949
+ this.#db.prepare(REMOTE_STEP_AGENT_INDEX_SQL),
950
+ this.#db.prepare(REMOTE_STEP_WORKFLOW_INDEX_SQL),
951
+ this.#db.prepare(REMOTE_STEP_OPERATION_INDEX_SQL),
952
+ this.#db.prepare(REMOTE_STEP_V5_WRITE_TRIGGER_SQL),
953
+ this.#db.prepare(`UPDATE ${REMOTE_STEP_SCHEMA_TABLE} SET version = 5 WHERE id = 1 AND version = 4`),
954
+ ]);
955
+ }
956
+ catch (error) {
957
+ if ((await readSchema()) !== 'current-v5')
958
+ throw error;
959
+ }
960
+ return;
961
+ }
962
+ if (stage === 'unversioned-v5') {
963
+ try {
964
+ await transactional.batch([
965
+ this.#db.prepare(REMOTE_STEP_RECOVERY_INDEX_SQL),
966
+ this.#db.prepare(REMOTE_STEP_AGENT_INDEX_SQL),
967
+ this.#db.prepare(REMOTE_STEP_WORKFLOW_INDEX_SQL),
968
+ this.#db.prepare(REMOTE_STEP_OPERATION_INDEX_SQL),
969
+ this.#db.prepare(REMOTE_STEP_V5_WRITE_TRIGGER_SQL),
970
+ this.#db.prepare(`INSERT INTO ${REMOTE_STEP_SCHEMA_TABLE} (id, version) VALUES (1, 5)`),
971
+ ]);
972
+ }
973
+ catch (error) {
974
+ if ((await readSchema()) !== 'current-v5')
975
+ throw error;
976
+ }
977
+ return;
978
+ }
979
+ throw new RemoteStepRefusal(503, 'remote step schema is unreadable');
980
+ }
981
+ async #snapshot(address) {
982
+ const result = await this.#db
983
+ .prepare(`SELECT snapshot FROM "${address.tablePrefix}mastra_workflow_snapshot"
984
+ WHERE workflow_name = ? AND run_id = ? LIMIT 2`)
985
+ .bind(address.workflowId, address.runId)
986
+ .all();
987
+ const rows = record(result)?.results;
988
+ if (!Array.isArray(rows) ||
989
+ rows.length !== 1 ||
990
+ typeof record(rows[0])?.snapshot !== 'string')
991
+ throw new RemoteStepRefusal(503, 'remote step snapshot is unreadable');
992
+ return record(rows[0])?.snapshot;
993
+ }
994
+ async #current(address) {
995
+ const summary = await this.#runtime.authoritativeStatus(address.workflowId, address.runId);
996
+ if (!summary)
997
+ throw new RemoteStepRefusal(404, 'run not found');
998
+ return 'targetKind' in address
999
+ ? selectedWorkflowSuspension(summary)
1000
+ : selectedSuspension(summary, this.#allowedToolIds);
1001
+ }
1002
+ async #stableSnapshot(address) {
1003
+ const before = await this.#current(address);
1004
+ const snapshot = await this.#snapshot(address);
1005
+ const state = await this.#execution(address);
1006
+ const lifecycle = lifecycleFromRequestContext(state.snapshot.requestContext);
1007
+ if (lifecycle?.transitionIntent || lifecycle?.terminal)
1008
+ throw new RemoteStepRefusal(409, 'remote step run is ending');
1009
+ const after = await this.#current(address);
1010
+ if (before.suspendedAt !== after.suspendedAt ||
1011
+ before.resumeCount !== after.resumeCount ||
1012
+ JSON.stringify(before.stepPath) !== JSON.stringify(after.stepPath) ||
1013
+ before.requestJson !== after.requestJson)
1014
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1015
+ return { suspension: after, snapshot, state };
1016
+ }
1017
+ async register(address, hostDeadlineAt, originalPrincipal) {
1018
+ if (address.deploymentId !== this.#deploymentId ||
1019
+ address.tablePrefix !== this.#tablePrefix ||
1020
+ !isPathSafeId(address.workflowId) ||
1021
+ !isPathSafeId(address.agentId) ||
1022
+ !isPathSafeId(address.threadId) ||
1023
+ !isPathSafeId(address.resourceId) ||
1024
+ !isPathSafeId(address.runId) ||
1025
+ !positiveTime(hostDeadlineAt))
1026
+ throw new RemoteStepRefusal(400, 'remote step address is malformed');
1027
+ validateTablePrefix(address.tablePrefix);
1028
+ let principal;
1029
+ try {
1030
+ principal = assertExecutionPrincipal(originalPrincipal, 'remote step principal');
1031
+ }
1032
+ catch {
1033
+ throw new RemoteStepRefusal(400, 'remote step principal is malformed');
1034
+ }
1035
+ const execution = await this.#execution(address, principal);
1036
+ const { suspension, snapshot } = await this.#stableSnapshot(address);
1037
+ const summary = await this.#runtime.authoritativeStatus(address.workflowId, address.runId);
1038
+ const deadlineAt = Math.min(hostDeadlineAt, summary?.deadlineAt ?? hostDeadlineAt);
1039
+ if (deadlineAt <= this.#now())
1040
+ throw new RemoteStepRefusal(409, 'remote step deadline elapsed');
1041
+ const invocationId = crypto.randomUUID();
1042
+ const stepPath = JSON.stringify(suspension.stepPath);
1043
+ await this.#db
1044
+ .prepare(`INSERT INTO ${REMOTE_STEP_TABLE} (
1045
+ invocation_id, principal_json, start_token, deployment_id, table_prefix, workflow_id, agent_id,
1046
+ thread_id, resource_id, run_id, step_path, suspended_at, resume_count,
1047
+ request_json, deadline_at, status, target_kind, suspension_marker, write_generation)
1048
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'agent', '${REMOTE_STEP_MARKER}', 1
1049
+ WHERE EXISTS (SELECT 1 FROM "${address.tablePrefix}mastra_workflow_snapshot"
1050
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1051
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1052
+ ON CONFLICT DO NOTHING`)
1053
+ .bind(invocationId, JSON.stringify(principal), execution.execution.startToken, address.deploymentId, address.tablePrefix, address.workflowId, address.agentId, address.threadId, address.resourceId, address.runId, stepPath, suspension.suspendedAt, suspension.resumeCount ?? -1, suspension.requestJson, deadlineAt, address.workflowId, address.runId, snapshot)
1054
+ .run();
1055
+ const result = await this.#db
1056
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1057
+ SET deadline_at = MIN(deadline_at, ?), write_revision = write_revision + 1, write_generation = write_generation + 1
1058
+ WHERE deployment_id = ? AND table_prefix = ? AND workflow_id = ?
1059
+ AND agent_id = ? AND thread_id = ? AND resource_id = ? AND run_id = ?
1060
+ AND step_path = ? AND suspended_at = ? AND resume_count = ?
1061
+ AND request_json = ? AND principal_json = ? AND start_token = ?
1062
+ AND EXISTS (SELECT 1 FROM "${address.tablePrefix}mastra_workflow_snapshot"
1063
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1064
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1065
+ RETURNING *`)
1066
+ .bind(deadlineAt, address.deploymentId, address.tablePrefix, address.workflowId, address.agentId, address.threadId, address.resourceId, address.runId, stepPath, suspension.suspendedAt, suspension.resumeCount ?? -1, suspension.requestJson, JSON.stringify(principal), execution.execution.startToken, address.workflowId, address.runId, snapshot)
1067
+ .all();
1068
+ const row = rowResult(result);
1069
+ if (!row || row.request_json !== suspension.requestJson)
1070
+ throw new RemoteStepRefusal(409, 'remote step registration did not settle');
1071
+ return decode(row);
1072
+ }
1073
+ async registerWorkflow(address, hostDeadlineAt, originalPrincipal) {
1074
+ if (address.targetKind !== 'workflow' ||
1075
+ address.deploymentId !== this.#deploymentId ||
1076
+ address.tablePrefix !== this.#tablePrefix ||
1077
+ !isPathSafeId(address.workflowId) ||
1078
+ !isPathSafeId(address.runId) ||
1079
+ !positiveTime(hostDeadlineAt))
1080
+ throw new RemoteStepRefusal(400, 'remote step address is malformed');
1081
+ validateTablePrefix(address.tablePrefix);
1082
+ let principal;
1083
+ try {
1084
+ principal = assertExecutionPrincipal(originalPrincipal, 'remote step principal');
1085
+ }
1086
+ catch {
1087
+ throw new RemoteStepRefusal(400, 'remote step principal is malformed');
1088
+ }
1089
+ const execution = await this.#execution(address, principal);
1090
+ const { suspension, snapshot } = await this.#stableSnapshot(address);
1091
+ const summary = await this.#runtime.authoritativeStatus(address.workflowId, address.runId);
1092
+ const deadlineAt = Math.min(hostDeadlineAt, summary?.deadlineAt ?? hostDeadlineAt);
1093
+ if (deadlineAt <= this.#now())
1094
+ throw new RemoteStepRefusal(409, 'remote step deadline elapsed');
1095
+ const requestDigest = await sha256Hex(suspension.requestJson);
1096
+ const stepPath = JSON.stringify(suspension.stepPath);
1097
+ const invocationId = crypto.randomUUID();
1098
+ await this.#db
1099
+ .prepare(`INSERT INTO ${REMOTE_STEP_TABLE} (
1100
+ invocation_id, principal_json, start_token, deployment_id, table_prefix,
1101
+ workflow_id, run_id, step_path, suspended_at, resume_count, request_json,
1102
+ deadline_at, status, target_kind, suspension_marker, request_digest, write_generation)
1103
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'workflow',
1104
+ '${WORKFLOW_REMOTE_STEP_MARKER}', ?, 1
1105
+ WHERE EXISTS (SELECT 1 FROM "${address.tablePrefix}mastra_workflow_snapshot"
1106
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1107
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1108
+ ON CONFLICT DO NOTHING`)
1109
+ .bind(invocationId, JSON.stringify(principal), execution.execution.startToken, address.deploymentId, address.tablePrefix, address.workflowId, address.runId, stepPath, suspension.suspendedAt, suspension.resumeCount ?? -1, suspension.requestJson, deadlineAt, requestDigest, address.workflowId, address.runId, snapshot)
1110
+ .run();
1111
+ const row = rowResult(await this.#db
1112
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1113
+ SET deadline_at = MIN(deadline_at, ?), write_revision = write_revision + 1, write_generation = write_generation + 1
1114
+ WHERE target_kind = 'workflow' AND deployment_id = ?
1115
+ AND table_prefix = ? AND workflow_id = ? AND run_id = ?
1116
+ AND step_path = ? AND suspended_at = ? AND resume_count = ?
1117
+ AND request_json = ? AND request_digest = ?
1118
+ AND principal_json = ? AND start_token = ?
1119
+ AND EXISTS (SELECT 1 FROM "${address.tablePrefix}mastra_workflow_snapshot"
1120
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1121
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1122
+ RETURNING *`)
1123
+ .bind(deadlineAt, address.deploymentId, address.tablePrefix, address.workflowId, address.runId, stepPath, suspension.suspendedAt, suspension.resumeCount ?? -1, suspension.requestJson, requestDigest, JSON.stringify(principal), execution.execution.startToken, address.workflowId, address.runId, snapshot)
1124
+ .all());
1125
+ if (!row)
1126
+ throw new RemoteStepRefusal(409, 'remote step registration did not settle');
1127
+ return decodeWorkflow(row);
1128
+ }
1129
+ async get(invocationId) {
1130
+ const row = await this.#getRow(invocationId);
1131
+ return row?.target_kind === 'agent' ? decode(row) : undefined;
1132
+ }
1133
+ async getWorkflow(invocationId) {
1134
+ const row = await this.#getRow(invocationId);
1135
+ return row?.target_kind === 'workflow' ? decodeWorkflow(row) : undefined;
1136
+ }
1137
+ async #getRow(invocationId) {
1138
+ if (!isPathSafeId(invocationId))
1139
+ throw new RemoteStepRefusal(400, 'invocation id is malformed');
1140
+ const row = rowResult(await this.#db
1141
+ .prepare(`SELECT * FROM ${REMOTE_STEP_TABLE} WHERE invocation_id = ?`)
1142
+ .bind(invocationId)
1143
+ .all());
1144
+ return row;
1145
+ }
1146
+ async #getAny(invocationId) {
1147
+ const row = await this.#getRow(invocationId);
1148
+ return row ? decodeAny(row) : undefined;
1149
+ }
1150
+ async readDispatchRequestJson(invocationId) {
1151
+ return this.#readDispatchRequestJson(invocationId, 'agent');
1152
+ }
1153
+ async readWorkflowDispatchRequestJson(invocationId) {
1154
+ return this.#readDispatchRequestJson(invocationId, 'workflow');
1155
+ }
1156
+ async #readDispatchRequestJson(invocationId, targetKind) {
1157
+ if (!isPathSafeId(invocationId))
1158
+ throw new RemoteStepRefusal(400, 'invocation id is malformed');
1159
+ const row = rowResult(await this.#db
1160
+ .prepare(`SELECT * FROM ${REMOTE_STEP_TABLE} WHERE invocation_id = ?`)
1161
+ .bind(invocationId)
1162
+ .all());
1163
+ if (!row)
1164
+ throw new RemoteStepRefusal(404, 'invocation not found');
1165
+ if (row.target_kind !== targetKind)
1166
+ throw new RemoteStepRefusal(404, 'invocation not found');
1167
+ decodeAny(row);
1168
+ return row.request_json;
1169
+ }
1170
+ async #execution(address, principal) {
1171
+ const state = await this.#runtime.authoritativeStartState(address.workflowId, address.runId);
1172
+ const target = state?.provenance.startIdentity?.target;
1173
+ if (state?.storage !== 'd1' || !target)
1174
+ throw new RemoteStepRefusal(503, 'remote step run identity is unreadable');
1175
+ if ((principal !== undefined &&
1176
+ (state.provenance.startIdentity?.owner.kind !== principal.kind ||
1177
+ state.provenance.startIdentity.owner.id !== principal.id)) ||
1178
+ state.execution.tablePrefix !== address.tablePrefix ||
1179
+ state.execution.workflowId !== address.workflowId ||
1180
+ state.execution.runId !== address.runId)
1181
+ throw new RemoteStepRefusal(409, 'remote step run identity changed');
1182
+ if ('targetKind' in address) {
1183
+ if (target.kind !== 'workflow' ||
1184
+ target.id !== address.workflowId ||
1185
+ state.provenance.agentStart !== undefined)
1186
+ throw new RemoteStepRefusal(409, 'remote step run identity changed');
1187
+ }
1188
+ else if (target.kind !== 'agent' || !isPathSafeId(target.resourceId)) {
1189
+ throw new RemoteStepRefusal(503, 'remote step run identity is unreadable');
1190
+ }
1191
+ else if (target.id !== address.agentId ||
1192
+ target.threadId !== address.threadId ||
1193
+ address.resourceId !== target.resourceId)
1194
+ throw new RemoteStepRefusal(409, 'remote step run identity changed');
1195
+ return state;
1196
+ }
1197
+ async #admission(invocation, priorBindings) {
1198
+ const observed = await this.#fence.readForAdmission();
1199
+ const proof = (await this.#execution(invocation, invocation.principal))
1200
+ .execution;
1201
+ if (proof.startToken !== invocation.startToken)
1202
+ throw new RemoteStepRefusal(409, 'remote step run generation changed');
1203
+ if (!admitsExistingRun(observed.reading, proof))
1204
+ throw new RemoteStepRefusal(503, 'remote step execution is fenced');
1205
+ const schema = await captureExecutionFenceAdmissionSchema(await this.#db
1206
+ .prepare(`PRAGMA table_xinfo(${EXECUTION_FENCE_TABLE})`)
1207
+ .all());
1208
+ const values = [];
1209
+ const bind = (value) => {
1210
+ values.push(value);
1211
+ return `?${priorBindings + values.length}`;
1212
+ };
1213
+ const predicate = executionFenceAdmissionSql({
1214
+ callerEpoch: bind(observed.reading.mutationEpoch ?? null),
1215
+ semantic: executionFenceAdmissionValues(observed).map(bind),
1216
+ schema: bind(schema),
1217
+ statePredicate: `f.state IN ('open', 'draining') OR
1218
+ (f.state = 'proof-only' AND f.proof_table_prefix IS ${bind(proof.tablePrefix)}
1219
+ AND f.proof_workflow_id IS ${bind(proof.workflowId)}
1220
+ AND f.proof_run_id IS ${bind(proof.runId)}
1221
+ AND f.proof_start_token IS ${bind(proof.startToken)})`,
1222
+ });
1223
+ return { predicate, values, bind, observed: observed.reading };
1224
+ }
1225
+ async issuePermit(invocationId, lifetimeMs) {
1226
+ const invocation = await this.#getAny(invocationId);
1227
+ if (!invocation)
1228
+ throw new RemoteStepRefusal(404, 'invocation not found');
1229
+ if ('targetKind' in invocation && !this.#verifyWorkflowCompletion)
1230
+ throw new RemoteStepRefusal(503, 'workflow remote step completion is unavailable');
1231
+ if (!positiveTime(lifetimeMs))
1232
+ throw new RemoteStepRefusal(400, 'permit lifetime is malformed');
1233
+ const now = this.#now();
1234
+ const expiresAt = Math.min(invocation.deadlineAt, now + lifetimeMs);
1235
+ if (!positiveTime(expiresAt) || expiresAt <= now)
1236
+ throw new RemoteStepRefusal(409, 'remote step deadline elapsed');
1237
+ const address = invocation;
1238
+ const { suspension, snapshot } = await this.#stableSnapshot(address);
1239
+ if (suspension.suspendedAt !== invocation.suspendedAt ||
1240
+ suspension.resumeCount !== invocation.resumeCount ||
1241
+ suspension.requestJson !== JSON.stringify(invocation.request) ||
1242
+ JSON.stringify(suspension.stepPath) !==
1243
+ JSON.stringify(invocation.stepPath) ||
1244
+ ('targetKind' in invocation &&
1245
+ (await sha256Hex(suspension.requestJson)) !== invocation.requestDigest))
1246
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1247
+ const gate = await this.#admission(invocation, 13);
1248
+ if (invocation.status === 'dispatched' &&
1249
+ invocation.permitConsumedAt === undefined &&
1250
+ invocation.permitExpiresAt !== undefined &&
1251
+ invocation.permitExpiresAt > now &&
1252
+ invocation.permitEpoch === gate.observed.mutationEpoch &&
1253
+ invocation.permitRevision === gate.observed.transitionRevision)
1254
+ return {
1255
+ invocationId,
1256
+ generation: invocation.permitGeneration,
1257
+ mutationEpoch: invocation.permitEpoch,
1258
+ transitionRevision: invocation.permitRevision,
1259
+ expiresAt: invocation.permitExpiresAt,
1260
+ };
1261
+ if (invocation.status === 'failed' ||
1262
+ invocation.permitConsumedAt !== undefined)
1263
+ throw new RemoteStepRefusal(409, 'remote step dispatch is active');
1264
+ const epoch = gate.observed.mutationEpoch;
1265
+ const revision = gate.observed.transitionRevision;
1266
+ if (epoch === undefined || revision === undefined)
1267
+ throw new RemoteStepRefusal(503, 'remote step fence is unversioned');
1268
+ const result = await this.#db
1269
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE} SET
1270
+ status = 'dispatched', permit_generation = permit_generation + 1,
1271
+ permit_epoch = ?, permit_revision = ?,
1272
+ permit_expires_at = MIN(?, deadline_at), permit_consumed_at = NULL,
1273
+ permit_digest = NULL, write_revision = write_revision + 1, write_generation = write_generation + 1
1274
+ WHERE invocation_id = ? AND permit_generation = ? AND deadline_at > ?
1275
+ AND status IN ('pending', 'dispatched')
1276
+ AND permit_consumed_at IS NULL AND request_json = ?
1277
+ AND target_kind = ? AND suspension_marker = ?
1278
+ AND request_digest IS ?
1279
+ AND EXISTS (SELECT 1 FROM "${address.tablePrefix}mastra_workflow_snapshot"
1280
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1281
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1282
+ AND ${gate.predicate} RETURNING *`)
1283
+ .bind(epoch, revision, expiresAt, invocationId, invocation.permitGeneration, now, suspension.requestJson, 'targetKind' in invocation ? 'workflow' : 'agent', 'targetKind' in invocation
1284
+ ? WORKFLOW_REMOTE_STEP_MARKER
1285
+ : REMOTE_STEP_MARKER, 'targetKind' in invocation ? invocation.requestDigest : null, invocation.workflowId, invocation.runId, snapshot, ...gate.values)
1286
+ .all();
1287
+ const row = rowResult(result);
1288
+ if (!row)
1289
+ throw new RemoteStepRefusal(409, 'remote step dispatch changed');
1290
+ return {
1291
+ invocationId,
1292
+ generation: row.permit_generation,
1293
+ mutationEpoch: epoch,
1294
+ transitionRevision: revision,
1295
+ expiresAt: row.permit_expires_at,
1296
+ };
1297
+ }
1298
+ async consumePermit(permit) {
1299
+ const invocation = await this.#getAny(permit.invocationId);
1300
+ if (!invocation)
1301
+ throw new RemoteStepRefusal(404, 'invocation not found');
1302
+ if ('targetKind' in invocation && !this.#verifyWorkflowCompletion)
1303
+ throw new RemoteStepRefusal(503, 'workflow remote step completion is unavailable');
1304
+ if (invocation.permitGeneration !== permit.generation ||
1305
+ invocation.permitEpoch !== permit.mutationEpoch ||
1306
+ invocation.permitRevision !== permit.transitionRevision ||
1307
+ invocation.permitExpiresAt !== permit.expiresAt)
1308
+ throw new RemoteStepRefusal(409, 'remote step permit changed');
1309
+ if (invocation.permitConsumedAt !== undefined)
1310
+ return { kind: 'already-consumed' };
1311
+ const now = this.#now();
1312
+ const { suspension, snapshot } = await this.#stableSnapshot(invocation);
1313
+ if (suspension.suspendedAt !== invocation.suspendedAt ||
1314
+ suspension.resumeCount !== invocation.resumeCount ||
1315
+ suspension.requestJson !== JSON.stringify(invocation.request) ||
1316
+ JSON.stringify(suspension.stepPath) !==
1317
+ JSON.stringify(invocation.stepPath) ||
1318
+ ('targetKind' in invocation &&
1319
+ (await sha256Hex(suspension.requestJson)) !== invocation.requestDigest))
1320
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1321
+ const rawPermit = rawDispatchPermit();
1322
+ const permitDigest = await sha256Hex(rawPermit);
1323
+ const gate = await this.#admission(invocation, 16);
1324
+ const result = await this.#db
1325
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1326
+ SET permit_consumed_at = ?, permit_digest = ?, write_revision = write_revision + 1, write_generation = write_generation + 1
1327
+ WHERE invocation_id = ? AND permit_generation = ?
1328
+ AND permit_epoch = ? AND permit_revision = ?
1329
+ AND permit_expires_at = ? AND permit_expires_at > ?
1330
+ AND deadline_at > ? AND permit_consumed_at IS NULL
1331
+ AND status = 'dispatched' AND request_json = ?
1332
+ AND target_kind = ? AND suspension_marker = ?
1333
+ AND request_digest IS ?
1334
+ AND EXISTS (SELECT 1 FROM "${invocation.tablePrefix}mastra_workflow_snapshot"
1335
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1336
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1337
+ AND ${gate.predicate} RETURNING invocation_id`)
1338
+ .bind(now, permitDigest, permit.invocationId, permit.generation, permit.mutationEpoch, permit.transitionRevision, permit.expiresAt, now, now, suspension.requestJson, 'targetKind' in invocation ? 'workflow' : 'agent', 'targetKind' in invocation
1339
+ ? WORKFLOW_REMOTE_STEP_MARKER
1340
+ : REMOTE_STEP_MARKER, 'targetKind' in invocation ? invocation.requestDigest : null, invocation.workflowId, invocation.runId, snapshot, ...gate.values)
1341
+ .all();
1342
+ if (rowResult(result))
1343
+ return { kind: 'accepted', rawPermit };
1344
+ const after = await this.#getAny(permit.invocationId);
1345
+ if (after?.permitGeneration === permit.generation &&
1346
+ after.permitConsumedAt !== undefined)
1347
+ return { kind: 'already-consumed' };
1348
+ throw new RemoteStepRefusal(409, 'remote step permit is unavailable');
1349
+ }
1350
+ async recordResult(invocationId, rawPermit, resultJson, evidenceJson) {
1351
+ if (!isPathSafeId(invocationId) || !RAW_PERMIT.test(rawPermit))
1352
+ throw new RemoteStepRefusal(400, 'remote step result identity is malformed');
1353
+ boundedJsonBytes(resultJson);
1354
+ boundedJsonBytes(evidenceJson);
1355
+ const stored = rowResult(await this.#db
1356
+ .prepare(`SELECT * FROM ${REMOTE_STEP_TABLE} WHERE invocation_id = ?`)
1357
+ .bind(invocationId)
1358
+ .all());
1359
+ if (!stored)
1360
+ throw new RemoteStepRefusal(404, 'invocation not found');
1361
+ const invocation = decodeAny(stored);
1362
+ const permitDigest = stored.permit_digest;
1363
+ if (typeof permitDigest !== 'string' ||
1364
+ !SHA256_HEX.test(permitDigest) ||
1365
+ invocation.permitConsumedAt === undefined)
1366
+ throw new RemoteStepRefusal(409, 'remote step permit was not consumed');
1367
+ const presentedDigest = await sha256Hex(rawPermit);
1368
+ if (!(await credentialsMatch(presentedDigest, permitDigest)))
1369
+ throw new RemoteStepRefusal(403, 'remote step permit is invalid');
1370
+ const resultDigest = await sha256Hex(resultJson);
1371
+ const quiescenceDigest = await sha256Hex(evidenceJson);
1372
+ const replay = (row) => {
1373
+ if (row.result_json !== resultJson ||
1374
+ row.result_digest !== resultDigest ||
1375
+ row.quiescence_digest !== quiescenceDigest ||
1376
+ !positiveTime(row.executor_quiescent_at))
1377
+ throw new RemoteStepRefusal(409, 'remote step result conflicts');
1378
+ return { kind: 'replay', resultJson, resultDigest };
1379
+ };
1380
+ if (stored.result_json !== null)
1381
+ return replay(stored);
1382
+ if ('targetKind' in invocation) {
1383
+ if (!this.#verifyWorkflowCompletion)
1384
+ throw new RemoteStepRefusal(503, 'workflow remote step completion is unavailable');
1385
+ await this.#verifyWorkflowCompletion({
1386
+ invocation,
1387
+ rawPermit,
1388
+ resultJson,
1389
+ evidenceJson,
1390
+ });
1391
+ }
1392
+ else {
1393
+ await this.#verifyCompletion({
1394
+ invocation,
1395
+ rawPermit,
1396
+ resultJson,
1397
+ evidenceJson,
1398
+ });
1399
+ }
1400
+ const result = await this.#db
1401
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1402
+ SET result_json = ?, result_digest = ?, quiescence_digest = ?,
1403
+ executor_quiescent_at = ?, status = 'result-retained',
1404
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1405
+ WHERE invocation_id = ? AND permit_digest = ?
1406
+ AND permit_consumed_at IS NOT NULL AND result_json IS NULL
1407
+ AND status = 'dispatched'
1408
+ RETURNING *`)
1409
+ .bind(resultJson, resultDigest, quiescenceDigest, this.#now(), invocationId, permitDigest)
1410
+ .all();
1411
+ if (rowResult(result))
1412
+ return { kind: 'recorded', resultJson, resultDigest };
1413
+ const after = rowResult(await this.#db
1414
+ .prepare(`SELECT * FROM ${REMOTE_STEP_TABLE} WHERE invocation_id = ?`)
1415
+ .bind(invocationId)
1416
+ .all());
1417
+ if (!after)
1418
+ throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1419
+ return replay(after);
1420
+ }
1421
+ async readRetainedResult(invocationId) {
1422
+ const row = await this.#getRow(invocationId);
1423
+ if (!row)
1424
+ return undefined;
1425
+ decodeAny(row);
1426
+ return this.#retainedResultFromRow(row);
1427
+ }
1428
+ async #retainedResultFromRow(row) {
1429
+ const resultJson = row.result_json;
1430
+ const resultDigest = row.result_digest;
1431
+ const quiescenceDigest = row.quiescence_digest;
1432
+ const executorQuiescentAt = row.executor_quiescent_at;
1433
+ if (resultJson === null)
1434
+ return undefined;
1435
+ if (row.status === 'settled' || row.status === 'failed')
1436
+ return undefined;
1437
+ if (!['result-retained', 'resuming'].includes(row.status) ||
1438
+ row.permit_consumed_at === null ||
1439
+ typeof resultDigest !== 'string' ||
1440
+ !SHA256_HEX.test(resultDigest) ||
1441
+ typeof quiescenceDigest !== 'string' ||
1442
+ !SHA256_HEX.test(quiescenceDigest) ||
1443
+ !positiveTime(executorQuiescentAt))
1444
+ throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1445
+ try {
1446
+ boundedJsonBytes(resultJson);
1447
+ }
1448
+ catch {
1449
+ throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1450
+ }
1451
+ if ((await sha256Hex(resultJson)) !== resultDigest)
1452
+ throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1453
+ return {
1454
+ invocationId: row.invocation_id,
1455
+ resultJson,
1456
+ resultDigest,
1457
+ quiescenceDigest,
1458
+ executorQuiescentAt,
1459
+ };
1460
+ }
1461
+ async readNotificationOperation(invocationId) {
1462
+ const row = await this.#getRow(invocationId);
1463
+ if (!row)
1464
+ return undefined;
1465
+ decodeAny(row);
1466
+ return this.#notificationOperationFromRow(row);
1467
+ }
1468
+ async #notificationOperationFromRow(row) {
1469
+ const operation = decodeNotificationOperation(row);
1470
+ if (operation &&
1471
+ (await sha256Hex(operation.projectionJson)) !== operation.requestDigest)
1472
+ throw new RemoteStepRefusal(503, 'remote step operation is unreadable');
1473
+ return operation;
1474
+ }
1475
+ async prepareNotificationOperation(invocationId, operationId, input) {
1476
+ if (!isPathSafeId(operationId))
1477
+ throw new RemoteStepRefusal(400, 'remote step operation id is malformed');
1478
+ const stored = await this.#getRow(invocationId);
1479
+ const invocation = stored?.target_kind === 'agent' ? decode(stored) : undefined;
1480
+ if (stored && !invocation)
1481
+ decodeAny(stored);
1482
+ const retained = stored
1483
+ ? await this.#retainedResultFromRow(stored)
1484
+ : undefined;
1485
+ if (!stored ||
1486
+ !invocation ||
1487
+ invocation.status !== 'result-retained' ||
1488
+ !retained)
1489
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1490
+ const operationKey = await sha256Hex(JSON.stringify([
1491
+ invocation.deploymentId,
1492
+ invocation.invocationId,
1493
+ invocation.startToken,
1494
+ invocation.stepPath,
1495
+ invocation.suspendedAt,
1496
+ invocation.resumeCount ?? -1,
1497
+ operationId,
1498
+ ]));
1499
+ const notificationId = operationKey;
1500
+ const request = { ...input, id: notificationId };
1501
+ const projection = await projectNotificationOperation(request);
1502
+ const requestJson = JSON.stringify(request);
1503
+ if (new TextEncoder().encode(requestJson).length >
1504
+ MAX_REMOTE_STEP_REQUEST_BYTES ||
1505
+ new TextEncoder().encode(projection.requestJson).length >
1506
+ MAX_REMOTE_STEP_REQUEST_BYTES)
1507
+ throw new RemoteStepRefusal(400, 'remote step operation exceeds its limit');
1508
+ const existing = await this.#notificationOperationFromRow(stored);
1509
+ if (existing) {
1510
+ if (existing.operationKey !== operationKey ||
1511
+ existing.requestJson !== requestJson ||
1512
+ existing.projectionJson !== projection.requestJson ||
1513
+ existing.requestDigest !== projection.requestDigest)
1514
+ throw new RemoteStepRefusal(409, 'remote step operation changed');
1515
+ return existing;
1516
+ }
1517
+ const result = rowResult(await this.#db
1518
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1519
+ SET operation_key = ?, operation_id = ?, notification_id = ?,
1520
+ notification_request_json = ?, notification_projection_version = ?,
1521
+ notification_projection_json = ?, notification_request_digest = ?,
1522
+ operation_state = 'prepared',
1523
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1524
+ WHERE invocation_id = ? AND target_kind = 'agent'
1525
+ AND status = 'result-retained' AND operation_state IS NULL
1526
+ AND principal_json = ? AND start_token = ? AND result_digest = ?
1527
+ AND write_revision = ? AND write_generation = ?
1528
+ RETURNING *`)
1529
+ .bind(operationKey, operationId, notificationId, requestJson, projection.version, projection.requestJson, projection.requestDigest, invocationId, JSON.stringify(invocation.principal), invocation.startToken, retained.resultDigest, stored.write_revision, stored.write_generation)
1530
+ .all());
1531
+ if (result)
1532
+ return decodeNotificationOperation(result);
1533
+ const after = await this.readNotificationOperation(invocationId);
1534
+ if (after?.operationKey === operationKey &&
1535
+ after.requestDigest === projection.requestDigest)
1536
+ return after;
1537
+ throw new RemoteStepRefusal(409, 'remote step operation changed');
1538
+ }
1539
+ async admitNotificationEffect(invocationId) {
1540
+ const stored = await this.#getRow(invocationId);
1541
+ if (!stored)
1542
+ throw new RemoteStepRefusal(404, 'invocation not found');
1543
+ const invocation = decode(stored);
1544
+ const operation = await this.#notificationOperationFromRow(stored);
1545
+ if (!operation ||
1546
+ !['prepared', 'effect-admitted'].includes(operation.state))
1547
+ throw new RemoteStepRefusal(409, 'remote step operation is unavailable');
1548
+ if (operation.state === 'effect-admitted')
1549
+ return operation;
1550
+ const retained = await this.#retainedResultFromRow(stored);
1551
+ if (!retained || invocation.status !== 'result-retained')
1552
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1553
+ const { suspension, snapshot } = await this.#stableSnapshot(invocation);
1554
+ if (suspension.suspendedAt !== invocation.suspendedAt ||
1555
+ suspension.resumeCount !== invocation.resumeCount ||
1556
+ suspension.requestJson !== JSON.stringify(invocation.request) ||
1557
+ JSON.stringify(suspension.stepPath) !==
1558
+ JSON.stringify(invocation.stepPath))
1559
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1560
+ const now = this.#now();
1561
+ const base = [
1562
+ now,
1563
+ invocationId,
1564
+ invocation.deploymentId,
1565
+ invocation.tablePrefix,
1566
+ invocation.workflowId,
1567
+ invocation.agentId,
1568
+ invocation.threadId,
1569
+ invocation.resourceId,
1570
+ invocation.runId,
1571
+ invocation.startToken,
1572
+ JSON.stringify(invocation.principal),
1573
+ retained.resultDigest,
1574
+ operation.operationKey,
1575
+ operation.requestDigest,
1576
+ stored.write_revision,
1577
+ stored.write_generation,
1578
+ now,
1579
+ invocation.workflowId,
1580
+ invocation.runId,
1581
+ snapshot,
1582
+ ];
1583
+ const gate = await this.#admission(invocation, base.length);
1584
+ try {
1585
+ const row = rowResult(await this.#db
1586
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1587
+ SET operation_state = 'effect-admitted', effect_admitted_at = ?,
1588
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1589
+ WHERE invocation_id = ? AND deployment_id = ? AND table_prefix = ?
1590
+ AND workflow_id = ? AND agent_id = ? AND thread_id = ?
1591
+ AND resource_id = ? AND run_id = ? AND start_token = ?
1592
+ AND principal_json = ? AND result_digest = ?
1593
+ AND operation_key = ? AND notification_request_digest = ?
1594
+ AND write_revision = ? AND write_generation = ? AND deadline_at > ?
1595
+ AND target_kind = 'agent' AND status = 'result-retained'
1596
+ AND operation_state = 'prepared'
1597
+ AND EXISTS (SELECT 1 FROM "${invocation.tablePrefix}mastra_workflow_snapshot"
1598
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1599
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1600
+ AND ${gate.predicate} RETURNING *`)
1601
+ .bind(...base, ...gate.values)
1602
+ .all());
1603
+ if (row)
1604
+ return decodeNotificationOperation(row);
1605
+ }
1606
+ catch (error) {
1607
+ const after = await this.readNotificationOperation(invocationId);
1608
+ if (after?.state === 'effect-admitted' &&
1609
+ after.operationKey === operation.operationKey &&
1610
+ after.requestDigest === operation.requestDigest)
1611
+ return after;
1612
+ throw error;
1613
+ }
1614
+ const after = await this.readNotificationOperation(invocationId);
1615
+ if (after?.state === 'effect-admitted' &&
1616
+ after.operationKey === operation.operationKey &&
1617
+ after.requestDigest === operation.requestDigest)
1618
+ return after;
1619
+ throw new RemoteStepRefusal(409, 'remote step effect admission changed');
1620
+ }
1621
+ async recordNotificationReceipt(invocationId, receipt) {
1622
+ const stored = await this.#getRow(invocationId);
1623
+ if (!stored)
1624
+ throw new RemoteStepRefusal(404, 'invocation not found');
1625
+ decode(stored);
1626
+ const operation = await this.#notificationOperationFromRow(stored);
1627
+ if (operation?.state !== 'effect-admitted' ||
1628
+ receipt.operationKey !== operation.operationKey ||
1629
+ receipt.notificationId !== operation.notificationId ||
1630
+ receipt.threadId !== stored.thread_id ||
1631
+ receipt.requestDigest !== operation.requestDigest)
1632
+ throw new RemoteStepRefusal(409, 'remote step notification receipt changed');
1633
+ const row = rowResult(await this.#db
1634
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1635
+ SET operation_state = 'receipt-recorded', receipt_recorded_at = ?,
1636
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1637
+ WHERE invocation_id = ? AND status = 'result-retained'
1638
+ AND operation_state = 'effect-admitted' AND operation_key = ?
1639
+ AND notification_id = ? AND notification_request_digest = ?
1640
+ AND result_digest = ? AND write_revision = ? AND write_generation = ?
1641
+ AND EXISTS (SELECT 1 FROM "${stored.table_prefix}${NOTIFICATION_OPERATION_RECEIPTS_TABLE}"
1642
+ WHERE operation_key = ? AND request_digest = ?
1643
+ AND thread_id = ? AND notification_id = ?)
1644
+ RETURNING *`)
1645
+ .bind(this.#now(), invocationId, operation.operationKey, operation.notificationId, operation.requestDigest, stored.result_digest, stored.write_revision, stored.write_generation, operation.operationKey, operation.requestDigest, stored.thread_id, operation.notificationId)
1646
+ .all());
1647
+ if (row)
1648
+ return decodeNotificationOperation(row);
1649
+ throw new RemoteStepRefusal(409, 'remote step notification receipt changed');
1650
+ }
1651
+ async admitNotificationResume(invocationId) {
1652
+ const stored = await this.#getRow(invocationId);
1653
+ if (!stored)
1654
+ throw new RemoteStepRefusal(404, 'invocation not found');
1655
+ const invocation = decode(stored);
1656
+ const operation = await this.#notificationOperationFromRow(stored);
1657
+ if (operation?.state !== 'receipt-recorded' ||
1658
+ invocation.status !== 'result-retained')
1659
+ throw new RemoteStepRefusal(409, 'remote step continuation is unavailable');
1660
+ const retained = await this.#retainedResultFromRow(stored);
1661
+ if (!retained)
1662
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1663
+ const { suspension, snapshot } = await this.#stableSnapshot(invocation);
1664
+ if (suspension.suspendedAt !== invocation.suspendedAt ||
1665
+ suspension.resumeCount !== invocation.resumeCount ||
1666
+ suspension.requestJson !== JSON.stringify(invocation.request) ||
1667
+ JSON.stringify(suspension.stepPath) !==
1668
+ JSON.stringify(invocation.stepPath))
1669
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1670
+ const now = this.#now();
1671
+ const owner = crypto.randomUUID();
1672
+ const base = [
1673
+ owner,
1674
+ now + 60_000,
1675
+ now,
1676
+ invocationId,
1677
+ invocation.deploymentId,
1678
+ invocation.tablePrefix,
1679
+ invocation.workflowId,
1680
+ invocation.agentId,
1681
+ invocation.threadId,
1682
+ invocation.resourceId,
1683
+ invocation.runId,
1684
+ invocation.startToken,
1685
+ JSON.stringify(invocation.principal),
1686
+ retained.resultDigest,
1687
+ operation.operationKey,
1688
+ operation.requestDigest,
1689
+ stored.write_revision,
1690
+ stored.write_generation,
1691
+ now,
1692
+ invocation.workflowId,
1693
+ invocation.runId,
1694
+ snapshot,
1695
+ ];
1696
+ const gate = await this.#admission(invocation, base.length);
1697
+ const row = rowResult(await this.#db
1698
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1699
+ SET status = 'resuming', resume_lease_owner = ?, resume_lease_expires_at = ?,
1700
+ operation_state = 'resume-admitted', resume_admitted_at = ?,
1701
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1702
+ WHERE invocation_id = ? AND deployment_id = ? AND table_prefix = ?
1703
+ AND workflow_id = ? AND agent_id = ? AND thread_id = ?
1704
+ AND resource_id = ? AND run_id = ? AND start_token = ?
1705
+ AND principal_json = ? AND result_digest = ? AND operation_key = ?
1706
+ AND notification_request_digest = ? AND write_revision = ?
1707
+ AND write_generation = ? AND deadline_at > ?
1708
+ AND operation_state = 'receipt-recorded' AND status = 'result-retained'
1709
+ AND receipt_recorded_at IS NOT NULL AND resume_admitted_at IS NULL
1710
+ AND EXISTS (SELECT 1 FROM "${invocation.tablePrefix}mastra_workflow_snapshot"
1711
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1712
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1713
+ AND ${gate.predicate} RETURNING invocation_id`)
1714
+ .bind(...base, ...gate.values)
1715
+ .all());
1716
+ if (!row)
1717
+ throw new RemoteStepRefusal(409, 'remote step continuation changed');
1718
+ return owner;
1719
+ }
1720
+ async claimWorkflowResume(invocationId, leaseMs, expectedMutationEpoch) {
1721
+ if (!isPathSafeId(invocationId) ||
1722
+ !Number.isSafeInteger(leaseMs) ||
1723
+ leaseMs < 1 ||
1724
+ leaseMs > 60_000)
1725
+ throw new RemoteStepRefusal(400, 'remote step resume claim is malformed');
1726
+ const stored = await this.#getRow(invocationId);
1727
+ if (stored?.target_kind !== 'workflow')
1728
+ throw new RemoteStepRefusal(404, 'invocation not found');
1729
+ const invocation = decodeWorkflow(stored);
1730
+ if (invocation.status !== 'result-retained')
1731
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1732
+ const retained = await this.#retainedResultFromRow(stored);
1733
+ if (!retained)
1734
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1735
+ const { suspension, snapshot, state } = await this.#stableSnapshot(invocation);
1736
+ if (state.kind !== 'result')
1737
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1738
+ const currentPayload = record(record(state.summary.suspendPayload)?.[suspension.stepPath.join('.')]);
1739
+ if (suspension.stepPath.length !== 1 ||
1740
+ suspension.stepPath[0]?.includes('.') ||
1741
+ (currentPayload && MASTRA_WORKFLOW_META_KEY in currentPayload) ||
1742
+ JSON.stringify(suspension.stepPath) !==
1743
+ JSON.stringify(invocation.stepPath) ||
1744
+ suspension.suspendedAt !== invocation.suspendedAt ||
1745
+ suspension.resumeCount !== invocation.resumeCount ||
1746
+ suspension.requestJson !== stored.request_json ||
1747
+ (await sha256Hex(stored.request_json)) !== invocation.requestDigest)
1748
+ throw new RemoteStepRefusal(409, 'remote step suspension changed');
1749
+ const now = this.#now();
1750
+ if ((state.summary.deadlineAt ?? invocation.deadlineAt) <= now)
1751
+ throw new RemoteStepRefusal(409, 'remote step deadline elapsed');
1752
+ const owner = crypto.randomUUID();
1753
+ const base = [
1754
+ owner,
1755
+ now + leaseMs,
1756
+ invocationId,
1757
+ invocation.deploymentId,
1758
+ invocation.tablePrefix,
1759
+ invocation.workflowId,
1760
+ invocation.runId,
1761
+ invocation.startToken,
1762
+ JSON.stringify(invocation.principal),
1763
+ stored.step_path,
1764
+ invocation.suspendedAt,
1765
+ stored.resume_count,
1766
+ stored.request_json,
1767
+ invocation.requestDigest,
1768
+ retained.resultDigest,
1769
+ invocation.permitGeneration,
1770
+ invocation.permitEpoch ?? null,
1771
+ stored.write_revision,
1772
+ stored.write_generation,
1773
+ now,
1774
+ invocation.workflowId,
1775
+ invocation.runId,
1776
+ snapshot,
1777
+ ];
1778
+ const gate = await this.#admission(invocation, base.length);
1779
+ assertMutationEpoch(gate.observed, expectedMutationEpoch);
1780
+ const result = await this.#db
1781
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1782
+ SET status = 'resuming', resume_lease_owner = ?, resume_lease_expires_at = ?,
1783
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1784
+ WHERE invocation_id = ? AND target_kind = 'workflow' AND operation_state IS NULL
1785
+ AND deployment_id = ? AND table_prefix = ? AND workflow_id = ? AND run_id = ?
1786
+ AND start_token = ? AND principal_json = ? AND step_path = ?
1787
+ AND suspended_at = ? AND resume_count = ? AND request_json = ? AND request_digest = ?
1788
+ AND result_digest = ? AND permit_generation = ? AND permit_epoch IS ?
1789
+ AND write_revision = ? AND write_generation = ? AND deadline_at > ?
1790
+ AND status = 'result-retained'
1791
+ AND EXISTS (SELECT 1 FROM "${invocation.tablePrefix}mastra_workflow_snapshot"
1792
+ WHERE workflow_name = ? AND run_id = ? AND snapshot = ?
1793
+ AND ${SNAPSHOT_EXECUTION_OPEN_SQL})
1794
+ AND ${gate.predicate} RETURNING invocation_id`)
1795
+ .bind(...base, ...gate.values)
1796
+ .all();
1797
+ if (!rowResult(result))
1798
+ throw new RemoteStepRefusal(409, 'remote step resume is claimed');
1799
+ return owner;
1800
+ }
1801
+ async settleWorkflowAfterResume(invocationId, leaseOwner, witnessed) {
1802
+ if (!isPathSafeId(invocationId) || !isPathSafeId(leaseOwner))
1803
+ throw new RemoteStepRefusal(400, 'remote step resume claim is malformed');
1804
+ const stored = await this.#getRow(invocationId);
1805
+ if (stored?.target_kind !== 'workflow')
1806
+ throw new RemoteStepRefusal(404, 'invocation not found');
1807
+ const invocation = decodeWorkflow(stored);
1808
+ if (invocation.status !== 'resuming' ||
1809
+ stored.resume_lease_owner !== leaseOwner)
1810
+ throw new RemoteStepRefusal(409, 'remote step resume claim changed');
1811
+ const retained = await this.#retainedResultFromRow(stored);
1812
+ if (!retained)
1813
+ throw new RemoteStepRefusal(503, 'remote step result is unreadable');
1814
+ const start = await this.#execution(invocation, invocation.principal);
1815
+ if (start.execution.startToken !== invocation.startToken)
1816
+ throw new RemoteStepRefusal(409, 'remote step run generation changed');
1817
+ const current = await this.#runtime.authoritativeStatus(invocation.workflowId, invocation.runId);
1818
+ if (!current || current.runId !== invocation.runId)
1819
+ throw new RemoteStepRefusal(503, 'remote step outcome is unreadable');
1820
+ const key = invocation.stepPath.join('.');
1821
+ const same = current.status === 'suspended' &&
1822
+ current.suspended?.some((path) => JSON.stringify(path) === JSON.stringify(invocation.stepPath)) &&
1823
+ current.suspendedAt?.[key] === invocation.suspendedAt &&
1824
+ current.resumeCount?.[key] === invocation.resumeCount;
1825
+ if (same || JSON.stringify(witnessed) !== JSON.stringify(current))
1826
+ return 'unresolved';
1827
+ const outcome = current.status === 'success' || current.status === 'suspended'
1828
+ ? 'applied'
1829
+ : [
1830
+ 'failed',
1831
+ 'tripwire',
1832
+ 'canceled',
1833
+ 'bailed',
1834
+ 'skipped',
1835
+ 'cancelled',
1836
+ 'timed_out',
1837
+ ].includes(current.status)
1838
+ ? 'terminal-not-success'
1839
+ : 'unresolved';
1840
+ if (outcome === 'unresolved')
1841
+ return outcome;
1842
+ const result = await this.#db
1843
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1844
+ SET status = ?, resume_lease_owner = NULL, resume_lease_expires_at = NULL,
1845
+ settled_at = ?, settlement_outcome = ?,
1846
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1847
+ WHERE invocation_id = ? AND target_kind = 'workflow' AND operation_state IS NULL
1848
+ AND status = 'resuming' AND resume_lease_owner = ?
1849
+ AND deployment_id = ? AND table_prefix = ? AND workflow_id = ? AND run_id = ?
1850
+ AND start_token = ? AND principal_json = ? AND permit_generation = ? AND permit_epoch IS ?
1851
+ AND result_digest = ? AND write_revision = ? AND write_generation = ?
1852
+ RETURNING invocation_id`)
1853
+ .bind(outcome === 'applied' ? 'settled' : 'failed', this.#now(), outcome, invocationId, leaseOwner, invocation.deploymentId, invocation.tablePrefix, invocation.workflowId, invocation.runId, invocation.startToken, JSON.stringify(invocation.principal), invocation.permitGeneration, invocation.permitEpoch ?? null, retained.resultDigest, stored.write_revision, stored.write_generation)
1854
+ .all();
1855
+ if (!rowResult(result))
1856
+ throw new RemoteStepRefusal(409, 'remote step resume claim changed');
1857
+ return outcome;
1858
+ }
1859
+ async claimResume(invocationId, leaseMs) {
1860
+ if (!isPathSafeId(invocationId) ||
1861
+ !Number.isSafeInteger(leaseMs) ||
1862
+ leaseMs < 1 ||
1863
+ leaseMs > 60_000)
1864
+ throw new RemoteStepRefusal(400, 'remote step resume claim is malformed');
1865
+ const invocation = await this.get(invocationId);
1866
+ if (!invocation)
1867
+ throw new RemoteStepRefusal(404, 'invocation not found');
1868
+ if (invocation.status !== 'result-retained')
1869
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1870
+ const start = await this.#execution(invocation, invocation.principal);
1871
+ if (start.execution.startToken !== invocation.startToken)
1872
+ throw new RemoteStepRefusal(409, 'remote step run generation changed');
1873
+ if (!(await this.readRetainedResult(invocationId)))
1874
+ throw new RemoteStepRefusal(409, 'remote step result is unavailable');
1875
+ const now = this.#now();
1876
+ const owner = crypto.randomUUID();
1877
+ const result = await this.#db
1878
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1879
+ SET status = 'resuming', resume_lease_owner = ?, resume_lease_expires_at = ?,
1880
+ write_revision = write_revision + 1, write_generation = write_generation + 1
1881
+ WHERE invocation_id = ? AND operation_state IS NULL
1882
+ AND deployment_id = ? AND table_prefix = ?
1883
+ AND workflow_id = ? AND agent_id = ? AND thread_id = ?
1884
+ AND resource_id = ? AND run_id = ? AND start_token = ?
1885
+ AND permit_generation = ? AND permit_epoch IS ?
1886
+ AND result_digest IS NOT NULL
1887
+ AND status = 'result-retained'
1888
+ RETURNING invocation_id`)
1889
+ .bind(owner, now + leaseMs, invocationId, invocation.deploymentId, invocation.tablePrefix, invocation.workflowId, invocation.agentId, invocation.threadId, invocation.resourceId, invocation.runId, invocation.startToken, invocation.permitGeneration, invocation.permitEpoch ?? null)
1890
+ .all();
1891
+ if (!rowResult(result))
1892
+ throw new RemoteStepRefusal(409, 'remote step resume is claimed');
1893
+ return owner;
1894
+ }
1895
+ async settleAfterResume(invocationId, leaseOwner, witnessed) {
1896
+ if (!isPathSafeId(invocationId) || !isPathSafeId(leaseOwner))
1897
+ throw new RemoteStepRefusal(400, 'remote step resume claim is malformed');
1898
+ const invocation = await this.get(invocationId);
1899
+ if (invocation?.status !== 'resuming')
1900
+ throw new RemoteStepRefusal(409, 'remote step resume claim changed');
1901
+ const start = await this.#execution(invocation, invocation.principal);
1902
+ if (start.execution.startToken !== invocation.startToken)
1903
+ throw new RemoteStepRefusal(409, 'remote step run generation changed');
1904
+ const current = await this.#runtime.authoritativeStatus(invocation.workflowId, invocation.runId);
1905
+ if (!current || current.runId !== invocation.runId)
1906
+ throw new RemoteStepRefusal(503, 'remote step outcome is unreadable');
1907
+ const same = (summary) => {
1908
+ if (summary.status !== 'suspended')
1909
+ return false;
1910
+ const key = invocation.stepPath.join('.');
1911
+ const pathPresent = summary.suspended?.some((path) => JSON.stringify(path) === JSON.stringify(invocation.stepPath));
1912
+ const suspended = record(record(summary.suspendPayload)?.[key]);
1913
+ const tool = record(suspended?.toolCallSuspended);
1914
+ return (pathPresent === true &&
1915
+ summary.suspendedAt?.[key] === invocation.suspendedAt &&
1916
+ summary.resumeCount?.[key] === invocation.resumeCount &&
1917
+ suspended?.type === 'suspension' &&
1918
+ tool?.remoteStep === REMOTE_STEP_MARKER &&
1919
+ JSON.stringify(tool.request) === JSON.stringify(invocation.request));
1920
+ };
1921
+ const sameObservedOutcome = (left, right) => left.runId === right.runId &&
1922
+ left.status === right.status &&
1923
+ ((left.status === 'success' &&
1924
+ JSON.stringify(left.result) === JSON.stringify(right.result)) ||
1925
+ (left.status === 'suspended' &&
1926
+ JSON.stringify(left.suspended) === JSON.stringify(right.suspended) &&
1927
+ JSON.stringify(left.suspendedAt) ===
1928
+ JSON.stringify(right.suspendedAt) &&
1929
+ JSON.stringify(left.resumeCount) ===
1930
+ JSON.stringify(right.resumeCount) &&
1931
+ JSON.stringify(left.suspendPayload) ===
1932
+ JSON.stringify(right.suspendPayload)));
1933
+ let outcome;
1934
+ if (same(current))
1935
+ outcome =
1936
+ this.#now() >= invocation.deadlineAt ? 'deadline-expired' : 'retry';
1937
+ else if (current.status === 'suspended' || current.status === 'success')
1938
+ outcome =
1939
+ witnessed && sameObservedOutcome(witnessed, current) && !same(witnessed)
1940
+ ? 'applied'
1941
+ : 'advanced-without-proof';
1942
+ else if ([
1943
+ 'failed',
1944
+ 'tripwire',
1945
+ 'canceled',
1946
+ 'bailed',
1947
+ 'skipped',
1948
+ 'cancelled',
1949
+ 'timed_out',
1950
+ ].includes(current.status))
1951
+ outcome = 'terminal-not-success';
1952
+ else
1953
+ throw new RemoteStepRefusal(503, 'remote step outcome is still changing');
1954
+ const result = await this.#db
1955
+ .prepare(`UPDATE ${REMOTE_STEP_TABLE}
1956
+ SET status = ?, resume_lease_owner = NULL, resume_lease_expires_at = NULL,
1957
+ settled_at = ?, settlement_outcome = ?, write_revision = write_revision + 1, write_generation = write_generation + 1
1958
+ WHERE invocation_id = ? AND status = 'resuming'
1959
+ AND resume_lease_owner = ? AND permit_generation = ?
1960
+ AND permit_epoch IS ? AND start_token = ?
1961
+ AND deployment_id = ? AND table_prefix = ? AND workflow_id = ?
1962
+ AND agent_id = ? AND thread_id = ? AND resource_id = ? AND run_id = ?
1963
+ RETURNING invocation_id`)
1964
+ .bind(outcome === 'retry'
1965
+ ? 'result-retained'
1966
+ : outcome === 'applied'
1967
+ ? 'settled'
1968
+ : 'failed', outcome === 'retry' ? null : this.#now(), outcome === 'retry' ? null : outcome, invocationId, leaseOwner, invocation.permitGeneration, invocation.permitEpoch ?? null, invocation.startToken, invocation.deploymentId, invocation.tablePrefix, invocation.workflowId, invocation.agentId, invocation.threadId, invocation.resourceId, invocation.runId)
1969
+ .all();
1970
+ if (!rowResult(result))
1971
+ throw new RemoteStepRefusal(409, 'remote step resume claim changed');
1972
+ return outcome;
1973
+ }
1974
+ async nextNotificationRecoveryBatch(limit) {
1975
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100)
1976
+ throw new RemoteStepRefusal(400, 'notification recovery limit is malformed');
1977
+ await this.initialize();
1978
+ const definition = record(await this.#db
1979
+ .prepare('SELECT sql FROM sqlite_schema WHERE type = ? AND name = ?')
1980
+ .bind('table', REMOTE_STEP_NOTIFICATION_CURSOR_TABLE)
1981
+ .all())?.results;
1982
+ if (!Array.isArray(definition) ||
1983
+ definition.length !== 1 ||
1984
+ record(definition[0])?.sql !== REMOTE_STEP_NOTIFICATION_CURSOR_SQL)
1985
+ throw new RemoteStepRefusal(503, 'notification recovery cursor is unreadable');
1986
+ await this.#db
1987
+ .prepare(`INSERT OR IGNORE INTO ${REMOTE_STEP_NOTIFICATION_CURSOR_TABLE}
1988
+ (deployment_id, table_prefix, version, after_invocation_id)
1989
+ VALUES (?, ?, 1, '')`)
1990
+ .bind(this.#deploymentId, this.#tablePrefix)
1991
+ .run();
1992
+ const cursorRows = record(await this.#db
1993
+ .prepare(`SELECT version, after_invocation_id
1994
+ FROM ${REMOTE_STEP_NOTIFICATION_CURSOR_TABLE}
1995
+ WHERE deployment_id = ? AND table_prefix = ?`)
1996
+ .bind(this.#deploymentId, this.#tablePrefix)
1997
+ .all())?.results;
1998
+ const cursor = Array.isArray(cursorRows) && cursorRows.length === 1
1999
+ ? record(cursorRows[0])
2000
+ : undefined;
2001
+ const after = cursor?.after_invocation_id;
2002
+ if (cursor?.version !== 1 ||
2003
+ typeof after !== 'string' ||
2004
+ (after !== '' && !isPathSafeId(after)))
2005
+ throw new RemoteStepRefusal(503, 'notification recovery cursor is unreadable');
2006
+ const scan = async (afterInvocationId) => {
2007
+ const values = record(await this.#db
2008
+ .prepare(`SELECT invocation_id FROM ${REMOTE_STEP_TABLE}
2009
+ INDEXED BY ${REMOTE_STEP_OPERATION_INDEX}
2010
+ WHERE invocation_id > ? AND deployment_id = ? AND table_prefix = ?
2011
+ AND target_kind = 'agent'
2012
+ AND status IN ('result-retained', 'resuming')
2013
+ AND operation_state IN ('prepared', 'effect-admitted',
2014
+ 'receipt-recorded', 'resume-admitted', 'unresolved')
2015
+ ORDER BY invocation_id LIMIT ?`)
2016
+ .bind(afterInvocationId, this.#deploymentId, this.#tablePrefix, limit)
2017
+ .all())?.results;
2018
+ if (!Array.isArray(values) ||
2019
+ values.some((value) => !isPathSafeId(record(value)?.invocation_id)))
2020
+ throw new RemoteStepRefusal(503, 'notification recovery scan is unreadable');
2021
+ return values.map((value) => record(value)?.invocation_id);
2022
+ };
2023
+ let ids = await scan(after);
2024
+ if (ids.length === 0 && after !== '')
2025
+ ids = await scan('');
2026
+ const next = ids.at(-1) ?? '';
2027
+ const advanced = record(await this.#db
2028
+ .prepare(`UPDATE ${REMOTE_STEP_NOTIFICATION_CURSOR_TABLE}
2029
+ SET after_invocation_id = ?
2030
+ WHERE deployment_id = ? AND table_prefix = ? AND version = 1
2031
+ AND after_invocation_id = ?
2032
+ RETURNING after_invocation_id`)
2033
+ .bind(next, this.#deploymentId, this.#tablePrefix, after)
2034
+ .all())?.results;
2035
+ if (!Array.isArray(advanced) || advanced.length !== 1)
2036
+ throw new RemoteStepRefusal(409, 'notification recovery cursor changed');
2037
+ return ids;
2038
+ }
2039
+ async recoverableResults(limit, afterInvocationId = '') {
2040
+ if (!Number.isSafeInteger(limit) ||
2041
+ limit < 1 ||
2042
+ limit > 100 ||
2043
+ (afterInvocationId !== '' && !isPathSafeId(afterInvocationId)))
2044
+ throw new RemoteStepRefusal(400, 'remote step recovery limit is malformed');
2045
+ const now = this.#now();
2046
+ const rows = record(await this.#db
2047
+ .prepare(`SELECT invocation_id, status, resume_lease_expires_at
2048
+ FROM ${REMOTE_STEP_TABLE} INDEXED BY ${REMOTE_STEP_RECOVERY_INDEX}
2049
+ WHERE invocation_id > ?
2050
+ AND target_kind = 'agent'
2051
+ AND operation_state IS NULL
2052
+ AND status IN ('result-retained', 'resuming')
2053
+ ORDER BY invocation_id LIMIT ?`)
2054
+ .bind(afterInvocationId, limit)
2055
+ .all())?.results;
2056
+ if (!Array.isArray(rows) ||
2057
+ rows.some((row) => !isPathSafeId(record(row)?.invocation_id) ||
2058
+ !['result-retained', 'resuming'].includes(record(row)?.status) ||
2059
+ (record(row)?.status === 'resuming' &&
2060
+ !positiveTime(record(row)?.resume_lease_expires_at))))
2061
+ throw new RemoteStepRefusal(503, 'remote step recovery scan is unreadable');
2062
+ const invocationIds = rows
2063
+ .filter((row) => {
2064
+ const value = record(row);
2065
+ return (value?.status === 'result-retained' ||
2066
+ (value?.status === 'resuming' &&
2067
+ positiveTime(value.resume_lease_expires_at) &&
2068
+ value.resume_lease_expires_at <= now));
2069
+ })
2070
+ .map((row) => record(row)?.invocation_id);
2071
+ const last = rows.at(-1);
2072
+ return {
2073
+ invocationIds,
2074
+ ...(rows.length === limit && last
2075
+ ? { nextCursor: record(last)?.invocation_id }
2076
+ : {}),
2077
+ };
2078
+ }
2079
+ async reconcileResult(invocationId) {
2080
+ const invocation = await this.get(invocationId);
2081
+ if (!invocation)
2082
+ throw new RemoteStepRefusal(404, 'invocation not found');
2083
+ if (invocation.status === 'resuming')
2084
+ return 'pending-quiescence';
2085
+ const owner = await this.claimResume(invocationId, 60_000);
2086
+ return this.settleAfterResume(invocationId, owner);
2087
+ }
2088
+ }
2089
+ //# sourceMappingURL=remote-step-journal.js.map