@soiljs/storage-postgres 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1423 @@
1
+ export { s3Artifacts } from './chunk-ZGVSDKKX.js';
2
+ import { createHash, randomUUID } from 'crypto';
3
+ import { Pool } from 'pg';
4
+ import { isTerminalTurnStatus, IdempotencyConflictError, isTerminalStepStatus, LeaseLostError, ConcurrencyConflictError, SessionBusyError } from '@soiljs/spi';
5
+
6
+ function fingerprint(value) {
7
+ return JSON.stringify(value, (_key, item) => {
8
+ if (item && typeof item === "object" && !Array.isArray(item))
9
+ return Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b)));
10
+ return item;
11
+ });
12
+ }
13
+ function sameScope(a, b) {
14
+ return fingerprint(a ?? {}) === fingerprint(b ?? {});
15
+ }
16
+ function conflict() {
17
+ throw new ConcurrencyConflictError();
18
+ }
19
+ function createLedger(state, timestamp) {
20
+ const now = () => new Date(timestamp).toISOString();
21
+ function transaction(fn) {
22
+ return Promise.resolve(structuredClone(fn()));
23
+ }
24
+ function get(id) {
25
+ const value = state.turns.get(id);
26
+ if (!value) throw new Error(`Turn ${id} not found.`);
27
+ return value;
28
+ }
29
+ function session(id) {
30
+ const value = state.sessions.get(id);
31
+ if (!value) throw new Error(`Session ${id} not found.`);
32
+ return value;
33
+ }
34
+ function fence(input) {
35
+ const snap = get(input.turnId);
36
+ const lease = snap.turn.lease;
37
+ if (!lease || lease.holderId !== input.lease.holderId || lease.epoch !== input.lease.epoch || Date.parse(lease.expiresAt) <= timestamp)
38
+ throw new LeaseLostError();
39
+ return snap;
40
+ }
41
+ function event(turn, type, data, step) {
42
+ const seq = ++state.seq;
43
+ state.events.push({
44
+ type,
45
+ seq,
46
+ eventId: `event_${seq}`,
47
+ occurredAt: now(),
48
+ sessionId: turn.sessionId,
49
+ turnId: turn.turnId,
50
+ rootTurnId: turn.rootTurnId,
51
+ ...turn.scope ? { scope: turn.scope } : {},
52
+ ...turn.parentTurnId ? { parentTurnId: turn.parentTurnId } : {},
53
+ traceId: turn.rootTurnId,
54
+ spanId: step?.stepId ?? turn.turnId,
55
+ ...step ? { stepId: step.stepId } : {},
56
+ data: {
57
+ agentId: turn.agentId,
58
+ agentVersion: turn.agentVersion,
59
+ iteration: step?.iteration ?? turn.iteration,
60
+ ...step ? {
61
+ kind: step.kind,
62
+ status: step.status,
63
+ toolName: step.toolName,
64
+ approvalId: step.approvalId,
65
+ ...type === "step.completed" && (step.kind === "model_call" || step.kind === "compaction") ? {
66
+ ...step.usage ? { usage: step.usage } : {},
67
+ ...step.protocolId ? { protocolId: step.protocolId } : {},
68
+ ...step.modelId ? { modelId: step.modelId } : {}
69
+ } : {}
70
+ } : {},
71
+ ...data
72
+ }
73
+ });
74
+ }
75
+ function touch(turn) {
76
+ turn.version++;
77
+ turn.updatedAt = now();
78
+ }
79
+ function claim(turn, request) {
80
+ if (!request.holderId || !Number.isSafeInteger(request.ttlMs) || request.ttlMs <= 0)
81
+ throw new Error("A lease requires a holderId and a positive integer ttlMs.");
82
+ if (turn.lease && Date.parse(turn.lease.expiresAt) > timestamp) conflict();
83
+ if (isTerminalTurnStatus(turn.status) || turn.status === "queued") conflict();
84
+ const epoch = (state.epochs.get(turn.turnId) ?? 0) + 1;
85
+ state.epochs.set(turn.turnId, epoch);
86
+ const lease = {
87
+ holderId: request.holderId,
88
+ epoch,
89
+ expiresAt: new Date(timestamp + request.ttlMs).toISOString()
90
+ };
91
+ turn.lease = lease;
92
+ turn.status = "running";
93
+ turn.wakeRequested = false;
94
+ touch(turn);
95
+ return lease;
96
+ }
97
+ function recompute(snap) {
98
+ const turn = snap.turn;
99
+ if (isTerminalTurnStatus(turn.status) || turn.status === "queued") return;
100
+ const local = snap.steps.some((s) => s.status === "pending" || s.status === "running");
101
+ const blocker = snap.steps.some((s) => s.status === "unknown") ? "waiting_resolution" : snap.steps.some((s) => s.status === "awaiting_approval") ? "waiting_approval" : snap.steps.some((s) => s.status === "waiting_child") ? "waiting_child" : void 0;
102
+ if (local || !blocker) {
103
+ turn.wakeRequested = !turn.lease;
104
+ touch(turn);
105
+ return;
106
+ }
107
+ const changed2 = turn.status !== blocker || turn.lease !== void 0;
108
+ turn.status = blocker;
109
+ delete turn.lease;
110
+ turn.wakeRequested = false;
111
+ touch(turn);
112
+ if (changed2) event(turn, "turn.paused", { reason: blocker });
113
+ }
114
+ function admit(input) {
115
+ const owner = session(input.sessionId);
116
+ const key = fingerprint([owner.scope, input.sessionId, input.idempotencyKey]);
117
+ const fp = fingerprint({
118
+ input: input.input,
119
+ context: input.context,
120
+ limits: input.limits,
121
+ mode: input.mode
122
+ });
123
+ const previous = input.idempotencyKey ? state.admissions.get(key) : void 0;
124
+ if (previous) {
125
+ if (previous.fingerprint !== fp) throw new IdempotencyConflictError();
126
+ return { turn: get(previous.turnId).turn, duplicate: true };
127
+ }
128
+ if (state.turns.has(input.turnId)) conflict();
129
+ if (owner.activeTurnId && input.mode === "reject")
130
+ throw new SessionBusyError(owner.activeTurnId);
131
+ const queued = owner.activeTurnId !== void 0;
132
+ const timestamp2 = now();
133
+ const turn = {
134
+ turnId: input.turnId,
135
+ sessionId: owner.sessionId,
136
+ agentId: owner.agentId,
137
+ agentVersion: owner.agentVersion,
138
+ ...owner.scope ? { scope: owner.scope } : {},
139
+ input: input.input,
140
+ context: { ...owner.context, ...input.context },
141
+ status: queued ? "queued" : "running",
142
+ iteration: 0,
143
+ ...queued ? { queueSeq: ++state.queue } : {},
144
+ ...input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {},
145
+ ...input.limits ? { limits: input.limits } : {},
146
+ rootTurnId: input.turnId,
147
+ depth: 0,
148
+ wakeRequested: false,
149
+ createdAt: timestamp2,
150
+ updatedAt: timestamp2,
151
+ version: 1
152
+ };
153
+ state.turns.set(turn.turnId, { turn, steps: [], attempts: [], steering: [], approvals: [] });
154
+ const lease = queued ? void 0 : claim(turn, input.lease);
155
+ if (!queued) owner.activeTurnId = turn.turnId;
156
+ owner.version++;
157
+ owner.updatedAt = timestamp2;
158
+ if (input.idempotencyKey) state.admissions.set(key, { fingerprint: fp, turnId: turn.turnId });
159
+ event(turn, queued ? "turn.queued" : "turn.started");
160
+ return { turn, ...lease ? { lease } : {}, duplicate: false };
161
+ }
162
+ function addStep(snap, input, iteration) {
163
+ if (snap.steps.some((s) => s.stepId === input.stepId)) conflict();
164
+ const step = {
165
+ ...input,
166
+ turnId: snap.turn.turnId,
167
+ iteration,
168
+ stepSeq: snap.steps.length + 1,
169
+ status: input.status ?? "pending",
170
+ createdAt: now(),
171
+ version: 1
172
+ };
173
+ snap.steps.push(step);
174
+ return step;
175
+ }
176
+ function doneStep(snap, input, kind, iteration) {
177
+ if (input.continuationArtifact && !input.artifacts?.some((ref) => ref.sha256 === input.continuationArtifact.sha256))
178
+ input = { ...input, artifacts: [...input.artifacts ?? [], input.continuationArtifact] };
179
+ let step = snap.steps.find((s) => s.stepId === input.stepId);
180
+ if (step && (isTerminalStepStatus(step.status) || step.kind !== kind)) conflict();
181
+ step ??= addStep(
182
+ snap,
183
+ {
184
+ stepId: input.stepId,
185
+ operationKey: input.operationKey,
186
+ kind,
187
+ ...input.input !== void 0 ? { input: input.input } : {}
188
+ },
189
+ iteration
190
+ );
191
+ let attempt = snap.attempts.find(
192
+ (a) => a.stepId === step.stepId && a.attemptNo === input.attemptNo
193
+ );
194
+ if (attempt && (attempt.status !== "running" || attempt.leaseEpoch !== snap.turn.lease.epoch || attempt.holderId !== snap.turn.lease.holderId))
195
+ conflict();
196
+ if (!attempt) {
197
+ attempt = {
198
+ turnId: snap.turn.turnId,
199
+ stepId: step.stepId,
200
+ attemptNo: input.attemptNo,
201
+ kind: "execute",
202
+ status: "running",
203
+ holderId: snap.turn.lease.holderId,
204
+ leaseEpoch: snap.turn.lease.epoch,
205
+ startedAt: now()
206
+ };
207
+ snap.attempts.push(attempt);
208
+ }
209
+ Object.assign(
210
+ step,
211
+ { status: "completed", output: input.output, completedAt: now(), version: step.version + 1 },
212
+ input.input !== void 0 ? { input: input.input } : {},
213
+ input.protocolId !== void 0 ? { protocolId: input.protocolId } : {},
214
+ input.modelId !== void 0 ? { modelId: input.modelId } : {},
215
+ input.continuation !== void 0 ? { continuation: input.continuation } : {},
216
+ input.continuationArtifact !== void 0 ? { continuationArtifact: input.continuationArtifact } : {},
217
+ input.usage ? { usage: input.usage } : {},
218
+ input.artifacts ? { artifacts: input.artifacts } : {}
219
+ );
220
+ Object.assign(
221
+ attempt,
222
+ { status: "succeeded", output: input.output, completedAt: now() },
223
+ input.usage ? { usage: input.usage } : {},
224
+ input.artifacts ? { artifacts: input.artifacts } : {}
225
+ );
226
+ event(snap.turn, "step.completed", void 0, step);
227
+ return step;
228
+ }
229
+ function terminalStep(snap, step, status, reason) {
230
+ step.status = status;
231
+ step.output = { status, reason };
232
+ step.completedAt = now();
233
+ step.version++;
234
+ const approval = snap.approvals.find((a) => a.stepId === step.stepId && a.status === "pending");
235
+ if (approval) {
236
+ approval.status = "rejected";
237
+ approval.reason = reason;
238
+ approval.resolvedAt = now();
239
+ event(snap.turn, "step.approval_resolved", { reason }, step);
240
+ }
241
+ }
242
+ function steer(input) {
243
+ const snap = get(input.turnId);
244
+ if (isTerminalTurnStatus(snap.turn.status)) {
245
+ if (!input.fallbackToNewTurn) return { accepted: false, reason: "turn_already_terminal" };
246
+ const next = admit({
247
+ sessionId: snap.turn.sessionId,
248
+ turnId: input.fallback.turnId,
249
+ input: input.input,
250
+ mode: "follow_up",
251
+ lease: input.fallback.lease,
252
+ context: { ...snap.turn.context }
253
+ });
254
+ return { accepted: true, mode: "promoted_to_turn", turnId: next.turn.turnId };
255
+ }
256
+ if (snap.turn.status === "queued") conflict();
257
+ if (!snap.steering.some((s) => s.steeringId === input.steeringId)) {
258
+ snap.steering.push({
259
+ steeringId: input.steeringId,
260
+ turnId: input.turnId,
261
+ input: input.input,
262
+ urgency: input.urgency ?? "next_iteration",
263
+ supersedeApprovals: input.supersedeApprovals ?? true,
264
+ status: "pending",
265
+ createdAt: now()
266
+ });
267
+ for (const step of snap.steps) {
268
+ if (step.status === "pending" && (step.kind === "tool_exec" || step.kind === "sub_turn"))
269
+ terminalStep(snap, step, "skipped", "superseded_by_steering");
270
+ if (step.status === "awaiting_approval" && (input.supersedeApprovals ?? true))
271
+ terminalStep(snap, step, "rejected", "superseded_by_steering");
272
+ }
273
+ event(snap.turn, "steering.queued", { steeringId: input.steeringId });
274
+ recompute(snap);
275
+ }
276
+ return { accepted: true, mode: "steered", turnId: input.turnId };
277
+ }
278
+ function finish(input) {
279
+ const snap = fence(input);
280
+ const turn = snap.turn;
281
+ if (isTerminalTurnStatus(turn.status)) conflict();
282
+ if (input.status === "completed" && snap.steps.some((s) => !isTerminalStepStatus(s.status)))
283
+ conflict();
284
+ const previousLease = turn.lease;
285
+ Object.assign(
286
+ turn,
287
+ { status: input.status, completedAt: now(), wakeRequested: false },
288
+ input.output !== void 0 ? { output: input.output } : {},
289
+ input.error ? { error: input.error } : {},
290
+ input.artifacts ? { artifacts: input.artifacts } : {}
291
+ );
292
+ delete turn.lease;
293
+ touch(turn);
294
+ const owner = session(turn.sessionId);
295
+ if (owner.activeTurnId === turn.turnId) delete owner.activeTurnId;
296
+ event(turn, `turn.${input.status}`);
297
+ const queue = [...state.turns.values()].map((s) => s.turn).filter((t) => t.sessionId === turn.sessionId && t.status === "queued").sort((a, b) => a.queueSeq - b.queueSeq);
298
+ if (input.drainQueued === "cancel")
299
+ for (const queued of queue) cancel(get(queued.turnId), "queue_drained", false);
300
+ const next = input.status === "completed" && input.drainQueued !== "cancel" ? queue[0] : void 0;
301
+ if (next) {
302
+ next.status = "running";
303
+ const nextLease = claim(
304
+ next,
305
+ input.nextLease ?? {
306
+ holderId: previousLease.holderId,
307
+ ttlMs: Math.max(1, Date.parse(previousLease.expiresAt) - timestamp)
308
+ }
309
+ );
310
+ owner.activeTurnId = next.turnId;
311
+ event(next, "turn.started");
312
+ owner.version++;
313
+ return { turn, nextTurn: next, nextLease };
314
+ }
315
+ owner.version++;
316
+ return { turn };
317
+ }
318
+ function backwrite(child) {
319
+ const parent = get(child.turn.parentTurnId);
320
+ const step = parent.steps.find((s) => s.stepId === child.turn.parentStepId);
321
+ if (!isTerminalStepStatus(step.status)) {
322
+ step.status = child.turn.status === "completed" ? "completed" : child.turn.status === "cancelled" ? "cancelled" : "failed";
323
+ step.output = child.turn.output ?? { status: child.turn.status, error: child.turn.error };
324
+ step.completedAt = now();
325
+ step.version++;
326
+ const attempt = [...parent.attempts].reverse().find((a) => a.stepId === step.stepId && a.status === "running");
327
+ if (attempt) {
328
+ attempt.status = step.status === "completed" ? "succeeded" : step.status === "cancelled" ? "cancelled" : "failed";
329
+ attempt.output = step.output;
330
+ attempt.completedAt = now();
331
+ }
332
+ event(
333
+ parent.turn,
334
+ step.status === "completed" ? "step.completed" : "step.failed",
335
+ void 0,
336
+ step
337
+ );
338
+ recompute(parent);
339
+ }
340
+ return { child: child.turn, parent: parent.turn, parentStep: step };
341
+ }
342
+ function cancel(snap, reason, cascade = true) {
343
+ if (isTerminalTurnStatus(snap.turn.status)) return;
344
+ for (const step of snap.steps) {
345
+ if (isTerminalStepStatus(step.status) || step.status === "unknown") continue;
346
+ if (step.status === "running" && step.effect === "external") {
347
+ step.status = "unknown";
348
+ step.version++;
349
+ step.error = { code: "CANCELLED_UNCONFIRMED", message: reason };
350
+ event(snap.turn, "step.unknown", { reason }, step);
351
+ } else terminalStep(snap, step, "cancelled", reason);
352
+ for (const attempt of snap.attempts.filter(
353
+ (a) => a.stepId === step.stepId && a.status === "running"
354
+ )) {
355
+ attempt.status = step.status === "unknown" ? "unknown" : "cancelled";
356
+ attempt.completedAt = now();
357
+ }
358
+ }
359
+ snap.turn.status = "cancelled";
360
+ snap.turn.completedAt = now();
361
+ snap.turn.wakeRequested = false;
362
+ delete snap.turn.lease;
363
+ touch(snap.turn);
364
+ const owner = session(snap.turn.sessionId);
365
+ if (owner.activeTurnId === snap.turn.turnId) delete owner.activeTurnId;
366
+ event(snap.turn, "turn.cancelled", { reason });
367
+ if (cascade) {
368
+ for (const child of state.turns.values())
369
+ if (child.turn.parentTurnId === snap.turn.turnId && child.turn.propagation?.cancelWithParent !== false)
370
+ cancel(child, reason);
371
+ }
372
+ if (snap.turn.parentTurnId) backwrite(snap);
373
+ }
374
+ const ledger = {
375
+ createSession: (input) => transaction(() => {
376
+ if (state.sessions.has(input.sessionId)) conflict();
377
+ const owner = {
378
+ ...input,
379
+ context: input.context ?? {},
380
+ createdAt: now(),
381
+ updatedAt: now(),
382
+ version: 1
383
+ };
384
+ state.sessions.set(input.sessionId, owner);
385
+ event(
386
+ {
387
+ sessionId: input.sessionId,
388
+ turnId: "",
389
+ rootTurnId: "",
390
+ ...input.scope ? { scope: input.scope } : {}
391
+ },
392
+ "session.created",
393
+ { agentId: input.agentId, agentVersion: input.agentVersion }
394
+ );
395
+ return owner;
396
+ }),
397
+ getSession: async (id, scope) => {
398
+ const value = state.sessions.get(id);
399
+ return structuredClone(value && (!scope || sameScope(value.scope, scope)) ? value : null);
400
+ },
401
+ listSessionTurns: async (sessionId, options) => structuredClone(
402
+ [...state.turns.values()].map((snapshot) => snapshot.turn).filter(
403
+ (turn) => turn.sessionId === sessionId && (!options?.scope || sameScope(turn.scope, options.scope))
404
+ ).slice(0, options?.limit ?? Infinity)
405
+ ),
406
+ admitTurn: (input) => transaction(() => admit(input)),
407
+ enqueueSteering: (input) => transaction(() => steer(input)),
408
+ consumeSteeringAndRecord: (input) => transaction(() => {
409
+ const snap = fence(input);
410
+ const pending = snap.steering.filter((s) => s.status === "pending");
411
+ if (!pending.length) return null;
412
+ const step = addStep(
413
+ snap,
414
+ {
415
+ stepId: input.stepId,
416
+ operationKey: input.operationKey,
417
+ kind: "steering_input",
418
+ input: pending.map((s) => s.input)
419
+ },
420
+ input.iteration
421
+ );
422
+ step.status = "completed";
423
+ step.output = pending.map((s) => s.input);
424
+ step.completedAt = now();
425
+ for (const entry of pending) {
426
+ entry.status = "consumed";
427
+ entry.consumedAt = now();
428
+ entry.consumedByStepId = step.stepId;
429
+ }
430
+ event(
431
+ snap.turn,
432
+ "steering.applied",
433
+ { steeringIds: pending.map((s) => s.steeringId) },
434
+ step
435
+ );
436
+ return step;
437
+ }),
438
+ commitCompactionStep: (input) => transaction(() => {
439
+ const snap = fence(input);
440
+ const step = doneStep(snap, input.step, "compaction", input.iteration);
441
+ snap.turn.compactionCursorStepId = input.compactedUpToStepId;
442
+ session(snap.turn.sessionId).compactionCursorStepId = input.compactedUpToStepId;
443
+ event(
444
+ snap.turn,
445
+ "compaction.committed",
446
+ { compactedUpToStepId: input.compactedUpToStepId },
447
+ step
448
+ );
449
+ return step;
450
+ }),
451
+ commitModelAndDispatchSteps: (input) => transaction(() => {
452
+ const snap = fence(input);
453
+ if (input.iteration <= snap.turn.iteration || snap.steps.some((s) => !isTerminalStepStatus(s.status) && s.stepId !== input.model.stepId))
454
+ conflict();
455
+ doneStep(snap, input.model, "model_call", input.iteration);
456
+ snap.turn.iteration = input.iteration;
457
+ for (const child of input.steps) {
458
+ const step = addStep(snap, child, input.iteration);
459
+ event(snap.turn, "step.dispatched", void 0, step);
460
+ if (step.status === "awaiting_approval") {
461
+ if (!step.approvalId) conflict();
462
+ snap.approvals.push({
463
+ approvalId: step.approvalId,
464
+ sessionId: snap.turn.sessionId,
465
+ turnId: input.turnId,
466
+ rootTurnId: snap.turn.rootTurnId,
467
+ ...snap.turn.parentTurnId ? { parentTurnId: snap.turn.parentTurnId } : {},
468
+ stepId: step.stepId,
469
+ status: "pending",
470
+ createdAt: now()
471
+ });
472
+ event(snap.turn, "step.approval_requested", { approvalId: step.approvalId }, step);
473
+ }
474
+ }
475
+ recompute(snap);
476
+ return snap;
477
+ }),
478
+ startStepAttempt: (input) => transaction(() => {
479
+ const snap = fence(input);
480
+ let step = snap.steps.find((s) => s.stepId === input.stepId);
481
+ if (!step && input.newStep) {
482
+ if (input.newStep.stepId !== input.stepId) conflict();
483
+ step = addStep(snap, input.newStep, input.newStep.iteration);
484
+ }
485
+ if (!step || isTerminalStepStatus(step.status) || step.status === "awaiting_approval" || step.status === "waiting_child" || input.expectedStepVersion !== void 0 && input.expectedStepVersion !== step.version)
486
+ conflict();
487
+ if (step.status === "unknown" && input.kind !== "reconcile") conflict();
488
+ for (const previous of snap.attempts.filter(
489
+ (a) => a.stepId === step.stepId && a.status === "running"
490
+ )) {
491
+ if (previous.leaseEpoch === input.lease.epoch) conflict();
492
+ previous.status = "unknown";
493
+ previous.completedAt = now();
494
+ previous.error = { code: "LEASE_EXPIRED", message: "Previous lease expired." };
495
+ }
496
+ const attempt = {
497
+ turnId: input.turnId,
498
+ stepId: step.stepId,
499
+ attemptNo: snap.attempts.filter((a) => a.stepId === step.stepId).length + 1,
500
+ kind: input.kind,
501
+ status: "running",
502
+ holderId: input.lease.holderId,
503
+ leaseEpoch: input.lease.epoch,
504
+ startedAt: now()
505
+ };
506
+ snap.attempts.push(attempt);
507
+ step.status = "running";
508
+ step.version++;
509
+ return { step, attempt };
510
+ }),
511
+ completeStep: (input) => transaction(() => {
512
+ const snap = fence(input);
513
+ const step = snap.steps.find((s) => s.stepId === input.stepId);
514
+ const attempt = snap.attempts.find(
515
+ (a) => a.stepId === input.stepId && a.attemptNo === input.attemptNo
516
+ );
517
+ if (!step || !attempt || attempt.leaseEpoch !== input.lease.epoch || attempt.holderId !== input.lease.holderId || step.version !== input.expectedStepVersion || isTerminalStepStatus(step.status) || attempt.status !== "running")
518
+ conflict();
519
+ if (input.status === "pending") {
520
+ const provenNotExecuted = attempt.kind === "reconcile" && input.evidence?.status === "not_executed";
521
+ const retryable = step.effect !== "external" && (step.kind === "model_call" || step.kind === "compaction" || step.kind === "tool_exec" && step.effect === "none") && ["failed", "cancelled", "unknown"].includes(input.attemptStatus);
522
+ if (!provenNotExecuted && !retryable) conflict();
523
+ }
524
+ Object.assign(
525
+ step,
526
+ { status: input.status, version: step.version + 1 },
527
+ input.output !== void 0 ? { output: input.output } : {},
528
+ input.artifacts ? { artifacts: input.artifacts } : {},
529
+ input.usage ? { usage: input.usage } : {},
530
+ input.error ? { error: input.error } : {},
531
+ isTerminalStepStatus(input.status) ? { completedAt: now() } : {}
532
+ );
533
+ Object.assign(
534
+ attempt,
535
+ { status: input.attemptStatus, completedAt: now() },
536
+ input.output !== void 0 ? { output: input.output } : {},
537
+ input.artifacts ? { artifacts: input.artifacts } : {},
538
+ input.usage ? { usage: input.usage } : {},
539
+ input.error ? { error: input.error } : {},
540
+ input.evidence !== void 0 ? { evidence: input.evidence } : {}
541
+ );
542
+ if (input.status === "pending") {
543
+ delete step.output;
544
+ delete step.error;
545
+ delete step.artifacts;
546
+ delete step.usage;
547
+ delete step.completedAt;
548
+ }
549
+ event(
550
+ snap.turn,
551
+ input.status === "pending" ? "step.dispatched" : input.status === "unknown" ? "step.unknown" : input.status === "failed" ? "step.failed" : "step.completed",
552
+ { attemptNo: input.attemptNo, attemptStatus: input.attemptStatus },
553
+ step
554
+ );
555
+ recompute(snap);
556
+ return step;
557
+ }),
558
+ dispatchSubTurn: (input) => transaction(() => {
559
+ const parent = get(input.turnId);
560
+ const previous = parent.steps.find((s) => s.stepId === input.parentStepId);
561
+ if (previous?.childTurnId) return { turn: get(previous.childTurnId).turn, duplicate: true };
562
+ fence(input);
563
+ if (!previous || previous.kind !== "sub_turn" || previous.status !== "running" || input.child.sessionId === parent.turn.sessionId || !sameScope(session(input.child.sessionId).scope, parent.turn.scope))
564
+ conflict();
565
+ const admitted = admit({
566
+ sessionId: input.child.sessionId,
567
+ turnId: input.child.turnId,
568
+ input: input.child.input,
569
+ mode: "reject",
570
+ lease: input.childLease,
571
+ ...input.child.limits ? { limits: input.child.limits } : {}
572
+ });
573
+ Object.assign(admitted.turn, {
574
+ parentTurnId: input.turnId,
575
+ parentStepId: previous.stepId,
576
+ rootTurnId: parent.turn.rootTurnId,
577
+ depth: parent.turn.depth + 1,
578
+ propagation: input.child.propagation ?? { cancelWithParent: true }
579
+ });
580
+ const childEvent = state.events.at(-1);
581
+ state.events[state.events.length - 1] = {
582
+ ...childEvent,
583
+ rootTurnId: parent.turn.rootTurnId,
584
+ parentTurnId: input.turnId,
585
+ traceId: parent.turn.rootTurnId
586
+ };
587
+ previous.childTurnId = admitted.turn.turnId;
588
+ previous.status = "waiting_child";
589
+ previous.version++;
590
+ event(parent.turn, "sub_turn.linked", { childTurnId: admitted.turn.turnId }, previous);
591
+ recompute(parent);
592
+ return admitted;
593
+ }),
594
+ completeChildAndWakeParent: (input) => transaction(() => {
595
+ const child = fence(input);
596
+ if (!child.turn.parentTurnId) conflict();
597
+ finish(input);
598
+ return backwrite(child);
599
+ }),
600
+ applyCommand: (envelope) => transaction(() => {
601
+ const key = fingerprint([envelope.scope, envelope.commandId]);
602
+ const fp = fingerprint({
603
+ actor: envelope.actor,
604
+ payload: envelope.payload,
605
+ scope: envelope.scope
606
+ });
607
+ const old = state.commands.get(key);
608
+ if (old) {
609
+ if (old.fingerprint !== fp) throw new IdempotencyConflictError();
610
+ return {
611
+ ...old.receipt,
612
+ status: old.receipt.status === "rejected" ? "rejected" : "duplicate"
613
+ };
614
+ }
615
+ const payload = envelope.payload;
616
+ const snap = state.turns.get(payload.turnId);
617
+ let reason;
618
+ let resultTurnId = payload.turnId;
619
+ if (!snap) reason = "not_found";
620
+ else if (!sameScope(snap.turn.scope, envelope.scope)) reason = "scope_mismatch";
621
+ else if (isTerminalTurnStatus(snap.turn.status) && payload.kind !== "steer")
622
+ reason = "turn_already_terminal";
623
+ else {
624
+ switch (payload.kind) {
625
+ case "steer": {
626
+ const result = steer({
627
+ ...payload,
628
+ steeringId: envelope.commandId,
629
+ fallbackToNewTurn: payload.fallbackToNewTurn ?? true,
630
+ fallback: {
631
+ turnId: `turn_${envelope.commandId}`,
632
+ lease: { holderId: "command-admission", ttlMs: 1 }
633
+ }
634
+ });
635
+ if (result.accepted) resultTurnId = result.turnId;
636
+ else reason = result.reason;
637
+ break;
638
+ }
639
+ case "approve": {
640
+ const approval = snap.approvals.find(
641
+ (a) => a.approvalId === payload.approvalId && a.status === "pending"
642
+ );
643
+ const step = approval && snap.steps.find(
644
+ (s) => s.stepId === approval.stepId && s.status === "awaiting_approval"
645
+ );
646
+ if (!approval || !step) {
647
+ reason = "invalid_state";
648
+ break;
649
+ }
650
+ approval.status = payload.decision;
651
+ approval.actor = envelope.actor;
652
+ approval.resolvedAt = now();
653
+ if (payload.reason) approval.reason = payload.reason;
654
+ if (payload.decision === "approved") {
655
+ step.status = "pending";
656
+ step.version++;
657
+ } else terminalStep(snap, step, "rejected", payload.reason ?? "approval_rejected");
658
+ event(snap.turn, "step.approval_resolved", { decision: payload.decision }, step);
659
+ recompute(snap);
660
+ break;
661
+ }
662
+ case "resolve_unknown": {
663
+ const step = snap.steps.find(
664
+ (s) => s.stepId === payload.stepId && s.status === "unknown"
665
+ );
666
+ if (!step) {
667
+ reason = "invalid_state";
668
+ break;
669
+ }
670
+ const resolution = payload.resolution;
671
+ if (resolution.kind === "confirmed_completed") {
672
+ step.status = "completed";
673
+ step.output = resolution.output;
674
+ } else if (resolution.kind === "confirmed_not_executed") {
675
+ step.status = resolution.retry ? "pending" : "cancelled";
676
+ step.output = { status: "not_executed" };
677
+ } else {
678
+ step.status = "failed";
679
+ step.error = { code: "MANUALLY_FAILED", message: resolution.reason };
680
+ }
681
+ step.version++;
682
+ if (isTerminalStepStatus(step.status)) step.completedAt = now();
683
+ event(snap.turn, "step.resolved", { resolution }, step);
684
+ recompute(snap);
685
+ break;
686
+ }
687
+ case "cancel":
688
+ cancel(snap, payload.reason ?? "cancelled_by_command");
689
+ if (payload.drainQueued === "cancel") {
690
+ for (const queued of state.turns.values())
691
+ if (queued.turn.sessionId === snap.turn.sessionId && queued.turn.status === "queued")
692
+ cancel(queued, "queue_drained");
693
+ }
694
+ break;
695
+ case "resume": {
696
+ if (snap.turn.status === "queued") {
697
+ const owner = session(snap.turn.sessionId);
698
+ if (owner.activeTurnId) {
699
+ reason = "invalid_state";
700
+ break;
701
+ }
702
+ snap.turn.status = "running";
703
+ snap.turn.wakeRequested = true;
704
+ owner.activeTurnId = snap.turn.turnId;
705
+ } else {
706
+ recompute(snap);
707
+ }
708
+ break;
709
+ }
710
+ }
711
+ }
712
+ const receipt = {
713
+ commandId: envelope.commandId,
714
+ processedAt: now(),
715
+ status: reason ? "rejected" : "applied",
716
+ ...reason ? { rejectionReason: reason } : { resultTurnId }
717
+ };
718
+ state.commands.set(key, { fingerprint: fp, receipt });
719
+ if (!reason && snap)
720
+ event(snap.turn, "command.applied", {
721
+ commandId: envelope.commandId,
722
+ kind: payload.kind
723
+ });
724
+ return receipt;
725
+ }),
726
+ finishTurnAndDequeue: (input) => transaction(() => finish(input)),
727
+ acquireLease: (input) => transaction(() => claim(get(input.turnId).turn, input)),
728
+ renewLease: (input) => transaction(() => {
729
+ const snap = fence(input);
730
+ if (!Number.isSafeInteger(input.ttlMs) || input.ttlMs <= 0)
731
+ throw new Error("A lease requires a positive integer ttlMs.");
732
+ const lease = {
733
+ ...snap.turn.lease,
734
+ expiresAt: new Date(timestamp + input.ttlMs).toISOString()
735
+ };
736
+ snap.turn.lease = lease;
737
+ return lease;
738
+ }),
739
+ releaseLease: (input) => transaction(() => {
740
+ const snap = fence(input);
741
+ delete snap.turn.lease;
742
+ touch(snap.turn);
743
+ }),
744
+ listRecoverableTurns: async (options) => structuredClone(
745
+ [...state.turns.values()].map((s) => s.turn).filter(
746
+ (t) => !isTerminalTurnStatus(t.status) && t.status !== "queued" && (!options.scope || sameScope(t.scope, options.scope)) && (!t.lease || Date.parse(t.lease.expiresAt) <= timestamp)
747
+ ).slice(0, options.limit)
748
+ ),
749
+ getTurnSnapshot: async (id, options) => {
750
+ const snap = state.turns.get(id);
751
+ if (!snap || options?.scope && !sameScope(snap.turn.scope, options.scope)) return null;
752
+ const after = options?.afterStepId ? snap.steps.find((s) => s.stepId === options.afterStepId)?.stepSeq : void 0;
753
+ return structuredClone({
754
+ ...snap,
755
+ steps: after === void 0 ? snap.steps : snap.steps.filter((s) => s.stepSeq > after)
756
+ });
757
+ }
758
+ };
759
+ return ledger;
760
+ }
761
+
762
+ // src/schema.ts
763
+ function quoteSchema(schema) {
764
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(schema)) throw new Error("Invalid PostgreSQL schema name.");
765
+ return `"${schema}"`;
766
+ }
767
+ function postgresMigrations(schema = "soil") {
768
+ const s = quoteSchema(schema);
769
+ return [
770
+ {
771
+ version: 1,
772
+ sql: `
773
+ CREATE SCHEMA IF NOT EXISTS ${s};
774
+ CREATE TABLE IF NOT EXISTS ${s}.schema_migrations (
775
+ version integer PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
776
+ );
777
+ CREATE TABLE IF NOT EXISTS ${s}.outbox_meta (
778
+ scope_key text PRIMARY KEY,
779
+ queue_seq bigint NOT NULL DEFAULT 0,
780
+ last_seq bigint NOT NULL DEFAULT 0,
781
+ pruned_through bigint NOT NULL DEFAULT 0,
782
+ gap_reason text NOT NULL DEFAULT 'retention_ttl'
783
+ );
784
+ CREATE TABLE IF NOT EXISTS ${s}.sessions (
785
+ scope_key text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
786
+ PRIMARY KEY (scope_key, id)
787
+ );
788
+ CREATE TABLE IF NOT EXISTS ${s}.turns (
789
+ scope_key text NOT NULL, id text NOT NULL, session_id text NOT NULL,
790
+ ordinal bigserial NOT NULL, status text NOT NULL,
791
+ parent_turn_id text, parent_step_id text, idempotency_key text,
792
+ epoch bigint NOT NULL DEFAULT 0, payload jsonb NOT NULL,
793
+ PRIMARY KEY (scope_key, id),
794
+ FOREIGN KEY (scope_key, session_id) REFERENCES ${s}.sessions(scope_key, id)
795
+ );
796
+ CREATE UNIQUE INDEX IF NOT EXISTS turns_single_active ON ${s}.turns(scope_key, session_id)
797
+ WHERE status IN ('running', 'waiting_approval', 'waiting_resolution', 'waiting_child');
798
+ CREATE UNIQUE INDEX IF NOT EXISTS turns_parent_step ON ${s}.turns(scope_key, parent_turn_id, parent_step_id)
799
+ WHERE parent_turn_id IS NOT NULL;
800
+ CREATE UNIQUE INDEX IF NOT EXISTS turns_idempotency ON ${s}.turns(scope_key, session_id, idempotency_key)
801
+ WHERE idempotency_key IS NOT NULL;
802
+ CREATE INDEX IF NOT EXISTS turns_session_order ON ${s}.turns(scope_key, session_id, ordinal);
803
+ CREATE TABLE IF NOT EXISTS ${s}.steps (
804
+ scope_key text NOT NULL, turn_id text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
805
+ step_seq integer GENERATED ALWAYS AS ((payload->>'stepSeq')::integer) STORED,
806
+ PRIMARY KEY (scope_key, turn_id, id),
807
+ FOREIGN KEY (scope_key, turn_id) REFERENCES ${s}.turns(scope_key, id)
808
+ );
809
+ CREATE UNIQUE INDEX IF NOT EXISTS steps_ledger_order ON ${s}.steps(scope_key, turn_id, step_seq);
810
+ CREATE TABLE IF NOT EXISTS ${s}.attempts (
811
+ scope_key text NOT NULL, turn_id text NOT NULL, step_id text NOT NULL,
812
+ attempt_no integer NOT NULL, payload jsonb NOT NULL, ordinal bigserial NOT NULL,
813
+ PRIMARY KEY (scope_key, turn_id, step_id, attempt_no),
814
+ FOREIGN KEY (scope_key, turn_id, step_id) REFERENCES ${s}.steps(scope_key, turn_id, id)
815
+ );
816
+ CREATE TABLE IF NOT EXISTS ${s}.steering_inbox (
817
+ scope_key text NOT NULL, turn_id text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
818
+ ordinal bigserial NOT NULL,
819
+ PRIMARY KEY (scope_key, turn_id, id),
820
+ FOREIGN KEY (scope_key, turn_id) REFERENCES ${s}.turns(scope_key, id)
821
+ );
822
+ CREATE TABLE IF NOT EXISTS ${s}.approvals (
823
+ scope_key text NOT NULL, turn_id text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
824
+ ordinal bigserial NOT NULL,
825
+ PRIMARY KEY (scope_key, turn_id, id),
826
+ FOREIGN KEY (scope_key, turn_id) REFERENCES ${s}.turns(scope_key, id)
827
+ );
828
+ CREATE TABLE IF NOT EXISTS ${s}.commands (
829
+ scope_key text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
830
+ PRIMARY KEY (scope_key, id)
831
+ );
832
+ CREATE TABLE IF NOT EXISTS ${s}.admissions (
833
+ scope_key text NOT NULL, id text NOT NULL, payload jsonb NOT NULL,
834
+ PRIMARY KEY (scope_key, id)
835
+ );
836
+ CREATE TABLE IF NOT EXISTS ${s}.outbox_events (
837
+ seq bigserial PRIMARY KEY, scope_key text NOT NULL, occurred_at timestamptz NOT NULL,
838
+ payload jsonb NOT NULL
839
+ );
840
+ CREATE INDEX IF NOT EXISTS outbox_scope_seq ON ${s}.outbox_events(scope_key, seq);
841
+ CREATE TABLE IF NOT EXISTS ${s}.outbox_cursors (
842
+ scope_key text NOT NULL, consumer_id text NOT NULL, acked_seq bigint NOT NULL DEFAULT 0,
843
+ PRIMARY KEY (scope_key, consumer_id)
844
+ );
845
+ CREATE TABLE IF NOT EXISTS ${s}.artifact_blobs_meta (
846
+ scope_key text NOT NULL, sha256 text NOT NULL, byte_size bigint NOT NULL,
847
+ created_at timestamptz NOT NULL DEFAULT clock_timestamp(), data bytea NOT NULL,
848
+ PRIMARY KEY (scope_key, sha256)
849
+ );
850
+ INSERT INTO ${s}.schema_migrations(version) VALUES (1) ON CONFLICT DO NOTHING;
851
+ `
852
+ }
853
+ ];
854
+ }
855
+ var POSTGRES_SCHEMA_VERSION = 1;
856
+
857
+ // src/postgres.ts
858
+ var json = (value) => JSON.stringify(value);
859
+ var changed = (a, b) => json(a) !== json(b);
860
+ function count(value, name) {
861
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid ${name}.`);
862
+ return value;
863
+ }
864
+ function sequence(value) {
865
+ const n = Number(value);
866
+ if (!Number.isSafeInteger(n) || n < 0)
867
+ throw new Error("PostgreSQL sequence exceeds safe integers.");
868
+ return n;
869
+ }
870
+ function postgresStorage(config) {
871
+ if ([config.connectionString, config.pool, config.client].filter(Boolean).length !== 1)
872
+ throw new Error("Supply exactly one connectionString, pool, or connected client.");
873
+ const s = quoteSchema(config.schema ?? "soil");
874
+ const scopeKey = fingerprint(config.scope ?? {});
875
+ let pool = config.pool;
876
+ let opened = false;
877
+ let opening;
878
+ let queue = Promise.resolve();
879
+ async function withClient(work) {
880
+ if (config.client) {
881
+ const job = queue.then(() => work(config.client));
882
+ queue = job.catch(() => {
883
+ });
884
+ return job;
885
+ }
886
+ const client = await pool.connect();
887
+ let broken;
888
+ try {
889
+ return await work(client);
890
+ } catch (error) {
891
+ if (error instanceof AggregateError) broken = error;
892
+ throw error;
893
+ } finally {
894
+ client.release?.(broken);
895
+ }
896
+ }
897
+ async function tx(work) {
898
+ if (!opened) throw new Error("PostgreSQL storage is not open.");
899
+ return withClient(async (client) => {
900
+ await client.query("BEGIN");
901
+ try {
902
+ const row = await client.query(
903
+ `SELECT * FROM ${s}.outbox_meta WHERE scope_key = $1 FOR UPDATE`,
904
+ [scopeKey]
905
+ );
906
+ if (!row.rows[0]) throw new Error("Missing PostgreSQL scope metadata.");
907
+ const result = await work(client, row.rows[0]);
908
+ await client.query("COMMIT");
909
+ return result;
910
+ } catch (error) {
911
+ try {
912
+ await client.query("ROLLBACK");
913
+ } catch (rollback) {
914
+ throw new AggregateError([error, rollback], "Transaction and rollback failed.", {
915
+ cause: rollback
916
+ });
917
+ }
918
+ throw error;
919
+ }
920
+ });
921
+ }
922
+ async function load(client, meta, method, args) {
923
+ const state = {
924
+ sessions: /* @__PURE__ */ new Map(),
925
+ turns: /* @__PURE__ */ new Map(),
926
+ epochs: /* @__PURE__ */ new Map(),
927
+ queue: sequence(meta.queue_seq),
928
+ seq: sequence(meta.last_seq),
929
+ events: [],
930
+ commands: /* @__PURE__ */ new Map(),
931
+ admissions: /* @__PURE__ */ new Map()
932
+ };
933
+ const request = args[0];
934
+ const targetId = method === "admitTurn" || method === "createSession" ? void 0 : request.payload?.turnId ?? request.turnId;
935
+ const target = targetId ? (await client.query(`SELECT * FROM ${s}.turns WHERE scope_key = $1 AND id = $2`, [
936
+ scopeKey,
937
+ targetId
938
+ ])).rows[0] : void 0;
939
+ const targetTurn = target?.payload;
940
+ const sessionIds = /* @__PURE__ */ new Set([
941
+ ...request.sessionId ? [request.sessionId] : [],
942
+ ...targetTurn ? [targetTurn.sessionId] : [],
943
+ ...request.child ? [request.child.sessionId] : []
944
+ ]);
945
+ const ids = /* @__PURE__ */ new Set([
946
+ ...request.turnId ? [request.turnId] : [],
947
+ ...targetId ? [targetId] : [],
948
+ ...request.child ? [request.child.turnId] : [],
949
+ ...request.fallback ? [request.fallback.turnId] : [],
950
+ ...request.commandId ? [`turn_${request.commandId}`] : []
951
+ ]);
952
+ if (method === "admitTurn" && request.idempotencyKey) {
953
+ const owner = await client.query(
954
+ `SELECT * FROM ${s}.sessions WHERE scope_key = $1 AND id = $2`,
955
+ [scopeKey, request.sessionId]
956
+ );
957
+ const key = fingerprint([
958
+ owner.rows[0]?.payload?.scope,
959
+ request.sessionId,
960
+ request.idempotencyKey
961
+ ]);
962
+ const previous = await client.query(
963
+ `SELECT * FROM ${s}.admissions WHERE scope_key = $1 AND id = $2`,
964
+ [scopeKey, key]
965
+ );
966
+ for (const row of previous.rows) {
967
+ const admission = row.payload;
968
+ state.admissions.set(String(row.id), admission);
969
+ ids.add(admission.turnId);
970
+ }
971
+ }
972
+ if (request.commandId) {
973
+ const key = fingerprint([request.scope, request.commandId]);
974
+ const previous = await client.query(
975
+ `SELECT * FROM ${s}.commands WHERE scope_key = $1 AND id = $2`,
976
+ [scopeKey, key]
977
+ );
978
+ for (const row of previous.rows)
979
+ state.commands.set(
980
+ String(row.id),
981
+ row.payload
982
+ );
983
+ }
984
+ const turns = method === "createSession" ? { rows: [] } : await client.query(
985
+ `SELECT * FROM ${s}.turns WHERE scope_key = $1 AND (id = ANY($2::text[]) OR (session_id = ANY($3::text[]) AND status NOT IN ('completed','failed','cancelled')) OR payload->>'rootTurnId' = $4) ORDER BY ordinal`,
986
+ [scopeKey, [...ids], [...sessionIds], targetTurn?.rootTurnId ?? null]
987
+ );
988
+ for (const row of turns.rows) {
989
+ const turn = row.payload;
990
+ state.turns.set(String(row.id), {
991
+ turn,
992
+ steps: [],
993
+ attempts: [],
994
+ steering: [],
995
+ approvals: []
996
+ });
997
+ state.epochs.set(String(row.id), sequence(row.epoch));
998
+ sessionIds.add(turn.sessionId);
999
+ }
1000
+ const owners = await client.query(
1001
+ `SELECT * FROM ${s}.sessions WHERE scope_key = $1 AND id = ANY($2::text[])`,
1002
+ [scopeKey, [...sessionIds]]
1003
+ );
1004
+ for (const row of owners.rows) state.sessions.set(String(row.id), row.payload);
1005
+ const fullIds = [...state.turns.values()].filter(
1006
+ ({ turn }) => turn.turnId === targetId || turn.turnId === targetTurn?.parentTurnId || method === "applyCommand" && turn.rootTurnId === targetTurn?.rootTurnId && !["completed", "failed", "cancelled", "queued"].includes(turn.status)
1007
+ ).map(({ turn }) => turn.turnId);
1008
+ if (fullIds.length) {
1009
+ for (const table of ["steps", "attempts", "steering_inbox", "approvals"]) {
1010
+ const result = await client.query(
1011
+ `SELECT * FROM ${s}.${table} WHERE scope_key = $1 AND turn_id = ANY($2::text[])${table === "steps" ? " ORDER BY step_seq" : " ORDER BY ordinal"}`,
1012
+ [scopeKey, fullIds]
1013
+ );
1014
+ for (const row of result.rows) {
1015
+ const snap = state.turns.get(String(row.turn_id));
1016
+ if (!snap) throw new Error("Dangling PostgreSQL ledger record.");
1017
+ if (table === "steps") snap.steps.push(row.payload);
1018
+ else if (table === "attempts")
1019
+ snap.attempts.push(row.payload);
1020
+ else if (table === "steering_inbox")
1021
+ snap.steering.push(row.payload);
1022
+ else snap.approvals.push(row.payload);
1023
+ }
1024
+ }
1025
+ }
1026
+ return state;
1027
+ }
1028
+ async function save(client, before, state) {
1029
+ async function record(table, columns, keys, payload) {
1030
+ const names = ["scope_key", ...columns, "payload"];
1031
+ await client.query(
1032
+ `INSERT INTO ${s}.${table} (${names.join(", ")}) VALUES (${names.map((_, i) => `$${i + 1}`).join(", ")}) ON CONFLICT (${names.slice(0, -1).join(", ")}) DO UPDATE SET payload = EXCLUDED.payload`,
1033
+ [scopeKey, ...keys, json(payload)]
1034
+ );
1035
+ }
1036
+ for (const [id, owner] of state.sessions)
1037
+ if (changed(before.sessions.get(id), owner)) await record("sessions", ["id"], [id], owner);
1038
+ const turns = [...state.turns.values()].sort(
1039
+ (a, b) => Number(!["completed", "failed", "cancelled"].includes(a.turn.status)) - Number(!["completed", "failed", "cancelled"].includes(b.turn.status))
1040
+ );
1041
+ for (const snap of turns) {
1042
+ const turn = snap.turn;
1043
+ const old = before.turns.get(turn.turnId);
1044
+ if (changed(old?.turn, turn) || before.epochs.get(turn.turnId) !== state.epochs.get(turn.turnId))
1045
+ await client.query(
1046
+ `INSERT INTO ${s}.turns (scope_key, id, session_id, status, parent_turn_id, parent_step_id, idempotency_key, epoch, payload) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT (scope_key, id) DO UPDATE SET status=EXCLUDED.status, parent_turn_id=EXCLUDED.parent_turn_id, parent_step_id=EXCLUDED.parent_step_id, epoch=EXCLUDED.epoch, payload=EXCLUDED.payload`,
1047
+ [
1048
+ scopeKey,
1049
+ turn.turnId,
1050
+ turn.sessionId,
1051
+ turn.status,
1052
+ turn.parentTurnId ?? null,
1053
+ turn.parentStepId ?? null,
1054
+ turn.idempotencyKey ?? null,
1055
+ state.epochs.get(turn.turnId) ?? 0,
1056
+ json(turn)
1057
+ ]
1058
+ );
1059
+ for (const step of snap.steps)
1060
+ if (changed(
1061
+ old?.steps.find((x) => x.stepId === step.stepId),
1062
+ step
1063
+ ))
1064
+ await record("steps", ["turn_id", "id"], [turn.turnId, step.stepId], step);
1065
+ for (const attempt of snap.attempts)
1066
+ if (changed(
1067
+ old?.attempts.find(
1068
+ (x) => x.stepId === attempt.stepId && x.attemptNo === attempt.attemptNo
1069
+ ),
1070
+ attempt
1071
+ ))
1072
+ await record(
1073
+ "attempts",
1074
+ ["turn_id", "step_id", "attempt_no"],
1075
+ [turn.turnId, attempt.stepId, attempt.attemptNo],
1076
+ attempt
1077
+ );
1078
+ for (const entry of snap.steering)
1079
+ if (changed(
1080
+ old?.steering.find((x) => x.steeringId === entry.steeringId),
1081
+ entry
1082
+ ))
1083
+ await record("steering_inbox", ["turn_id", "id"], [turn.turnId, entry.steeringId], entry);
1084
+ for (const approval of snap.approvals)
1085
+ if (changed(
1086
+ old?.approvals.find((x) => x.approvalId === approval.approvalId),
1087
+ approval
1088
+ ))
1089
+ await record(
1090
+ "approvals",
1091
+ ["turn_id", "id"],
1092
+ [turn.turnId, approval.approvalId],
1093
+ approval
1094
+ );
1095
+ }
1096
+ for (const [id, item] of state.commands)
1097
+ if (changed(before.commands.get(id), item)) await record("commands", ["id"], [id], item);
1098
+ for (const [id, item] of state.admissions)
1099
+ if (changed(before.admissions.get(id), item)) await record("admissions", ["id"], [id], item);
1100
+ let lastSeq = before.seq;
1101
+ for (const event of state.events) {
1102
+ const { seq: _temporary, ...data } = event;
1103
+ const result = await client.query(
1104
+ `INSERT INTO ${s}.outbox_events(scope_key, occurred_at, payload) VALUES ($1,$2,$3) RETURNING seq`,
1105
+ [scopeKey, event.occurredAt, json({ ...data, eventId: randomUUID() })]
1106
+ );
1107
+ lastSeq = sequence(result.rows[0]?.seq);
1108
+ }
1109
+ await client.query(`UPDATE ${s}.outbox_meta SET queue_seq=$2, last_seq=$3 WHERE scope_key=$1`, [
1110
+ scopeKey,
1111
+ state.queue,
1112
+ lastSeq
1113
+ ]);
1114
+ }
1115
+ const readMethods = /* @__PURE__ */ new Set([
1116
+ "getSession",
1117
+ "listSessionTurns",
1118
+ "listRecoverableTurns",
1119
+ "getTurnSnapshot"
1120
+ ]);
1121
+ async function readLedger(client, method, args) {
1122
+ if (method === "getSession") {
1123
+ const result2 = await client.query(
1124
+ `SELECT payload FROM ${s}.sessions WHERE scope_key=$1 AND id=$2 AND ($3::jsonb IS NULL OR COALESCE(payload->'scope','{}'::jsonb)=$3::jsonb)`,
1125
+ [scopeKey, args[0], args[1] ? json(args[1]) : null]
1126
+ );
1127
+ return result2.rows[0]?.payload ?? null;
1128
+ }
1129
+ if (method === "listSessionTurns") {
1130
+ const options2 = args[1];
1131
+ const result2 = await client.query(
1132
+ `SELECT payload FROM ${s}.turns WHERE scope_key=$1 AND session_id=$2 AND ($3::jsonb IS NULL OR COALESCE(payload->'scope','{}'::jsonb)=$3::jsonb) ORDER BY ordinal LIMIT $4`,
1133
+ [
1134
+ scopeKey,
1135
+ args[0],
1136
+ options2?.scope ? json(options2.scope) : null,
1137
+ count(options2?.limit ?? 2147483647, "limit")
1138
+ ]
1139
+ );
1140
+ return result2.rows.map((row) => row.payload);
1141
+ }
1142
+ if (method === "listRecoverableTurns") {
1143
+ const options2 = args[0];
1144
+ const result2 = await client.query(
1145
+ `SELECT payload FROM ${s}.turns WHERE scope_key=$1 AND status NOT IN ('completed','failed','cancelled','queued') AND ($2::jsonb IS NULL OR COALESCE(payload->'scope','{}'::jsonb)=$2::jsonb) AND (payload->'lease' IS NULL OR (payload#>>'{lease,expiresAt}')::timestamptz<=clock_timestamp()) ORDER BY ordinal LIMIT $3`,
1146
+ [scopeKey, options2.scope ? json(options2.scope) : null, count(options2.limit, "limit")]
1147
+ );
1148
+ return result2.rows.map((row) => row.payload);
1149
+ }
1150
+ const options = args[1];
1151
+ const turn = await client.query(
1152
+ `SELECT payload FROM ${s}.turns WHERE scope_key=$1 AND id=$2 AND ($3::jsonb IS NULL OR COALESCE(payload->'scope','{}'::jsonb)=$3::jsonb)`,
1153
+ [scopeKey, args[0], options?.scope ? json(options.scope) : null]
1154
+ );
1155
+ if (!turn.rows[0]) return null;
1156
+ const steps = await client.query(
1157
+ `SELECT payload FROM ${s}.steps WHERE scope_key=$1 AND turn_id=$2 AND step_seq>COALESCE((SELECT step_seq FROM ${s}.steps WHERE scope_key=$1 AND turn_id=$2 AND id=$3),0) ORDER BY step_seq`,
1158
+ [scopeKey, args[0], options?.afterStepId ?? null]
1159
+ );
1160
+ const result = {
1161
+ turn: turn.rows[0].payload,
1162
+ steps: steps.rows.map((row) => row.payload),
1163
+ attempts: [],
1164
+ steering: [],
1165
+ approvals: []
1166
+ };
1167
+ for (const [table, property] of [
1168
+ ["attempts", "attempts"],
1169
+ ["steering_inbox", "steering"],
1170
+ ["approvals", "approvals"]
1171
+ ]) {
1172
+ const rows = await client.query(
1173
+ `SELECT payload FROM ${s}.${table} WHERE scope_key=$1 AND turn_id=$2 ORDER BY ordinal`,
1174
+ [scopeKey, args[0]]
1175
+ );
1176
+ Object.assign(result, { [property]: rows.rows.map((row) => row.payload) });
1177
+ }
1178
+ return result;
1179
+ }
1180
+ const ledger = new Proxy({}, {
1181
+ get(_target, method) {
1182
+ return (...args) => tx(async (client, meta) => {
1183
+ if (readMethods.has(method)) return readLedger(client, method, args);
1184
+ if (method === "createSession" && config.scope) {
1185
+ const input = args[0];
1186
+ if (input.scope && fingerprint(input.scope) !== scopeKey)
1187
+ throw new Error("Session scope differs from adapter scope.");
1188
+ args[0] = { ...input, scope: config.scope };
1189
+ }
1190
+ const state = await load(client, meta, method, args);
1191
+ const before = structuredClone(state);
1192
+ const clock = await client.query("SELECT clock_timestamp() AS now");
1193
+ const domain = createLedger(
1194
+ state,
1195
+ new Date(clock.rows[0].now).getTime()
1196
+ );
1197
+ const action = domain[method];
1198
+ const result = await action(...args);
1199
+ await save(client, before, state);
1200
+ return result;
1201
+ });
1202
+ }
1203
+ });
1204
+ const artifacts = config.artifacts ?? {
1205
+ async put(input) {
1206
+ if (config.scope && input.scope && fingerprint(input.scope) !== scopeKey)
1207
+ throw new Error("Artifact scope differs from adapter scope.");
1208
+ const bytes = new Uint8Array(input.data);
1209
+ const sha256 = createHash("sha256").update(bytes).digest("hex");
1210
+ await tx(async (client) => {
1211
+ await client.query(
1212
+ `INSERT INTO ${s}.artifact_blobs_meta(scope_key, sha256, byte_size, data) VALUES ($1,$2,$3,$4) ON CONFLICT DO NOTHING`,
1213
+ [scopeKey, sha256, bytes.byteLength, Buffer.from(bytes)]
1214
+ );
1215
+ });
1216
+ return {
1217
+ uri: `postgres://${config.schema ?? "soil"}/${encodeURIComponent(scopeKey)}/sha256/${sha256}`,
1218
+ sha256,
1219
+ byteSize: bytes.byteLength,
1220
+ contentType: input.contentType
1221
+ };
1222
+ },
1223
+ async get(ref) {
1224
+ if (ref.uri !== `postgres://${config.schema ?? "soil"}/${encodeURIComponent(scopeKey)}/sha256/${ref.sha256}`)
1225
+ return null;
1226
+ return tx(async (client) => {
1227
+ const row = await client.query(
1228
+ `SELECT data FROM ${s}.artifact_blobs_meta WHERE scope_key=$1 AND sha256=$2`,
1229
+ [scopeKey, ref.sha256]
1230
+ );
1231
+ const bytes = row.rows[0]?.data;
1232
+ if (!bytes) return null;
1233
+ if (bytes.byteLength !== ref.byteSize || createHash("sha256").update(bytes).digest("hex") !== ref.sha256)
1234
+ throw new Error("Artifact integrity check failed.");
1235
+ return new Uint8Array(bytes);
1236
+ });
1237
+ },
1238
+ async pruneUnreferenced(options) {
1239
+ if (!Number.isFinite(Date.parse(options.olderThan))) throw new Error("Invalid olderThan.");
1240
+ if (options.limit !== void 0) count(options.limit, "prune limit");
1241
+ const candidates = await tx(
1242
+ async (client) => client.query(
1243
+ `SELECT sha256, byte_size FROM ${s}.artifact_blobs_meta WHERE scope_key=$1 AND created_at < $2 ORDER BY created_at, sha256`,
1244
+ [scopeKey, options.olderThan]
1245
+ )
1246
+ );
1247
+ let deletedCount = 0, freedBytes = 0;
1248
+ for (const candidate of candidates.rows) {
1249
+ if (deletedCount >= (options.limit ?? Infinity)) break;
1250
+ const hash = String(candidate.sha256);
1251
+ if (await options.isReferenced(hash)) continue;
1252
+ const deleted = await tx(async (client) => {
1253
+ const referenced = await client.query(
1254
+ `SELECT 1 FROM ${s}.turns WHERE scope_key=$1 AND payload->'artifacts' @> $2::jsonb UNION ALL SELECT 1 FROM ${s}.steps WHERE scope_key=$1 AND payload->'artifacts' @> $2::jsonb UNION ALL SELECT 1 FROM ${s}.attempts WHERE scope_key=$1 AND payload->'artifacts' @> $2::jsonb LIMIT 1`,
1255
+ [scopeKey, json([{ sha256: hash }])]
1256
+ );
1257
+ if (referenced.rows.length) return false;
1258
+ const result = await client.query(
1259
+ `DELETE FROM ${s}.artifact_blobs_meta WHERE scope_key=$1 AND sha256=$2 AND created_at < $3`,
1260
+ [scopeKey, hash, options.olderThan]
1261
+ );
1262
+ return result.rowCount === 1;
1263
+ });
1264
+ if (deleted) {
1265
+ deletedCount++;
1266
+ freedBytes += sequence(candidate.byte_size);
1267
+ }
1268
+ }
1269
+ return { deletedCount, freedBytes };
1270
+ }
1271
+ };
1272
+ return {
1273
+ kind: "postgres",
1274
+ ledger,
1275
+ artifacts,
1276
+ async open() {
1277
+ if (opened) return;
1278
+ if (opening) return opening;
1279
+ opening = (async () => {
1280
+ if (!pool && !config.client)
1281
+ pool = new Pool({
1282
+ connectionString: config.connectionString,
1283
+ connectionTimeoutMillis: 5e3
1284
+ });
1285
+ await withClient(async (client) => {
1286
+ await client.query("BEGIN");
1287
+ try {
1288
+ if (config.migrate !== false) {
1289
+ await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [
1290
+ `soil-migrate:${s}`
1291
+ ]);
1292
+ for (const migration of postgresMigrations(config.schema))
1293
+ await client.query(migration.sql);
1294
+ }
1295
+ await client.query(
1296
+ `INSERT INTO ${s}.outbox_meta(scope_key) VALUES ($1) ON CONFLICT DO NOTHING`,
1297
+ [scopeKey]
1298
+ );
1299
+ await client.query("COMMIT");
1300
+ } catch (error) {
1301
+ try {
1302
+ await client.query("ROLLBACK");
1303
+ } catch (rollback) {
1304
+ throw new AggregateError([error, rollback], "Migration and rollback failed.", {
1305
+ cause: rollback
1306
+ });
1307
+ }
1308
+ throw error;
1309
+ }
1310
+ });
1311
+ opened = true;
1312
+ })();
1313
+ try {
1314
+ await opening;
1315
+ } catch (error) {
1316
+ if (!config.pool) {
1317
+ await pool?.end?.();
1318
+ pool = void 0;
1319
+ }
1320
+ throw error;
1321
+ } finally {
1322
+ opening = void 0;
1323
+ }
1324
+ },
1325
+ async close() {
1326
+ if (opening) await opening;
1327
+ opened = false;
1328
+ await queue;
1329
+ if (!config.pool) {
1330
+ await pool?.end?.();
1331
+ pool = void 0;
1332
+ }
1333
+ },
1334
+ outbox: {
1335
+ read: (options) => tx(async (client, meta) => {
1336
+ count(options.limit, "limit");
1337
+ const ack = await client.query(
1338
+ `SELECT acked_seq FROM ${s}.outbox_cursors WHERE scope_key=$1 AND consumer_id=$2`,
1339
+ [scopeKey, options.consumerId]
1340
+ );
1341
+ const cursor = Math.max(
1342
+ count(options.afterSeq ?? 0, "afterSeq"),
1343
+ sequence(ack.rows[0]?.acked_seq ?? 0)
1344
+ );
1345
+ const result = await client.query(
1346
+ `SELECT seq, payload FROM ${s}.outbox_events WHERE scope_key=$1 AND seq>$2 ORDER BY seq LIMIT $3`,
1347
+ [scopeKey, cursor, options.limit]
1348
+ );
1349
+ const batch = {
1350
+ events: result.rows.map((row) => ({
1351
+ ...row.payload,
1352
+ seq: sequence(row.seq)
1353
+ }))
1354
+ };
1355
+ if (cursor < sequence(meta.pruned_through))
1356
+ batch.gap = {
1357
+ fromSeq: cursor + 1,
1358
+ toSeq: sequence(meta.pruned_through),
1359
+ reason: meta.gap_reason
1360
+ };
1361
+ return batch;
1362
+ }),
1363
+ ack: (options) => tx(async (client, meta) => {
1364
+ const upTo = Math.min(count(options.upToSeq, "upToSeq"), sequence(meta.last_seq));
1365
+ await client.query(
1366
+ `INSERT INTO ${s}.outbox_cursors(scope_key, consumer_id, acked_seq) VALUES ($1,$2,$3) ON CONFLICT (scope_key, consumer_id) DO UPDATE SET acked_seq=GREATEST(${s}.outbox_cursors.acked_seq, EXCLUDED.acked_seq)`,
1367
+ [scopeKey, options.consumerId, upTo]
1368
+ );
1369
+ }),
1370
+ prune: (policy) => tx(async (client, meta) => {
1371
+ let prunedCount = 0;
1372
+ let through = sequence(meta.pruned_through);
1373
+ let reason = meta.gap_reason;
1374
+ if (policy.maxRetentionMs !== void 0) {
1375
+ count(policy.maxRetentionMs, "maxRetentionMs");
1376
+ const deleted = await client.query(
1377
+ `DELETE FROM ${s}.outbox_events WHERE scope_key=$1 AND seq <= (SELECT COALESCE(MAX(seq),0) FROM ${s}.outbox_events WHERE scope_key=$1 AND occurred_at <= clock_timestamp() - $2 * interval '1 millisecond') RETURNING seq`,
1378
+ [scopeKey, policy.maxRetentionMs]
1379
+ );
1380
+ if (deleted.rows.length) {
1381
+ prunedCount += deleted.rows.length;
1382
+ through = deleted.rows.reduce(
1383
+ (max, row) => Math.max(max, sequence(row.seq)),
1384
+ through
1385
+ );
1386
+ reason = "retention_ttl";
1387
+ }
1388
+ }
1389
+ if (policy.maxPendingEvents !== void 0) {
1390
+ count(policy.maxPendingEvents, "maxPendingEvents");
1391
+ const deleted = await client.query(
1392
+ `DELETE FROM ${s}.outbox_events WHERE scope_key=$1 AND seq IN (SELECT seq FROM ${s}.outbox_events WHERE scope_key=$1 ORDER BY seq DESC OFFSET $2) RETURNING seq`,
1393
+ [scopeKey, policy.maxPendingEvents]
1394
+ );
1395
+ if (deleted.rows.length) {
1396
+ prunedCount += deleted.rows.length;
1397
+ through = deleted.rows.reduce(
1398
+ (max, row) => Math.max(max, sequence(row.seq)),
1399
+ through
1400
+ );
1401
+ reason = "max_pending_exceeded";
1402
+ }
1403
+ }
1404
+ await client.query(
1405
+ `UPDATE ${s}.outbox_meta SET pruned_through=$2, gap_reason=$3 WHERE scope_key=$1`,
1406
+ [scopeKey, through, reason]
1407
+ );
1408
+ const first = await client.query(
1409
+ `SELECT MIN(seq) AS oldest FROM ${s}.outbox_events WHERE scope_key=$1`,
1410
+ [scopeKey]
1411
+ );
1412
+ return {
1413
+ prunedCount,
1414
+ oldestAvailableSeq: sequence(first.rows[0]?.oldest ?? sequence(meta.last_seq) + 1)
1415
+ };
1416
+ })
1417
+ }
1418
+ };
1419
+ }
1420
+
1421
+ export { POSTGRES_SCHEMA_VERSION, postgresMigrations, postgresStorage };
1422
+ //# sourceMappingURL=index.js.map
1423
+ //# sourceMappingURL=index.js.map