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,376 @@
1
+ // Generated from packages/operation-coordinator/src/operations.ts. Do not edit directly.
2
+ /**
3
+ * Operation registration, supervision updates and terminal outcomes.
4
+ *
5
+ * Launch identity is immutable. Registering the same launch twice is an
6
+ * idempotent replay; changing any of it is refused, because a store that
7
+ * rewrites an owner or a task binding cannot be used to prove who owns a wait.
8
+ *
9
+ * A terminal outcome is recorded once per operation (`terminalRevision` 1) with
10
+ * the supervisor's event id. A replay with the same event id returns the
11
+ * recorded revision without side effects; a different terminal event for the
12
+ * same operation is refused instead of overwriting the first evidence.
13
+ */
14
+ import { StoreError } from "./errors.ts";
15
+ import { mapOperation, ownerFromRow, readOperation, requireOperation } from "./rows.ts";
16
+ import {
17
+ columnText,
18
+ getRows,
19
+ isUniqueViolation,
20
+ run,
21
+ type StoreContext,
22
+ } from "./sqlite.ts";
23
+ import type {
24
+ EvidenceRefInput,
25
+ ObserverHealth,
26
+ OperationFilter,
27
+ OperationRecord,
28
+ RecordSupervisionInput,
29
+ RecordTerminalOutcomeInput,
30
+ RecordTerminalOutcomeResult,
31
+ RegisterOperationInput,
32
+ RegisterOperationResult,
33
+ SupervisionIdentity,
34
+ TerminalOutcome,
35
+ WaitRecord,
36
+ } from "./types.ts";
37
+ import {
38
+ describeOwnerDiff,
39
+ normalizeOwner,
40
+ optionalText,
41
+ requireBoolean,
42
+ requireEnum,
43
+ requireEvidenceKind,
44
+ requireId,
45
+ requireObserver,
46
+ requireOptionalCounter,
47
+ requireText,
48
+ sameOwner,
49
+ } from "./validate.ts";
50
+ import { mapOutbox } from "./rows.ts";
51
+ import { settleWaitsForOperation } from "./waits.ts";
52
+
53
+ const HEALTH_VALUES: readonly ObserverHealth[] = ["active", "unmonitored", "lost"];
54
+ const OUTCOME_VALUES: readonly TerminalOutcome[] = ["succeeded", "failed", "cancelled", "lost"];
55
+
56
+ function normalizeSupervision(value: unknown): SupervisionIdentity | null {
57
+ if (value === undefined || value === null) return null;
58
+ if (typeof value !== "object" || Array.isArray(value)) {
59
+ throw new StoreError("validation", "Invalid supervision: must be an object");
60
+ }
61
+ const supervision = value as Partial<SupervisionIdentity>;
62
+ return {
63
+ hostId: requireId("supervision.hostId", supervision.hostId),
64
+ runnerId: supervision.runnerId === undefined || supervision.runnerId === null
65
+ ? null
66
+ : requireId("supervision.runnerId", supervision.runnerId),
67
+ processStartToken: supervision.processStartToken === undefined || supervision.processStartToken === null
68
+ ? null
69
+ : requireId("supervision.processStartToken", supervision.processStartToken),
70
+ };
71
+ }
72
+
73
+ function normalizeEvidence(value: unknown): EvidenceRefInput[] {
74
+ if (value === undefined || value === null) return [];
75
+ if (!Array.isArray(value)) {
76
+ throw new StoreError("validation", "Invalid evidence: must be an array");
77
+ }
78
+ return value.map((entry, index) => {
79
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
80
+ throw new StoreError("validation", `Invalid evidence[${index}]: must be an object`);
81
+ }
82
+ const item = entry as Partial<EvidenceRefInput>;
83
+ const normalized: EvidenceRefInput = {
84
+ kind: requireEvidenceKind(`evidence[${index}].kind`, item.kind),
85
+ ref: requireText(`evidence[${index}].ref`, item.ref, 1024),
86
+ detailLost: item.detailLost === undefined ? false : requireBoolean(
87
+ `evidence[${index}].detailLost`,
88
+ item.detailLost,
89
+ ),
90
+ };
91
+ const summary = optionalText(`evidence[${index}].summary`, item.summary, 2048);
92
+ if (summary !== null) normalized.summary = summary;
93
+ const bytes = requireOptionalCounter(`evidence[${index}].bytes`, item.bytes);
94
+ if (bytes !== null) normalized.bytes = bytes;
95
+ return normalized;
96
+ });
97
+ }
98
+
99
+ export function registerOperation(
100
+ ctx: StoreContext,
101
+ input: RegisterOperationInput,
102
+ ): RegisterOperationResult {
103
+ const operationId = requireId("operationId", input.operationId);
104
+ const taskId = requireId("taskId", input.taskId);
105
+ const launchToken = requireId("launchToken", input.launchToken);
106
+ const owner = normalizeOwner("owner", input.owner);
107
+ const observer = requireObserver("observer", input.observer);
108
+ const supervision = normalizeSupervision(input.supervision);
109
+ const authorityRef = optionalText("authorityRef", input.authorityRef, 512);
110
+ const intentRef = optionalText("intentRef", input.intentRef, 200);
111
+
112
+ const assertTaskAvailable = (): void => {
113
+ const byTask = getRows(ctx, "SELECT * FROM operations WHERE task_id = ?", taskId)[0];
114
+ if (!byTask) return;
115
+ const existingOwner = ownerFromRow(byTask);
116
+ if (!sameOwner(existingOwner, owner)) {
117
+ throw new StoreError(
118
+ "task-ownership",
119
+ `Background task ${taskId} is owned by another execution owner. A task id belongs to the launch that registered it; a different owner must not attach to it.`,
120
+ );
121
+ }
122
+ throw new StoreError(
123
+ "operation-conflict",
124
+ `Background task ${taskId} is already bound to operation ${columnText(byTask, "operation_id")}. One durable operation exists per task launch; reconcile the recorded one instead of registering a second.`,
125
+ );
126
+ };
127
+
128
+ const assertLaunchIdentity = (existing: OperationRecord): void => {
129
+ const differences: string[] = [];
130
+ if (existing.taskId !== taskId) differences.push("taskId");
131
+ if (existing.launchToken !== launchToken) differences.push("launchToken");
132
+ if (!sameOwner(existing.owner, owner)) {
133
+ differences.push(`owner (${describeOwnerDiff(existing.owner, owner)})`);
134
+ }
135
+ if (existing.observer.kind !== observer.kind || existing.observer.version !== observer.version) {
136
+ differences.push("observer");
137
+ }
138
+ if (differences.length > 0) {
139
+ throw new StoreError(
140
+ "operation-conflict",
141
+ `Operation ${operationId} is already registered with a different launch identity: ${differences.join(", ")}. Launch identity and ownership are immutable; register a new operation id for a new launch.`,
142
+ );
143
+ }
144
+ };
145
+
146
+ return ctx.transaction(() => {
147
+ const existing = readOperation(ctx, operationId);
148
+ if (existing) {
149
+ assertLaunchIdentity(existing);
150
+ return { operation: existing, created: false };
151
+ }
152
+ assertTaskAvailable();
153
+
154
+ const at = ctx.now();
155
+ try {
156
+ run(
157
+ ctx,
158
+ `INSERT INTO operations (
159
+ operation_id, task_id, launch_token,
160
+ owner_kind, owner_session_id, owner_workspace, owner_branch_id, owner_goal_id,
161
+ observer_kind, observer_version, supervision_json, authority_ref, intent_ref,
162
+ phase, health, health_reason, terminal_revision, created_at, updated_at
163
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'running', 'active', NULL, 0, ?, ?)`,
164
+ operationId,
165
+ taskId,
166
+ launchToken,
167
+ owner.kind,
168
+ owner.sessionId,
169
+ owner.workspace,
170
+ owner.branchId ?? null,
171
+ owner.goalId ?? null,
172
+ observer.kind,
173
+ observer.version,
174
+ supervision ? JSON.stringify(supervision) : null,
175
+ authorityRef,
176
+ intentRef,
177
+ at,
178
+ at,
179
+ );
180
+ } catch (error) {
181
+ // Another process may have registered the same launch (or the same task)
182
+ // between the check above and this insert. Re-read and report the same
183
+ // typed outcome instead of leaking a raw constraint error.
184
+ if (!isUniqueViolation(error, "operations.task_id", "operations.operation_id")) throw error;
185
+ const raced = readOperation(ctx, operationId);
186
+ if (raced) {
187
+ assertLaunchIdentity(raced);
188
+ return { operation: raced, created: false };
189
+ }
190
+ assertTaskAvailable();
191
+ throw error;
192
+ }
193
+ return { operation: requireOperation(ctx, operationId), created: true };
194
+ });
195
+ }
196
+
197
+ /**
198
+ * Replace the supervision identity and/or observer health. A replacement host
199
+ * may take over observation; ownership and launch identity stay untouched.
200
+ */
201
+ export function recordSupervision(
202
+ ctx: StoreContext,
203
+ input: RecordSupervisionInput,
204
+ ): OperationRecord {
205
+ const operationId = requireId("operationId", input.operationId);
206
+ const owner = normalizeOwner("owner", input.owner);
207
+ const supervision = normalizeSupervision(input.supervision);
208
+ const health = input.health === undefined
209
+ ? null
210
+ : requireEnum("health", input.health, HEALTH_VALUES);
211
+ const reason = optionalText("reason", input.reason, 1024);
212
+ if (health === null && supervision === null) {
213
+ throw new StoreError("validation", "Invalid supervision update: nothing to record");
214
+ }
215
+
216
+ return ctx.transaction(() => {
217
+ const operation = requireOperation(ctx, operationId);
218
+ if (!sameOwner(operation.owner, owner)) {
219
+ throw new StoreError(
220
+ "foreign-owner",
221
+ `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}).`,
222
+ );
223
+ }
224
+ const nextHealth = health ?? operation.health;
225
+ const nextReason = nextHealth === "active" ? null : (reason ?? operation.healthReason);
226
+ if (nextHealth !== "active" && nextReason === null) {
227
+ throw new StoreError(
228
+ "validation",
229
+ "Invalid reason: observer health other than active requires a recorded reason",
230
+ );
231
+ }
232
+ run(
233
+ ctx,
234
+ "UPDATE operations SET supervision_json = ?, health = ?, health_reason = ?, updated_at = ? WHERE operation_id = ?",
235
+ supervision ? JSON.stringify(supervision) : operation.supervision
236
+ ? JSON.stringify(operation.supervision)
237
+ : null,
238
+ nextHealth,
239
+ nextReason,
240
+ ctx.now(),
241
+ operationId,
242
+ );
243
+ return requireOperation(ctx, operationId);
244
+ });
245
+ }
246
+
247
+ export function recordTerminalOutcome(
248
+ ctx: StoreContext,
249
+ input: RecordTerminalOutcomeInput,
250
+ ): RecordTerminalOutcomeResult {
251
+ const operationId = requireId("operationId", input.operationId);
252
+ const eventId = requireId("eventId", input.eventId);
253
+ const outcome = requireEnum("outcome", input.outcome, OUTCOME_VALUES);
254
+ const owner = normalizeOwner("owner", input.owner);
255
+ const evidence = normalizeEvidence(input.evidence);
256
+ const reason = optionalText("reason", input.reason, 1024);
257
+ const detailLost = input.detailLost === undefined
258
+ ? outcome === "lost"
259
+ : requireBoolean("detailLost", input.detailLost);
260
+
261
+ return ctx.transaction(() => {
262
+ const operation = requireOperation(ctx, operationId);
263
+ if (!sameOwner(operation.owner, owner)) {
264
+ throw new StoreError(
265
+ "foreign-owner",
266
+ `Operation ${operationId} belongs to another execution owner (differs in ${describeOwnerDiff(operation.owner, owner)}); a terminal outcome must be reported by or for its registered owner.`,
267
+ );
268
+ }
269
+ if (operation.phase === "terminal") {
270
+ if (operation.terminalEventId === eventId) {
271
+ return {
272
+ operation,
273
+ recorded: false,
274
+ outbox: listOutboxForRevision(ctx, operationId, operation.terminalRevision),
275
+ ready: [],
276
+ };
277
+ }
278
+ throw new StoreError(
279
+ "terminal-conflict",
280
+ `Operation ${operationId} already recorded terminal event ${operation.terminalEventId} (${operation.terminalOutcome}). Event ${eventId} is a different terminal event and cannot replace it; a replayed event must reuse its original event id.`,
281
+ );
282
+ }
283
+
284
+ // A replay may omit evidence: the recorded revision already holds it. Only a
285
+ // new terminal revision must be interpretable on its own.
286
+ if (evidence.length === 0 && reason === null) {
287
+ throw new StoreError(
288
+ "validation",
289
+ "Invalid reason: a terminal outcome without evidence must record why (for example lost supervision), so the result is interpretable.",
290
+ );
291
+ }
292
+ const at = ctx.now();
293
+ evidence.forEach((item, ordinal) => {
294
+ run(
295
+ ctx,
296
+ `INSERT INTO operation_evidence (
297
+ operation_id, terminal_revision, ordinal, kind, ref, summary, detail_lost, bytes, captured_at
298
+ ) VALUES (?, 1, ?, ?, ?, ?, ?, ?, ?)`,
299
+ operationId,
300
+ ordinal,
301
+ item.kind,
302
+ item.ref,
303
+ item.summary ?? null,
304
+ item.detailLost ? 1 : 0,
305
+ item.bytes ?? null,
306
+ at,
307
+ );
308
+ });
309
+ run(
310
+ ctx,
311
+ `UPDATE operations
312
+ SET phase = 'terminal', terminal_revision = 1, terminal_outcome = ?, terminal_event_id = ?,
313
+ terminal_detail_lost = ?, terminal_reason = ?, terminal_at = ?, updated_at = ?
314
+ WHERE operation_id = ?`,
315
+ outcome,
316
+ eventId,
317
+ detailLost ? 1 : 0,
318
+ reason,
319
+ at,
320
+ at,
321
+ operationId,
322
+ );
323
+ const settledOperation = requireOperation(ctx, operationId);
324
+ const settled = settleWaitsForOperation(ctx, settledOperation, at);
325
+ const outbox = listOutboxForRevision(ctx, operationId, 1);
326
+ return {
327
+ operation: settledOperation,
328
+ recorded: true,
329
+ outbox,
330
+ ready: settled.ready as WaitRecord[],
331
+ };
332
+ });
333
+ }
334
+
335
+ export function getOperation(ctx: StoreContext, operationId: string): OperationRecord | null {
336
+ return readOperation(ctx, operationId);
337
+ }
338
+
339
+ export function listOperations(
340
+ ctx: StoreContext,
341
+ filter: OperationFilter = {},
342
+ ): OperationRecord[] {
343
+ const clauses: string[] = [];
344
+ const params: Array<string | number> = [];
345
+ if (filter.owner) {
346
+ const owner = normalizeOwner("owner", filter.owner);
347
+ clauses.push(
348
+ "owner_kind = ? AND owner_session_id = ? AND owner_workspace = ? AND coalesce(owner_branch_id, '') = ? AND coalesce(owner_goal_id, '') = ?",
349
+ );
350
+ params.push(owner.kind, owner.sessionId, owner.workspace, owner.branchId ?? "", owner.goalId ?? "");
351
+ }
352
+ if (filter.phase !== undefined) {
353
+ clauses.push("phase = ?");
354
+ params.push(requireEnum("phase", filter.phase, ["running", "terminal"] as const));
355
+ }
356
+ if (filter.taskId !== undefined) {
357
+ clauses.push("task_id = ?");
358
+ params.push(requireId("taskId", filter.taskId));
359
+ }
360
+ const where = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
361
+ return getRows(ctx, `SELECT * FROM operations ${where} ORDER BY created_at, operation_id`, ...params)
362
+ .map(mapOperation);
363
+ }
364
+
365
+ function listOutboxForRevision(
366
+ ctx: StoreContext,
367
+ operationId: string,
368
+ terminalRevision: number,
369
+ ) {
370
+ return getRows(
371
+ ctx,
372
+ "SELECT * FROM outbox_events WHERE operation_id = ? AND terminal_revision = ? ORDER BY created_at, event_id",
373
+ operationId,
374
+ terminalRevision,
375
+ ).map((row) => mapOutbox(ctx, row));
376
+ }