@codemem/opencode-plugin 0.47.5 → 0.48.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.
@@ -3,6 +3,12 @@ import {
3
3
  createRuntimeLocation,
4
4
  V2_ADAPTER_DIAGNOSTICS,
5
5
  } from "./host-contract.js";
6
+ import {
7
+ formatMemoryToolOutcome,
8
+ isMemoryToolId,
9
+ MEMORY_TOOL_NAMESPACE,
10
+ MEMORY_TOOL_NAMESPACE_DESCRIPTION,
11
+ } from "./memory-tools.js";
6
12
  import { createCodememRuntime } from "./runtime.js";
7
13
  import { registerV2NotificationBridge } from "./v2-notification-bridge.js";
8
14
 
@@ -381,6 +387,111 @@ export const createV2Tool = (name, definition, { isActive = () => true } = {}) =
381
387
  };
382
388
  };
383
389
 
390
+ let toolErrorClass;
391
+ // Tool.Error is how a V2 tool reports a failure the model sees and recovers
392
+ // from, like an MCP isError result. Loaded lazily so OpenCode 1 hosts, which
393
+ // import this module through the package entrypoint, never load the V2 SDK.
394
+ const createV2ToolError = async (message) => {
395
+ toolErrorClass ??= await import("@opencode/plugin/promise/tool").then(
396
+ (module) => module.Error,
397
+ () => Error,
398
+ );
399
+ return toolErrorClass === Error ? new Error(message) : new toolErrorClass({ message });
400
+ };
401
+
402
+ export const createV2MemoryTool = (contract, execute, { directory, isActive = () => true }) => ({
403
+ name: contract.name,
404
+ description: contract.description,
405
+ input: contract.input,
406
+ options: { namespace: MEMORY_TOOL_NAMESPACE, codemode: true },
407
+ execute: async (args, context) => {
408
+ if (!isActive()) throw new Error("Codemem tool is unavailable after adapter cleanup");
409
+ const outcome = await execute(contract.name, asRecord(args), {
410
+ directory,
411
+ sessionID: context?.sessionID,
412
+ callID: context?.id,
413
+ signal: context?.signal,
414
+ });
415
+ const { isError, text, note } = formatMemoryToolOutcome(outcome);
416
+ if (isError) throw await createV2ToolError(note ? `${text}\n${note}` : text);
417
+ const noteParts = note ? [{ type: "text", text: note }] : [];
418
+ return { content: [{ type: "text", text }, ...noteParts] };
419
+ },
420
+ });
421
+
422
+ const addV2MemoryTools = (editor, memoryTools, options) => {
423
+ if (!memoryTools) return;
424
+ editor.namespace({
425
+ name: MEMORY_TOOL_NAMESPACE,
426
+ description: MEMORY_TOOL_NAMESPACE_DESCRIPTION,
427
+ });
428
+ for (const contract of memoryTools.contracts) {
429
+ editor.add(createV2MemoryTool(contract, memoryTools.execute, options));
430
+ }
431
+ };
432
+
433
+ const isV2CodememMcpConfigured = async (context) => {
434
+ const response = await context.mcp.list();
435
+ if (!Array.isArray(response?.data)) throw new TypeError("MCP server list unavailable");
436
+ return response.data.some(
437
+ (server) => server?.name === MEMORY_TOOL_NAMESPACE && server?.status?.status !== "disabled",
438
+ );
439
+ };
440
+
441
+ /** True when the setup-time MCP list already shows a codemem server (usually empty in OpenCode 2). */
442
+ const resolveV2InitialDeferral = async (context, memoryTools) => {
443
+ const register = await memoryTools.shouldRegister({
444
+ isCodememMcpConfigured: typeof context.mcp?.list === "function"
445
+ ? () => isV2CodememMcpConfigured(context)
446
+ : null,
447
+ });
448
+ return !register;
449
+ };
450
+
451
+ // OpenCode 2 loads MCP config after plugin setup returns (observed: mcp.list()
452
+ // is [] during setup), so precedence is also read from the MCP config itself.
453
+ // A read-only mcp.transform sees the configured servers every time OpenCode
454
+ // rebuilds the MCP registry, before the server connects. Each pass recomputes
455
+ // precedence; when it changes either way, the tools reload so an added codemem
456
+ // server withdraws them and a removed or disabled one restores them.
457
+ const observeV2McpPrecedence = async (context, memoryTools, gate, isActive) => {
458
+ if (typeof context.mcp?.transform !== "function") return null;
459
+ const applyChange = async (deferToMcp) => {
460
+ if (deferToMcp) await memoryTools.announceMcpPreferred();
461
+ await context.tool.reload();
462
+ };
463
+ return context.mcp.transform((editor) => {
464
+ if (!isActive()) return;
465
+ const server = editor.get(MEMORY_TOOL_NAMESPACE);
466
+ const deferToMcp = Boolean(server) && server.disabled !== true;
467
+ if (deferToMcp === gate.deferToMcp) return;
468
+ gate.deferToMcp = deferToMcp;
469
+ // Reload outside the MCP transform pass.
470
+ setTimeout(() => void applyChange(deferToMcp).catch(() => {}), 0);
471
+ });
472
+ };
473
+
474
+ const registerV2Tools = async (context, runtime, isActive) => {
475
+ const memoryTools = runtime.memoryTools;
476
+ const gate = { deferToMcp: memoryTools ? await resolveV2InitialDeferral(context, memoryTools) : false };
477
+ const mcpObserver = memoryTools
478
+ ? await observeV2McpPrecedence(context, memoryTools, gate, isActive)
479
+ : null;
480
+ const tools = await context.tool.transform((editor) => {
481
+ if (!isActive()) return;
482
+ for (const [name, definition] of Object.entries(runtime.tools)) {
483
+ editor.add(createV2Tool(name, definition, { isActive }));
484
+ }
485
+ // The plugin instance's directory, not the runtime cwd (which prefers the
486
+ // worktree): stdio MCP ran in this directory, and sharing scopes match it.
487
+ addV2MemoryTools(editor, gate.deferToMcp ? null : memoryTools, {
488
+ directory: context.location.directory,
489
+ isActive,
490
+ });
491
+ });
492
+ return mcpObserver ? [tools, mcpObserver] : [tools];
493
+ };
494
+
384
495
  const defaultWaitForEventTask = (eventTask, timeoutMs) =>
385
496
  new Promise((resolve) => {
386
497
  let settled = false;
@@ -614,21 +725,34 @@ const cleanupAdapter = async ({
614
725
  if (firstError) throw firstError;
615
726
  };
616
727
 
617
- export const createOpenCodeV2Adapter = ({
618
- createRuntime = createCodememRuntime,
619
- eventTaskTimeoutMs = DEFAULT_EVENT_TASK_TIMEOUT_MS,
620
- waitForCaptureTask = defaultWaitForEventTask,
621
- waitForContextTask = defaultWaitForEventTask,
622
- waitForDiagnosticTask = defaultWaitForEventTask,
623
- waitForEventTask = defaultWaitForEventTask,
624
- waitForRegistrationTask = defaultWaitForEventTask,
625
- waitForRuntimeDisposalTask = defaultWaitForEventTask,
626
- } = {}) => async (context) => {
728
+ const ADAPTER_DEFAULTS = Object.freeze({
729
+ createRuntime: createCodememRuntime,
730
+ eventTaskTimeoutMs: DEFAULT_EVENT_TASK_TIMEOUT_MS,
731
+ waitForCaptureTask: defaultWaitForEventTask,
732
+ waitForContextTask: defaultWaitForEventTask,
733
+ waitForDiagnosticTask: defaultWaitForEventTask,
734
+ waitForEventTask: defaultWaitForEventTask,
735
+ waitForRegistrationTask: defaultWaitForEventTask,
736
+ waitForRuntimeDisposalTask: defaultWaitForEventTask,
737
+ });
738
+
739
+ // Explicit `undefined` keeps the default, as destructuring defaults would.
740
+ const resolveAdapterOptions = (overrides) => ({
741
+ ...ADAPTER_DEFAULTS,
742
+ ...Object.fromEntries(Object.entries(overrides).filter(([, value]) => value !== undefined)),
743
+ });
744
+
745
+ /** Create the runtime; release the notification bridge when activation stops here. */
746
+ const createAdapterRuntime = async (context, notificationBridge, options) => {
627
747
  const location = context.location;
628
- const notificationBridge = await registerV2NotificationBridge(context);
748
+ const releaseBridge = () => disposeNotificationRegistration(
749
+ notificationBridge.registration,
750
+ options.waitForRegistrationTask,
751
+ options.eventTaskTimeoutMs,
752
+ );
629
753
  let runtime;
630
754
  try {
631
- runtime = await createRuntime({
755
+ runtime = await options.createRuntime({
632
756
  location: createRuntimeLocation({
633
757
  project: { ...location.project, root: location.project.canonical },
634
758
  directory: location.directory,
@@ -637,126 +761,161 @@ export const createOpenCodeV2Adapter = ({
637
761
  host: createRuntimeHost({ log: async () => {}, notify: notificationBridge.notify }),
638
762
  });
639
763
  } catch (error) {
640
- await disposeNotificationRegistration(
641
- notificationBridge.registration,
642
- waitForRegistrationTask,
643
- eventTaskTimeoutMs,
644
- );
764
+ await releaseBridge();
645
765
  throw error;
646
766
  }
647
- if (!runtime) {
648
- await disposeNotificationRegistration(
649
- notificationBridge.registration,
650
- waitForRegistrationTask,
651
- eventTaskTimeoutMs,
652
- );
653
- return undefined;
654
- }
767
+ if (!runtime) await releaseBridge();
768
+ return runtime;
769
+ };
655
770
 
656
- const abortController = new AbortController();
657
- const registrations = notificationBridge.registration ? [notificationBridge.registration] : [];
658
- const translator = createV2EventTranslator();
659
- const scheduleCapture = createCaptureScheduler();
660
- const scheduleContext = createContextScheduler();
661
- let active = true;
662
- let eventTask;
663
- try {
664
- registrations.push(await context.session.hook("context", async (input) => {
665
- if (!active) return;
666
- try {
667
- await scheduleContext.schedule(contextScheduleKey(input), async () => {
668
- if (active) await transformV2Context(runtime, input, { isActive: () => active });
669
- });
670
- } catch {
671
- await reportDiagnosticWithinTimeout(
672
- runtime,
673
- V2_ADAPTER_DIAGNOSTICS.contextRecallFailed,
674
- waitForDiagnosticTask,
675
- eventTaskTimeoutMs,
676
- );
677
- }
678
- }));
679
- registrations.push(await context.tool.hook("execute.after", async (input) => {
680
- if (!active) return;
681
- const translated = translateV2ToolResult(input);
682
- await captureRuntimeTaskWithinTimeout({
683
- runtime,
684
- run: () => runtime.handleToolResult(translated.input, translated.output),
685
- scheduleCapture,
686
- diagnosticCode: V2_ADAPTER_DIAGNOSTICS.toolCaptureFailed,
687
- timeoutMs: eventTaskTimeoutMs,
688
- waitForCaptureTask,
689
- waitForDiagnosticTask,
771
+ const registerContextHook = (context, state, options) =>
772
+ context.session.hook("context", async (input) => {
773
+ if (!state.active) return;
774
+ try {
775
+ await state.scheduleContext.schedule(contextScheduleKey(input), async () => {
776
+ if (state.active) {
777
+ await transformV2Context(state.runtime, input, { isActive: () => state.active });
778
+ }
690
779
  });
691
- }));
692
- registrations.push(await context.tool.transform((editor) => {
693
- if (!active) return;
694
- for (const [name, definition] of Object.entries(runtime.tools)) {
695
- editor.add(createV2Tool(name, definition, { isActive: () => active }));
696
- }
697
- }));
698
- eventTask = consumeEvents(context, abortController.signal, runtime, translator, {
699
- eventTaskTimeoutMs,
700
- scheduleCapture,
701
- waitForCaptureTask,
702
- waitForDiagnosticTask,
703
- });
704
- } catch (error) {
705
- active = false;
706
- runtime.deactivate?.();
707
- abortController.abort();
708
- translator.clear();
709
- const registrationCleanup = await waitForRegistrationDisposal(
710
- registrations,
711
- waitForRegistrationTask,
712
- eventTaskTimeoutMs,
713
- );
714
- if (!registrationCleanup.completed) {
715
- await reportDiagnosticWithinTimeout(
716
- runtime,
717
- V2_ADAPTER_DIAGNOSTICS.registrationCleanupTimeout,
718
- waitForDiagnosticTask,
719
- eventTaskTimeoutMs,
720
- );
721
- }
722
- const runtimeCleanup = await waitForRuntimeDisposal(
723
- runtime,
724
- waitForRuntimeDisposalTask,
725
- eventTaskTimeoutMs,
726
- );
727
- if (!runtimeCleanup.completed) {
780
+ } catch {
728
781
  await reportDiagnosticWithinTimeout(
729
- runtime,
730
- V2_ADAPTER_DIAGNOSTICS.runtimeCleanupTimeout,
731
- waitForDiagnosticTask,
732
- eventTaskTimeoutMs,
782
+ state.runtime,
783
+ V2_ADAPTER_DIAGNOSTICS.contextRecallFailed,
784
+ options.waitForDiagnosticTask,
785
+ options.eventTaskTimeoutMs,
733
786
  );
734
787
  }
788
+ });
789
+
790
+ /**
791
+ * True for a native memory tool result, including a Code Mode `execute` call
792
+ * whose inner calls (result metadata `toolCalls`) include a memory tool. The
793
+ * whole script result is skipped: it carries the retrieved memories.
794
+ */
795
+ const isNativeMemoryToolResult = (input) => {
796
+ if (isMemoryToolId(input?.tool)) return true;
797
+ const calls = asRecord(asRecord(input?.result).metadata).toolCalls;
798
+ return Array.isArray(calls) && calls.some((call) => isMemoryToolId(call?.tool));
799
+ };
800
+
801
+ const registerCaptureHook = (context, state, options) =>
802
+ context.tool.hook("execute.after", async (input) => {
803
+ // Native memory tool output is retrieved memory; capturing it would distill it into new
804
+ // memories. With the flag off, MCP-provided codemem tools keep their existing capture path.
805
+ if (!state.active || (state.runtime.memoryTools && isNativeMemoryToolResult(input))) return;
806
+ const translated = translateV2ToolResult(input);
807
+ await captureRuntimeTaskWithinTimeout({
808
+ runtime: state.runtime,
809
+ run: () => state.runtime.handleToolResult(translated.input, translated.output),
810
+ scheduleCapture: state.scheduleCapture,
811
+ diagnosticCode: V2_ADAPTER_DIAGNOSTICS.toolCaptureFailed,
812
+ timeoutMs: options.eventTaskTimeoutMs,
813
+ waitForCaptureTask: options.waitForCaptureTask,
814
+ waitForDiagnosticTask: options.waitForDiagnosticTask,
815
+ });
816
+ });
817
+
818
+ const reportCleanupTimeout = async (runtime, cleanup, code, options) => {
819
+ if (cleanup.completed) return;
820
+ await reportDiagnosticWithinTimeout(
821
+ runtime,
822
+ code,
823
+ options.waitForDiagnosticTask,
824
+ options.eventTaskTimeoutMs,
825
+ );
826
+ };
827
+
828
+ /** Undo a partial activation after a registration failed. */
829
+ const rollBackActivation = async (state, options) => {
830
+ state.active = false;
831
+ state.runtime.deactivate?.();
832
+ state.abortController.abort();
833
+ state.translator.clear();
834
+ const registrationCleanup = await waitForRegistrationDisposal(
835
+ state.registrations,
836
+ options.waitForRegistrationTask,
837
+ options.eventTaskTimeoutMs,
838
+ );
839
+ await reportCleanupTimeout(
840
+ state.runtime,
841
+ registrationCleanup,
842
+ V2_ADAPTER_DIAGNOSTICS.registrationCleanupTimeout,
843
+ options,
844
+ );
845
+ const runtimeCleanup = await waitForRuntimeDisposal(
846
+ state.runtime,
847
+ options.waitForRuntimeDisposalTask,
848
+ options.eventTaskTimeoutMs,
849
+ );
850
+ await reportCleanupTimeout(
851
+ state.runtime,
852
+ runtimeCleanup,
853
+ V2_ADAPTER_DIAGNOSTICS.runtimeCleanupTimeout,
854
+ options,
855
+ );
856
+ };
857
+
858
+ const activateAdapter = async (context, runtime, registrations, options) => {
859
+ const state = {
860
+ active: true,
861
+ abortController: new AbortController(),
862
+ eventTask: undefined,
863
+ registrations,
864
+ runtime,
865
+ scheduleCapture: createCaptureScheduler(),
866
+ scheduleContext: createContextScheduler(),
867
+ translator: createV2EventTranslator(),
868
+ };
869
+ try {
870
+ registrations.push(await registerContextHook(context, state, options));
871
+ registrations.push(await registerCaptureHook(context, state, options));
872
+ registrations.push(...(await registerV2Tools(context, runtime, () => state.active)));
873
+ state.eventTask = consumeEvents(context, state.abortController.signal, runtime, state.translator, {
874
+ eventTaskTimeoutMs: options.eventTaskTimeoutMs,
875
+ scheduleCapture: state.scheduleCapture,
876
+ waitForCaptureTask: options.waitForCaptureTask,
877
+ waitForDiagnosticTask: options.waitForDiagnosticTask,
878
+ });
879
+ } catch (error) {
880
+ await rollBackActivation(state, options);
735
881
  // Preserve the setup error that explains why activation failed.
736
882
  throw error;
737
883
  }
884
+ return state;
885
+ };
738
886
 
887
+ const createAdapterCleanup = (state, options) => {
739
888
  let cleanupTask;
740
889
  return () => {
741
890
  if (!cleanupTask) {
742
- active = false;
891
+ state.active = false;
743
892
  cleanupTask = cleanupAdapter({
744
- abortController,
745
- contextTask: scheduleContext.waitForIdle(),
746
- eventTask,
747
- eventTaskTimeoutMs,
748
- registrations,
749
- runtime,
750
- translator,
751
- waitForDiagnosticTask,
752
- waitForContextTask,
753
- waitForEventTask,
754
- waitForRegistrationTask,
755
- waitForRuntimeDisposalTask,
893
+ abortController: state.abortController,
894
+ contextTask: state.scheduleContext.waitForIdle(),
895
+ eventTask: state.eventTask,
896
+ eventTaskTimeoutMs: options.eventTaskTimeoutMs,
897
+ registrations: state.registrations,
898
+ runtime: state.runtime,
899
+ translator: state.translator,
900
+ waitForDiagnosticTask: options.waitForDiagnosticTask,
901
+ waitForContextTask: options.waitForContextTask,
902
+ waitForEventTask: options.waitForEventTask,
903
+ waitForRegistrationTask: options.waitForRegistrationTask,
904
+ waitForRuntimeDisposalTask: options.waitForRuntimeDisposalTask,
756
905
  });
757
906
  }
758
907
  return cleanupTask;
759
908
  };
760
909
  };
761
910
 
911
+ export const createOpenCodeV2Adapter = (overrides = {}) => async (context) => {
912
+ const options = resolveAdapterOptions(overrides);
913
+ const notificationBridge = await registerV2NotificationBridge(context);
914
+ const runtime = await createAdapterRuntime(context, notificationBridge, options);
915
+ if (!runtime) return undefined;
916
+ const registrations = notificationBridge.registration ? [notificationBridge.registration] : [];
917
+ const state = await activateAdapter(context, runtime, registrations, options);
918
+ return createAdapterCleanup(state, options);
919
+ };
920
+
762
921
  export const setupOpenCodeV2 = createOpenCodeV2Adapter();
@@ -100,6 +100,33 @@ const warnSpoolPersistenceFailure = async (state, sessionID, reason) => {
100
100
 
101
101
  const SPOOL_STAGES = new Set(["directory", "existing_entry", "capacity", "temporary_write", "publish", "directory_sync"]);
102
102
  const SPOOL_ERRNOS = new Set(["EACCES", "EPERM", "ENOSPC", "EROFS", "ENOTDIR", "EEXIST", "EIO", "EINVAL", "EMFILE", "ENFILE"]);
103
+ const SPOOL_CONFLICT_BRANCHES = ["active_comparison", "rejected_comparison", "rejected_identity", "publish_comparison"];
104
+ const SPOOL_CONFLICT_REASONS = ["invalid_json", "invalid_shape", "field_mismatch", "identity_mismatch"];
105
+ const SPOOL_CONFLICT_FIELDS = [
106
+ "started_at", "host_generation", "capture_context", "session_stream_id", "session_id",
107
+ "stream_id", "opencode_session_id", "cwd", "project", "source", "event_type",
108
+ "payload", "payload.timestamp", "payload._adapter", "payload._adapter.ts", "payload._raw_spooled", "payload.args",
109
+ ];
110
+
111
+ const spoolConflictDiagnostic = (error) => {
112
+ try {
113
+ const diagnostic = error?.spoolConflict;
114
+ // Rebuild from literals at the logging boundary, including for foreign errors.
115
+ const branch = SPOOL_CONFLICT_BRANCHES.find((value) => value === diagnostic?.branch);
116
+ const reason = SPOOL_CONFLICT_REASONS.find((value) => value === diagnostic?.reason);
117
+ if (!branch || !reason) return "";
118
+ const fields = diagnostic.fields;
119
+ const changed = Array.isArray(fields)
120
+ ? SPOOL_CONFLICT_FIELDS.filter((field) => fields.includes(field))
121
+ : [];
122
+ let suffix = ` branch=${branch} reason=${reason}`;
123
+ if (changed.length) suffix += ` fields=${changed.join(",")}`;
124
+ if (diagnostic.other === true) suffix += " other=true";
125
+ return suffix;
126
+ } catch {
127
+ return "";
128
+ }
129
+ };
103
130
 
104
131
  const spoolFailureDiagnostic = (error) => {
105
132
  const stage = SPOOL_STAGES.has(error?.spoolStage) ? error.spoolStage : "unknown";
@@ -107,7 +134,8 @@ const spoolFailureDiagnostic = (error) => {
107
134
  if (error?.code === RAW_EVENT_SPOOL_CONFLICT_CODE) code = "conflict";
108
135
  else if (error?.code === RAW_EVENT_SPOOL_FULL_CODE) code = "full";
109
136
  else if (SPOOL_ERRNOS.has(error?.code)) code = error.code;
110
- return `raw_events.spool.failure stage=${stage} code=${code} category=persistence`;
137
+ return `raw_events.spool.failure stage=${stage} code=${code} category=persistence`
138
+ + spoolConflictDiagnostic(error);
111
139
  };
112
140
 
113
141
  const persistSafeSpoolDiagnostic = async (state, line) => {
@@ -0,0 +1,104 @@
1
+ export const DEFAULT_DRAIN_LIMIT: number;
2
+ export const DEFAULT_MAX_ENTRIES: number;
3
+ export const MAX_REJECTED_RAW_EVENT_INSPECTION_BYTES: number;
4
+ export const RAW_EVENT_SPOOL_CONFLICT_CODE: "raw_event_spool_conflict";
5
+ export const RAW_EVENT_SPOOL_FULL_CODE: "raw_event_spool_full";
6
+
7
+ export interface RejectedRawEventMetadata {
8
+ receipt: string;
9
+ bytes: number;
10
+ status: 400 | 413;
11
+ reason: "invalid_payload" | "payload_too_large";
12
+ }
13
+
14
+ export type RejectedRawEventInspection =
15
+ | (RejectedRawEventMetadata & { validation: "valid"; serialized: string })
16
+ | (RejectedRawEventMetadata & {
17
+ validation: "invalid" | "read_limit_exceeded" | "changed_during_read";
18
+ });
19
+
20
+ export class RawEventSpoolInspectionError extends Error {
21
+ code: string;
22
+ constructor(code: string, message: string);
23
+ }
24
+
25
+ export function resolveSpoolDirectory(homeDir?: string): string;
26
+ export function listRejectedRawEventSpoolEntries(options: {
27
+ homeDir?: string;
28
+ validation: "metadata";
29
+ }): Promise<(RejectedRawEventMetadata & { validation: "not_checked" })[]>;
30
+ export function listRejectedRawEventSpoolEntries(options?: {
31
+ homeDir?: string;
32
+ validation?: "payload";
33
+ }): Promise<RejectedRawEventMetadata[]>;
34
+ export function inspectRejectedRawEventSpoolEntry(options: {
35
+ receipt: string;
36
+ homeDir?: string;
37
+ maxBytes?: number;
38
+ }): Promise<RejectedRawEventInspection>;
39
+ export type RejectedRawEventAcknowledgement = {
40
+ acknowledged: true;
41
+ acknowledgement: "queued" | "ingested";
42
+ };
43
+ export type RejectedRawEventDeliveryResult =
44
+ | RejectedRawEventAcknowledgement
45
+ | { acknowledged: false }
46
+ | false;
47
+ export type RejectedRawEventRecoveryResult = {
48
+ lock: "not_acquired" | "released" | "release_failed";
49
+ } & (
50
+ | {
51
+ delivery: "not_attempted";
52
+ cleanup: "not_attempted";
53
+ reason:
54
+ | "invalid_receipt"
55
+ | "invalid_delivery"
56
+ | "receipt_not_found"
57
+ | "inspection_failed"
58
+ | "unsafe_entry"
59
+ | "invalid"
60
+ | "read_limit_exceeded"
61
+ | "changed_during_read"
62
+ | "lock_busy"
63
+ | "lock_repair_required"
64
+ | "lock_failed";
65
+ }
66
+ | {
67
+ delivery: "unacknowledged";
68
+ cleanup: "not_attempted";
69
+ reason: "delivery_failed" | "delivery_rejected" | "invalid_acknowledgement";
70
+ }
71
+ | {
72
+ delivery: "accepted";
73
+ acknowledgement: "queued" | "ingested";
74
+ cleanup: "changed" | "failed" | "removed" | "uncertain";
75
+ }
76
+ );
77
+ export function recoverRejectedRawEventSpoolEntry(options: {
78
+ receipt: string;
79
+ homeDir?: string;
80
+ /** Runs under the directory serializer. Must not await another mutation in the same spool. */
81
+ deliver: (entry: {
82
+ serialized: string;
83
+ }) => RejectedRawEventDeliveryResult | Promise<RejectedRawEventDeliveryResult>;
84
+ }): Promise<RejectedRawEventRecoveryResult>;
85
+ export function writeRawEventSpoolEntry(options: {
86
+ envelope: Record<string, unknown>;
87
+ serialized?: string;
88
+ homeDir?: string;
89
+ maxEntries?: number;
90
+ }): Promise<{ eventId: string; serialized: string }>;
91
+ export function retainRejectedRawEventSpoolEntry(options: {
92
+ eventId: string;
93
+ status: 400 | 413;
94
+ reason: "invalid_payload" | "payload_too_large";
95
+ homeDir?: string;
96
+ }): Promise<RejectedRawEventMetadata & { lock?: "release_failed" }>;
97
+ export function removeRawEventSpoolEntry(options: {
98
+ eventId: string;
99
+ homeDir?: string;
100
+ }): Promise<void>;
101
+ export function loadRawEventSpoolEntries(options?: { homeDir?: string; limit?: number }): Promise<{
102
+ entries: { eventId: string; envelope: Record<string, unknown>; serialized: string }[];
103
+ corruptCount: number;
104
+ }>;