pi-better-subagents 0.26.2 → 0.27.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.26.2",
3
+ "version": "0.27.1",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -54,6 +54,7 @@
54
54
  "files": [
55
55
  "*.ts",
56
56
  "*.mjs",
57
+ "shared-operation-coordinator/**/*.ts",
57
58
  "config.json",
58
59
  "README.md",
59
60
  "roles/**/*.md",
@@ -0,0 +1,61 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { readFileSync, realpathSync, statSync } from 'node:fs';
3
+
4
+ export interface ParkCheckpoint {
5
+ version: 1;
6
+ sessionId: string;
7
+ sessionFile: string;
8
+ toolCallId: string;
9
+ waitId: string;
10
+ generation: number;
11
+ entryId: string;
12
+ prefixBytes: number;
13
+ prefixSha256: string;
14
+ }
15
+
16
+ /** Proof of a saved tool result, never a request to rewrite native history. */
17
+ export function captureParkCheckpoint(input: {
18
+ sessionId: string; sessionFile: string; toolCallId: string; waitId: string; generation: number;
19
+ }): ParkCheckpoint {
20
+ if (!input.sessionId || !input.toolCallId || !input.waitId || !Number.isSafeInteger(input.generation) || input.generation < 1) {
21
+ throw new Error('Invalid park checkpoint identity');
22
+ }
23
+ const sessionFile = realpathSync.native(input.sessionFile);
24
+ const size = statSync(sessionFile).size;
25
+ if (size > 64 * 1024 * 1024) throw new Error('Conversation exceeds the supported park-checkpoint size');
26
+ const bytes = readFileSync(sessionFile);
27
+ if (!bytes.length || bytes.at(-1) !== 10) throw new Error('Native session has an incomplete checkpoint write');
28
+ const lines = bytes.toString('utf8').trimEnd().split('\n');
29
+ const records = lines.map(line => JSON.parse(line));
30
+ if (records[0]?.type !== 'session' || records[0]?.id !== input.sessionId) throw new Error('Park checkpoint belongs to another conversation');
31
+ const messages = records.filter(entry => entry.type === 'message');
32
+ const last = messages.at(-1);
33
+ const result = last?.message;
34
+ if (!last?.id || result?.role !== 'toolResult' || result.toolCallId !== input.toolCallId || result.toolName !== 'wait_for_operations' || result.isError) {
35
+ throw new Error('The wait tool result is not the last persisted conversation message');
36
+ }
37
+ const marker = result.details?.operationWait;
38
+ const text = Array.isArray(result.content) ? result.content.filter((part: any) => part?.type === 'text').map((part: any) => part.text).join('\n') : '';
39
+ let parsed: any;
40
+ try { parsed = JSON.parse(text); } catch { /* Structured details remain authoritative when present. */ }
41
+ const wait = marker ?? parsed?.operationWait;
42
+ if (wait?.waitId !== input.waitId || wait?.generation !== input.generation) throw new Error('Persisted wait result does not match the registered wait generation');
43
+ const request = messages.slice(0, -1).reverse().find(entry => entry.message?.role === 'assistant' &&
44
+ entry.message.content?.some((part: any) => part?.type === 'toolCall' && part.id === input.toolCallId));
45
+ const call = request?.message.content.find((part: any) => part?.type === 'toolCall' && part.id === input.toolCallId);
46
+ if (call?.name !== 'wait_for_operations') throw new Error('No matching native wait tool call precedes its result');
47
+ return { version: 1, ...input, sessionFile, entryId: last.id, prefixBytes: bytes.length,
48
+ prefixSha256: createHash('sha256').update(bytes).digest('hex') };
49
+ }
50
+
51
+ /** Appends are allowed after resume, but replacement/truncation cannot impersonate a checkpoint. */
52
+ export function verifyParkCheckpoint(checkpoint: ParkCheckpoint): void {
53
+ if (checkpoint.version !== 1 || !Number.isSafeInteger(checkpoint.prefixBytes) || checkpoint.prefixBytes < 1 || checkpoint.prefixBytes > 64 * 1024 * 1024) {
54
+ throw new Error('Unsupported park checkpoint');
55
+ }
56
+ if (realpathSync.native(checkpoint.sessionFile) !== checkpoint.sessionFile) throw new Error('Park checkpoint path changed');
57
+ const bytes = readFileSync(checkpoint.sessionFile);
58
+ if (bytes.length < checkpoint.prefixBytes || createHash('sha256').update(bytes.subarray(0, checkpoint.prefixBytes)).digest('hex') !== checkpoint.prefixSha256) {
59
+ throw new Error('Saved conversation no longer contains the verified park checkpoint');
60
+ }
61
+ }
package/parse.ts CHANGED
@@ -33,7 +33,7 @@ import { logPathFor } from "./registry.ts";
33
33
  interface ContentBlock { type: string; text?: string; thinking?: string; name?: string }
34
34
  interface Cost { total?: number }
35
35
  interface MsgUsage { input?: number; output?: number; cacheRead?: number; cost?: Cost }
36
- interface Msg { role?: string; content?: string | ContentBlock[]; usage?: MsgUsage }
36
+ interface Msg { role?: string; content?: string | ContentBlock[]; usage?: MsgUsage; stopReason?: string; errorMessage?: string }
37
37
 
38
38
  /** Cumulative token + cost spend across a run's turns. */
39
39
  export interface Usage {
@@ -133,6 +133,12 @@ export interface ParsedRun {
133
133
  unmatchedToolCalls: UnmatchedToolCall[];
134
134
  /** True if we saw the terminal `agent_end`/`agent_settled` event. */
135
135
  sawEnd: boolean;
136
+ /**
137
+ * Message of the last model request that failed and that no later assistant
138
+ * turn superseded. A stream ending on one did not do the work: Pi still ends
139
+ * the loop normally, so the terminal event alone cannot prove success.
140
+ */
141
+ modelError?: string;
136
142
  /** Cumulative token + cost spend so far. */
137
143
  usage: Usage;
138
144
  /** Diagnostics about truncation or parse failure, surfaced to the user. */
@@ -1101,6 +1107,8 @@ interface ParseState {
1101
1107
  openToolCalls: Map<string, UnmatchedToolCall>;
1102
1108
  anonymousToolCall: number;
1103
1109
  sawEnd: boolean;
1110
+ /** Last unrecovered failed model request, cleared by a later successful turn. */
1111
+ modelError?: string;
1104
1112
  /** Bytes were skipped by a bounded cold start on an already-large log. */
1105
1113
  windowTruncated: boolean;
1106
1114
  /** Log size at the last read, for the truncation diagnostic. */
@@ -1245,6 +1253,15 @@ function foldParseEvent(state: ParseState, e: Record<string, unknown>): void {
1245
1253
  // Latest finalized assistant text wins, so a run without a
1246
1254
  // terminal `agent_end` still yields its LAST answer, not its first.
1247
1255
  if (t) { state.lastActivity = t; state.finalText = t; }
1256
+ // A failed request is evidence until a later assistant turn proves the
1257
+ // model serves again. Only the LAST request matters: earlier failures
1258
+ // show up as `auto_retry_*` retries that already recovered. The stop
1259
+ // reason decides, because Pi pairs `stopReason: "aborted"` with a real
1260
+ // error message and an aborted turn is a stop, not a provider failure.
1261
+ const errorMessage = typeof m.errorMessage === "string" ? m.errorMessage.trim() : "";
1262
+ state.modelError = m.stopReason === "error"
1263
+ ? errorMessage || "assistant stopReason=error"
1264
+ : undefined;
1248
1265
  const u = m?.usage;
1249
1266
  if (u) {
1250
1267
  state.usage.input += u.input ?? 0;
@@ -1350,6 +1367,7 @@ export function parseRun(id: string): ParsedRun {
1350
1367
  toolCallCount: view.toolCallCount,
1351
1368
  unmatchedToolCalls: [...view.openToolCalls.values()],
1352
1369
  sawEnd: view.sawEnd,
1370
+ modelError: view.modelError,
1353
1371
  usage,
1354
1372
  diagnostics,
1355
1373
  };
package/registry.ts CHANGED
@@ -250,14 +250,20 @@ export interface RunMeta {
250
250
  * `subagent_list` keep working for dismissed runs).
251
251
  */
252
252
  dismissedAt?: number;
253
+ catalog?: CatalogLaunchSnapshot;
253
254
  /**
254
- * Optional catalog launch snapshot. Additive: metadata written before the
255
- * catalog has no `catalog` key and still parses. The first launch
256
- * publication freezes `name` and `catalog` together, including when
257
- * catalog is absent or null. Later status, result, and stop writes keep
258
- * that whole snapshot and must not fill a missing catalog.
255
+ * Durable park disposition for a worker attempt that ended while waiting on
256
+ * an observed dependency. Additive: a record without it is an ordinary run.
257
+ * The attempt status stays `completed`; this field is what distinguishes
258
+ * "this attempt finished" from "the assignment finished" (ADR 0020).
259
259
  */
260
- catalog?: CatalogLaunchSnapshot;
260
+ park?: ParkRecord;
261
+ /**
262
+ * Supervised-operation binding for this attempt. Additive. Records only
263
+ * references (bridge run id, conversation id, authority reference) and the
264
+ * captured worker policy — never the per-run bridge token.
265
+ */
266
+ operations?: RunOperationsBinding;
261
267
  /**
262
268
  * Harness-owned timing policy and one-shot markers (soft deadline, grace,
263
269
  * hard ceiling, stuck window). Written at launch so /reload keeps it.
@@ -298,6 +304,186 @@ function metaPathFor(id: string): string {
298
304
  return join(runDir(id), "meta.json");
299
305
  }
300
306
 
307
+ // ---- park disposition and supervised-operations binding -------------------
308
+
309
+ /**
310
+ * Phase of a parked assignment's wait, mirrored from the coordinator record for
311
+ * display, resume decisions and cleanup protection. `consumed`/`cancelled` are
312
+ * terminal; `held` needs its owner.
313
+ */
314
+ export type ParkPhase =
315
+ | "parking"
316
+ | "waiting"
317
+ | "ready"
318
+ | "resuming"
319
+ | "held"
320
+ | "consumed"
321
+ | "cancelled";
322
+
323
+ /** Proof that the wait tool result is the persisted end of the saved conversation. */
324
+ export interface ParkCheckpointIdentity {
325
+ sessionId: string;
326
+ sessionFile: string;
327
+ toolCallId: string;
328
+ entryId: string;
329
+ prefixBytes: number;
330
+ prefixSha256: string;
331
+ }
332
+
333
+ /**
334
+ * Durable park disposition of one attempt: which wait generation it parked on,
335
+ * the verified native checkpoint, and what happened afterwards. Written only by
336
+ * the parent after the checkpoint was verified and the coordinator admitted it,
337
+ * so an attempt cannot claim a park it did not prove.
338
+ */
339
+ export interface ParkRecord {
340
+ version: 1;
341
+ waitId: string;
342
+ generation: number;
343
+ phase: ParkPhase;
344
+ /** Attempt that parked (this run id). */
345
+ attemptId: string;
346
+ /** Foreground owner binding recorded for admission, when known. */
347
+ ownerSessionId?: string;
348
+ ownerWorkspace?: string;
349
+ ownerBranchId?: string | null;
350
+ ownerGoalId?: string | null;
351
+ /** The next reasoning step the worker recorded when it parked. */
352
+ continuationNote?: string;
353
+ /** Verified saved-conversation checkpoint. */
354
+ checkpoint?: ParkCheckpointIdentity;
355
+ parkedAt: number;
356
+ updatedAt: number;
357
+ /** Why the wait is held instead of continuing. */
358
+ heldReason?: string;
359
+ /** Continuation attempt admitted for this wait generation. */
360
+ resumedAt?: number;
361
+ resumedBy?: string;
362
+ /** Launch token persisted with the attempt id BEFORE the child is spawned. */
363
+ resumeLaunchToken?: string;
364
+ /**
365
+ * Store-issued resume claim identity persisted with the attempt, so a proven
366
+ * failed exit can hold the generation with exact claim identity (the claim
367
+ * token is the same value the durable claim row already stores).
368
+ */
369
+ resumeClaimId?: string;
370
+ resumeClaimToken?: string;
371
+ cancelledAt?: number;
372
+ cancelReason?: string;
373
+ }
374
+
375
+ /** References for a run whose child may use supervised operations. */
376
+ export interface RunOperationsBinding {
377
+ version: 1;
378
+ /** Bridge run id; equals the attempt id. */
379
+ bridgeRunId: string;
380
+ conversationId: string;
381
+ authorityReference: string;
382
+ /** Foreground branch/goal binding recorded for resume admission. */
383
+ branchId?: string | null;
384
+ goalId?: string | null;
385
+ /**
386
+ * Workspace the worker conversation was registered under (the sandbox or clone
387
+ * the child ran in). Background ownership uses this, not the foreground cwd.
388
+ */
389
+ workspace?: string;
390
+ /**
391
+ * Launch token persisted with the resume attempt BEFORE spawn, so a crash
392
+ * between publication and the child's own publication is reconciled instead
393
+ * of relaunched. Never a credential.
394
+ */
395
+ resumeLaunchToken?: string;
396
+ /** Worker policy captured at launch; Background intersects it, never the child. */
397
+ policy: {
398
+ version: 1;
399
+ sandbox: unknown;
400
+ tools: readonly string[];
401
+ clean: boolean;
402
+ deadlineAt: number | null;
403
+ };
404
+ /** Tools the child bridge exposes. */
405
+ tools: readonly string[];
406
+ }
407
+
408
+ export function parkRecordPath(id: string): string {
409
+ return join(runDir(id), "park.json");
410
+ }
411
+
412
+ /** Verify the shape before trusting a record read from disk. */
413
+ function parseParkRecord(value: unknown): ParkRecord | undefined {
414
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
415
+ const record = value as Partial<ParkRecord>;
416
+ if (record.version !== 1) return undefined;
417
+ if (typeof record.waitId !== "string" || !record.waitId) return undefined;
418
+ if (!Number.isSafeInteger(record.generation) || (record.generation ?? 0) < 1) return undefined;
419
+ if (typeof record.attemptId !== "string" || !record.attemptId) return undefined;
420
+ if (typeof record.parkedAt !== "number" || !Number.isFinite(record.parkedAt)) return undefined;
421
+ const phases: readonly ParkPhase[] = ["parking", "waiting", "ready", "resuming", "held", "consumed", "cancelled"];
422
+ if (!phases.includes(record.phase as ParkPhase)) return undefined;
423
+ return record as ParkRecord;
424
+ }
425
+
426
+ /**
427
+ * Write the park disposition atomically and mirror it into the run's metadata.
428
+ * The mirror keeps listings, the Goal provider and cleanup from needing a second
429
+ * read; the file remains the authoritative copy for this attempt.
430
+ */
431
+ export function writeParkRecord(id: string, record: ParkRecord): void {
432
+ if (!/^[A-Za-z0-9_-]+$/.test(id)) throw new Error("Invalid run ID.");
433
+ mkdirSync(runDir(id), { recursive: true });
434
+ const path = parkRecordPath(id);
435
+ const temp = join(dirname(path), `.park.${randomBytes(6).toString("hex")}.tmp`);
436
+ writeFileSync(temp, JSON.stringify(record), { mode: 0o600, flag: "wx" });
437
+ renameSync(temp, path);
438
+ const meta = readMeta(id);
439
+ if (meta && (meta.park?.phase !== record.phase
440
+ || meta.park?.heldReason !== record.heldReason
441
+ || meta.park?.resumedBy !== record.resumedBy)) {
442
+ meta.park = record;
443
+ writeMeta(meta);
444
+ }
445
+ }
446
+
447
+ /** Read the attempt's park disposition; absent for an ordinary run. */
448
+ export function readParkRecord(id: string): ParkRecord | undefined {
449
+ try {
450
+ return parseParkRecord(JSON.parse(readFileSync(parkRecordPath(id), "utf-8")));
451
+ } catch (error) {
452
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return undefined;
453
+ // The volatile run directory may already be reclaimed; the durable
454
+ // completed-attempt record carries the park snapshot taken at finalization.
455
+ return readMeta(id)?.park;
456
+ }
457
+ }
458
+
459
+ /** Merge one phase/reason change into the park disposition. */
460
+ export function updateParkRecord(
461
+ id: string,
462
+ patch: Partial<Omit<ParkRecord, "version" | "waitId" | "generation" | "attemptId" | "parkedAt">>,
463
+ ): ParkRecord | undefined {
464
+ const current = readParkRecord(id);
465
+ if (!current) return undefined;
466
+ const next: ParkRecord = { ...current, ...patch, updatedAt: Date.now() };
467
+ writeParkRecord(id, next);
468
+ return next;
469
+ }
470
+
471
+ /** A park still owns a pending continuation: `parking`, `waiting`, `ready`, `resuming` or `held`. */
472
+ export function isPendingPark(record: Pick<ParkRecord, "phase">): boolean {
473
+ return record.phase !== "consumed" && record.phase !== "cancelled";
474
+ }
475
+
476
+ /**
477
+ * Runs whose park disposition can still resume. Used by cleanup protection and
478
+ * by resume reconciliation; a consumed or cancelled park is not included.
479
+ */
480
+ export function listPendingParkedRuns(metas: readonly RunMeta[] = listMetas()): RunMeta[] {
481
+ return metas.filter((meta) => {
482
+ const record = meta.park ?? readParkRecord(meta.id);
483
+ return record !== undefined && isPendingPark(record);
484
+ });
485
+ }
486
+
301
487
  /**
302
488
  * How long a launch attempt that never produced a child is kept before a sweep
303
489
  * reclaims it. Launch preparation takes seconds; the grace only exists so a
package/session-store.ts CHANGED
@@ -53,6 +53,9 @@ const ARCHIVE_META_KEYS = [
53
53
  "rootRunId", "resumedFrom", "recipe", "sandbox", "taskRuntime", "callback",
54
54
  "batchId", "batchName", "model", "effort", "spawnPid", "spawnPidStartTime",
55
55
  "dismissedAt",
56
+ // A parked attempt's disposition and operation binding outlive the volatile
57
+ // run directory: the resume path and cleanup protection read this record.
58
+ "park", "operations",
56
59
  ] as const satisfies readonly (keyof RunMeta)[];
57
60
 
58
61
  interface ArchivedAttemptRecord {
@@ -7,6 +7,8 @@ const EXECUTION_POLICY = [
7
7
  "Serialize only for a concrete dependency, conflicting writes or ownership, resource or concurrency limit, documented rollout gate, or explicit availability requirement. Record the reason in the plan or explain it to the user. Do not invent a canary or host-by-host availability requirement.",
8
8
  "If concurrency raises an unresolved material operational trade-off (for example, draining all hosts could leave no available runners), ask the user once before the affected operations. Continue independent preparation meanwhile. Existing authorization, safety checks, workflow prerequisites, and human-approved rollout constraints remain binding; urgency does not waive them.",
9
9
  "Choose the execution mechanism after deciding what can run together: foreground tools for small, tightly coupled, or interactive work; subagents for bounded independent reasoning or implementation when the active delegation mode permits; background tasks for independent long-running commands or waits. Manual delegation forbids proactive subagents, not concurrent foreground tools or background commands. Use available batch or parallel tool interfaces where appropriate and inspect every launch receipt for failures or skipped work.",
10
+ "Established command-only jobs and external waits belong to background operations, including in coordinator mode. Use bg_task_spawn for a long command and bg_task_watch for a repeated check; use watch_delivery for supported merge delivery so a stateful domain watcher observes the queue. A subagent assignment must require reasoning or implementation beyond launching and waiting. Workers retain their assigned validation: use supervised background tools and wait_for_operations to park, then resume the same conversation to interpret and acknowledge the terminal result. A linked external wait must have a registered observer and an execution owner. Continue independent work while it runs; a task launch or a completed parked attempt is not completion of the assignment.",
11
+ "If a worker hands back a command, the coordinator launches it through background tools with the supplied cwd and inspects its terminal result before claiming verification. Workers may run focused implementation checks; moving a command to a worker does not make it a background task.",
10
12
  "A unit waiting or failing does not block other ready independent units unless the evidence shows a shared blocker. Preserve each unit's guards and rollback boundary. Before completing verification, the plan, or the goal, inspect and integrate every relevant terminal result or failure; launch is not completion.",
11
13
  ].join("\n");
12
14
 
@@ -0,0 +1,113 @@
1
+ // Generated from packages/operation-coordinator/index.ts. Do not edit directly.
2
+ /**
3
+ * Durable operation coordinator.
4
+ *
5
+ * A small, reusable library that records what a harness is waiting for and who
6
+ * owns the result. It provides no provider transport, no process launch, no tool
7
+ * execution and no model call: Background Tasks, Subagents and the parent
8
+ * harness share these records instead of duplicating a journal.
9
+ *
10
+ * The contracts here implement the accepted invariant in
11
+ * `docs/adr/0020-observed-waits-retain-an-owner.md` and the record shapes in
12
+ * `docs/plans/observed-waits-design.md`.
13
+ *
14
+ * ```ts
15
+ * import { openStore } from "operation-coordinator";
16
+ *
17
+ * const store = openStore({ path: join(agentDir, "operation-coordinator.sqlite") });
18
+ * store.registerOperation({ operationId, taskId, launchToken, owner, observer });
19
+ * // later, from the supervisor:
20
+ * store.recordTerminalOutcome({ operationId, eventId, outcome: "succeeded", owner, evidence });
21
+ * // the owner interprets the evidence it read, then consumes the wait:
22
+ * store.recordEvidenceRead({ waitId, generation, owner, operationId, terminalRevision: 1 });
23
+ * store.acknowledgeResult({ waitId, generation, owner, disposition: "continue", note, terminalRevisions });
24
+ * ```
25
+ *
26
+ * Rules the store enforces by itself:
27
+ *
28
+ * - an owner, task id and launch token are immutable once registered;
29
+ * - one durable operation per background task, and one pending wait generation
30
+ * per owner identity;
31
+ * - a parked worker reaches `waiting`/`ready` only with checkpoint and writer
32
+ * exit proof, and a dependency that settled earlier is never missed;
33
+ * - duplicate terminal events and replayed reconciliation produce one terminal
34
+ * revision and one delivery per wait generation;
35
+ * - resume attempt ids and launch tokens are persisted before spawn, and one
36
+ * generation has one active claim;
37
+ * - cancellation increments a fencing epoch and invalidates the pending claim;
38
+ * - an acknowledgement requires a recorded read of the exact evidence revision by
39
+ * the owner, and only then are evidence pins released;
40
+ * - no credential, token value or environment value is stored; obvious secret
41
+ * material in a note or reference is refused.
42
+ *
43
+ * `node:sqlite` (Node 24+) is required. There is no in-memory fallback: an
44
+ * unavailable or unreadable database disables the feature instead of pretending
45
+ * to be durable.
46
+ */
47
+ export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
48
+ export type {
49
+ AcknowledgeDisposition,
50
+ AcknowledgeResultInput,
51
+ AcknowledgeResultOutput,
52
+ CancelWaitInput,
53
+ CancelWaitResult,
54
+ ClaimOutboxInput,
55
+ ClaimResumeInput,
56
+ EvidenceKind,
57
+ EvidencePinRecord,
58
+ EvidenceReadRecord,
59
+ EvidenceRefInput,
60
+ HoldFailedResumeInput,
61
+ HoldFailedResumeResult,
62
+ ObserverHealth,
63
+ ObserverIdentity,
64
+ OperationEvidenceRecord,
65
+ OperationFilter,
66
+ OperationPhase,
67
+ OperationRecord,
68
+ OutboxDispatchClaim,
69
+ OutboxDispatchInput,
70
+ OutboxEventRecord,
71
+ OutboxFilter,
72
+ OutboxState,
73
+ OwnerIdentity,
74
+ OwnerKind,
75
+ PublishResumeAttemptInput,
76
+ PublishResumeAttemptResult,
77
+ RecordEvidencePinInput,
78
+ RecordEvidencePinResult,
79
+ RecordEvidenceReadInput,
80
+ RecordEvidenceReadResult,
81
+ RecordSupervisionInput,
82
+ RecordTerminalOutcomeInput,
83
+ RecordTerminalOutcomeResult,
84
+ RegisterOperationInput,
85
+ RegisterOperationResult,
86
+ RegisterWaitInput,
87
+ RegisterWaitResult,
88
+ ReleaseOutboxInput,
89
+ ReleaseResumeClaimInput,
90
+ ReleaseResumeClaimResult,
91
+ ResumeClaimFilter,
92
+ ResumeClaimRecord,
93
+ ResumeClaimResult,
94
+ ResumeClaimState,
95
+ ResumeLeaseIdentity,
96
+ StoreOptions,
97
+ SupervisionIdentity,
98
+ TerminalOutcome,
99
+ TransitionWaitPhaseInput,
100
+ TransitionWaitPhaseResult,
101
+ WaitAcknowledgement,
102
+ WaitDependencyInput,
103
+ WaitDependencyRecord,
104
+ WaitFilter,
105
+ WaitParkIntent,
106
+ WaitPhase,
107
+ WaitRecord,
108
+ WaitRef,
109
+ } from "./src/types.ts";
110
+ export { StoreError, isStoreError } from "./src/errors.ts";
111
+ export type { StoreErrorCode } from "./src/errors.ts";
112
+ export { openStore, ownerDiff } from "./src/store.ts";
113
+ export type { Store } from "./src/store.ts";
@@ -0,0 +1,75 @@
1
+ // Generated from packages/operation-coordinator/src/errors.ts. Do not edit directly.
2
+ /**
3
+ * Refusals from the durable operation coordinator.
4
+ *
5
+ * Every refusal is a typed `code` so a transport can turn it into a specific
6
+ * model-facing reason instead of a generic failure. A refusal never leaves a
7
+ * partial record: all writes run inside one immediate transaction.
8
+ */
9
+ export type StoreErrorCode =
10
+ /** The database was written by another schema version. Records are left untouched. */
11
+ | "schema-version"
12
+ /** This runtime has no `node:sqlite`, so durability cannot be promised. */
13
+ | "sqlite-unavailable"
14
+ /** Another process holds the write lock for longer than the configured budget. */
15
+ | "store-busy"
16
+ /** A stored row could not be parsed back into its record shape. */
17
+ | "store-corruption"
18
+ /** Caller input is malformed, out of bounds, or looks like credential material. */
19
+ | "validation"
20
+ /** The operation id is not registered in this store. */
21
+ | "unknown-operation"
22
+ /** An operation already exists with different immutable launch identity. */
23
+ | "operation-conflict"
24
+ /** The background task id belongs to a different owner. */
25
+ | "task-ownership"
26
+ /** The caller is not the recorded owner of the record it wants to change. */
27
+ | "foreign-owner"
28
+ /** A different terminal event is already recorded for this operation. */
29
+ | "terminal-conflict"
30
+ /** The owner already has a pending wait generation. */
31
+ | "pending-wait-generation"
32
+ /** The wait id / generation is not registered in this store. */
33
+ | "unknown-wait"
34
+ /** The requested wait phase transition is not allowed from the current phase. */
35
+ | "wait-phase"
36
+ /** The caller's view of the current phase is out of date (out-of-order call). */
37
+ | "stale-phase"
38
+ /** The caller addressed a generation that is not the current one. */
39
+ | "stale-generation"
40
+ /** The caller's cancellation epoch is out of date; the wait changed underneath. */
41
+ | "stale-cancel-epoch"
42
+ /** Not every dependency has a terminal outcome yet. */
43
+ | "dependencies-unsettled"
44
+ /** A parked wait tried to reach waiting/ready without checkpoint and writer proof. */
45
+ | "checkpoint-proof"
46
+ /** A published resume cannot be held without proven writer exit and a free lease. */
47
+ | "resume-proof"
48
+ /** Another resume claim is already active for this wait generation. */
49
+ | "concurrent-claim"
50
+ /** The resume claim is not in a state that allows the requested step. */
51
+ | "claim-state"
52
+ /** The attempt id is already published by another resume claim. */
53
+ | "attempt-conflict"
54
+ /** The owner must record reading the exact terminal evidence before acknowledging. */
55
+ | "evidence-read-required"
56
+ /** The acknowledged evidence revision is not the dependency's terminal revision. */
57
+ | "stale-evidence"
58
+ /** The outbox event is not in a state that allows the requested step. */
59
+ | "outbox-state"
60
+ /** The store has been closed. */
61
+ | "closed";
62
+
63
+ export class StoreError extends Error {
64
+ readonly code: StoreErrorCode;
65
+
66
+ constructor(code: StoreErrorCode, message: string) {
67
+ super(message);
68
+ this.name = "StoreError";
69
+ this.code = code;
70
+ }
71
+ }
72
+
73
+ export function isStoreError(error: unknown): error is StoreError {
74
+ return error instanceof StoreError;
75
+ }