@voltro/workflow 0.80.0 → 0.82.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.
@@ -0,0 +1,2069 @@
1
+ import { C as e, S as t, _ as n, b as r, l as i, m as a } from "./journalEncryption--n5VDdYO.js";
2
+ import { Context as o, Effect as s, Schema as c } from "effect";
3
+ import { WorkflowRestartObservationSchema as l, WorkflowRestartSelectionSchema as u, WorkflowRestartTargetSchema as d, WorkflowStartTerminalOutcomeSchema as f } from "@voltro/protocol";
4
+ import { and as p, derivedRowId as m, eq as h, gt as g, id as _, integer as ee, isNull as v, json as y, or as te, table as ne, text as b, timestamp as re } from "@voltro/database";
5
+ import { createHash as ie, randomUUID as x } from "node:crypto";
6
+ import { isDeepStrictEqual as ae } from "node:util";
7
+ import { SqlClient as S } from "@effect/sql";
8
+ //#region src/admissionTransaction.ts
9
+ var oe = "_voltro_workflow_admission_locks", se = "deployment", C = async (e, t) => (await e.insertIgnoreWithOutcome(oe, {
10
+ id: se,
11
+ nonce: x()
12
+ }, { conflictColumns: ["id"] }), e.transactional(async (e) => {
13
+ if ((await e.query({
14
+ table: "_voltro_workflow_admission_locks",
15
+ predicate: h("id", se),
16
+ lock: "update",
17
+ order: [],
18
+ take: 1,
19
+ skip: void 0,
20
+ projection: void 0
21
+ })).length !== 1) throw Error("Admission coordinator row is missing; refusing an unlocked decision");
22
+ if (await e.update("_voltro_workflow_admission_locks", se, { nonce: x() }) === null) throw Error("Admission coordinator row disappeared; refusing an unlocked decision");
23
+ return t(e);
24
+ })), ce = class extends Error {
25
+ workflowName;
26
+ field;
27
+ constructor(e, t, n) {
28
+ super(`workflow '${e}': ${t}(payload) threw — a flow-control key function must be total over every payload the workflow accepts, because it runs before the run exists and there is nowhere to report a partial failure to. Cause: ${n instanceof Error ? n.message : String(n)}`), this.name = "FlowControlKeyError", this.workflowName = e, this.field = t, this.cause = n;
29
+ }
30
+ }, w = (e, t, n, r) => {
31
+ try {
32
+ let e = n(r);
33
+ if (typeof e != "string" || e.length === 0) throw Error(`returned ${e === "" ? "an empty string" : String(e)}; expected a non-empty string`);
34
+ return e;
35
+ } catch (n) {
36
+ throw new ce(e, t, n);
37
+ }
38
+ }, le = (e, t) => JSON.stringify([e ?? null, t]), ue = (e, t) => {
39
+ let n = e.workflowName, r = 0;
40
+ if (e.priority !== void 0) try {
41
+ let n = e.priority(t);
42
+ if (!Number.isFinite(n)) throw Error(`returned ${String(n)}; expected a finite number`);
43
+ r = Math.trunc(n);
44
+ } catch (e) {
45
+ throw new ce(n, "priority", e);
46
+ }
47
+ return {
48
+ ...e.debounce === void 0 ? {} : { debounceKey: w(n, "debounce.key", e.debounce.key, t) },
49
+ ...e.singleton === void 0 ? {} : { singletonKey: w(n, "singleton.key", e.singleton.key, t) },
50
+ ...e.concurrency === void 0 ? {} : { concurrencyKey: le(e.concurrency.pool, e.concurrency.key === void 0 ? "" : w(n, "concurrency.key", e.concurrency.key, t)) },
51
+ ...e.throttle?.key === void 0 ? e.throttle === void 0 ? {} : { throttleKey: "" } : { throttleKey: w(n, "throttle.key", e.throttle.key, t) },
52
+ ...e.rateLimit?.key === void 0 ? e.rateLimit === void 0 ? {} : { rateLimitKey: "" } : { rateLimitKey: w(n, "rateLimit.key", e.rateLimit.key, t) },
53
+ ...e.batch?.key === void 0 ? e.batch === void 0 ? {} : { batchKey: "" } : { batchKey: w(n, "batch.key", e.batch.key, t) },
54
+ priority: r
55
+ };
56
+ }, de = (e, t, n, r) => {
57
+ let i = e.filter((e) => e > r - n);
58
+ if (i.length < t) return;
59
+ let a = [...i].sort((e, t) => t - e)[t - 1];
60
+ if (a !== void 0) return a + n;
61
+ }, fe = (e) => {
62
+ let { control: t, keys: n, state: r, now: i, reconsidering: a } = e;
63
+ if (r.paused === !0) return {
64
+ kind: "defer",
65
+ mode: "paused",
66
+ dueAt: i,
67
+ collapse: a ? "hold" : "append",
68
+ keys: n
69
+ };
70
+ if (t.rateLimit !== void 0) {
71
+ let e = de(r.recentAdmissions ?? [], t.rateLimit.limit, t.rateLimit.periodMs, i);
72
+ if (e !== void 0) return {
73
+ kind: "drop",
74
+ reason: "rate-limit",
75
+ retryAfterMs: Math.max(0, e - i),
76
+ keys: n
77
+ };
78
+ }
79
+ if (t.singleton !== void 0 && r.singletonUnacknowledged === !0) return {
80
+ kind: "defer",
81
+ mode: "singleton",
82
+ dueAt: i,
83
+ collapse: a ? "hold" : "append",
84
+ keys: n
85
+ };
86
+ if (t.singleton !== void 0 && t.singleton.mode === "skip" && r.singletonHolder !== void 0) return {
87
+ kind: "skip",
88
+ incumbent: r.singletonHolder,
89
+ keys: n
90
+ };
91
+ if (t.debounce !== void 0) {
92
+ let e = r.debouncePending, o = e?.firstSeenAt ?? i, s = e?.deadlineAt ?? (t.debounce.timeoutMs === void 0 ? void 0 : o + t.debounce.timeoutMs);
93
+ return a ? s !== void 0 && i >= s ? {
94
+ kind: "admit",
95
+ reason: "debounce-deadline",
96
+ keys: n,
97
+ ...T(t, r)
98
+ } : {
99
+ kind: "admit",
100
+ reason: "debounce-elapsed",
101
+ keys: n,
102
+ ...T(t, r)
103
+ } : {
104
+ kind: "defer",
105
+ mode: "debounce",
106
+ dueAt: s === void 0 ? i + t.debounce.periodMs : Math.min(i + t.debounce.periodMs, s),
107
+ ...s === void 0 ? {} : { deadlineAt: s },
108
+ collapse: "replace",
109
+ keys: n
110
+ };
111
+ }
112
+ if (t.batch !== void 0) {
113
+ let e = r.batchPending, o = (e?.count ?? 0) + +!a, s = (e?.firstSeenAt ?? i) + t.batch.timeoutMs;
114
+ return o >= t.batch.maxSize ? {
115
+ kind: "admit",
116
+ reason: "batch-full",
117
+ keys: n,
118
+ ...T(t, r)
119
+ } : a && i >= s ? {
120
+ kind: "admit",
121
+ reason: "batch-timeout",
122
+ keys: n,
123
+ ...T(t, r)
124
+ } : {
125
+ kind: "defer",
126
+ mode: "batch",
127
+ dueAt: s,
128
+ collapse: a ? "hold" : "append",
129
+ keys: n
130
+ };
131
+ }
132
+ if (t.throttle !== void 0) {
133
+ let e = de(r.recentAdmissions ?? [], t.throttle.limit, t.throttle.periodMs, i);
134
+ if (e !== void 0) return {
135
+ kind: "defer",
136
+ mode: "throttle",
137
+ dueAt: e,
138
+ collapse: a ? "hold" : "append",
139
+ keys: n
140
+ };
141
+ }
142
+ return t.concurrency !== void 0 && (r.inFlight ?? 0) >= t.concurrency.limit ? {
143
+ kind: "defer",
144
+ mode: "concurrency",
145
+ dueAt: i,
146
+ collapse: a ? "hold" : "append",
147
+ keys: n
148
+ } : {
149
+ kind: "admit",
150
+ reason: pe(t) ? "under-limits" : "no-controls",
151
+ keys: n,
152
+ ...T(t, r)
153
+ };
154
+ }, pe = (e) => e.debounce !== void 0 || e.singleton !== void 0 || e.concurrency !== void 0 || e.throttle !== void 0 || e.rateLimit !== void 0 || e.batch !== void 0, T = (e, t) => e.singleton?.mode === "cancel" && t.singletonHolder !== void 0 ? { evict: t.singletonHolder } : {}, me = (e, t, n) => {
155
+ let r = e.timeouts?.startMs;
156
+ return r !== void 0 && n - t.firstSeenAt >= r;
157
+ }, he = (e, t, n) => {
158
+ let r = e.timeouts?.finishMs;
159
+ return r === void 0 || t.terminal ? !1 : n - t.startedAt >= r;
160
+ }, ge = (e, t) => e.priority === t.priority ? e.firstSeenAt === t.firstSeenAt ? e.id < t.id ? -1 : +(e.id > t.id) : e.firstSeenAt - t.firstSeenAt : t.priority - e.priority, E = "_voltro_workflow_failure_reports", _e = c.Struct({
161
+ id: c.String,
162
+ workflowName: c.String,
163
+ tenantId: c.NullOr(c.String),
164
+ sourceId: c.String,
165
+ sourceKind: c.Literal("submission", "intent", "run"),
166
+ handler: c.NullOr(c.String),
167
+ callerContext: c.Unknown,
168
+ report: c.Struct({
169
+ workflow: c.String,
170
+ payload: c.Unknown,
171
+ errorTag: c.NullOr(c.String),
172
+ errorMessage: c.NullOr(c.String),
173
+ runId: c.NullOr(c.String),
174
+ executionId: c.NullOr(c.String),
175
+ reason: c.String,
176
+ failedAt: c.Number
177
+ })
178
+ }), D = async (e, t) => {
179
+ let n = await e.query({
180
+ table: E,
181
+ predicate: h("id", t),
182
+ order: [],
183
+ take: 1,
184
+ skip: void 0,
185
+ projection: void 0
186
+ });
187
+ return n[0] === void 0 ? void 0 : c.decodeUnknownSync(_e)(n[0]);
188
+ }, ve = async (e, t) => {
189
+ if (t.id.length === 0 || t.sourceId.length === 0) throw Error("Workflow failure requires a stable report and source identity");
190
+ let n = await D(e, t.id);
191
+ if (n !== void 0) {
192
+ if (n.workflowName !== t.workflowName || n.tenantId !== t.tenantId || n.sourceId !== t.sourceId || n.sourceKind !== t.sourceKind) throw Error("Workflow failure identity belongs to a different source, workflow or tenant");
193
+ return n;
194
+ }
195
+ let i = c.decodeUnknownSync(_e)(t), a = {
196
+ ...i,
197
+ report: {
198
+ ...i.report,
199
+ errorMessage: r(i.workflowName, i.report.errorMessage)
200
+ }
201
+ };
202
+ if (a.report.workflow !== a.workflowName) throw Error("Workflow failure report does not describe its owning workflow");
203
+ return await e.insert(E, {
204
+ ...a,
205
+ handoffReceiptId: null,
206
+ handoffAttempt: 0,
207
+ acceptedExecutionId: null
208
+ }), a;
209
+ }, ye = async (e, t, n) => {
210
+ let r, i = t === "submissionId" ? h(t, n) : p(h(t, n), v("submissionId"), v("terminal"));
211
+ for (;;) {
212
+ let t = await e.query({
213
+ table: N,
214
+ predicate: r === void 0 ? i : p(i, g("id", r)),
215
+ order: [{
216
+ column: "id",
217
+ direction: "asc"
218
+ }],
219
+ take: 100,
220
+ skip: void 0,
221
+ projection: void 0
222
+ });
223
+ if (t.length === 0) return !1;
224
+ for (let n of t) {
225
+ let t = P(n), i = await e.query({
226
+ table: E,
227
+ predicate: h("handoffReceiptId", t.id),
228
+ order: [],
229
+ take: 1,
230
+ skip: void 0,
231
+ projection: void 0
232
+ });
233
+ if (i.length !== 0) {
234
+ if (i[0]?.handler !== t.workflowName || i[0]?.tenantId !== t.tenantId) throw Error("Failure delivery receipt belongs to a different workflow or tenant");
235
+ return !0;
236
+ }
237
+ r = t.id;
238
+ }
239
+ }
240
+ }, be = (e, t) => ye(e, "submissionId", t), xe = (e, t) => ye(e, "pendingId", t), Se = async (e, t, n, r) => {
241
+ for await (let i of Pe(e, t, n)) {
242
+ if (i.tenantId !== r) throw Error("Failure delivery belongs to a different resident tenant");
243
+ if (await be(e, i.id)) return !0;
244
+ }
245
+ return !1;
246
+ }, Ce = c.Struct({
247
+ handoffReceiptId: c.NullOr(c.String),
248
+ handoffAttempt: c.NonNegativeInt,
249
+ acceptedExecutionId: c.NullOr(c.NonEmptyString)
250
+ }), we = (e, t) => `wfrc_${ie("sha256").update(JSON.stringify([
251
+ "failure",
252
+ e,
253
+ t
254
+ ])).digest("hex").slice(0, 40)}`, Te = async (e, t) => {
255
+ let n = await e.query({
256
+ table: E,
257
+ predicate: h("id", t),
258
+ order: [],
259
+ take: 1,
260
+ skip: void 0,
261
+ projection: void 0
262
+ }), r = c.decodeUnknownSync(Ce)(n[0]);
263
+ if (r.handoffReceiptId === null && (r.handoffAttempt !== 0 || r.acceptedExecutionId !== null)) throw Error("Failure report has contradictory unstarted handoff metadata");
264
+ return r;
265
+ }, Ee = (t) => {
266
+ if (t.handler === null || !i(t.handler)) return t.report;
267
+ let r = `failure report for '${t.handler}'`;
268
+ return e({
269
+ ...t.report,
270
+ payload: n(t.report.payload, `${r}.payload`),
271
+ errorMessage: a(t.report.errorMessage)
272
+ }, r);
273
+ }, De = async (e, t, n, r, i) => {
274
+ if (t.handler === null || t.handler.length === 0) throw Error("Cannot queue an unconfigured failure handler");
275
+ if (!Number.isSafeInteger(n) || n < 0) throw Error("Failure handoff attempt exhausted");
276
+ if (!Number.isFinite(r)) throw Error("Failure handoff retry deadline is invalid");
277
+ let a = await st({
278
+ store: e,
279
+ workflowName: t.handler,
280
+ payload: Ee(t),
281
+ callerContext: t.callerContext,
282
+ tenantId: t.tenantId,
283
+ at: r,
284
+ now: i
285
+ }), o = await Ye(e, {
286
+ id: we(t.id, n),
287
+ workflowName: t.handler,
288
+ tenantId: t.tenantId,
289
+ pendingId: a.intentId
290
+ });
291
+ if (await e.update("_voltro_workflow_failure_reports", t.id, {
292
+ handoffReceiptId: o.id,
293
+ handoffAttempt: n
294
+ }) === null) throw Error("Failure report disappeared during durable handoff");
295
+ return {
296
+ kind: "queued",
297
+ receiptId: o.id,
298
+ intentId: o.pendingId
299
+ };
300
+ }, O = async (e, t, n) => {
301
+ if (!Number.isFinite(n)) throw Error("Failure handoff requires a finite timestamp");
302
+ let r = await D(e, t);
303
+ if (r === void 0) throw Error("Cannot hand off an unknown workflow failure");
304
+ let { handoffReceiptId: i, handoffAttempt: a, acceptedExecutionId: o } = await Te(e, t);
305
+ if (r.handler === null) {
306
+ if (i !== null || o !== null) throw Error("Unconfigured failure report has a contradictory handoff");
307
+ return { kind: "unconfigured" };
308
+ }
309
+ if (r.handler.length === 0) throw Error("Failure report has an empty handler");
310
+ let s = we(t, a);
311
+ if (i !== null) {
312
+ if (i !== s) throw Error("Failure handoff receipt belongs to a different report");
313
+ let t = await F(e, i);
314
+ if (t === void 0 || t.workflowName !== r.handler || t.tenantId !== r.tenantId) throw Error("Failure report has no matching durable start receipt");
315
+ return {
316
+ kind: "queued",
317
+ receiptId: t.id,
318
+ intentId: t.pendingId
319
+ };
320
+ }
321
+ return De(e, r, 0, n, n);
322
+ }, k = class extends Error {
323
+ reason;
324
+ constructor(e) {
325
+ super(`Workflow failure delivery requires reconciliation: ${e}`), this.reason = e;
326
+ }
327
+ }, Oe = async (e, t, n) => {
328
+ let r = await O(e, t, n);
329
+ if (r.kind === "unconfigured") return r;
330
+ let i = await Te(e, t), a = await F(e, r.receiptId);
331
+ if (a === void 0) throw Error("Failure handoff receipt disappeared during reconciliation");
332
+ if (i.acceptedExecutionId !== null) {
333
+ if (a.terminal !== null || a.submissionId === null) throw Error("Accepted failure report has no submitted receipt");
334
+ return {
335
+ kind: "accepted",
336
+ executionId: i.acceptedExecutionId
337
+ };
338
+ }
339
+ if (a.terminal !== null) {
340
+ if (a.terminal.kind === "cancelled") return {
341
+ kind: "cancelled",
342
+ receiptId: a.id
343
+ };
344
+ let r = await D(e, t);
345
+ if (r === void 0) throw Error("Failure report disappeared during retry");
346
+ let o = i.handoffAttempt + 1, s = Math.max(W(o, () => 1), a.terminal.kind === "dropped" ? a.terminal.retryAfterMs : 0);
347
+ return De(e, r, o, Math.max(n, a.terminal.at + s), n);
348
+ }
349
+ if (a.submissionId === null) {
350
+ let t = (await e.query({
351
+ table: I,
352
+ predicate: h("id", a.pendingId),
353
+ order: [],
354
+ take: 1,
355
+ skip: void 0,
356
+ projection: void 0
357
+ }))[0];
358
+ if (t === void 0) throw new k("arrival-missing");
359
+ if (t.workflowName !== a.workflowName || t.tenantId !== a.tenantId) throw new k("arrival-owner-mismatch");
360
+ if (t.deadLetteredAt !== null) throw new k("arrival-dead-lettered");
361
+ return r;
362
+ }
363
+ let o = await M(e, a.submissionId);
364
+ if (o === void 0 || !o.receiptsBound || o.workflowName !== a.workflowName || o.tenantId !== a.tenantId || !o.intentIds.includes(a.pendingId)) throw Error("Failure handoff receipt has no matching admission submission");
365
+ if (o.failureId !== null) {
366
+ let r = await D(e, o.failureId);
367
+ if (o.executionId !== null || o.dispatchAttempts > 1 || r === void 0 || r.sourceKind !== "submission" || r.sourceId !== o.id || r.workflowName !== o.workflowName || r.tenantId !== o.tenantId || r.report.executionId !== null || r.report.runId !== null) throw new k("rejection-proof-invalid");
368
+ let a = await D(e, t);
369
+ if (a === void 0) throw Error("Failure report disappeared during rejected handler retry");
370
+ let s = i.handoffAttempt + 1;
371
+ return De(e, a, s, Math.max(n, r.report.failedAt + W(s, () => 1)), n);
372
+ }
373
+ if (o.executionId === null) return r;
374
+ if (o.failureId !== null || o.executionId.length === 0 || o.preparedExecutionId !== o.executionId) throw Error("Failure handler acknowledgement contradicts its prepared submission");
375
+ if (await e.update("_voltro_workflow_failure_reports", t, { acceptedExecutionId: o.executionId }) === null) throw Error("Failure report disappeared during acceptance acknowledgement");
376
+ return {
377
+ kind: "accepted",
378
+ executionId: o.executionId
379
+ };
380
+ }, ke = c.Struct({
381
+ runId: c.NonEmptyString,
382
+ workflowName: c.NonEmptyString,
383
+ executionId: c.NonEmptyString,
384
+ generation: c.NonEmptyString,
385
+ parentStatus: c.Literal("succeeded", "failed", "cancelled"),
386
+ closedAt: c.DateFromSelf
387
+ }), Ae = async (e, t, n) => {
388
+ let [r] = await e.query({
389
+ table: "_voltro_workflow_runs",
390
+ predicate: h("executionId", n),
391
+ lock: "update",
392
+ order: [],
393
+ take: 1,
394
+ skip: void 0,
395
+ projection: void 0
396
+ });
397
+ if (r !== void 0) {
398
+ if (r.tag !== t) throw Error("Admission acknowledgement belongs to a different resident workflow");
399
+ if (typeof r.id != "string" || r.id.length === 0) throw Error("Resident execution has no run identity");
400
+ if (r.status === "running" || r.status === "suspended") return {
401
+ runId: r.id,
402
+ completedAt: null
403
+ };
404
+ if (r.status !== "succeeded" && r.status !== "failed" && r.status !== "cancelled") throw Error("Resident execution has an unrecognized status");
405
+ if (!(r.completedAt instanceof Date) || !Number.isFinite(r.completedAt.getTime())) throw Error("Terminal workflow has no valid completion timestamp for lease release");
406
+ return {
407
+ runId: r.id,
408
+ completedAt: r.completedAt
409
+ };
410
+ }
411
+ let [i] = await e.query({
412
+ table: "_voltro_workflow_parent_closures",
413
+ predicate: h("executionId", n),
414
+ lock: "update",
415
+ order: [{
416
+ column: "closedAt",
417
+ direction: "desc"
418
+ }, {
419
+ column: "id",
420
+ direction: "desc"
421
+ }],
422
+ take: 1,
423
+ skip: void 0,
424
+ projection: void 0
425
+ });
426
+ if (i === void 0) return;
427
+ let a = c.decodeUnknownSync(ke)(i);
428
+ if (a.workflowName !== t || a.executionId !== n) throw Error("Admission acknowledgement belongs to a different resident workflow");
429
+ if (!Number.isFinite(a.closedAt.getTime())) throw Error("Workflow closure has no valid completion timestamp");
430
+ return {
431
+ runId: a.runId,
432
+ completedAt: a.closedAt
433
+ };
434
+ }, A = "_voltro_workflow_submissions", je = "wfsub", Me = () => `${je}_${x()}`, j = c.Struct({
435
+ id: c.String,
436
+ workflowName: c.String,
437
+ tenantId: c.NullOr(c.String),
438
+ ledgerId: c.String,
439
+ preparedExecutionId: c.NullOr(c.String),
440
+ executionId: c.NullOr(c.String),
441
+ runId: c.NullOr(c.String),
442
+ receiptsBound: c.Boolean,
443
+ dispatchAttempts: c.NonNegativeInt,
444
+ failureId: c.NullOr(c.String),
445
+ retry: c.Struct({
446
+ attempts: c.Int,
447
+ after: c.Number,
448
+ lastError: c.NullOr(c.String),
449
+ stoppedAt: c.NullOr(c.Number)
450
+ }),
451
+ payload: c.Unknown,
452
+ callerContext: c.Unknown,
453
+ intentIds: c.Array(c.String),
454
+ eviction: c.NullOr(c.Struct({
455
+ executionId: c.String,
456
+ runId: c.String
457
+ }))
458
+ }), Ne = c.decodeUnknownSync(j);
459
+ async function* Pe(e, t, n) {
460
+ let r;
461
+ for (;;) {
462
+ let i = p(h("preparedExecutionId", t), g("dispatchAttempts", 0)), a = await e.query({
463
+ table: A,
464
+ predicate: r === void 0 ? i : p(i, g("id", r)),
465
+ order: [{
466
+ column: "id",
467
+ direction: "asc"
468
+ }],
469
+ take: 100,
470
+ skip: void 0,
471
+ projection: void 0
472
+ });
473
+ if (a.length === 0) return;
474
+ for (let e of a) {
475
+ let i = Ne(e);
476
+ if (i.workflowName !== n || !i.receiptsBound || i.failureId !== null || i.executionId !== null && i.executionId !== t) throw Error("Workflow completion has an inconsistent resident submission owner");
477
+ yield i, r = i.id;
478
+ }
479
+ }
480
+ }
481
+ var Fe = async (e, t, n) => (await Ie(e, t, n)).map((e) => Ne(e)), Ie = async (e, t, n) => {
482
+ if (!Number.isSafeInteger(t) || t < 1) throw Error("Submission recovery requires a positive page size");
483
+ return e.query({
484
+ table: A,
485
+ predicate: n === void 0 ? p(h("receiptsBound", !0), v("executionId"), v("failureId")) : p(h("receiptsBound", !0), v("executionId"), v("failureId"), g("id", n)),
486
+ order: [{
487
+ column: "id",
488
+ direction: "asc"
489
+ }],
490
+ take: t,
491
+ skip: void 0,
492
+ projection: void 0
493
+ });
494
+ }, M = async (e, t) => {
495
+ let n = await e.query({
496
+ table: A,
497
+ predicate: h("id", t),
498
+ order: [],
499
+ take: 1,
500
+ skip: void 0,
501
+ projection: void 0
502
+ });
503
+ return n[0] === void 0 ? void 0 : c.decodeUnknownSync(j)(n[0]);
504
+ }, Le = async (e, t) => C(e, (e) => Re(e, t)), Re = async (e, t) => {
505
+ if (t.id.length === 0) throw Error("Admission submission requires a stable non-empty identity");
506
+ let n = await e.query({
507
+ table: A,
508
+ predicate: h("id", t.id),
509
+ order: [],
510
+ take: 1,
511
+ skip: void 0,
512
+ projection: void 0
513
+ });
514
+ if (n[0] !== void 0) {
515
+ let e = c.decodeUnknownSync(j)(n[0]);
516
+ if (e.workflowName !== t.control.workflowName || e.tenantId !== t.tenantId) throw Error("Admission submission identity belongs to a different workflow or tenant");
517
+ let r = JSON.parse(JSON.stringify(e.payload) ?? "null"), i = JSON.parse(JSON.stringify(t.encodedPayload) ?? "null");
518
+ if (!ae(r, i)) throw Error("Admission submission identity is already bound to a different payload");
519
+ return {
520
+ kind: "reserved",
521
+ submission: e,
522
+ reused: !0
523
+ };
524
+ }
525
+ let r = ue(t.control, t.keyPayload), i = await bt({
526
+ store: e,
527
+ control: t.control,
528
+ keys: r,
529
+ paused: t.paused,
530
+ now: t.now,
531
+ reconsidering: !0
532
+ });
533
+ if (i.kind !== "admit") return {
534
+ kind: "not-admitted",
535
+ decision: i
536
+ };
537
+ let a = await lt({
538
+ store: e,
539
+ control: t.control,
540
+ keys: r,
541
+ outcome: "admitted",
542
+ mode: t.mode,
543
+ reason: i.reason,
544
+ collapsed: t.collapsed,
545
+ waitedMs: t.now - t.firstSeenAt,
546
+ executionId: null,
547
+ runId: null,
548
+ tenantId: t.tenantId,
549
+ now: t.now
550
+ });
551
+ if (a === void 0) throw Error("Admission reservation has no ledger identity");
552
+ return {
553
+ kind: "reserved",
554
+ submission: await ze(e, {
555
+ id: t.id,
556
+ workflowName: t.control.workflowName,
557
+ tenantId: t.tenantId,
558
+ ledgerId: a,
559
+ payload: t.encodedPayload,
560
+ callerContext: t.callerContext,
561
+ intentIds: t.intentIds,
562
+ eviction: i.evict ?? null
563
+ }),
564
+ reused: !1
565
+ };
566
+ }, ze = async (e, t) => {
567
+ if (t.id.length === 0 || t.ledgerId.length === 0) throw Error("Submission requires its reserved admission identity");
568
+ let n = {
569
+ ...t,
570
+ callerContext: t.callerContext ?? null,
571
+ intentIds: [...t.intentIds],
572
+ preparedExecutionId: null,
573
+ executionId: null,
574
+ runId: null,
575
+ receiptsBound: !1,
576
+ dispatchAttempts: 0,
577
+ failureId: null,
578
+ retry: {
579
+ attempts: 0,
580
+ after: 0,
581
+ lastError: null,
582
+ stoppedAt: null
583
+ }
584
+ };
585
+ return await e.insert(A, n), n;
586
+ }, Be = async (e, t, n) => C(e, (e) => Ve(e, t, n)), Ve = async (e, t, n) => {
587
+ if (n.executionId.length === 0) throw Error("Engine acknowledgement requires an execution identity");
588
+ let r = await e.query({
589
+ table: A,
590
+ predicate: h("id", t),
591
+ order: [],
592
+ take: 1,
593
+ skip: void 0,
594
+ projection: void 0
595
+ });
596
+ if (r[0] === void 0) throw Error("Cannot acknowledge an unknown admission submission");
597
+ let i = c.decodeUnknownSync(j)(r[0]);
598
+ if (i.failureId !== null) throw Error("Cannot acknowledge a permanently rejected admission submission");
599
+ if (i.preparedExecutionId !== null && i.preparedExecutionId !== n.executionId) throw Error("Engine acknowledgement contradicts the prepared execution identity");
600
+ if (i.executionId !== null && i.executionId !== n.executionId || i.runId !== null && n.runId !== null && i.runId !== n.runId) throw Error("Admission submission already belongs to a different execution or run");
601
+ let a = await Ae(e, i.workflowName, n.executionId), o = i.runId ?? n.runId;
602
+ if (a !== void 0 && o !== null && a.runId !== o) throw Error("Admission acknowledgement belongs to a different resident run");
603
+ let s = {
604
+ executionId: n.executionId,
605
+ runId: o ?? a?.runId ?? null
606
+ }, l = a?.completedAt ?? void 0;
607
+ if (await e.update("_voltro_workflow_admissions", i.ledgerId, {
608
+ ...s,
609
+ ...l === void 0 ? {} : { releasedAt: l }
610
+ }) === null) throw Error("Admission submission has no lease to acknowledge");
611
+ if (await e.update("_voltro_workflow_submissions", t, s) === null) throw Error("Admission submission disappeared during acknowledgement");
612
+ return {
613
+ ...i,
614
+ ...s
615
+ };
616
+ }, He = async (e, t, n) => {
617
+ if (n.length === 0) throw Error("Prepared submission requires a non-empty execution identity");
618
+ let r = await M(e, t);
619
+ if (r === void 0) throw Error("Cannot prepare an unknown admission submission");
620
+ if (!r.receiptsBound || r.failureId !== null) throw Error("Cannot prepare an incomplete or terminal admission submission");
621
+ if (r.preparedExecutionId !== null) {
622
+ if (r.executionId !== null && r.executionId !== r.preparedExecutionId) throw Error("Submission acceptance contradicts its prepared identity");
623
+ return r;
624
+ }
625
+ if (r.executionId !== null) throw Error("Cannot prepare an accepted submission without its prepared identity");
626
+ if (r.dispatchAttempts !== 0) throw Error("Cannot choose an execution identity after an unbound dispatch");
627
+ if (r.retry.stoppedAt !== null) throw Error("Cannot prepare a stopped admission submission");
628
+ if (await e.update("_voltro_workflow_submissions", t, { preparedExecutionId: n }) === null) throw Error("Admission submission disappeared while preparing execution");
629
+ return {
630
+ ...r,
631
+ preparedExecutionId: n
632
+ };
633
+ }, Ue = async (e, t, n, i, a = !1) => {
634
+ if (a !== !1 && (!Number.isSafeInteger(a) || a < 1)) throw Error("Submission retry limit must be a positive integer or false");
635
+ let o = await M(e, t);
636
+ if (o === void 0) throw Error("Cannot record failure for an unknown submission");
637
+ if (o.executionId !== null || o.failureId !== null || o.retry.stoppedAt !== null) return o;
638
+ let s = o.retry.attempts + 1, c = {
639
+ attempts: s,
640
+ lastError: r(o.workflowName, n),
641
+ after: i + W(s),
642
+ stoppedAt: a !== !1 && s >= a ? i : null
643
+ };
644
+ if (await e.update("_voltro_workflow_submissions", t, { retry: c }) === null) throw Error("Admission submission disappeared while recording failure");
645
+ return {
646
+ ...o,
647
+ retry: c
648
+ };
649
+ }, We = async (e, t, n) => {
650
+ let r = await M(e, t);
651
+ if (r === void 0) throw Error("Cannot dispatch an unknown admission submission");
652
+ if (!r.receiptsBound || r.executionId !== null || r.failureId !== null || r.retry.stoppedAt !== null || r.retry.after > n) return null;
653
+ let i = r.dispatchAttempts + 1;
654
+ if (!Number.isSafeInteger(i)) throw Error("Submission dispatch counter exhausted");
655
+ if (await e.update("_voltro_workflow_submissions", t, { dispatchAttempts: i }) === null) throw Error("Admission submission disappeared before dispatch");
656
+ return {
657
+ ...r,
658
+ dispatchAttempts: i
659
+ };
660
+ }, Ge = async (e, t, n, r) => {
661
+ if (!Number.isSafeInteger(n) || n < 0) throw Error("Invalid submission dispatch attempt");
662
+ let i = await M(e, t);
663
+ if (i === void 0) throw Error("Cannot reject an unknown admission submission");
664
+ if (i.failureId !== null) {
665
+ let n = await D(e, i.failureId);
666
+ if (n === void 0 || n.sourceKind !== "submission" || n.sourceId !== t || n.workflowName !== i.workflowName || n.tenantId !== i.tenantId) throw Error("Rejected submission has no matching durable failure report");
667
+ return await O(e, n.id, r.now), n;
668
+ }
669
+ if (!i.receiptsBound || i.executionId !== null || i.dispatchAttempts !== n || n > 1) return;
670
+ let a = `wffr_${ie("sha256").update(JSON.stringify(["submission", t])).digest("hex").slice(0, 40)}`, o = await ve(e, {
671
+ id: a,
672
+ sourceKind: "submission",
673
+ sourceId: t,
674
+ workflowName: i.workflowName,
675
+ tenantId: i.tenantId,
676
+ handler: await be(e, t) ? null : r.handler,
677
+ callerContext: i.callerContext,
678
+ report: {
679
+ workflow: i.workflowName,
680
+ payload: i.payload,
681
+ errorTag: "WorkflowPayloadError",
682
+ errorMessage: r.errorMessage,
683
+ reason: "permanent input rejection before engine acceptance",
684
+ failedAt: r.now,
685
+ runId: null,
686
+ executionId: null
687
+ }
688
+ });
689
+ if (await e.update("_voltro_workflow_admissions", i.ledgerId, { releasedAt: new Date(r.now) }) === null) throw Error("Rejected admission submission has no lease");
690
+ if (await e.update("_voltro_workflow_submissions", t, { failureId: a }) === null) throw Error("Admission submission disappeared during rejection");
691
+ return await O(e, o.id, r.now), o;
692
+ }, Ke = async (e, t) => {
693
+ if (t.failureId === null) throw Error("Workflow submission has no rejection marker");
694
+ let n = await D(e, t.failureId);
695
+ if (t.executionId !== null || t.dispatchAttempts > 1 || n === void 0 || n.sourceKind !== "submission" || n.sourceId !== t.id || n.workflowName !== t.workflowName || n.tenantId !== t.tenantId || n.report.executionId !== null || n.report.runId !== null) throw Error("Workflow start rejection has contradictory ownership or execution evidence");
696
+ return n.id;
697
+ }, N = "_voltro_workflow_start_receipts", qe = c.Struct({
698
+ id: c.String,
699
+ workflowName: c.String,
700
+ tenantId: c.NullOr(c.String),
701
+ pendingId: c.String,
702
+ submissionId: c.NullOr(c.String),
703
+ terminal: c.NullOr(f)
704
+ }).pipe(c.filter((e) => e.submissionId === null || e.terminal === null, { message: () => "A start receipt cannot be both submitted and terminal before admission" })), P = c.decodeUnknownSync(qe), F = async (e, t) => {
705
+ let n = await e.query({
706
+ table: N,
707
+ predicate: h("id", t),
708
+ order: [],
709
+ take: 1,
710
+ skip: void 0,
711
+ projection: void 0
712
+ });
713
+ return n[0] === void 0 ? void 0 : P(n[0]);
714
+ }, Je = async (e, t) => {
715
+ let n = await F(e, t.receiptId);
716
+ if (n === void 0 || n.workflowName !== t.workflowName || n.tenantId !== t.tenantId) throw Error("Workflow start receipt is missing or belongs to another workflow or tenant");
717
+ if (n.terminal !== null) {
718
+ if (n.terminal.kind === "abandoned") {
719
+ let t = await D(e, n.terminal.failureId);
720
+ if (t === void 0 || t.workflowName !== n.workflowName || t.tenantId !== n.tenantId || t.sourceKind !== "intent" || t.report.executionId !== null || t.report.runId !== null) throw Error("Abandoned workflow receipt has no matching failure report");
721
+ }
722
+ return {
723
+ kind: "terminal",
724
+ outcome: n.terminal
725
+ };
726
+ }
727
+ if (n.submissionId === null) {
728
+ let t = await e.query({
729
+ table: I,
730
+ predicate: h("id", n.pendingId),
731
+ order: [],
732
+ take: 1,
733
+ skip: void 0,
734
+ projection: void 0
735
+ });
736
+ if (t[0] === void 0) throw Error("Workflow receipt has no pending input or submission");
737
+ let r = H(t[0]);
738
+ if (r.workflowName !== n.workflowName || r.tenantId !== n.tenantId) throw Error("Workflow receipt pending input belongs to another workflow or tenant");
739
+ if (r.deadLetteredAt !== void 0) throw Error("Workflow receipt input is dead-lettered; reconciliation required");
740
+ return { kind: "pending" };
741
+ }
742
+ let r = await M(e, n.submissionId);
743
+ if (r === void 0 || !r.receiptsBound || r.workflowName !== n.workflowName || r.tenantId !== n.tenantId || !r.intentIds.includes(n.pendingId)) throw Error("Workflow receipt has no matching admission submission");
744
+ if (r.failureId !== null) return {
745
+ kind: "rejected",
746
+ failureId: await Ke(e, r)
747
+ };
748
+ if (r.executionId === null) {
749
+ if (r.retry.stoppedAt !== null) throw Error("Workflow start acceptance is unresolved; reconciliation required");
750
+ return { kind: "pending" };
751
+ }
752
+ if (r.executionId.length === 0 || r.executionId !== r.preparedExecutionId) throw Error("Workflow start acknowledgement contradicts its prepared identity");
753
+ return {
754
+ kind: "accepted",
755
+ executionId: r.executionId
756
+ };
757
+ }, Ye = async (e, t) => {
758
+ if (t.id.length === 0 || t.id === t.pendingId) throw Error("Workflow start receipt requires an identity distinct from its queue slot");
759
+ let n = P((await e.insertIgnoreWithOutcome(N, {
760
+ ...t,
761
+ submissionId: null,
762
+ terminal: null
763
+ }, { conflictColumns: ["id"] })).row);
764
+ if (n.workflowName !== t.workflowName || n.tenantId !== t.tenantId || n.pendingId !== t.pendingId) throw Error("Workflow start receipt identity belongs to a different start");
765
+ return n;
766
+ }, Xe = async (e, t) => {
767
+ let n = await M(e, t);
768
+ if (n === void 0) throw Error("Cannot bind receipts to an unknown admission submission");
769
+ if (n.receiptsBound) return 0;
770
+ let r = 0;
771
+ for (let t of new Set(n.intentIds)) for (;;) {
772
+ let i = await e.query({
773
+ table: N,
774
+ predicate: p(h("pendingId", t), v("submissionId"), v("terminal")),
775
+ order: [{
776
+ column: "id",
777
+ direction: "asc"
778
+ }],
779
+ take: 100,
780
+ skip: void 0,
781
+ projection: void 0
782
+ });
783
+ if (i.length === 0) break;
784
+ for (let t of i) {
785
+ let i = P(t);
786
+ if (i.workflowName !== n.workflowName || i.tenantId !== n.tenantId) throw Error("Pending receipt belongs to a different workflow or tenant");
787
+ if (await e.update("_voltro_workflow_start_receipts", i.id, { submissionId: n.id }) === null) throw Error("Workflow start receipt disappeared during queue transfer");
788
+ r++;
789
+ }
790
+ }
791
+ if (await e.update("_voltro_workflow_submissions", t, { receiptsBound: !0 }) === null) throw Error("Admission submission disappeared during receipt binding");
792
+ return r;
793
+ }, Ze = async (e, t) => {
794
+ let n = c.decodeUnknownSync(f)(t.terminal);
795
+ for (;;) {
796
+ let r = await e.query({
797
+ table: N,
798
+ predicate: p(h("pendingId", t.pendingId), v("submissionId"), v("terminal")),
799
+ order: [{
800
+ column: "id",
801
+ direction: "asc"
802
+ }],
803
+ take: 100,
804
+ skip: void 0,
805
+ projection: void 0
806
+ });
807
+ if (r.length === 0) return;
808
+ for (let i of r) {
809
+ let r = P(i);
810
+ if (r.workflowName !== t.workflowName || r.tenantId !== t.tenantId) throw Error("Terminal receipt belongs to a different workflow or tenant");
811
+ if (await e.update("_voltro_workflow_start_receipts", r.id, { terminal: n }) === null) throw Error("Start receipt disappeared while recording its terminal outcome");
812
+ }
813
+ }
814
+ }, I = "_voltro_workflow_pending", L = "_voltro_workflow_admissions", R = "_voltro_workflow_pauses", z = (e, t, n) => e.encodeWorkflowPayload === void 0 ? n : e.encodeWorkflowPayload(t, n), Qe = (e, t, n) => e.decodeWorkflowPayload === void 0 ? n : e.decodeWorkflowPayload(t, n), $e = 864e5, et = (e, t, n) => `wfp_${ie("sha256").update(`${e}\u0000${t}\u0000${n}`).digest("hex").slice(0, 40)}`, B = (e) => {
815
+ if (e instanceof Date) return e.getTime();
816
+ if (typeof e == "number") return e;
817
+ let t = Date.parse(String(e));
818
+ return Number.isNaN(t) ? 0 : t;
819
+ }, V = (e, t) => {
820
+ let n = typeof e == "number" ? e : Number(e);
821
+ return Number.isFinite(n) ? Math.trunc(n) : t;
822
+ }, H = (e) => ({
823
+ id: String(e.id),
824
+ tenantId: e.tenantId === null || e.tenantId === void 0 ? null : String(e.tenantId),
825
+ workflowName: String(e.workflowName),
826
+ controlKey: String(e.controlKey ?? ""),
827
+ mode: String(e.mode),
828
+ payload: e.payload,
829
+ callerContext: e.callerContext ?? null,
830
+ queuedAppVersion: e.queuedAppVersion === null || e.queuedAppVersion === void 0 ? null : String(e.queuedAppVersion),
831
+ queuedSchemaFingerprint: e.queuedSchemaFingerprint === null || e.queuedSchemaFingerprint === void 0 ? null : String(e.queuedSchemaFingerprint),
832
+ priority: V(e.priority, 0),
833
+ dueAt: B(e.dueAt),
834
+ deadlineAt: e.deadlineAt === null || e.deadlineAt === void 0 ? void 0 : B(e.deadlineAt),
835
+ collapsed: V(e.collapsed, 1),
836
+ firstSeenAt: B(e.firstSeenAt),
837
+ attempts: V(e.attempts, 0),
838
+ lastError: e.lastError === null || e.lastError === void 0 ? null : a(String(e.lastError)),
839
+ deadLetteredAt: e.deadLetteredAt === null || e.deadLetteredAt === void 0 ? void 0 : B(e.deadLetteredAt)
840
+ }), U = (e, t, n, r) => ({
841
+ table: e,
842
+ predicate: t,
843
+ order: n,
844
+ take: r,
845
+ skip: void 0,
846
+ projection: void 0
847
+ }), tt = async (e) => {
848
+ let t = await e.query(U(R, void 0, [], 1e3));
849
+ return new Set(t.map((e) => String(e.id)));
850
+ }, nt = async (e, t, n, r) => {
851
+ await e.upsert(R, {
852
+ id: t,
853
+ pausedAt: /* @__PURE__ */ new Date(),
854
+ pausedBy: n,
855
+ reason: r
856
+ }, {
857
+ conflictColumns: ["id"],
858
+ update: [
859
+ "pausedAt",
860
+ "pausedBy",
861
+ "reason"
862
+ ]
863
+ });
864
+ }, rt = async (e, t) => e.delete(R, t), it = async (e) => {
865
+ let { store: t, control: n, keys: r, now: i } = e, a = { paused: e.paused }, o = [];
866
+ n.debounce !== void 0 && r.debounceKey !== void 0 && o.push((async () => {
867
+ let e = (await t.query(U(I, p(h("workflowName", n.workflowName), h("controlKey", r.debounceKey), h("mode", "debounce")), [], 1)))[0];
868
+ if (e === void 0) return;
869
+ let i = e.deadlineAt === null || e.deadlineAt === void 0 ? void 0 : B(e.deadlineAt);
870
+ a.debouncePending = {
871
+ firstSeenAt: B(e.firstSeenAt),
872
+ collapsed: V(e.collapsed, 1),
873
+ ...i === void 0 ? {} : { deadlineAt: i }
874
+ };
875
+ })()), n.batch !== void 0 && r.batchKey !== void 0 && o.push((async () => {
876
+ let e = await t.query(U(I, p(h("workflowName", n.workflowName), h("controlKey", r.batchKey), h("mode", "batch")), [{
877
+ column: "firstSeenAt",
878
+ direction: "asc"
879
+ }], n.batch.maxSize + 1));
880
+ e.length !== 0 && (a.batchPending = {
881
+ count: e.length,
882
+ firstSeenAt: B(e[0].firstSeenAt)
883
+ });
884
+ })()), n.singleton !== void 0 && r.singletonKey !== void 0 && o.push((async () => {
885
+ let e = await at(t, n.workflowName, r.singletonKey, i);
886
+ e === "unacknowledged" ? a.singletonUnacknowledged = !0 : e !== void 0 && (a.singletonHolder = e);
887
+ })()), n.concurrency !== void 0 && r.concurrencyKey !== void 0 && o.push((async () => {
888
+ let e = n.concurrency.pool === void 0 ? [h("workflowName", n.workflowName)] : [], o = await t.query(U(L, p(...e, h("concurrencyKey", r.concurrencyKey), v("releasedAt"), te(v("executionId"), g("expiresAt", new Date(i)))), [], n.concurrency.limit));
889
+ a.inFlight = o.length;
890
+ })());
891
+ let s = n.rateLimit ?? n.throttle, c = r.rateLimitKey ?? r.throttleKey;
892
+ return s !== void 0 && c !== void 0 && o.push((async () => {
893
+ let e = await t.query(U(L, p(h("workflowName", n.workflowName), h("rateKey", c), h("outcome", "admitted"), g("admittedAt", new Date(i - s.periodMs))), [{
894
+ column: "admittedAt",
895
+ direction: "desc"
896
+ }], s.limit));
897
+ a.recentAdmissions = e.map((e) => B(e.admittedAt));
898
+ })()), await Promise.all(o), a;
899
+ }, at = async (e, t, n, r) => {
900
+ if ((await e.query(U("_voltro_workflow_admissions", p(h("workflowName", t), h("singletonKey", n), v("releasedAt"), v("executionId")), [], 1))).length > 0) return "unacknowledged";
901
+ let i = (await e.query(U(L, p(h("workflowName", t), h("singletonKey", n), v("releasedAt"), g("expiresAt", new Date(r))), [{
902
+ column: "admittedAt",
903
+ direction: "desc"
904
+ }], 1)))[0];
905
+ if (i === void 0) return;
906
+ let a = i.executionId;
907
+ if (a != null) return {
908
+ executionId: String(a),
909
+ runId: i.runId === null || i.runId === void 0 ? "" : String(i.runId),
910
+ admittedAt: B(i.admittedAt)
911
+ };
912
+ }, ot = async (e) => {
913
+ let { store: t, control: n, decision: r, now: i } = e, a = ct(r.mode, r.keys);
914
+ if (r.collapse === "hold") {
915
+ let o = e.existingId ?? et(n.workflowName, r.mode, a);
916
+ return await t.update(I, o, {
917
+ dueAt: new Date(r.dueAt),
918
+ updatedAt: new Date(i)
919
+ }), o;
920
+ }
921
+ if (r.collapse === "replace") {
922
+ let o = et(n.workflowName, r.mode, a);
923
+ return await Ze(t, {
924
+ pendingId: o,
925
+ workflowName: n.workflowName,
926
+ tenantId: e.tenantId,
927
+ terminal: {
928
+ kind: "superseded",
929
+ at: i
930
+ }
931
+ }), await t.upsert(I, {
932
+ id: o,
933
+ tenantId: e.tenantId,
934
+ workflowName: n.workflowName,
935
+ controlKey: a,
936
+ mode: r.mode,
937
+ payload: z(t, n.workflowName, e.payload),
938
+ callerContext: e.callerContext ?? null,
939
+ queuedAppVersion: e.queuedAppVersion ?? null,
940
+ queuedSchemaFingerprint: e.queuedSchemaFingerprint ?? null,
941
+ priority: r.keys.priority,
942
+ dueAt: new Date(r.dueAt),
943
+ deadlineAt: r.deadlineAt === void 0 ? null : new Date(r.deadlineAt),
944
+ collapsed: 1,
945
+ firstSeenAt: new Date(i),
946
+ updatedAt: new Date(i),
947
+ attempts: 0,
948
+ lastError: null,
949
+ deadLetteredAt: null
950
+ }, {
951
+ conflictColumns: ["id"],
952
+ update: (a) => ({
953
+ payload: z(t, n.workflowName, e.payload),
954
+ callerContext: e.callerContext ?? null,
955
+ queuedAppVersion: e.queuedAppVersion ?? null,
956
+ queuedSchemaFingerprint: e.queuedSchemaFingerprint ?? null,
957
+ priority: r.keys.priority,
958
+ dueAt: new Date(r.dueAt),
959
+ deadlineAt: r.deadlineAt === void 0 ? a.deadlineAt ?? null : new Date(r.deadlineAt),
960
+ collapsed: V(a.collapsed, 1) + 1,
961
+ updatedAt: new Date(i),
962
+ attempts: 0,
963
+ lastError: null,
964
+ deadLetteredAt: null
965
+ })
966
+ }), o;
967
+ }
968
+ let o = await t.insert(I, {
969
+ id: `wfpi_${x()}`,
970
+ tenantId: e.tenantId,
971
+ workflowName: n.workflowName,
972
+ controlKey: a,
973
+ mode: r.mode,
974
+ payload: z(t, n.workflowName, e.payload),
975
+ callerContext: e.callerContext ?? null,
976
+ queuedAppVersion: e.queuedAppVersion ?? null,
977
+ queuedSchemaFingerprint: e.queuedSchemaFingerprint ?? null,
978
+ priority: r.keys.priority,
979
+ dueAt: new Date(r.dueAt),
980
+ deadlineAt: r.deadlineAt === void 0 ? null : new Date(r.deadlineAt),
981
+ collapsed: 1,
982
+ firstSeenAt: new Date(i),
983
+ updatedAt: new Date(i),
984
+ attempts: 0,
985
+ lastError: null,
986
+ deadLetteredAt: null
987
+ });
988
+ return String(o.id);
989
+ }, st = async (e) => {
990
+ let t = await e.store.insert(I, {
991
+ id: `wfpi_${x()}`,
992
+ tenantId: e.tenantId,
993
+ workflowName: e.workflowName,
994
+ controlKey: "",
995
+ mode: "delayed",
996
+ payload: z(e.store, e.workflowName, e.payload),
997
+ callerContext: e.callerContext ?? null,
998
+ queuedAppVersion: e.queuedAppVersion ?? null,
999
+ queuedSchemaFingerprint: e.queuedSchemaFingerprint ?? null,
1000
+ priority: 0,
1001
+ dueAt: new Date(e.at),
1002
+ deadlineAt: null,
1003
+ collapsed: 1,
1004
+ firstSeenAt: new Date(e.now),
1005
+ updatedAt: new Date(e.now),
1006
+ attempts: 0,
1007
+ lastError: null,
1008
+ deadLetteredAt: null
1009
+ });
1010
+ return {
1011
+ intentId: String(t.id),
1012
+ dueAt: e.at
1013
+ };
1014
+ }, ct = (e, t) => {
1015
+ switch (e) {
1016
+ case "debounce": return t.debounceKey ?? "";
1017
+ case "batch": return t.batchKey ?? "";
1018
+ case "throttle": return t.throttleKey ?? "";
1019
+ case "concurrency": return t.concurrencyKey ?? "";
1020
+ case "singleton": return t.singletonKey ?? "";
1021
+ default: return "";
1022
+ }
1023
+ }, lt = async (e) => {
1024
+ let { control: t, keys: n, now: r } = e, i = t.timeouts?.finishMs ?? 864e5, a = await e.store.insert(L, {
1025
+ id: `wfad_${x()}`,
1026
+ tenantId: e.tenantId,
1027
+ workflowName: t.workflowName,
1028
+ outcome: e.outcome,
1029
+ mode: e.mode,
1030
+ reason: e.reason,
1031
+ collapsed: e.collapsed,
1032
+ waitedMs: e.waitedMs,
1033
+ executionId: e.executionId,
1034
+ runId: e.runId,
1035
+ singletonKey: n.singletonKey ?? null,
1036
+ concurrencyKey: n.concurrencyKey ?? null,
1037
+ concurrencyReservation: t.concurrency === void 0 ? null : {
1038
+ pool: t.concurrency.pool ?? null,
1039
+ key: n.concurrencyKey ?? null,
1040
+ limit: t.concurrency.limit
1041
+ },
1042
+ rateKey: n.rateLimitKey ?? n.throttleKey ?? null,
1043
+ admittedAt: new Date(r),
1044
+ expiresAt: e.outcome === "admitted" ? new Date(r + i) : null,
1045
+ releasedAt: e.outcome === "admitted" ? null : new Date(r)
1046
+ });
1047
+ return String(a.id);
1048
+ }, ut = async (e, t, n) => {
1049
+ let r = !1;
1050
+ for (;;) {
1051
+ let i = await e.query(U(L, p(h("executionId", t), h("outcome", "admitted"), v("releasedAt")), [], 10));
1052
+ if (i.length === 0) return r;
1053
+ for (let t of i) if (await e.update("_voltro_workflow_admissions", String(t.id), { releasedAt: new Date(n) }) === null) throw Error("Admission lease disappeared during release");
1054
+ r = !0;
1055
+ }
1056
+ }, dt = async (e, t, n) => (await ft(e, t, n)).due, ft = async (e, t, n) => {
1057
+ let r = (await e.query(U(I, v("deadLetteredAt"), [{
1058
+ column: "priority",
1059
+ direction: "desc"
1060
+ }, {
1061
+ column: "firstSeenAt",
1062
+ direction: "asc"
1063
+ }], n))).map(H), i;
1064
+ for (let e of r) e.dueAt <= t || (i === void 0 || e.dueAt < i) && (i = e.dueAt);
1065
+ return {
1066
+ due: r.filter((e) => e.dueAt <= t).sort(ge),
1067
+ nextDueAt: i
1068
+ };
1069
+ }, pt = async (e, t) => (await e.query(U(I, void 0, [{
1070
+ column: "firstSeenAt",
1071
+ direction: "asc"
1072
+ }], t))).map(H), mt = async (e, t) => e.delete(I, t), ht = async (e, t, n, r) => C(e, (e) => gt(e, t, n, r)), gt = async (e, t, n, r) => {
1073
+ let i = (await e.query(U(I, h("id", t), [], 1)))[0];
1074
+ if (i === void 0) return !1;
1075
+ let a = H(i);
1076
+ if (await e.insert(L, {
1077
+ id: `wfa_${x()}`,
1078
+ tenantId: a.tenantId,
1079
+ workflowName: a.workflowName,
1080
+ outcome: "discarded",
1081
+ mode: a.mode,
1082
+ reason: n,
1083
+ collapsed: a.collapsed,
1084
+ waitedMs: Math.max(0, r - a.firstSeenAt),
1085
+ executionId: null,
1086
+ runId: null,
1087
+ singletonKey: null,
1088
+ concurrencyKey: a.controlKey === "" ? null : a.controlKey,
1089
+ rateKey: null,
1090
+ admittedAt: new Date(r),
1091
+ expiresAt: null,
1092
+ releasedAt: new Date(r)
1093
+ }), await Ze(e, {
1094
+ pendingId: t,
1095
+ workflowName: a.workflowName,
1096
+ tenantId: a.tenantId,
1097
+ terminal: {
1098
+ kind: "cancelled",
1099
+ at: r
1100
+ }
1101
+ }), !await e.delete("_voltro_workflow_pending", t)) throw Error("Pending intent disappeared during discard");
1102
+ return !0;
1103
+ }, W = (e, t = Math.random) => {
1104
+ let n = Math.min(1e3 * 2 ** Math.max(0, e - 1), 3e5);
1105
+ return Math.round(n / 2 + t() * (n / 2));
1106
+ }, _t = async (e, t, n, i) => {
1107
+ let a = t.attempts + 1;
1108
+ await e.update(I, t.id, {
1109
+ attempts: a,
1110
+ lastError: r(t.workflowName, n.slice(0, 500)),
1111
+ dueAt: new Date(i + W(a)),
1112
+ updatedAt: new Date(i)
1113
+ });
1114
+ }, vt = async (e, t, n, i) => await e.update(I, t.id, {
1115
+ attempts: t.attempts + 1,
1116
+ lastError: r(t.workflowName, n.slice(0, 500)),
1117
+ deadLetteredAt: new Date(i),
1118
+ updatedAt: new Date(i)
1119
+ }) !== null, yt = async (e, t, n) => {
1120
+ let r = (await e.query(U(I, h("id", t), [], 1)))[0];
1121
+ return r === void 0 || r.deadLetteredAt === null || r.deadLetteredAt === void 0 ? !1 : await e.update(I, t, {
1122
+ attempts: 0,
1123
+ lastError: null,
1124
+ deadLetteredAt: null,
1125
+ dueAt: new Date(n),
1126
+ updatedAt: new Date(n)
1127
+ }) !== null;
1128
+ }, bt = async (e) => {
1129
+ let t = await it({
1130
+ store: e.store,
1131
+ control: e.control,
1132
+ keys: e.keys,
1133
+ now: e.now,
1134
+ paused: e.paused
1135
+ });
1136
+ return fe({
1137
+ control: e.control,
1138
+ keys: e.keys,
1139
+ state: t,
1140
+ now: e.now,
1141
+ reconsidering: e.reconsidering
1142
+ });
1143
+ }, xt = async (e, t, n = 1e3) => {
1144
+ let r = await e.query(U(L, void 0, [{
1145
+ column: "admittedAt",
1146
+ direction: "asc"
1147
+ }], n)), i = t.getTime(), a = r.filter((e) => e.releasedAt != null && B(e.admittedAt) < i);
1148
+ return await Promise.all(a.map((t) => e.delete(L, String(t.id)))), a.length;
1149
+ }, G = "_voltro_workflow_control_requests", K = c.String.pipe(c.minLength(1)), St = c.Struct({
1150
+ kind: c.Literal("confirmed", "already-terminal"),
1151
+ status: c.Literal("succeeded", "failed", "cancelled"),
1152
+ completedAt: c.Number.pipe(c.finite()),
1153
+ output: c.Unknown,
1154
+ errorTag: c.NullOr(c.String),
1155
+ errorMessage: c.NullOr(c.String)
1156
+ }), Ct = c.Struct({
1157
+ kind: c.Literal("confirmed"),
1158
+ status: c.Literal("running"),
1159
+ enteredAt: c.Number.pipe(c.finite()),
1160
+ generation: K
1161
+ }), wt = c.Union(St, Ct), Tt = c.Struct({
1162
+ reason: c.NonEmptyString,
1163
+ detail: c.optional(c.Record({
1164
+ key: c.String,
1165
+ value: c.Unknown
1166
+ }))
1167
+ }), Et = c.Struct({ tenantId: c.NullOr(c.String) }), q = c.Struct({
1168
+ requestId: c.String.pipe(c.pattern(/^[1-9]\d*$/)),
1169
+ replyId: c.String.pipe(c.pattern(/^[1-9]\d*$/)),
1170
+ restartToken: c.NullOr(c.NonEmptyString)
1171
+ }), Dt = c.Struct({
1172
+ id: K,
1173
+ runId: K,
1174
+ workflowName: K,
1175
+ executionId: K,
1176
+ generation: K,
1177
+ operation: c.Literal("cancel", "terminate", "resume"),
1178
+ requestedAt: c.Number.pipe(c.finite()),
1179
+ owner: c.NullOr(Et),
1180
+ cause: c.optional(c.NullOr(Tt)),
1181
+ dispatchAttempts: c.Number.pipe(c.int(), c.nonNegative()),
1182
+ resumeJournal: c.NullOr(q),
1183
+ result: c.NullOr(wt)
1184
+ }), Ot = c.Struct({
1185
+ ...Dt.fields,
1186
+ requestedAt: c.DateFromSelf
1187
+ }), J = (e) => {
1188
+ let t = c.decodeUnknownSync(Ot)(e);
1189
+ return c.decodeUnknownSync(Dt)({
1190
+ ...t,
1191
+ requestedAt: t.requestedAt.getTime()
1192
+ });
1193
+ }, kt = async (e, t, n, r) => {
1194
+ if (await e.update("_voltro_workflow_control_requests", t.id, { result: n }) === null) throw Error("Workflow control request disappeared during settlement");
1195
+ await e.insert("_voltro_workflow_run_events", {
1196
+ id: m("wfev", JSON.stringify(["control-settled", t.id])),
1197
+ runId: t.runId,
1198
+ eventType: "control-settled",
1199
+ occurredAt: new Date(r),
1200
+ stepName: null,
1201
+ attempt: null,
1202
+ payload: {
1203
+ requestId: t.id,
1204
+ operation: t.operation,
1205
+ workflowName: t.workflowName,
1206
+ executionId: t.executionId,
1207
+ generation: t.generation,
1208
+ cause: t.cause ?? null,
1209
+ kind: n.kind,
1210
+ status: n.status,
1211
+ ..."generation" in n ? { enteredGeneration: n.generation } : {}
1212
+ }
1213
+ });
1214
+ }, At = async (e, t) => {
1215
+ let n = [], r;
1216
+ for (;;) {
1217
+ let i = await e({
1218
+ table: G,
1219
+ predicate: p(h("runId", t.runId), h("workflowName", t.workflowName), h("executionId", t.executionId), h("generation", t.generation), te(h("operation", "cancel"), h("operation", "terminate")), ...r === void 0 ? [] : [g("id", r)]),
1220
+ order: [{
1221
+ column: "id",
1222
+ direction: "asc"
1223
+ }],
1224
+ take: 100,
1225
+ skip: void 0,
1226
+ projection: void 0
1227
+ });
1228
+ for (let e of i) {
1229
+ let t = J(e);
1230
+ t.result === null && n.push(t);
1231
+ }
1232
+ if (i.length < 100) return n;
1233
+ r = J(i[i.length - 1]).id;
1234
+ }
1235
+ }, jt = async (e, t) => (await At(e, t)).length > 0, Mt = (e, t) => jt((t) => e.query({
1236
+ ...t,
1237
+ lock: "update"
1238
+ }), t), Nt = {
1239
+ source: "flow-control",
1240
+ timeout: "finish"
1241
+ }, Pt = c.Struct({
1242
+ reason: c.NonEmptyString,
1243
+ detail: c.Struct({
1244
+ source: c.Literal("flow-control"),
1245
+ timeout: c.Literal("finish"),
1246
+ onFailure: c.NullOr(c.NonEmptyString)
1247
+ })
1248
+ }), Ft = (e) => {
1249
+ let t = c.decodeUnknownOption(Pt)(e.cause);
1250
+ return t._tag === "Some" ? t.value : void 0;
1251
+ }, Y = async (e, t) => {
1252
+ let [n] = await e.query({
1253
+ table: G,
1254
+ predicate: h("id", t),
1255
+ lock: "update",
1256
+ order: [],
1257
+ take: 1,
1258
+ skip: void 0,
1259
+ projection: void 0
1260
+ });
1261
+ if (n !== void 0) return J(n);
1262
+ }, It = async (e, t) => {
1263
+ let n;
1264
+ for (;;) {
1265
+ let r = await e.query({
1266
+ table: G,
1267
+ predicate: p(h("parentClosureId", t), ...n === void 0 ? [] : [g("id", n)]),
1268
+ lock: "update",
1269
+ order: [{
1270
+ column: "id",
1271
+ direction: "asc"
1272
+ }],
1273
+ take: 100,
1274
+ skip: void 0,
1275
+ projection: void 0
1276
+ });
1277
+ for (let e of r) {
1278
+ let r = J(e);
1279
+ if (r.cause?.reason !== "parent-close" || r.cause.detail?.closureId !== t || r.operation === "resume") throw Error("Parent closure control has contradictory ownership");
1280
+ if (r.result === null) return !0;
1281
+ n = r.id;
1282
+ }
1283
+ if (r.length < 100) return !1;
1284
+ }
1285
+ }, Lt = async (e, t) => {
1286
+ let n = c.decodeUnknownSync(Dt)({
1287
+ ...t,
1288
+ owner: null,
1289
+ cause: t.cause ?? null,
1290
+ dispatchAttempts: 0,
1291
+ resumeJournal: null,
1292
+ result: null
1293
+ }), r = await Y(e, n.id);
1294
+ if (r !== void 0) {
1295
+ if (r.runId !== n.runId || r.workflowName !== n.workflowName || r.executionId !== n.executionId || r.generation !== n.generation || r.operation !== n.operation) throw Error("Workflow control identity belongs to a different target or operation");
1296
+ return r;
1297
+ }
1298
+ let i = new Date(n.requestedAt);
1299
+ if (!Number.isFinite(i.getTime())) throw Error("Workflow control timestamp is outside the supported date range");
1300
+ let [a] = await e.query({
1301
+ table: "_voltro_workflow_runs",
1302
+ predicate: h("id", n.runId),
1303
+ lock: "update",
1304
+ order: [],
1305
+ take: 1,
1306
+ skip: void 0,
1307
+ projection: void 0
1308
+ });
1309
+ if (a !== void 0 && (a.tag !== n.workflowName || a.executionId !== n.executionId)) throw Error("Workflow control target does not match its resident run");
1310
+ let o = c.decodeUnknownOption(Et)(a?.runnerGeneration === n.generation ? a.subject : void 0), s = {
1311
+ ...n,
1312
+ owner: o._tag === "Some" ? o.value : null
1313
+ }, l = a !== void 0 && a.runnerGeneration === n.generation && (a.status === "succeeded" || a.status === "failed" || a.status === "cancelled") ? {
1314
+ ...s,
1315
+ result: c.decodeUnknownSync(wt)({
1316
+ kind: "already-terminal",
1317
+ status: a.status,
1318
+ completedAt: c.decodeUnknownSync(c.DateFromSelf)(a.completedAt).getTime(),
1319
+ output: a.output,
1320
+ errorTag: a.errorTag,
1321
+ errorMessage: a.errorMessage
1322
+ })
1323
+ } : s, u = l.cause?.reason === "parent-close" ? c.decodeUnknownSync(c.NonEmptyString)(l.cause.detail?.closureId) : null;
1324
+ return await e.insert(G, {
1325
+ ...l,
1326
+ requestedAt: i,
1327
+ parentClosureId: u
1328
+ }), l.result !== null && await kt(e, l, l.result, n.requestedAt), l;
1329
+ }, Rt = async (e, t, n) => {
1330
+ let r = await Y(e, t);
1331
+ if (r === void 0) throw Error("Workflow control request is missing");
1332
+ if (r.operation !== "resume") throw Error("Only resume controls can bind a suspension journal");
1333
+ if (r.result !== null) return {
1334
+ kind: "settled",
1335
+ request: r
1336
+ };
1337
+ let [i] = await e.query({
1338
+ table: "_voltro_workflow_runs",
1339
+ predicate: h("id", r.runId),
1340
+ lock: "update",
1341
+ order: [],
1342
+ take: 1,
1343
+ skip: void 0,
1344
+ projection: void 0
1345
+ });
1346
+ if (i === void 0) return {
1347
+ kind: "unknown",
1348
+ request: r
1349
+ };
1350
+ if (i.tag !== r.workflowName || i.executionId !== r.executionId) throw Error("Workflow control target does not match its resident run");
1351
+ if (i.runnerGeneration !== r.generation) return {
1352
+ kind: "superseded",
1353
+ request: r
1354
+ };
1355
+ if (i.status !== "suspended" || i.runnerEnteredAt !== null) return {
1356
+ kind: "not-suspended",
1357
+ request: r
1358
+ };
1359
+ let a = c.decodeUnknownSync(c.NullOr(c.Struct({
1360
+ requestId: q.fields.requestId,
1361
+ restartToken: q.fields.restartToken
1362
+ })))(i.engineDelivery);
1363
+ if (a === null) return {
1364
+ kind: "unknown",
1365
+ request: r
1366
+ };
1367
+ if (r.resumeJournal !== null) {
1368
+ if (r.resumeJournal.requestId !== a.requestId || r.resumeJournal.restartToken !== a.restartToken) throw Error("Resume journal binding does not match its resident delivery");
1369
+ return {
1370
+ kind: "bound",
1371
+ request: r
1372
+ };
1373
+ }
1374
+ if (r.dispatchAttempts !== 0) return {
1375
+ kind: "unknown",
1376
+ request: r
1377
+ };
1378
+ let o = await n({
1379
+ workflowName: r.workflowName,
1380
+ executionId: r.executionId,
1381
+ ...a
1382
+ });
1383
+ if (o === void 0) return {
1384
+ kind: "waiting-journal",
1385
+ request: r
1386
+ };
1387
+ let s = c.decodeUnknownSync(q)(o);
1388
+ if (s.requestId !== a.requestId || s.restartToken !== a.restartToken) throw Error("Observed suspension belongs to another engine delivery");
1389
+ if (await e.update("_voltro_workflow_control_requests", r.id, { resumeJournal: s }) === null) throw Error("Workflow control request disappeared during suspension binding");
1390
+ return {
1391
+ kind: "bound",
1392
+ request: {
1393
+ ...r,
1394
+ resumeJournal: s
1395
+ }
1396
+ };
1397
+ }, zt = async (e, t) => {
1398
+ let n = await Y(e, t);
1399
+ if (n === void 0) throw Error("Workflow control request is missing");
1400
+ if (n.result !== null) return {
1401
+ kind: "settled",
1402
+ request: n
1403
+ };
1404
+ let [r] = await e.query({
1405
+ table: "_voltro_workflow_runs",
1406
+ predicate: h("id", n.runId),
1407
+ lock: "update",
1408
+ order: [],
1409
+ take: 1,
1410
+ skip: void 0,
1411
+ projection: void 0
1412
+ });
1413
+ if (r === void 0) return {
1414
+ kind: "unknown",
1415
+ request: n
1416
+ };
1417
+ if (r.tag !== n.workflowName || r.executionId !== n.executionId) throw Error("Workflow control target does not match its resident run");
1418
+ if (r.runnerGeneration !== n.generation) return {
1419
+ kind: "superseded",
1420
+ request: n
1421
+ };
1422
+ if (r.status === "succeeded" || r.status === "failed" || r.status === "cancelled") return {
1423
+ kind: "already-terminal",
1424
+ request: n,
1425
+ run: r
1426
+ };
1427
+ if (r.status !== "running" && r.status !== "suspended") throw Error("Workflow control target has an invalid resident status");
1428
+ let i = n.dispatchAttempts + 1;
1429
+ if (!Number.isSafeInteger(i)) throw Error("Workflow control attempt counter exhausted");
1430
+ if (await e.update("_voltro_workflow_control_requests", n.id, { dispatchAttempts: i }) === null) throw Error("Workflow control request disappeared before dispatch");
1431
+ return {
1432
+ kind: "dispatch",
1433
+ request: {
1434
+ ...n,
1435
+ dispatchAttempts: i
1436
+ }
1437
+ };
1438
+ }, Bt = async (e, n) => {
1439
+ let a = n.owner, o;
1440
+ for (;;) {
1441
+ let s = await e.query({
1442
+ table: G,
1443
+ predicate: p(h("runId", a.runId), h("workflowName", a.workflowName), h("executionId", a.executionId), h("generation", a.generation), ...o === void 0 ? [] : [g("id", o)]),
1444
+ lock: "update",
1445
+ order: [{
1446
+ column: "id",
1447
+ direction: "asc"
1448
+ }],
1449
+ take: 100,
1450
+ skip: void 0,
1451
+ projection: void 0
1452
+ });
1453
+ for (let o of s) {
1454
+ if (typeof o.id != "string") throw Error("Workflow control request has an invalid identity");
1455
+ let s = await Y(e, o.id);
1456
+ if (s === void 0) throw Error("Workflow control request disappeared during completion");
1457
+ if (s.result !== null) continue;
1458
+ let l = n.outcome;
1459
+ await kt(e, s, c.decodeUnknownSync(wt)({
1460
+ kind: l.status === "cancelled" && s.operation !== "resume" ? "confirmed" : "already-terminal",
1461
+ status: l.status,
1462
+ completedAt: n.now,
1463
+ output: l.status === "succeeded" ? i(a.workflowName) ? t(l.output, `workflow '${a.workflowName}' result`) : l.output : null,
1464
+ errorTag: l.status === "failed" ? l.errorTag : null,
1465
+ errorMessage: l.status === "failed" ? r(a.workflowName, l.errorMessage) : null
1466
+ }), n.now);
1467
+ }
1468
+ if (s.length < 100) return;
1469
+ let l = s[s.length - 1];
1470
+ if (typeof l.id != "string") throw Error("Workflow control cursor has an invalid identity");
1471
+ o = l.id;
1472
+ }
1473
+ }, Vt = async (e, t, n, r) => {
1474
+ let i = c.decodeUnknownSync(Ct)({
1475
+ kind: "confirmed",
1476
+ status: "running",
1477
+ generation: n,
1478
+ enteredAt: r
1479
+ }), a;
1480
+ for (;;) {
1481
+ let n = await e.query({
1482
+ table: G,
1483
+ predicate: p(h("runId", t.runId), h("workflowName", t.workflowName), h("executionId", t.executionId), h("generation", t.generation), h("operation", "resume"), ...a === void 0 ? [] : [g("id", a)]),
1484
+ lock: "update",
1485
+ order: [{
1486
+ column: "id",
1487
+ direction: "asc"
1488
+ }],
1489
+ take: 100,
1490
+ skip: void 0,
1491
+ projection: void 0
1492
+ });
1493
+ for (let t of n) {
1494
+ if (typeof t.id != "string") throw Error("Workflow control request has an invalid identity");
1495
+ let n = await Y(e, t.id);
1496
+ if (n === void 0) throw Error("Workflow control request disappeared during resume");
1497
+ n.result === null && await kt(e, n, i, r);
1498
+ }
1499
+ if (n.length < 100) return;
1500
+ let o = n[n.length - 1];
1501
+ if (typeof o.id != "string") throw Error("Workflow control cursor has an invalid identity");
1502
+ a = o.id;
1503
+ }
1504
+ }, Ht = "voltro-workflow-restart", Ut = class extends o.Tag("voltro/CurrentWorkflowDelivery")() {}, Wt = (e) => ({
1505
+ ...e,
1506
+ registerEntity: (t, n, r) => e.registerEntity(t, t.type.startsWith("Workflow/") ? n.pipe(s.map((e) => {
1507
+ let t = e.run;
1508
+ if (typeof t != "function") throw Error("Workflow entity is missing its run handler");
1509
+ return {
1510
+ ...e,
1511
+ run: (e) => {
1512
+ let n = {
1513
+ requestId: String(e.requestId),
1514
+ restartToken: e.headers["voltro-workflow-restart"] ?? null
1515
+ };
1516
+ return s.suspend(() => {
1517
+ let n = t(e);
1518
+ return s.isEffect(n) ? n : s.die(/* @__PURE__ */ Error("Workflow run handler must return an Effect"));
1519
+ }).pipe(s.provideService(Ut, n));
1520
+ }
1521
+ };
1522
+ })) : n, r)
1523
+ }), Gt = c.parseJson(c.Struct({
1524
+ _tag: c.Literal("Success"),
1525
+ value: c.Struct({ _tag: c.Literal("Suspended") })
1526
+ })), Kt = c.parseJson(c.Record({
1527
+ key: c.String,
1528
+ value: c.String
1529
+ })), qt = (e) => s.gen(function* () {
1530
+ if (!/^[1-9]\d*$/.test(e.requestId) || e.workflowName.length === 0 || e.executionId.length === 0) return yield* s.die(/* @__PURE__ */ Error("Suspension observation requires an exact engine delivery owner"));
1531
+ let [t] = yield* (yield* S.SqlClient).withoutTransforms()`
1532
+ SELECT m.entity_type, m.entity_id, m.tag, m.headers, r.id AS reply_id, r.payload
1533
+ FROM cluster_messages m LEFT JOIN cluster_replies r
1534
+ ON r.id = m.last_reply_id AND r.request_id = m.id AND r.kind = 0
1535
+ WHERE m.id = ${e.requestId} AND m.kind = 0`;
1536
+ if (t === void 0) return;
1537
+ if (t.entity_type !== `Workflow/${e.workflowName}` || t.entity_id !== e.executionId || t.tag !== "run") return yield* s.die(/* @__PURE__ */ Error("Suspension observation belongs to another execution or procedure"));
1538
+ if (((yield* s.sync(() => c.decodeUnknownSync(Kt)(t.headers)))["voltro-workflow-restart"] ?? null) !== e.restartToken || t.reply_id === null || c.decodeUnknownOption(Gt)(t.payload)._tag === "None") return;
1539
+ let n = String(t.reply_id);
1540
+ return /^[1-9]\d*$/.test(n) ? {
1541
+ ...e,
1542
+ replyId: n
1543
+ } : yield* s.die(/* @__PURE__ */ Error("Suspension reply has an invalid identity"));
1544
+ }).pipe(s.provideService(S.SafeIntegers, !0)), Jt = (e, t) => s.gen(function* () {
1545
+ let { restart: n, suspension: r } = t, i = /* @__PURE__ */ new Map();
1546
+ for (let t of e) {
1547
+ if (!/^[1-9]\d*$/.test(t.requestId) || !/^[1-9]\d*$/.test(t.replyId)) return yield* s.die(/* @__PURE__ */ Error("Journal reset requires positive decimal request and reply identities"));
1548
+ let e = i.get(t.requestId);
1549
+ if (e !== void 0 && e !== t.replyId) return yield* s.die(/* @__PURE__ */ Error("Journal reset contains conflicting observations for one request"));
1550
+ i.set(t.requestId, t.replyId);
1551
+ }
1552
+ if (n !== void 0 && (!i.has(n.requestId) || n.token.length === 0 || n.token === n.previousToken || n.workflowName.length === 0 || n.executionId.length === 0)) return yield* s.die(/* @__PURE__ */ Error("Journal restart requires a selected request, new token and execution owner"));
1553
+ if (i.size === 0) return {
1554
+ kind: "reset",
1555
+ count: 0
1556
+ };
1557
+ let a = [...i].sort(([e], [t]) => e < t ? -1 : +(e > t)), o = (yield* S.SqlClient).withoutTransforms(), l = o("cluster_messages"), u = o("cluster_replies"), d = o.onDialectOrElse({
1558
+ pg: () => o.literal("FALSE"),
1559
+ orElse: () => o.literal("0")
1560
+ });
1561
+ return yield* s.gen(function* () {
1562
+ let e = /* @__PURE__ */ new Map();
1563
+ for (let [t] of a) {
1564
+ let r = yield* o.onDialectOrElse({
1565
+ mssql: () => o`
1566
+ SELECT last_reply_id FROM ${l} WITH (UPDLOCK, HOLDLOCK)
1567
+ WHERE id = ${t} AND kind = 0`,
1568
+ sqlite: () => o`
1569
+ SELECT last_reply_id FROM ${l} WHERE id = ${t} AND kind = 0`,
1570
+ orElse: () => o`
1571
+ SELECT last_reply_id FROM ${l} WHERE id = ${t} AND kind = 0 FOR UPDATE`
1572
+ });
1573
+ if (r.length !== 1) return {
1574
+ kind: "changed",
1575
+ requestId: t
1576
+ };
1577
+ if (e.set(t, String(r[0]?.last_reply_id)), n !== void 0) {
1578
+ let [e] = yield* o`
1579
+ SELECT entity_type, entity_id, tag FROM ${l} WHERE id = ${t}`;
1580
+ if (e?.entity_type !== `Workflow/${n.workflowName}` || e.entity_id !== n.executionId || e.tag !== (t === n.requestId ? "run" : "activity")) return yield* s.die(/* @__PURE__ */ Error("Journal restart selection belongs to another execution or procedure"));
1581
+ }
1582
+ }
1583
+ let t;
1584
+ if (r !== void 0) {
1585
+ let [e] = yield* o`
1586
+ SELECT entity_type, entity_id, tag, headers FROM ${l} WHERE id = ${r.requestId}`;
1587
+ if (e?.entity_type !== `Workflow/${r.workflowName}` || e.entity_id !== r.executionId || e.tag !== "run" || r.workflowName.length === 0 || r.executionId.length === 0) return yield* s.die(/* @__PURE__ */ Error("Journal resume selection belongs to another execution or procedure"));
1588
+ if (((yield* s.sync(() => c.decodeUnknownSync(c.parseJson(c.Record({
1589
+ key: c.String,
1590
+ value: c.String
1591
+ })))(e.headers)))["voltro-workflow-restart"] ?? null) !== r.restartToken) return {
1592
+ kind: "changed",
1593
+ requestId: r.requestId
1594
+ };
1595
+ }
1596
+ if (n !== void 0) {
1597
+ let [e] = yield* o`
1598
+ SELECT tag, entity_type, headers FROM ${l} WHERE id = ${n.requestId}`;
1599
+ if (e?.tag !== "run" || !e.entity_type.startsWith("Workflow/")) return yield* s.die(/* @__PURE__ */ Error("Journal restart marker can only target a workflow run"));
1600
+ if (t = yield* s.sync(() => c.decodeUnknownSync(c.parseJson(c.Record({
1601
+ key: c.String,
1602
+ value: c.String
1603
+ })))(e.headers)), t["voltro-workflow-restart"] === n.token) return {
1604
+ kind: "already-reset",
1605
+ count: a.length
1606
+ };
1607
+ if ((t["voltro-workflow-restart"] ?? null) !== n.previousToken) return {
1608
+ kind: "changed",
1609
+ requestId: n.requestId
1610
+ };
1611
+ }
1612
+ for (let [t, n] of a) {
1613
+ if (e.get(t) !== n) return {
1614
+ kind: "changed",
1615
+ requestId: t
1616
+ };
1617
+ let i = yield* o`SELECT payload FROM ${u}
1618
+ WHERE id = ${n} AND request_id = ${t} AND kind = 0`;
1619
+ if (i.length !== 1 || r !== void 0 && c.decodeUnknownOption(Gt)(i[0]?.payload)._tag === "None") return {
1620
+ kind: "changed",
1621
+ requestId: t
1622
+ };
1623
+ }
1624
+ n !== void 0 && (yield* o`UPDATE ${l} SET headers = ${JSON.stringify({
1625
+ ...t,
1626
+ [Ht]: n.token
1627
+ })}
1628
+ WHERE id = ${n.requestId}`);
1629
+ for (let [e] of a) yield* o`DELETE FROM ${u} WHERE request_id = ${e} AND kind = 0`, yield* o`DELETE FROM ${l} WHERE request_id = ${e} AND kind = 2`, yield* o`UPDATE ${l} SET processed = ${d}, last_reply_id = NULL,
1630
+ last_read = NULL WHERE request_id = ${e}`;
1631
+ return {
1632
+ kind: "reset",
1633
+ count: a.length
1634
+ };
1635
+ }).pipe(o.withTransaction, s.provideService(S.SafeIntegers, !0));
1636
+ }), Yt = (e, t) => Jt(e, t === void 0 ? {} : { restart: t }), Xt = (e) => Jt([e], { suspension: e }), X = ne("_voltro_workflow_restart_requests", {
1637
+ id: _({ prefix: "wfrs" }),
1638
+ runId: b(),
1639
+ workflowName: b(),
1640
+ executionId: b(),
1641
+ generation: b(),
1642
+ token: b(),
1643
+ ledgerId: b(),
1644
+ tenantId: b().nullable(),
1645
+ delivery: y(),
1646
+ replies: y(),
1647
+ selection: y().nullable(),
1648
+ eviction: y().nullable(),
1649
+ requestedAt: re(),
1650
+ dispatchAttempts: ee().default(0),
1651
+ enteredGeneration: b().nullable()
1652
+ }).unique(["runId", "generation"]).unique(["runId", "token"]).nonReactive(), Z = c.NonEmptyString, Q = c.Struct({
1653
+ requestId: Z,
1654
+ restartToken: c.NullOr(Z)
1655
+ }), Zt = c.Struct({
1656
+ requestId: Z,
1657
+ replyId: Z
1658
+ }), Qt = u, $t = ne("_voltro_workflow_restart_withdrawals", {
1659
+ id: _({ prefix: "wfrw" }),
1660
+ runId: b(),
1661
+ workflowName: b(),
1662
+ tenantId: b().nullable(),
1663
+ selection: y(),
1664
+ withdrawnAt: re()
1665
+ }).nonReactive(), en = c.Struct({
1666
+ id: c.NonEmptyString,
1667
+ runId: c.NonEmptyString,
1668
+ workflowName: c.NonEmptyString,
1669
+ tenantId: c.NullOr(c.NonEmptyString),
1670
+ selection: Qt,
1671
+ withdrawnAt: c.DateFromSelf
1672
+ }), tn = async (e, t) => {
1673
+ let n = c.decodeUnknownSync(d)(t), [r] = await e.query({
1674
+ table: $t.tableName,
1675
+ predicate: h("id", n.requestId),
1676
+ lock: "update",
1677
+ order: [],
1678
+ take: 1,
1679
+ skip: void 0,
1680
+ projection: void 0
1681
+ });
1682
+ if (r === void 0) return;
1683
+ let i = c.decodeUnknownSync(en)(r);
1684
+ if (i.runId !== n.runId) throw Error("Restart identity belongs to a different command");
1685
+ if (!Number.isFinite(i.withdrawnAt.getTime())) throw Error("Invalid restart withdrawal timestamp");
1686
+ return i;
1687
+ }, nn = async (e, t) => {
1688
+ if (await tn(e, t) !== void 0) throw Error("Restart request was permanently withdrawn");
1689
+ }, $ = c.Struct({
1690
+ id: Z,
1691
+ runId: Z,
1692
+ workflowName: Z,
1693
+ executionId: Z,
1694
+ generation: Z,
1695
+ token: Z,
1696
+ ledgerId: Z,
1697
+ tenantId: c.NullOr(Z),
1698
+ delivery: Q,
1699
+ replies: c.Array(Zt),
1700
+ selection: Qt,
1701
+ eviction: c.NullOr(c.Struct({
1702
+ executionId: Z,
1703
+ runId: c.String
1704
+ })),
1705
+ requestedAt: c.DateFromSelf,
1706
+ dispatchAttempts: c.NonNegativeInt,
1707
+ enteredGeneration: c.NullOr(Z)
1708
+ }), rn = (e, t) => e.kind === t.kind && (e.kind === "failed-steps" || t.kind === "from-step" && e.stepName === t.stepName), an = async (e, t) => {
1709
+ let n = c.decodeUnknownSync(d)(t), [r] = await e.query({
1710
+ table: X.tableName,
1711
+ predicate: h("id", n.requestId),
1712
+ lock: "update",
1713
+ order: [],
1714
+ take: 1,
1715
+ skip: void 0,
1716
+ projection: void 0
1717
+ });
1718
+ if (r === void 0) return;
1719
+ let i = c.decodeUnknownSync($)(r);
1720
+ if (i.runId !== n.runId) throw Error("Restart identity belongs to a different command");
1721
+ return i;
1722
+ }, on = async (e, t) => {
1723
+ let n = await tn(e, t);
1724
+ if (n !== void 0) return c.decodeUnknownSync(l)({
1725
+ ...t,
1726
+ kind: "withdrawn",
1727
+ workflowName: n.workflowName,
1728
+ selection: n.selection,
1729
+ withdrawnAt: n.withdrawnAt.getTime()
1730
+ });
1731
+ let r = await an(e, t);
1732
+ if (r === void 0) return c.decodeUnknownSync(l)({
1733
+ ...t,
1734
+ kind: "not-found"
1735
+ });
1736
+ let i = {
1737
+ requestId: r.id,
1738
+ runId: r.runId,
1739
+ workflowName: r.workflowName,
1740
+ executionId: r.executionId,
1741
+ originalGeneration: r.generation,
1742
+ selection: r.selection,
1743
+ requestedAt: r.requestedAt.getTime(),
1744
+ dispatchAttempts: r.dispatchAttempts
1745
+ };
1746
+ return c.decodeUnknownSync(l)(r.enteredGeneration === null ? {
1747
+ ...i,
1748
+ kind: "pending"
1749
+ } : {
1750
+ ...i,
1751
+ kind: "entered",
1752
+ enteredGeneration: r.enteredGeneration
1753
+ });
1754
+ }, sn = async (e, t) => {
1755
+ for (let e of [
1756
+ t.id,
1757
+ t.runId,
1758
+ t.workflowName
1759
+ ]) c.decodeUnknownSync(Z)(e);
1760
+ if (t.id.length > 64) throw Error("Invalid restart request identity");
1761
+ c.decodeUnknownSync(c.NullOr(Z))(t.tenantId);
1762
+ let n = c.decodeUnknownSync(Qt)(t.selection);
1763
+ await nn(e, {
1764
+ requestId: t.id,
1765
+ runId: t.runId
1766
+ });
1767
+ let r = await an(e, {
1768
+ requestId: t.id,
1769
+ runId: t.runId
1770
+ });
1771
+ if (r !== void 0) {
1772
+ if (r.runId !== t.runId || r.workflowName !== t.workflowName || r.tenantId !== t.tenantId || !rn(r.selection, n)) throw Error("Restart identity belongs to a different command");
1773
+ return r;
1774
+ }
1775
+ }, cn = async (e, t) => {
1776
+ let n = c.decodeUnknownSync(en)({
1777
+ ...t,
1778
+ withdrawnAt: new Date(t.now)
1779
+ });
1780
+ if (c.decodeUnknownSync(d)({
1781
+ requestId: n.id,
1782
+ runId: n.runId
1783
+ }), !Number.isFinite(n.withdrawnAt.getTime())) throw Error("Invalid restart withdrawal timestamp");
1784
+ let r = await tn(e, {
1785
+ requestId: n.id,
1786
+ runId: n.runId
1787
+ });
1788
+ if (r !== void 0) {
1789
+ if (r.workflowName !== n.workflowName || r.tenantId !== n.tenantId || !rn(r.selection, n.selection)) throw Error("Restart identity belongs to a different command");
1790
+ return {
1791
+ kind: "withdrawn",
1792
+ withdrawal: r,
1793
+ reused: !0
1794
+ };
1795
+ }
1796
+ let i = await sn(e, n);
1797
+ if (i !== void 0) return {
1798
+ kind: "reserved",
1799
+ request: i
1800
+ };
1801
+ let [a] = await e.query({
1802
+ table: "_voltro_workflow_runs",
1803
+ predicate: h("id", n.runId),
1804
+ lock: "update",
1805
+ order: [],
1806
+ take: 1,
1807
+ skip: void 0,
1808
+ projection: void 0
1809
+ });
1810
+ if (a === void 0 || a.tag !== n.workflowName) throw Error("Restart withdrawal requires its resident workflow");
1811
+ if ((c.decodeUnknownSync(c.NullOr(c.Struct({ tenantId: c.NullOr(Z) })))(a.subject ?? null)?.tenantId ?? null) !== n.tenantId) throw Error("Restart withdrawal belongs to another resident tenant");
1812
+ return await e.insert($t.tableName, n), {
1813
+ kind: "withdrawn",
1814
+ withdrawal: n,
1815
+ reused: !1
1816
+ };
1817
+ }, ln = async (e, t) => {
1818
+ c.decodeUnknownSync(Z)(t.generation);
1819
+ let n = await sn(e, t);
1820
+ if (n !== void 0 && n.generation !== t.generation) throw Error("Restart identity belongs to a different command");
1821
+ return n;
1822
+ }, un = async (e, t) => {
1823
+ for (let e of [
1824
+ t.id,
1825
+ t.runId,
1826
+ t.generation,
1827
+ t.token
1828
+ ]) c.decodeUnknownSync(Z)(e);
1829
+ if (t.id.length > 64 || !Number.isFinite(new Date(t.now).getTime())) throw Error("Invalid restart request identity or timestamp");
1830
+ await nn(e, {
1831
+ requestId: t.id,
1832
+ runId: t.runId
1833
+ });
1834
+ let n = c.decodeUnknownSync(Q)(t.delivery), r = c.decodeUnknownSync(Qt)(t.selection);
1835
+ if (n.restartToken === t.token) throw Error("Restart requires a new delivery token");
1836
+ let i = c.decodeUnknownSync(c.Array(Zt))(t.replies), a = /* @__PURE__ */ new Map();
1837
+ for (let e of i) {
1838
+ if (!/^[1-9]\d*$/.test(e.requestId) || !/^[1-9]\d*$/.test(e.replyId) || a.has(e.requestId)) throw Error("Restart requires distinct, exact journal reply identities");
1839
+ a.set(e.requestId, e.replyId);
1840
+ }
1841
+ if (!a.has(n.requestId)) throw Error("Restart selection must include its run reply");
1842
+ let [o] = await e.query({
1843
+ table: X.tableName,
1844
+ predicate: h("id", t.id),
1845
+ lock: "update",
1846
+ order: [],
1847
+ take: 1,
1848
+ skip: void 0,
1849
+ projection: void 0
1850
+ });
1851
+ if (o !== void 0) {
1852
+ let e = c.decodeUnknownSync($)(o);
1853
+ if (e.runId !== t.runId || e.generation !== t.generation || e.token !== t.token || e.workflowName !== t.control.workflowName || e.tenantId !== t.tenantId || e.delivery.requestId !== n.requestId || e.delivery.restartToken !== n.restartToken || !rn(e.selection, r) || e.replies.length !== a.size || e.replies.some((e) => a.get(e.requestId) !== e.replyId)) throw Error("Restart identity belongs to a different request");
1854
+ return {
1855
+ kind: "reserved",
1856
+ request: e,
1857
+ reused: !0
1858
+ };
1859
+ }
1860
+ let [s] = await e.query({
1861
+ table: "_voltro_workflow_runs",
1862
+ predicate: h("id", t.runId),
1863
+ lock: "update",
1864
+ order: [],
1865
+ take: 1,
1866
+ skip: void 0,
1867
+ projection: void 0
1868
+ });
1869
+ if (s === void 0 || s.tag !== t.control.workflowName || s.runnerGeneration !== t.generation || s.status !== "failed" || s.discardedAt != null || typeof s.executionId != "string" || s.executionId.length === 0) throw Error("Restart requires its undiscarded failed resident generation");
1870
+ if ((c.decodeUnknownSync(c.NullOr(c.Struct({ tenantId: c.NullOr(Z) })))(s.subject ?? null)?.tenantId ?? null) !== t.tenantId) throw Error("Restart belongs to another resident tenant");
1871
+ let l = c.decodeUnknownSync(Q)(s.engineDelivery);
1872
+ if (l.requestId !== n.requestId || l.restartToken !== n.restartToken) throw Error("Restart journal delivery does not belong to its resident generation");
1873
+ let [u] = await e.query({
1874
+ table: X.tableName,
1875
+ predicate: p(h("runId", t.runId), te(h("generation", t.generation), h("token", t.token))),
1876
+ lock: "update",
1877
+ order: [],
1878
+ take: 1,
1879
+ skip: void 0,
1880
+ projection: ["id", "generation"]
1881
+ });
1882
+ if (u !== void 0) {
1883
+ if (u.generation !== t.generation) throw Error("Restart delivery token was already used by this run");
1884
+ return { kind: "already-requested" };
1885
+ }
1886
+ let d = Qe(e, t.control.workflowName, s.payload), f = ue(t.control, d), m = await bt({
1887
+ store: e,
1888
+ control: t.control,
1889
+ keys: f,
1890
+ paused: t.paused,
1891
+ now: t.now,
1892
+ reconsidering: !0
1893
+ });
1894
+ if (m.kind !== "admit") return {
1895
+ kind: "not-admitted",
1896
+ decision: m
1897
+ };
1898
+ let g = await lt({
1899
+ store: e,
1900
+ control: t.control,
1901
+ keys: f,
1902
+ outcome: "admitted",
1903
+ mode: "restart",
1904
+ reason: m.reason,
1905
+ collapsed: 1,
1906
+ waitedMs: 0,
1907
+ executionId: null,
1908
+ runId: null,
1909
+ tenantId: t.tenantId,
1910
+ now: t.now
1911
+ });
1912
+ if (g === void 0) throw Error("Restart has no admission reservation");
1913
+ let _ = c.decodeUnknownSync($)({
1914
+ id: t.id,
1915
+ runId: t.runId,
1916
+ workflowName: t.control.workflowName,
1917
+ executionId: s.executionId,
1918
+ generation: t.generation,
1919
+ token: t.token,
1920
+ ledgerId: g,
1921
+ tenantId: t.tenantId,
1922
+ delivery: n,
1923
+ replies: i,
1924
+ selection: r,
1925
+ eviction: m.evict ?? null,
1926
+ requestedAt: new Date(t.now),
1927
+ dispatchAttempts: 0,
1928
+ enteredGeneration: null
1929
+ });
1930
+ return await e.insert(X.tableName, _), {
1931
+ kind: "reserved",
1932
+ request: _,
1933
+ reused: !1
1934
+ };
1935
+ }, dn = async (e, t) => {
1936
+ let [n] = await e.query({
1937
+ table: X.tableName,
1938
+ predicate: h("id", t),
1939
+ lock: "update",
1940
+ order: [],
1941
+ take: 1,
1942
+ skip: void 0,
1943
+ projection: void 0
1944
+ });
1945
+ if (n === void 0) throw Error("Restart dispatch has no resident request");
1946
+ let r = c.decodeUnknownSync($)(n);
1947
+ if (r.enteredGeneration !== null) throw Error("Restart request has already entered its resident generation");
1948
+ let [i] = await e.query({
1949
+ table: "_voltro_workflow_admissions",
1950
+ predicate: h("id", r.ledgerId),
1951
+ lock: "update",
1952
+ order: [],
1953
+ take: 1,
1954
+ skip: void 0,
1955
+ projection: void 0
1956
+ });
1957
+ if (i === void 0 || i.outcome !== "admitted" || i.releasedAt !== null || i.workflowName !== r.workflowName || i.tenantId !== r.tenantId || i.executionId !== null || i.runId !== null) throw Error("Restart dispatch has no matching held resident reservation");
1958
+ let [a] = await e.query({
1959
+ table: "_voltro_workflow_runs",
1960
+ predicate: h("id", r.runId),
1961
+ lock: "update",
1962
+ order: [],
1963
+ take: 1,
1964
+ skip: void 0,
1965
+ projection: void 0
1966
+ });
1967
+ if (a === void 0 || a.tag !== r.workflowName || a.executionId !== r.executionId || a.runnerGeneration !== r.generation || a.status !== "failed" || a.discardedAt != null) throw Error("Restart dispatch no longer owns its failed resident generation");
1968
+ let o = c.decodeUnknownSync(Q)(a.engineDelivery);
1969
+ if (o.requestId !== r.delivery.requestId || o.restartToken !== r.delivery.restartToken) throw Error("Restart dispatch no longer owns its journal delivery");
1970
+ return {
1971
+ request: r,
1972
+ run: a
1973
+ };
1974
+ }, fn = async (e, t) => {
1975
+ let { request: n } = await dn(e, t), r = n.dispatchAttempts + 1;
1976
+ if (!Number.isSafeInteger(r)) throw Error("Restart dispatch attempt counter exhausted");
1977
+ if (await e.update(X.tableName, t, { dispatchAttempts: r }) === null) throw Error("Restart request disappeared before dispatch");
1978
+ return {
1979
+ ...n,
1980
+ dispatchAttempts: r
1981
+ };
1982
+ }, pn = (e) => s.gen(function* () {
1983
+ let { request: t } = yield* s.promise(() => e.transaction((t) => dn(t, e.requestId)));
1984
+ if (!(yield* s.promise(() => e.acquireCapacity(t)))) return { kind: "waiting-capacity" };
1985
+ let n = yield* s.promise(() => e.transaction((e) => fn(e, t.id)));
1986
+ return yield* Yt(n.replies, {
1987
+ requestId: n.delivery.requestId,
1988
+ previousToken: n.delivery.restartToken,
1989
+ token: n.token,
1990
+ workflowName: n.workflowName,
1991
+ executionId: n.executionId
1992
+ });
1993
+ }), mn = async (e, t) => {
1994
+ for (let e of [
1995
+ t.runId,
1996
+ t.workflowName,
1997
+ t.executionId,
1998
+ t.generation
1999
+ ]) c.decodeUnknownSync(Z)(e);
2000
+ if (!Number.isFinite(new Date(t.now).getTime())) throw Error("Restart entry requires a valid timestamp");
2001
+ let n = c.decodeUnknownSync(Q)(t.delivery);
2002
+ if (n.restartToken === null) throw Error("Restart entry has no delivery token");
2003
+ let [r] = await e.query({
2004
+ table: X.tableName,
2005
+ predicate: p(h("runId", t.runId), h("token", n.restartToken)),
2006
+ lock: "update",
2007
+ order: [],
2008
+ take: 1,
2009
+ skip: void 0,
2010
+ projection: ["id"]
2011
+ });
2012
+ if (r === void 0) throw Error("Restart delivery has no matching resident request");
2013
+ let { request: i, run: a } = await dn(e, c.decodeUnknownSync(Z)(r.id));
2014
+ if (i.runId !== t.runId || i.workflowName !== t.workflowName || i.executionId !== t.executionId || i.generation === t.generation || i.delivery.requestId !== n.requestId || i.token !== n.restartToken) throw Error("Restart entry does not match its reserved delivery");
2015
+ if (i.dispatchAttempts === 0) throw Error("Restart entry has no committed dispatch attempt");
2016
+ if (await e.update("_voltro_workflow_admissions", i.ledgerId, {
2017
+ executionId: i.executionId,
2018
+ runId: i.runId
2019
+ }) === null) throw Error("Restart reservation disappeared during entry");
2020
+ if (await e.update(X.tableName, i.id, { enteredGeneration: t.generation }) === null) throw Error("Restart request disappeared during entry");
2021
+ let o = await e.update("_voltro_workflow_runs", i.runId, {
2022
+ runnerGeneration: t.generation,
2023
+ engineDelivery: n,
2024
+ runnerEnteredAt: new Date(t.now),
2025
+ reclaimCount: 0,
2026
+ status: "running",
2027
+ errorTag: null,
2028
+ errorMessage: null,
2029
+ output: null,
2030
+ completedAt: null,
2031
+ durationMs: null
2032
+ });
2033
+ if (o === null) throw Error("Restart run disappeared during entry");
2034
+ return {
2035
+ row: o,
2036
+ previous: a,
2037
+ event: await e.insert("_voltro_workflow_run_events", {
2038
+ id: m("wfev", JSON.stringify(["restart", i.id])),
2039
+ runId: i.runId,
2040
+ eventType: "run-redriven",
2041
+ occurredAt: new Date(t.now),
2042
+ stepName: null,
2043
+ attempt: null,
2044
+ payload: {
2045
+ requestId: i.id,
2046
+ executionId: i.executionId,
2047
+ previousGeneration: i.generation,
2048
+ generation: t.generation
2049
+ }
2050
+ })
2051
+ };
2052
+ }, hn = 6e5, gn = class extends o.Tag("@voltro/workflow/ClusterDiagnostics")() {}, _n = (e, t, n = Date.now()) => s.flatMap(e.messagesFor(t), (t) => {
2053
+ if (t.length === 0) return s.succeed(void 0);
2054
+ let r = [...new Set(t.filter((e) => !e.processed).map((e) => e.shardId))], i = r.length === 0 ? s.succeed([]) : e.shardLockHolders(r);
2055
+ return s.map(i, (r) => ({
2056
+ runner: e.ownAddress,
2057
+ shardLockMode: e.shardLockMode,
2058
+ messages: t.map((e) => ({
2059
+ tag: e.tag,
2060
+ shardId: e.shardId,
2061
+ processed: e.processed,
2062
+ lastRead: e.lastRead === null ? null : e.lastRead.toISOString(),
2063
+ unreadForMs: !e.processed && e.lastRead !== null ? Math.max(0, n - e.lastRead.getTime()) : null
2064
+ })),
2065
+ shardLocks: r
2066
+ }));
2067
+ });
2068
+ //#endregion
2069
+ export { ut as $, L as A, O as At, dt as B, he as Bt, Mt as C, M as Ct, Y as D, Re as Dt, At as E, Le as Et, vt as F, D as Ft, nt as G, C as Gt, bt as H, de as Ht, Qe as I, ve as It, ot as J, et as K, mt as L, ce as Lt, R as M, xe as Mt, I as N, Oe as Nt, Bt as O, Ae as Ot, pt as P, E as Pt, lt as Q, ht as R, ge as Rt, Ft as S, He as St, jt as T, Ge as Tt, _t as U, le as Ut, z as V, me as Vt, st as W, ue as Wt, it as X, xt as Y, tt as Z, Wt as _, Pe as _t, sn as a, Xe as at, zt as b, Fe as bt, un as c, Ye as ct, X as d, Ke as dt, rt as et, $t as f, je as ft, Ht as g, Ne as gt, Ut as h, We as ht, mn as i, N as it, $e as j, Se as jt, Vt as k, k as kt, pn as l, Je as lt, Xt as m, Ve as mt, gn as n, yt as nt, on as o, P as ot, qt as p, Be as pt, ft as q, _n as r, H as rt, ln as s, F as st, hn as t, W as tt, cn as u, Ze as ut, Nt as v, Me as vt, It as w, Ie as wt, Rt as x, ze as xt, Lt as y, Ue as yt, gt as z, fe as zt };