pi-better-subagents 0.26.2 → 0.27.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,431 @@
1
+ // Generated from packages/operation-coordinator/src/outbox.ts. Do not edit directly.
2
+ /**
3
+ * Durable result delivery.
4
+ *
5
+ * The outbox is addressed to the wait's owner identity, not to a process. One
6
+ * event exists per terminal revision per wait generation, so duplicate terminal
7
+ * events, reload replay and repeated reconciliation cannot enqueue a second
8
+ * event for the same result.
9
+ *
10
+ * Delivery itself is at-least-once, not exactly-once. The unique event and its
11
+ * unique index make enqueue idempotent, but `markOutboxDelivered` commits after
12
+ * the caller emitted the result: a crash between emission and that write leaves
13
+ * the event claimed, and a reconciled host may emit it again. Recipients must
14
+ * key on the event id (or operation, revision, wait and generation) instead of
15
+ * assuming a result is emitted once.
16
+ *
17
+ * Delivery and interpretation are separate: a dispatched or delivered event is
18
+ * not a consumed result. Only `acknowledgeResult` marks the generation consumed,
19
+ * and only an acknowledgement releases the evidence pins that kept the terminal
20
+ * evidence alive.
21
+ */
22
+ import { randomUUID } from "node:crypto";
23
+ import { StoreError } from "./errors.ts";
24
+ import {
25
+ dependencyState,
26
+ mapOutbox,
27
+ readOperationEvidence,
28
+ readOutboxRow,
29
+ requireWaitRow,
30
+ } from "./rows.ts";
31
+ import { columnJson, columnNullableText, columnText, getRows, run, type StoreContext } from "./sqlite.ts";
32
+ import type {
33
+ ClaimOutboxInput,
34
+ OutboxDispatchClaim,
35
+ OutboxDispatchInput,
36
+ OutboxEventRecord,
37
+ OutboxFilter,
38
+ OutboxState,
39
+ OwnerIdentity,
40
+ ReleaseOutboxInput,
41
+ WaitDependencyRecord,
42
+ } from "./types.ts";
43
+ import { requireCounter, requireId, requireText } from "./validate.ts";
44
+
45
+ const OUTBOX_STATES: readonly OutboxState[] = [
46
+ "pending",
47
+ "claimed",
48
+ "delivered",
49
+ "acknowledged",
50
+ "voided",
51
+ ];
52
+
53
+ /** Delivery is only meaningful once the generation can act on the evidence. */
54
+ const DELIVERABLE_WAIT_PHASES = ["ready", "resuming"];
55
+ const UNCONSUMED_OUTBOX_STATES = ["pending", "claimed", "delivered"];
56
+
57
+ function placeholders(count: number): string {
58
+ return new Array(count).fill("?").join(", ");
59
+ }
60
+
61
+ /**
62
+ * Enqueue one event per settled dependency at its terminal revision, and pin the
63
+ * evidence that event refers to. Idempotent: the unique
64
+ * (operation, revision, wait, generation) index decides whether anything is new.
65
+ */
66
+ export function enqueueGenerationOutbox(
67
+ ctx: StoreContext,
68
+ waitId: string,
69
+ generation: number,
70
+ recipient: OwnerIdentity,
71
+ dependencies: WaitDependencyRecord[],
72
+ at: number,
73
+ ): OutboxEventRecord[] {
74
+ const inserted: OutboxEventRecord[] = [];
75
+ for (const dependency of dependencies) {
76
+ if (dependency.terminalRevision <= 0) continue;
77
+ const eventId = `evt_${randomUUID()}`;
78
+ const changes = run(
79
+ ctx,
80
+ `INSERT OR IGNORE INTO outbox_events (
81
+ event_id, operation_id, terminal_revision, wait_id, generation,
82
+ recipient_kind, recipient_session_id, recipient_workspace, recipient_branch_id, recipient_goal_id,
83
+ state, attempts, created_at
84
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)`,
85
+ eventId,
86
+ dependency.operationId,
87
+ dependency.terminalRevision,
88
+ waitId,
89
+ generation,
90
+ recipient.kind,
91
+ recipient.sessionId,
92
+ recipient.workspace,
93
+ recipient.branchId ?? null,
94
+ recipient.goalId ?? null,
95
+ at,
96
+ );
97
+ if (changes === 0) continue;
98
+ for (const evidence of readOperationEvidence(ctx, dependency.operationId, dependency.terminalRevision)) {
99
+ run(
100
+ ctx,
101
+ `INSERT OR IGNORE INTO evidence_pins (
102
+ pin_id, wait_id, generation, operation_id, terminal_revision,
103
+ kind, ref, summary, detail_lost, bytes, pinned_at
104
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
105
+ `pin_${randomUUID()}`,
106
+ waitId,
107
+ generation,
108
+ evidence.operationId,
109
+ evidence.terminalRevision,
110
+ evidence.kind,
111
+ evidence.ref,
112
+ evidence.summary ?? null,
113
+ evidence.detailLost ? 1 : 0,
114
+ evidence.bytes ?? null,
115
+ at,
116
+ );
117
+ }
118
+ const row = readOutboxRow(ctx, eventId);
119
+ if (row) inserted.push(mapOutbox(ctx, row));
120
+ }
121
+ return inserted;
122
+ }
123
+
124
+ /** Enqueue for a generation that just became ready, reading its dependencies. */
125
+ export function enqueueReadyGeneration(
126
+ ctx: StoreContext,
127
+ waitId: string,
128
+ generation: number,
129
+ at: number,
130
+ ): OutboxEventRecord[] {
131
+ const row = requireWaitRow(ctx, waitId, generation);
132
+ const recipient: OwnerIdentity = {
133
+ kind: columnText(row, "owner_kind") as OwnerIdentity["kind"],
134
+ sessionId: columnText(row, "owner_session_id"),
135
+ workspace: columnText(row, "owner_workspace"),
136
+ branchId: columnNullableText(row, "owner_branch_id"),
137
+ goalId: columnNullableText(row, "owner_goal_id"),
138
+ };
139
+ const state = dependencyState(ctx, waitId, generation);
140
+ if (!state.settled) {
141
+ throw new StoreError(
142
+ "dependencies-unsettled",
143
+ `Wait ${waitId} generation ${generation} still has unfinished dependencies; result delivery is enqueued only when every dependency has a terminal outcome.`,
144
+ );
145
+ }
146
+ return enqueueGenerationOutbox(ctx, waitId, generation, recipient, state.dependencies, at);
147
+ }
148
+
149
+ /** Release the pins of a generation; used by acknowledgement and cancellation. */
150
+ export function releaseGenerationPins(
151
+ ctx: StoreContext,
152
+ waitId: string,
153
+ generation: number,
154
+ reason: string,
155
+ at: number,
156
+ ): string[] {
157
+ const rows = getRows(
158
+ ctx,
159
+ "SELECT pin_id FROM evidence_pins WHERE wait_id = ? AND generation = ? AND released_at IS NULL",
160
+ waitId,
161
+ generation,
162
+ );
163
+ const ids = rows.map((row) => columnText(row, "pin_id"));
164
+ if (ids.length === 0) return [];
165
+ run(
166
+ ctx,
167
+ `UPDATE evidence_pins SET released_at = ?, release_reason = ?
168
+ WHERE wait_id = ? AND generation = ? AND released_at IS NULL`,
169
+ at,
170
+ reason,
171
+ waitId,
172
+ generation,
173
+ );
174
+ return ids;
175
+ }
176
+
177
+ /** Void unconsumed deliveries of a generation; cancellation resolves the wait, not the result. */
178
+ export function voidGenerationOutbox(
179
+ ctx: StoreContext,
180
+ waitId: string,
181
+ generation: number,
182
+ reason: string,
183
+ at: number,
184
+ ): string[] {
185
+ const rows = getRows(
186
+ ctx,
187
+ `SELECT event_id FROM outbox_events
188
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`,
189
+ waitId,
190
+ generation,
191
+ ...UNCONSUMED_OUTBOX_STATES,
192
+ );
193
+ const ids = rows.map((row) => columnText(row, "event_id"));
194
+ if (ids.length === 0) return [];
195
+ run(
196
+ ctx,
197
+ `UPDATE outbox_events SET state = 'voided', voided_at = ?, reason = ?, dispatch_claim_json = NULL
198
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`,
199
+ at,
200
+ reason,
201
+ waitId,
202
+ generation,
203
+ ...UNCONSUMED_OUTBOX_STATES,
204
+ );
205
+ return ids;
206
+ }
207
+
208
+ /** Mark the generation's deliveries consumed by interpretation. */
209
+ export function acknowledgeGenerationOutbox(
210
+ ctx: StoreContext,
211
+ waitId: string,
212
+ generation: number,
213
+ at: number,
214
+ ): string[] {
215
+ const rows = getRows(
216
+ ctx,
217
+ `SELECT event_id FROM outbox_events
218
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`,
219
+ waitId,
220
+ generation,
221
+ ...UNCONSUMED_OUTBOX_STATES,
222
+ );
223
+ const ids = rows.map((row) => columnText(row, "event_id"));
224
+ if (ids.length === 0) return [];
225
+ run(
226
+ ctx,
227
+ `UPDATE outbox_events SET state = 'acknowledged', acknowledged_at = ?, dispatch_claim_json = NULL
228
+ WHERE wait_id = ? AND generation = ? AND state IN (${placeholders(UNCONSUMED_OUTBOX_STATES.length)})`,
229
+ at,
230
+ waitId,
231
+ generation,
232
+ ...UNCONSUMED_OUTBOX_STATES,
233
+ );
234
+ return ids;
235
+ }
236
+
237
+ function ownerClause(prefix: string, owner: OwnerIdentity): { sql: string; params: Array<string | null> } {
238
+ return {
239
+ sql: `${prefix}_kind = ? AND ${prefix}_session_id = ? AND ${prefix}_workspace = ?
240
+ AND coalesce(${prefix}_branch_id, '') = ? AND coalesce(${prefix}_goal_id, '') = ?`,
241
+ params: [owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? ""],
242
+ };
243
+ }
244
+
245
+ export function listOutbox(ctx: StoreContext, filter: OutboxFilter = {}): OutboxEventRecord[] {
246
+ const clauses: string[] = [];
247
+ const params: Array<string | number | null> = [];
248
+ if (filter.recipient) {
249
+ const clause = ownerClause("recipient", filter.recipient);
250
+ clauses.push(clause.sql);
251
+ params.push(...clause.params);
252
+ }
253
+ if (filter.state !== undefined) {
254
+ const states = Array.isArray(filter.state) ? filter.state : [filter.state as OutboxState];
255
+ for (const state of states) {
256
+ if (!OUTBOX_STATES.includes(state)) {
257
+ throw new StoreError("validation", `Invalid state: must be one of ${OUTBOX_STATES.join(", ")}`);
258
+ }
259
+ }
260
+ clauses.push(`state IN (${placeholders(states.length)})`);
261
+ params.push(...states);
262
+ }
263
+ if (filter.waitId !== undefined) {
264
+ clauses.push("wait_id = ?");
265
+ params.push(requireId("waitId", filter.waitId));
266
+ }
267
+ if (filter.generation !== undefined) {
268
+ clauses.push("generation = ?");
269
+ params.push(requireCounter("generation", filter.generation));
270
+ }
271
+ if (filter.operationId !== undefined) {
272
+ clauses.push("operation_id = ?");
273
+ params.push(requireId("operationId", filter.operationId));
274
+ }
275
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
276
+ return getRows(
277
+ ctx,
278
+ `SELECT * FROM outbox_events ${where} ORDER BY created_at, event_id`,
279
+ ...params,
280
+ ).map((row) => mapOutbox(ctx, row));
281
+ }
282
+
283
+ function readDispatchClaim(row: Record<string, unknown>): OutboxDispatchClaim | null {
284
+ return columnJson<OutboxDispatchClaim>(row, "dispatch_claim_json");
285
+ }
286
+
287
+ function assertDispatchTokenUnused(ctx: StoreContext, claimToken: string): void {
288
+ const rows = getRows(
289
+ ctx,
290
+ "SELECT event_id, dispatch_claim_json FROM outbox_events WHERE state = 'claimed'",
291
+ );
292
+ for (const row of rows) {
293
+ const claim = readDispatchClaim(row);
294
+ if (claim === null) continue;
295
+ if (claim.token === claimToken) {
296
+ throw new StoreError(
297
+ "outbox-state",
298
+ `Dispatch token ${claimToken} is already held by event ${columnText(row, "event_id")}. Use a fresh token for a new dispatch attempt.`,
299
+ );
300
+ }
301
+ }
302
+ }
303
+
304
+ /**
305
+ * Claim pending deliveries for dispatch. Claiming records an attempt but does not
306
+ * consume the result: an event that is never acknowledged stays visible.
307
+ */
308
+ export function claimOutbox(ctx: StoreContext, input: ClaimOutboxInput): OutboxEventRecord[] {
309
+ const claimToken = requireId("claimToken", input.claimToken);
310
+ const claimedBy = requireText("claimedBy", input.claimedBy, 200);
311
+ const limit = input.limit === undefined ? 10 : requireCounter("limit", input.limit);
312
+ if (limit < 1) {
313
+ throw new StoreError("validation", "Invalid limit: must be at least 1");
314
+ }
315
+ const recipient = input.recipient;
316
+
317
+ return ctx.transaction(() => {
318
+ assertDispatchTokenUnused(ctx, claimToken);
319
+ const clauses = [
320
+ "state = 'pending'",
321
+ `EXISTS (SELECT 1 FROM waits w WHERE w.wait_id = outbox_events.wait_id
322
+ AND w.generation = outbox_events.generation
323
+ AND w.phase IN (${placeholders(DELIVERABLE_WAIT_PHASES.length)}))`,
324
+ ];
325
+ const params: Array<string | number | null> = [...DELIVERABLE_WAIT_PHASES];
326
+ if (input.waitId !== undefined) {
327
+ clauses.push("wait_id = ?");
328
+ params.push(requireId("waitId", input.waitId));
329
+ }
330
+ if (input.generation !== undefined) {
331
+ clauses.push("generation = ?");
332
+ params.push(requireCounter("generation", input.generation));
333
+ }
334
+ if (recipient) {
335
+ const clause = ownerClause("recipient", recipient);
336
+ clauses.push(clause.sql);
337
+ params.push(...clause.params);
338
+ }
339
+ const rows = getRows(
340
+ ctx,
341
+ `SELECT * FROM outbox_events WHERE ${clauses.join(" AND ")} ORDER BY created_at, event_id LIMIT ?`,
342
+ ...params,
343
+ limit,
344
+ );
345
+ const at = ctx.now();
346
+ const claimed: OutboxEventRecord[] = [];
347
+ for (const row of rows) {
348
+ const eventId = columnText(row, "event_id");
349
+ run(
350
+ ctx,
351
+ `UPDATE outbox_events
352
+ SET state = 'claimed', attempts = attempts + 1, claimed_at = ?, dispatch_claim_json = ?
353
+ WHERE event_id = ? AND state = 'pending'`,
354
+ at,
355
+ JSON.stringify({ token: claimToken, claimedBy, claimedAt: at }),
356
+ eventId,
357
+ );
358
+ const updated = readOutboxRow(ctx, eventId);
359
+ if (updated) claimed.push(mapOutbox(ctx, updated));
360
+ }
361
+ return claimed;
362
+ });
363
+ }
364
+
365
+ function requireClaimedEvent(
366
+ ctx: StoreContext,
367
+ input: OutboxDispatchInput,
368
+ ): Record<string, unknown> {
369
+ const eventId = requireId("eventId", input.eventId);
370
+ const claimToken = requireId("claimToken", input.claimToken);
371
+ const row = readOutboxRow(ctx, eventId);
372
+ if (!row) {
373
+ throw new StoreError("outbox-state", `No outbox event ${eventId} is recorded.`);
374
+ }
375
+ const state = columnText(row, "state");
376
+ if (state !== "claimed") {
377
+ throw new StoreError(
378
+ "outbox-state",
379
+ `Outbox event ${eventId} is ${state}; only a claimed delivery can be completed or released.`,
380
+ );
381
+ }
382
+ const claim = readDispatchClaim(row);
383
+ if (claim === null || claim.token !== claimToken) {
384
+ throw new StoreError(
385
+ "outbox-state",
386
+ `Outbox event ${eventId} is claimed by a different dispatch token; the caller does not hold this delivery.`,
387
+ );
388
+ }
389
+ return row;
390
+ }
391
+
392
+ export function markOutboxDelivered(
393
+ ctx: StoreContext,
394
+ input: OutboxDispatchInput,
395
+ ): OutboxEventRecord {
396
+ return ctx.transaction(() => {
397
+ const row = requireClaimedEvent(ctx, input);
398
+ const eventId = columnText(row, "event_id");
399
+ run(
400
+ ctx,
401
+ "UPDATE outbox_events SET state = 'delivered', delivered_at = ?, dispatch_claim_json = NULL WHERE event_id = ?",
402
+ ctx.now(),
403
+ eventId,
404
+ );
405
+ const updated = readOutboxRow(ctx, eventId);
406
+ return mapOutbox(ctx, updated as Record<string, unknown>);
407
+ });
408
+ }
409
+
410
+ /**
411
+ * Return a claimed delivery to the queue with a recorded reason. Attempts and the
412
+ * recovery reason are retained, and the result stays unconsumed.
413
+ */
414
+ export function releaseOutbox(
415
+ ctx: StoreContext,
416
+ input: ReleaseOutboxInput,
417
+ ): OutboxEventRecord {
418
+ const reason = requireText("reason", input.reason, 1024);
419
+ return ctx.transaction(() => {
420
+ const row = requireClaimedEvent(ctx, input);
421
+ const eventId = columnText(row, "event_id");
422
+ run(
423
+ ctx,
424
+ "UPDATE outbox_events SET state = 'pending', reason = ?, dispatch_claim_json = NULL WHERE event_id = ?",
425
+ reason,
426
+ eventId,
427
+ );
428
+ const updated = readOutboxRow(ctx, eventId);
429
+ return mapOutbox(ctx, updated as Record<string, unknown>);
430
+ });
431
+ }