@vinhnt-sdk/durable-state 0.0.0-stage → 0.23.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.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +186 -2
  3. package/dist/attachment/attachment-ref.d.ts +99 -0
  4. package/dist/attachment/attachment-ref.d.ts.map +1 -0
  5. package/dist/attachment/attachment-ref.js +117 -0
  6. package/dist/attachment/attachment-ref.js.map +1 -0
  7. package/dist/errors.d.ts +121 -0
  8. package/dist/errors.d.ts.map +1 -0
  9. package/dist/errors.js +166 -0
  10. package/dist/errors.js.map +1 -0
  11. package/dist/index.d.ts +16 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +84 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/state/channel.d.ts +115 -0
  16. package/dist/state/channel.d.ts.map +1 -0
  17. package/dist/state/channel.js +65 -0
  18. package/dist/state/channel.js.map +1 -0
  19. package/dist/state/checkpoint.d.ts +141 -0
  20. package/dist/state/checkpoint.d.ts.map +1 -0
  21. package/dist/state/checkpoint.js +109 -0
  22. package/dist/state/checkpoint.js.map +1 -0
  23. package/dist/state/executor.d.ts +42 -0
  24. package/dist/state/executor.d.ts.map +1 -0
  25. package/dist/state/executor.js +254 -0
  26. package/dist/state/executor.js.map +1 -0
  27. package/dist/state/graph-state.d.ts +113 -0
  28. package/dist/state/graph-state.d.ts.map +1 -0
  29. package/dist/state/graph-state.js +121 -0
  30. package/dist/state/graph-state.js.map +1 -0
  31. package/dist/state/interrupt.d.ts +97 -0
  32. package/dist/state/interrupt.d.ts.map +1 -0
  33. package/dist/state/interrupt.js +70 -0
  34. package/dist/state/interrupt.js.map +1 -0
  35. package/dist/state/session-adapter.d.ts +76 -0
  36. package/dist/state/session-adapter.d.ts.map +1 -0
  37. package/dist/state/session-adapter.js +210 -0
  38. package/dist/state/session-adapter.js.map +1 -0
  39. package/package.json +46 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 vinhnt-develop
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
1
+ # @vinhnt-sdk/durable-state
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > Status: BETA
4
+ > Durable state management for agent orchestration — StateChannel, Reducer, Checkpointer, Interrupt/Resume, AttachmentRef.
5
+
6
+ This package brings **durable, checkpointable state** to vinhnt-sdk as a separate, optional package. It does **not** replace the existing `SessionRuntimeState`, `RunEventSnapshot`, or `SerializedRunState` — it runs alongside them as a channel-based state layer that can be checkpointed, time-traveled, and interrupted/resumed.
7
+
8
+ ## Why a separate package?
9
+
10
+ - `@vinhnt-sdk/workflow` is lightweight orchestration primitives (`parallel`, `sequential`, `conditional`) — not stateful, no checkpointing.
11
+ - A dedicated package keeps the immutable-delta + reducer-per-channel model cleanly separated from vinhnt's mutable `SessionRuntimeState`.
12
+ - The package is dependency-light (only `@vinhnt-sdk/schema`; `@vinhnt-sdk/session` is an optional peer dep), so consumers install it only when they need durable state.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ # npm
18
+ npm install @vinhnt-sdk/durable-state
19
+
20
+ # pnpm (monorepo)
21
+ pnpm add @vinhnt-sdk/durable-state
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```typescript
27
+ import {
28
+ StateGraphBuilder,
29
+ StateGraphExecutor,
30
+ createChannel,
31
+ appendReducer,
32
+ overwriteReducer,
33
+ createMemoryCheckpointer,
34
+ interrupt,
35
+ Command,
36
+ } from "@vinhnt-sdk/durable-state";
37
+ import type { MessageContentPart } from "@vinhnt-sdk/schema";
38
+
39
+ // 1. Define state schema (typed channels)
40
+ const builder = new StateGraphBuilder("my-graph", "My Graph");
41
+ builder.addChannel("messages", createChannel<MessageContentPart[]>("messages", {
42
+ reducer: appendReducer(),
43
+ default: [],
44
+ }));
45
+ builder.addChannel("step", createChannel<number>("step", {
46
+ reducer: overwriteReducer(),
47
+ default: 0,
48
+ }));
49
+ const graph = builder.build();
50
+
51
+ // 2. Create checkpointer (MemoryCheckpointer for dev; SQLite/Postgres for prod)
52
+ const checkpointer = createMemoryCheckpointer();
53
+
54
+ // 3. Create executor and register node implementations
55
+ const executor = new StateGraphExecutor(graph, checkpointer);
56
+ executor.addNode("process", async (state, config) => {
57
+ // ... node logic, returns PartialState or Command
58
+ return { messages: [...state.messages, { type: "text", text: "done" }] };
59
+ });
60
+
61
+ // 4. Run — threadId maps to vinhnt sessionId
62
+ const result = await executor.run("process", {
63
+ threadId: "session_123",
64
+ checkpointNs: "",
65
+ });
66
+
67
+ // 5. Resume from interrupt (if result.interrupt is set)
68
+ const resumed = await executor.resume(
69
+ { threadId: "session_123", checkpointNs: "" },
70
+ Command.resume("user approved"),
71
+ );
72
+ ```
73
+
74
+ ## Exports
75
+
76
+ ### StateChannel & Reducer
77
+
78
+ | Export | Description |
79
+ |--------|-------------|
80
+ | `StateChannel<T, D>` | Typed channel with name, reducer, default value |
81
+ | `Reducer<S, D>` | `(current, delta) => newValue` signature |
82
+ | `Overwrite<T>` | Marker to bypass reducer and set value directly |
83
+ | `createChannel(name, default)` | Last-write-wins channel |
84
+ | `createChannelWithReducer(name, reducer, default)` | Custom reducer channel |
85
+ | `overwriteReducer()`, `appendReducer()`, `mergeReducer()` | Built-in reducers |
86
+ | `channelName(name)` | Branded channel name |
87
+
88
+ ### StateGraph
89
+
90
+ | Export | Description |
91
+ |--------|-------------|
92
+ | `StateGraphBuilder` | Build typed state schema (channels + reducers) |
93
+ | `StateGraphDefinition` | Built, validated graph contract |
94
+ | `build()` | Validate and produce definition |
95
+ | `initialState(definition)` | Initialize all channels to defaults |
96
+ | `applyDelta(definition, current, delta)` | Apply partial state delta via reducers |
97
+
98
+ ### Checkpointer & Snapshot
99
+
100
+ | Export | Description |
101
+ |--------|-------------|
102
+ | `GraphConfig` | Thread id, checkpoint namespace, checkpoint id |
103
+ | `StateSnapshot` | values, next, config, metadata, createdAt, parentConfig, tasks |
104
+ | `Checkpointer` | put, putWrites, getTuple, list, (delete) |
105
+ | `MemoryCheckpointer` | In-memory implementation (dev only) |
106
+ | `createMemoryCheckpointer()` | Factory |
107
+ | `createSnapshot(config, values, opts)` | Snapshot factory |
108
+
109
+ ### Executor
110
+
111
+ | Export | Description |
112
+ |--------|-------------|
113
+ | `StateGraphExecutor` | Drive graph node by node, apply deltas, checkpoint |
114
+ | `StepResult` | snapshot, completed, output, interrupt |
115
+ | `GraphNode<S>` | Node function type: `(state, config) => PartialState \| Command` |
116
+
117
+ ### Interrupt & Command
118
+
119
+ | Export | Description |
120
+ |--------|-------------|
121
+ | `interrupt(value, opts)` | Pause graph, throw GraphInterrupt, wait for resume |
122
+ | `Command` | `resume(value)`, `update(state)`, `goto(node)`, `graph(PARENT)` |
123
+ | `Command.resume(value)` | Resume from interrupt |
124
+ | `Command.resumeWithUpdate(value, update)` | Resume + state update |
125
+ | `Command.resumeAndGoto(value, goto)` | Resume + jump to node |
126
+ | `Command.update(update)` | State update only |
127
+ | `Command.goto(node)` | Goto only |
128
+ | `Command.PARENT` | Navigate to parent graph from subgraph |
129
+ | `isCommand(value)` | Type guard |
130
+
131
+ ### Attachment / Binary Store
132
+
133
+ | Export | Description |
134
+ |--------|-------------|
135
+ | `AttachmentRef` | Lightweight ref to binary stored outside JSON |
136
+ | `BinaryAttachmentStore` | save, get, list, delete, exists |
137
+ | `InMemoryBinaryAttachmentStore` | In-memory implementation (dev only) |
138
+ | `createAttachmentRef(init)` | Factory |
139
+ | `createInMemoryBinaryAttachmentStore()` | Factory |
140
+
141
+ ### Errors
142
+
143
+ | Export | Description |
144
+ |--------|-------------|
145
+ | `DurableStateError` | Base error (code, domain, category, retryable, context) |
146
+ | `ChannelNotFoundError` | Channel not declared in graph |
147
+ | `CheckpointError` | Checkpoint storage failure |
148
+ | `GraphInterrupt` | Control-flow interrupt (not a failure) |
149
+ | `CommandError` | Invalid command state |
150
+ | `AttachmentRefError` | Attachment ref not resolvable |
151
+ | `isDurableStateError(value)` | Type guard |
152
+ | `hasDurableStateErrorCode(value, code)` | Structural code check |
153
+
154
+ ## Design notes
155
+
156
+ ### State model
157
+
158
+ Durable state uses **immutable deltas + per-channel reducers**. A node returns `PartialState` (updates for specific channels), and each channel's reducer merges the delta:
159
+
160
+ ```
161
+ newValue = reducer(currentValue, delta)
162
+ ```
163
+
164
+ Channels can use `Overwrite<T>` to bypass the reducer and replace the value entirely.
165
+
166
+ ### Checkpoint / Time-travel
167
+
168
+ `StateSnapshot` captures `values`, `next` (next nodes), `config` (thread/checkpoint ids), `metadata`, `createdAt`, `parentConfig`, and `tasks`. Listing snapshots for a thread lets you traverse checkpoints and replay from any point.
169
+
170
+ ### Interrupt / Resume
171
+
172
+ `interrupt()` pauses execution and saves a checkpoint. `Command({ resume: value })` resumes from the interrupt, passing `value` back to the interrupted node. This is the cleanest durable HITL primitive — the turn ends instead of holding a process promise.
173
+
174
+ ### Binary attachments
175
+
176
+ `AttachmentRef` points to external storage (filesystem, S3, etc.). The JSON checkpoint only stores the ref, avoiding base64 bloat. Use `BinaryAttachmentStore` to save/retrieve actual bytes.
177
+
178
+ ## Compatibility with vinhnt-sdk
179
+
180
+ - **Layer**: L1 (depends on `@vinhnt-sdk/schema`; `@vinhnt-sdk/session` is an optional peer dep).
181
+ - **No breaking changes** to existing packages.
182
+ - **`SerializedRunState`** remains the run-loop checkpoint; durable-state snapshots are an orthogonal channel-state checkpoint.
183
+ - **`threadId`** in `GraphConfig` maps to vinhnt `sessionId`.
184
+
185
+ ## License
186
+
187
+ MIT
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Kind of attachment — file or image.
3
+ */
4
+ export type AttachmentKind = "file" | "image";
5
+ /**
6
+ * A lightweight reference to a binary attachment stored outside JSON state.
7
+ *
8
+ * The attachment payload itself lives in an external store (filesystem, S3,
9
+ * object storage). The checkpoint/snapshot only stores this reference,
10
+ * avoiding base64 bloat in JSON snapshots while still allowing the attachment
11
+ * to be resolved and restored when needed.
12
+ *
13
+ * @example
14
+ * ```typescript
15
+ * const ref: AttachmentRef = {
16
+ * id: "att_abc123",
17
+ * sessionId: "session_456",
18
+ * path: "/.vinhnt/uploads/session_456/2026-10-25/image.png",
19
+ * name: "screenshot.png",
20
+ * size: 245760,
21
+ * mimeType: "image/png",
22
+ * kind: "image",
23
+ * createdAt: "2026-10-25T03:35:00Z",
24
+ * };
25
+ * ```
26
+ */
27
+ export interface AttachmentRef {
28
+ /** Globally unique attachment identifier. */
29
+ readonly id: string;
30
+ /** Session the attachment belongs to. */
31
+ readonly sessionId: string;
32
+ /** Storage path — filesystem path or object-store key. */
33
+ readonly path: string;
34
+ /** Original file name. */
35
+ readonly name: string;
36
+ /** File size in bytes. */
37
+ readonly size: number;
38
+ /** MIME type (optional — inferred if not provided). */
39
+ readonly mimeType?: string;
40
+ /** "file" or "image". */
41
+ readonly kind: AttachmentKind;
42
+ /** ISO timestamp when the attachment was stored. */
43
+ readonly createdAt: string;
44
+ }
45
+ /**
46
+ * Create an AttachmentRef.
47
+ */
48
+ export declare function createAttachmentRef(init: Omit<AttachmentRef, "id" | "createdAt"> & {
49
+ id?: string;
50
+ createdAt?: string;
51
+ }): AttachmentRef;
52
+ /**
53
+ * Abstract store for binary attachments — save, retrieve, list, delete.
54
+ *
55
+ * Implementations can use local filesystem (matching vinhnt-agent's
56
+ * `POST /agent/uploads`), S3, or any object store.
57
+ */
58
+ export interface BinaryAttachmentStore {
59
+ /** Store binary content and return an AttachmentRef. */
60
+ save(sessionId: string, name: string, content: Buffer | Uint8Array | ReadableStream<Uint8Array>, options?: {
61
+ mimeType?: string;
62
+ kind?: AttachmentKind;
63
+ }): Promise<AttachmentRef>;
64
+ /** Retrieve binary content by attachment id. */
65
+ get(attachmentId: string): Promise<{
66
+ ref: AttachmentRef;
67
+ content: ReadableStream<Uint8Array>;
68
+ }>;
69
+ /** List attachments for a session. */
70
+ list(sessionId: string): Promise<readonly AttachmentRef[]>;
71
+ /** Delete an attachment by id. */
72
+ delete(attachmentId: string): Promise<void>;
73
+ /** Check whether an attachment exists. */
74
+ exists(attachmentId: string): Promise<boolean>;
75
+ }
76
+ /**
77
+ * In-memory binary attachment store — for development and testing only.
78
+ * Not durable across process restarts.
79
+ */
80
+ export declare class InMemoryBinaryAttachmentStore implements BinaryAttachmentStore {
81
+ private readonly attachments;
82
+ private readonly contents;
83
+ save(sessionId: string, name: string, content: Buffer | Uint8Array | ReadableStream<Uint8Array>, options?: {
84
+ mimeType?: string;
85
+ kind?: AttachmentKind;
86
+ }): Promise<AttachmentRef>;
87
+ get(attachmentId: string): Promise<{
88
+ ref: AttachmentRef;
89
+ content: ReadableStream<Uint8Array>;
90
+ }>;
91
+ list(sessionId: string): Promise<readonly AttachmentRef[]>;
92
+ delete(attachmentId: string): Promise<void>;
93
+ exists(attachmentId: string): Promise<boolean>;
94
+ }
95
+ /**
96
+ * Create a default in-memory binary attachment store.
97
+ */
98
+ export declare function createInMemoryBinaryAttachmentStore(): InMemoryBinaryAttachmentStore;
99
+ //# sourceMappingURL=attachment-ref.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachment-ref.d.ts","sourceRoot":"","sources":["../../src/attachment/attachment-ref.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,OAAO,CAAC;AAE9C;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,WAAW,aAAa;IAC5B,6CAA6C;IAC7C,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,yCAAyC;IACzC,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,0DAA0D;IAC1D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0BAA0B;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,0BAA0B;IAC1B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,uDAAuD;IACvD,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC3B,yBAAyB;IACzB,QAAQ,CAAC,IAAI,EAAE,cAAc,CAAC;IAC9B,oDAAoD;IACpD,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,IAAI,GAAG,WAAW,CAAC,GAAG;IAAE,EAAE,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,GAClF,aAAa,CAWf;AAED;;;;;GAKG;AACH,MAAM,WAAW,qBAAqB;IACpC,wDAAwD;IACxD,IAAI,CACF,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,GAAG,UAAU,GAAG,cAAc,CAAC,UAAU,CAAC,EACzD,OAAO,C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,GAAG,OAAO,CAAC,IAAI,CAAC;IAW3C,MAAM,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;CAGrD;AAED;;GAEG;AACH,wBAAgB,mCAAmC,IAAI,6BAA6B,CAEnF"}
@@ -0,0 +1,117 @@
1
+ import { AttachmentRefError } from "../errors.js";
2
+ /**
3
+ * Create an AttachmentRef.
4
+ */
5
+ export function createAttachmentRef(init) {
6
+ return {
7
+ id: init.id ?? crypto.randomUUID(),
8
+ sessionId: init.sessionId,
9
+ path: init.path,
10
+ name: init.name,
11
+ size: init.size,
12
+ mimeType: init.mimeType,
13
+ kind: init.kind,
14
+ createdAt: init.createdAt ?? new Date().toISOString(),
15
+ };
16
+ }
17
+ /**
18
+ * In-memory binary attachment store — for development and testing only.
19
+ * Not durable across process restarts.
20
+ */
21
+ export class InMemoryBinaryAttachmentStore {
22
+ attachments = new Map();
23
+ contents = new Map();
24
+ async save(sessionId, name, content, options) {
25
+ const bytes = await toBytes(content);
26
+ const ref = createAttachmentRef({
27
+ sessionId,
28
+ name,
29
+ path: `memory://${sessionId}/${name}`,
30
+ size: bytes.length,
31
+ mimeType: options?.mimeType,
32
+ kind: options?.kind ?? "file",
33
+ });
34
+ this.attachments.set(ref.id, ref);
35
+ this.contents.set(ref.id, bytes);
36
+ return ref;
37
+ }
38
+ async get(attachmentId) {
39
+ const ref = this.attachments.get(attachmentId);
40
+ if (ref === undefined) {
41
+ throw new AttachmentRefError(attachmentId, `Attachment not found: ${attachmentId}`, {
42
+ requestId: undefined,
43
+ traceId: undefined,
44
+ });
45
+ }
46
+ const content = this.contents.get(attachmentId);
47
+ if (content === undefined) {
48
+ throw new AttachmentRefError(attachmentId, `Attachment content missing: ${attachmentId}`, {
49
+ requestId: undefined,
50
+ traceId: undefined,
51
+ });
52
+ }
53
+ return {
54
+ ref,
55
+ content: toReadableStream(content),
56
+ };
57
+ }
58
+ async list(sessionId) {
59
+ return [...this.attachments.values()].filter((r) => r.sessionId === sessionId);
60
+ }
61
+ async delete(attachmentId) {
62
+ if (!this.attachments.has(attachmentId)) {
63
+ throw new AttachmentRefError(attachmentId, `Attachment not found: ${attachmentId}`, {
64
+ requestId: undefined,
65
+ traceId: undefined,
66
+ });
67
+ }
68
+ this.attachments.delete(attachmentId);
69
+ this.contents.delete(attachmentId);
70
+ }
71
+ async exists(attachmentId) {
72
+ return this.attachments.has(attachmentId);
73
+ }
74
+ }
75
+ /**
76
+ * Create a default in-memory binary attachment store.
77
+ */
78
+ export function createInMemoryBinaryAttachmentStore() {
79
+ return new InMemoryBinaryAttachmentStore();
80
+ }
81
+ /**
82
+ * Convert any binary input to Uint8Array.
83
+ */
84
+ async function toBytes(content) {
85
+ if (content instanceof Uint8Array)
86
+ return content;
87
+ if (Buffer.isBuffer(content))
88
+ return new Uint8Array(content);
89
+ const chunks = [];
90
+ const reader = content.getReader();
91
+ while (true) {
92
+ const { done, value } = await reader.read();
93
+ if (done)
94
+ break;
95
+ chunks.push(value);
96
+ }
97
+ const total = chunks.reduce((sum, c) => sum + c.length, 0);
98
+ const result = new Uint8Array(total);
99
+ let offset = 0;
100
+ for (const chunk of chunks) {
101
+ result.set(chunk, offset);
102
+ offset += chunk.length;
103
+ }
104
+ return result;
105
+ }
106
+ /**
107
+ * Wrap a Uint8Array as a ReadableStream<Uint8Array>.
108
+ */
109
+ function toReadableStream(content) {
110
+ return new ReadableStream({
111
+ start(controller) {
112
+ controller.enqueue(content);
113
+ controller.close();
114
+ },
115
+ });
116
+ }
117
+ //# sourceMappingURL=attachment-ref.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachment-ref.js","sourceRoot":"","sources":["../../src/attachment/attachment-ref.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAgDlD;;GAEG;AACH,MAAM,UAAU,mBAAmB,CACjC,IAAmF;IAEnF,OAAO;QACL,EAAE,EAAE,IAAI,CAAC,EAAE,IAAI,MAAM,CAAC,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AC"}
@@ -0,0 +1,121 @@
1
+ import { SdkError } from "@vinhnt-sdk/schema";
2
+ /**
3
+ * Error domain for durable-state package.
4
+ * Local definition to avoid coupling to schema's closed ErrorDomain union.
5
+ */
6
+ export type DurableStateDomain = string;
7
+ /**
8
+ * Error category for durable-state package.
9
+ */
10
+ export type DurableStateCategory = "user" | "system" | "dependency" | "config";
11
+ /**
12
+ * Base error for all @vinhnt-sdk/durable-state errors.
13
+ *
14
+ * Extends {@link SdkError} with machine-readable code, retryable flag,
15
+ * correlation IDs (requestId, traceId), and structured context.
16
+ *
17
+ * @example
18
+ * ```typescript
19
+ * throw new DurableStateError(
20
+ * "CHANNEL_NOT_FOUND",
21
+ * `Channel "messages" not declared in graph "my-graph"`,
22
+ * { channel: "messages", graphId: "my-graph" }
23
+ * );
24
+ * if (error.code === "CHANNEL_NOT_FOUND") { ... }
25
+ * ```
26
+ */
27
+ export declare class DurableStateError extends SdkError {
28
+ /** Additional structured context attached to the error. */
29
+ readonly context?: Record<string, unknown>;
30
+ constructor(code: string, message: string, options?: {
31
+ retryable?: boolean;
32
+ cause?: unknown;
33
+ requestId?: string;
34
+ traceId?: string;
35
+ category?: string;
36
+ context?: Record<string, unknown>;
37
+ });
38
+ static isInstance(error: unknown): error is DurableStateError;
39
+ }
40
+ /**
41
+ * Thrown when a state channel is referenced but not declared in the graph.
42
+ */
43
+ export declare class ChannelNotFoundError extends DurableStateError {
44
+ readonly channel: string;
45
+ readonly graphId: string;
46
+ constructor(channel: string, graphId: string, ctx?: {
47
+ requestId?: string;
48
+ traceId?: string;
49
+ });
50
+ static isInstance(error: unknown): error is ChannelNotFoundError;
51
+ }
52
+ /**
53
+ * Thrown when a checkpoint operation fails (storage unavailable, corrupt data).
54
+ */
55
+ export declare class CheckpointError extends DurableStateError {
56
+ readonly checkpointId?: string;
57
+ readonly threadId?: string;
58
+ constructor(message: string, options?: {
59
+ checkpointId?: string;
60
+ threadId?: string;
61
+ cause?: unknown;
62
+ retryable?: boolean;
63
+ requestId?: string;
64
+ traceId?: string;
65
+ });
66
+ static isInstance(error: unknown): error is CheckpointError;
67
+ }
68
+ /**
69
+ * Thrown when an interrupt is triggered during graph execution.
70
+ *
71
+ * This is a control-flow exception, not a failure. The graph pauses at the
72
+ * interrupt point and can be resumed with `Command({ resume: value })`.
73
+ */
74
+ export declare class GraphInterrupt extends DurableStateError {
75
+ /** The value passed to interrupt(), available on resume. */
76
+ readonly interruptValue: unknown;
77
+ /** Stable interrupt id for multi-interrupt resume mapping. */
78
+ readonly interruptId: string;
79
+ /** Node that raised the interrupt. */
80
+ readonly nodeId: string;
81
+ constructor(interruptValue: unknown, options?: {
82
+ interruptId?: string;
83
+ nodeId?: string;
84
+ requestId?: string;
85
+ traceId?: string;
86
+ });
87
+ static isInstance(error: unknown): error is GraphInterrupt;
88
+ }
89
+ /**
90
+ * Thrown when a Command is issued but the graph is not in a resumable state.
91
+ */
92
+ export declare class CommandError extends DurableStateError {
93
+ readonly commandType: string;
94
+ constructor(message: string, commandType: string, options?: {
95
+ requestId?: string;
96
+ traceId?: string;
97
+ context?: Record<string, unknown>;
98
+ });
99
+ static isInstance(error: unknown): error is CommandError;
100
+ }
101
+ /**
102
+ * Thrown when an attachment reference cannot be resolved (missing file, corrupt ref).
103
+ */
104
+ export declare class AttachmentRefError extends DurableStateError {
105
+ readonly attachmentId: string;
106
+ constructor(attachmentId: string, message: string, options?: {
107
+ cause?: unknown;
108
+ requestId?: string;
109
+ traceId?: string;
110
+ });
111
+ static isInstance(error: unknown): error is AttachmentRefError;
112
+ }
113
+ /**
114
+ * Type-safe guard for DurableStateError across module boundaries.
115
+ */
116
+ export declare function isDurableStateError(value: unknown): value is DurableStateError;
117
+ /**
118
+ * Structural error-code check — safe across duplicated package installs.
119
+ */
120
+ export declare function hasDurableStateErrorCode(value: unknown, code: string): boolean;
121
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors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