@restatedev/agents 0.2.0 → 0.4.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 (136) hide show
  1. package/README.md +89 -49
  2. package/dist/calls.d.ts +29 -8
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +79 -18
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +238 -156
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +161 -71
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +277 -226
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +323 -107
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +234 -180
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +123 -40
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +75 -7
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +154 -27
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +110 -24
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +271 -183
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +354 -247
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +385 -138
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +337 -193
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +178 -48
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -79
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +235 -31
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -145
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -193
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
@@ -31,7 +31,7 @@ import {
31
31
  type SessionPersistenceCreateOptions,
32
32
  type SessionPersistenceSnapshot,
33
33
  } from '@deepseek-ai/dsh-session-persistence';
34
- import type { Database } from '@restatedev/sessions';
34
+ import type { Database, Transaction } from '@restatedev/sessions';
35
35
  import { Schema } from '@restatedev/sessions/internal';
36
36
 
37
37
  const SCHEMA = new Schema('restate-agents.deepseek', [
@@ -39,13 +39,6 @@ const SCHEMA = new Schema('restate-agents.deepseek', [
39
39
  'CREATE TABLE restate_deepseek_events (session TEXT NOT NULL, seq INTEGER NOT NULL, event TEXT NOT NULL, PRIMARY KEY (session, seq))',
40
40
  ]);
41
41
 
42
- /** The stored events of session `id`, in order: for reading the log without a harness. */
43
- export async function storedEvents(db: Database, id: SessionId): Promise<SessionEvent[]> {
44
- await SCHEMA.ensure(db);
45
- const rows = await db.values('SELECT event FROM restate_deepseek_events WHERE session = ? ORDER BY seq', [id]);
46
- return rows.map(([event]) => JSON.parse(String(event)) as SessionEvent);
47
- }
48
-
49
42
  /** A session as stored: its header, inherited prefix length and event count. */
50
43
  interface Stored {
51
44
  header: SessionHeader;
@@ -65,6 +58,14 @@ export class SqlSessionPersistence extends SessionPersistence {
65
58
  created = new Map<SessionId, Omit<Stored, 'count'>>();
66
59
  handles = new Set<SqlSessionHandle>();
67
60
  abandoned = false;
61
+ /**
62
+ * What each flush's events are copied into beside the log, in the flush's
63
+ * transaction: the conversation of turns (index.ts), so that the copy and
64
+ * the log commit together.
65
+ */
66
+ copy: ((tx: Transaction, events: readonly SessionEvent[]) => Promise<void>) | undefined;
67
+ /** What runs once each flush is stored, outside its transaction: to tell others what it stored, say. */
68
+ flushed: (() => Promise<void>) | undefined;
68
69
 
69
70
  /** `config.db`: the object's database (`ctx.db`). */
70
71
  constructor(ctx: Context, config: { db: Database }) {
@@ -268,11 +269,13 @@ class SqlSessionHandle implements SessionHandle {
268
269
  JSON.stringify(event),
269
270
  ]);
270
271
  }
272
+ if (this.#store.copy) await this.#store.copy(tx, batch);
271
273
  }),
272
274
  );
273
275
  if (created) this.#store.created.delete(this.id);
274
276
  this.#pending.splice(0, batch.length);
275
277
  this.#stored += batch.length;
278
+ if (this.#store.flushed) await this.#store.flushed();
276
279
  }
277
280
 
278
281
  async close(): Promise<void> {
package/src/index.ts CHANGED
@@ -1,6 +1,5 @@
1
1
  // @restatedev/agents: agent frameworks in Restate session objects. Each framework
2
- // is a subpath (@restatedev/agents/pi, /opencode, /langgraph, /claude,
3
- // /deepseek); this is what they share: session objects, tools for
2
+ // is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek); this is what they share: session objects, tools for
4
3
  // any of them, and the tools that are Restate itself.
5
4
 
6
5
  export {
@@ -11,12 +10,22 @@ export {
11
10
  type MessagesRequest,
12
11
  type Part,
13
12
  REFUSED,
14
- type Turn,
13
+ type Answering,
15
14
  UNANSWERED,
16
15
  type Configure,
17
16
  } from './common.ts';
18
17
  export { sessionObject, type Status, type Stopped } from './object.ts';
19
- export { companionOf, deliver, signals, type Companion, type Resolved, type Signal, type Waiting } from './signals.ts';
18
+ export {
19
+ companionOf,
20
+ deliver,
21
+ signals,
22
+ type Companion,
23
+ type Resolved,
24
+ type Signal,
25
+ type Steered,
26
+ type Steering,
27
+ type Waiting,
28
+ } from './signals.ts';
20
29
  export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall, type ToolContext } from './tools.ts';
21
30
  export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
22
31
 
@@ -1,10 +1,10 @@
1
1
  # LangGraph
2
2
 
3
3
  [LangGraph](https://langchain-ai.github.io/langgraphjs/) runs an agent as a
4
- graph of steps and stores a checkpoint after each one, so a run can resume
5
- where it stopped. Here the checkpoints are in the agent's SQL database
6
- ([SQL in Restate virtual objects](../../../sessions/README.md)), and the thread is
7
- the object's key.
4
+ graph of steps. The built-in agent here stores each step in the agent's
5
+ conversation of turns, in its SQL database
6
+ ([SQL in Restate virtual objects](../../../sessions/README.md)); a graph of
7
+ your own keeps its checkpoints there too, with `SqlCheckpointSaver`.
8
8
 
9
9
  ## Use
10
10
 
@@ -31,32 +31,112 @@ text, options)` answers a prompt in a handler of your own, once, however
31
31
  often the handler runs; each prompt of an invocation is a prompt of its own. The graph is the usual tool-calling
32
32
  loop: a model node, a tools node, and back to the model until it answers.
33
33
 
34
+ ## A graph of your own
35
+
36
+ Bring a graph built on LangGraph's `MessagesAnnotation` (or a compiled one,
37
+ such as LangChain's `createAgent` makes): `chat` then runs it, with each
38
+ message as a new `HumanMessage`, and answers with its last AI message
39
+ ([`graph.ts`](graph.ts)). It has its own model and tools, so it takes no
40
+ `model`, `system`, `tools` or `recursionLimit`.
41
+
42
+ ```ts
43
+ const desk = langgraph.agent({ name: 'desk', graph });
44
+ // LangGraph's run context, for a graph with a context schema of its own: by default the handler's context.
45
+ const desk = langgraph.agent({ name: 'desk', graph, context: { region: 'eu' } });
46
+ ```
47
+
48
+ - **Its checkpoints are in the key's database** (`SqlCheckpointSaver`, one
49
+ thread per key), each stored before its step runs (`durability: 'sync'`):
50
+ a retried attempt resumes the run it cut off, and a step stored is not run
51
+ again. Between turns the thread keeps its latest checkpoint (`prune`).
52
+ - **The `messages` view shows the run as it goes**: after each step, the AI
53
+ and tool messages it added are copied into the conversation, by their ids.
54
+ The conversation is a log: a message the graph removes or edits later
55
+ stays as it was copied.
56
+ - **`interrupt()` waits for a signal** named `interrupt`, which the agent's
57
+ `pending` view lists with the interrupt's value, and `signal` resolves; the
58
+ run resumes with the signal's value as `interrupt()`'s result. The turn
59
+ waits without holding a process. Static breakpoints (`interruptBefore`,
60
+ `interruptAfter`) have nothing to wait for: a graph with them is refused.
61
+ - **A step's side effects run again after a crash** (a payment, a plain
62
+ LangChain tool): a graph is durable a step at a time. A model request may
63
+ be made again; for the rest, use Restate's tools.
64
+ - **Any error fails the attempt**, which Restate retries; a
65
+ `restate.TerminalError` (and LangGraph's own errors that a retry would
66
+ meet again) ends the turn. A stopped, refused or failed run is not
67
+ resumed: the next message starts a run of its own, with what closed the
68
+ last one (its cut-off calls' results and the note that ends it) first.
69
+ - **The graph's state is its own**: its models read the state, not the
70
+ conversation, so `window`, `budget` and `summarize` do not reach them.
71
+ Trim it in the graph (a node that returns a `RemoveMessage` for each
72
+ message to drop, say).
73
+ - **`output`**: the graph's own prompts must ask for it. A graph that writes
74
+ a `structuredResponse` (LangChain's `createAgent` with a `responseFormat`)
75
+ answers with it, as JSON; else its last AI message is validated.
76
+
77
+ ### Restate's steps in a graph of your own
78
+
79
+ A graph is durable a step at a time: a crash runs the step it cut off
80
+ again, which is fine for a model request, but not for a payment. Make a
81
+ step's side effects Restate's, done once:
82
+
83
+ - **Prebuilt nodes** ([`nodes.ts`](nodes.ts)): `nodes.waitForSignal`,
84
+ `nodes.workflow`, `nodes.call`, `nodes.send` and `nodes.subagent` each
85
+ read their input from the state and write what they get back to the field
86
+ `output`. A node run again (a crash, a retried attempt) gets the same task
87
+ id from LangGraph, so it joins the call, the workflow or the wait it
88
+ started rather than start another.
89
+
90
+ ```ts
91
+ const graph = new StateGraph(State)
92
+ .addNode('approve', nodes.waitForSignal('approval', { input: (s) => s.refund, output: 'approved' }))
93
+ .addNode('ship', nodes.workflow(shipping, { input: (s) => s.order, output: 'receipt' }));
94
+ ```
95
+
96
+ - **Restate's tools** in a `ToolNode`, or LangChain's `createAgent`:
97
+ `langgraph.tools([...])` makes `tool()`s and Restate's tools (`call`,
98
+ `send`, `workflow`, `subagent`, `signal`) LangChain tools. Restate's make
99
+ their calls once per tool call, as the model's reply with the call's id is
100
+ checkpointed before the tools run; LangChain's tools are passed through.
101
+
102
+ Both take the handler's context from the graph's run: `langgraph.agent({
103
+ graph })` gives it, and a handler of your own passes it as the run context
104
+ (`invoke(input, { context: ctx, durability: 'sync' })`, with a
105
+ `SqlCheckpointSaver(ctx.db)`). A node refuses to run without it, a
106
+ checkpointer, or `durability: 'sync'`.
107
+
34
108
  ## Through crashes
35
109
 
36
- The checkpointer ([`checkpointer.ts`](checkpointer.ts), `SqlCheckpointSaver`)
37
- keeps checkpoints, channel values and pending writes in three tables; a step
38
- stores only the channels it changed. An agent's thread keeps its latest
39
- checkpoint only (`history: 'latest'`), as each step changes the message
40
- list: kept at every step, it would grow with the square of the
41
- conversation. `new SqlCheckpointSaver(db)` of your own graph keeps them all,
42
- for LangGraph's history. The handler is not replayed: a retried
43
- attempt runs it again from the start, and LangGraph carries on from the last
44
- step it stored.
45
-
46
- - **Each step is stored before the next starts** (`durability: 'sync'`). So
47
- the tool calls a model made are stored before any tool runs, and a crash
48
- during the tools resumes them with the same tool call ids, without asking
49
- the model again.
110
+ The built-in agent keeps no checkpoints: its conversation is the object's
111
+ conversation of turns ([docs/conversation.md](../../docs/conversation.md)),
112
+ whose items are LangChain's messages, and its graph starts from what the
113
+ model sees of it (the earlier turns as their prompt and answer, within
114
+ `budget`; the latest `window` turns whole). The handler is not replayed: a
115
+ retried attempt runs it again from the start, from what is stored.
116
+
117
+ - **The model node stores its reply before it returns, and the tools node
118
+ each result as it lands.** So a crash during the tools runs those without
119
+ a result again, with the same tool call ids, without asking the model
120
+ again; and a stored final reply is the answer.
50
121
  - **A tool is idempotent by its tool call id** (`callId` of `tool()`'s
51
122
  `run`), which it passes on, such as in an idempotency key.
52
123
  - **A tool's error fails the attempt**, and Restate retries it (the ToolNode
53
124
  would hand it to the model); a `restate.TerminalError` of a
54
125
  `@restatedev/agents` tool is its answer to the model, and so are arguments
55
126
  that do not fit a tool, and a call of a tool the agent does not have.
56
- - **A message is answered once per invocation**: the graph records each
57
- answer in its state, by invocation id, and a retried attempt returns it. A
58
- run that a crash interrupted (its prompt without an answer) is finished
59
- before the next message starts.
127
+ - **A turn takes at most `recursionLimit` steps** (default 10 000): past
128
+ it, it fails for good. So do LangGraph's other errors that a retry would
129
+ meet again: an invalid state update, and a run with no input
130
+ ([`errors.ts`](errors.ts)).
131
+ - **A message is answered once per invocation** (`answerOnce`). A turn that
132
+ a killed invocation left is closed (`ended`), never finished.
133
+
134
+ The checkpointer ([`checkpointer.ts`](checkpointer.ts), `SqlCheckpointSaver`),
135
+ for a graph of your own, keeps checkpoints, channel values and pending
136
+ writes in three tables; a step stores only the channels it changed. With
137
+ `history: 'latest'` a thread keeps its latest checkpoint only, and the
138
+ ancestors a `DeltaChannel` is rebuilt from; by default it keeps them all,
139
+ for LangGraph's history.
60
140
 
61
141
  ## Run
62
142
 
@@ -76,12 +156,22 @@ The tests run on a scripted model, [`test/fakes/langgraph.ts`](../../test/fakes/
76
156
  LangGraph's checkpointer conformance suite
77
157
  (`@langchain/langgraph-checkpoint-validation`, 718 tests); and
78
158
  [`langgraph-fork.test.ts`](../../test/storage/langgraph-fork.test.ts),
79
- a forked thread.
159
+ a forked thread; [`langgraph-latest.test.ts`](../../test/storage/langgraph-latest.test.ts),
160
+ `history: 'latest'` with a `DeltaChannel`, and graphs of more channels than
161
+ an `OR` of them can match.
162
+ - [`test/langgraph-graph.test.ts`](../../test/langgraph-graph.test.ts): a
163
+ graph of your own: its thread across turns, a run a crash cut off,
164
+ `interrupt()` as signals (a retried attempt joins the same wait), the
165
+ structured response, what closed a failed run, and the graphs refused;
166
+ [`langgraph-nodes.test.ts`](../../test/langgraph-nodes.test.ts), the
167
+ prebuilt nodes and `tools()`, through crashes;
168
+ [`storage/langgraph-prune.test.ts`](../../test/storage/langgraph-prune.test.ts),
169
+ the checkpointer's `prune` and `metadata`.
80
170
  - [`test/langgraph.test.ts`](../../test/langgraph.test.ts):
81
171
  each point above, with crashes that stop an attempt in a tool call, or
82
172
  at any of its state requests; the
83
- system prompt; arguments that do not fit a tool; and `messages`. With
84
- `durability: 'async'`, it fails.
173
+ system prompt; arguments that do not fit a tool; the recursion limit; and
174
+ `messages`.
85
175
  - [`test/langgraph.ts`](../../test/langgraph.ts): the
86
176
  bank agent, through crashes in [the crash test](../../../e2e/crash.ts)
87
177
  (`pnpm --filter e2e crash`): every message moves money exactly once.
@@ -22,7 +22,13 @@
22
22
  // thread's earlier checkpoints, their writes and the values only they had:
23
23
  // a thread then takes the space of its state once, not once per step (a
24
24
  // message list stored again at each step grows with the square of its
25
- // length).
25
+ // length). A graph with a `DeltaChannel` keeps the checkpoints LangGraph
26
+ // rebuilds that channel from too (`#kept`), which a `put` finds from those
27
+ // the one before kept, without reading them again.
28
+ //
29
+ // A checkpoint's channel versions are matched as rows, `(channel, version)
30
+ // IN (VALUES (?, ?), …)`, never as an `OR` of each pair: the database refuses
31
+ // an expression more than 100 deep, and a graph may have more channels.
26
32
  import { randomUUID } from 'node:crypto';
27
33
  import type { RunnableConfig } from '@langchain/core/runnables';
28
34
  import {
@@ -102,23 +108,72 @@ function matches(actual: unknown, expected: unknown): boolean {
102
108
  }
103
109
 
104
110
  /**
105
- * Drop what the thread `threadId` (namespace `ns`) keeps from before
106
- * `checkpoint`: its other checkpoints, their pending writes, and the channel
107
- * values at versions other than `checkpoint`'s.
111
+ * `versions`, pairs of a channel and its version, as SQL rows to match
112
+ * `(channel, version)` against, `(VALUES (?, ?), …)`, and their parameters.
113
+ */
114
+ function pairs(versions: [string, unknown][]): [string, string[]] {
115
+ return [
116
+ `(VALUES ${versions.map(() => '(?, ?)').join(', ')})`,
117
+ versions.flatMap(([channel, version]) => [channel, String(version)]),
118
+ ];
119
+ }
120
+
121
+ /** The tables of a thread's checkpoints. */
122
+ const TABLES = ['restate_langgraph_checkpoints', 'restate_langgraph_channel_values', 'restate_langgraph_writes'];
123
+
124
+ /**
125
+ * A checkpoint the latest of its thread needs (see `#kept`): its id, its
126
+ * parent's, its channels' versions, and the delta channels whose steps since
127
+ * their snapshots it counts (`counters_since_delta_snapshot`), of those it
128
+ * holds.
108
129
  */
109
- async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, checkpoint: Checkpoint) {
130
+ interface Needed {
131
+ id: string;
132
+ parent: string | null;
133
+ versions: ChannelVersions;
134
+ counted: Set<string>;
135
+ }
136
+
137
+ /** `checkpoint` (with `metadata`) as a checkpoint its thread's latest needs. */
138
+ function needed(
139
+ id: string,
140
+ parent: string | null,
141
+ checkpoint: Pick<Checkpoint, 'channel_versions'>,
142
+ metadata: unknown,
143
+ ) {
144
+ const versions = checkpoint.channel_versions ?? {};
145
+ const counters = (metadata as { counters_since_delta_snapshot?: object } | undefined)?.counters_since_delta_snapshot;
146
+ return { id, parent, versions, counted: new Set(Object.keys(counters ?? {}).filter((c) => c in versions)) };
147
+ }
148
+
149
+ /**
150
+ * Drop what the thread `threadId` (namespace `ns`) keeps besides `kept`, its
151
+ * latest checkpoint and those it needs: the other checkpoints, their pending
152
+ * writes, and the channel values at versions none of `kept` has.
153
+ */
154
+ async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, kept: Needed[]) {
110
155
  const thread = [threadId, ns];
156
+ const ids = kept.map((checkpoint) => checkpoint.id);
111
157
  for (const table of ['restate_langgraph_checkpoints', 'restate_langgraph_writes']) {
112
- await tx.execute(`DELETE FROM ${table} WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id <> ?`, [
113
- ...thread,
114
- checkpoint.id,
115
- ]);
158
+ await tx.execute(
159
+ `DELETE FROM ${table} WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id NOT IN (${ids.map(() => '?').join(', ')})`,
160
+ [...thread, ...ids],
161
+ );
162
+ }
163
+ const versions = new Map<string, [string, unknown]>();
164
+ for (const checkpoint of kept) {
165
+ for (const [channel, version] of Object.entries(checkpoint.versions)) {
166
+ versions.set(`${channel}\u0000${String(version)}`, [channel, version]);
167
+ }
116
168
  }
117
- const versions = Object.entries(checkpoint.channel_versions ?? {});
118
- const kept = versions.map(() => '(channel = ? AND version = ?)').join(' OR ') || '0';
169
+ if (versions.size === 0) {
170
+ await tx.execute('DELETE FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ?', thread);
171
+ return;
172
+ }
173
+ const [rows, params] = pairs([...versions.values()]);
119
174
  await tx.execute(
120
- `DELETE FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND NOT (${kept})`,
121
- [...thread, ...versions.flatMap(([channel, version]) => [channel, String(version)])],
175
+ `DELETE FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND (channel, version) NOT IN ${rows}`,
176
+ [...thread, ...params],
122
177
  );
123
178
  }
124
179
 
@@ -126,21 +181,34 @@ async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, che
126
181
  export class SqlCheckpointSaver extends BaseCheckpointSaver {
127
182
  #db: Database;
128
183
  #latest: boolean;
184
+ #metadata: Record<string, unknown>;
185
+ /**
186
+ * With `history: 'latest'`, the checkpoints the latest of each thread
187
+ * (`[thread, namespace]`) needs, from it back, as the last `put` stored
188
+ * them: a `put` of its child needs some of them, which it reads no more.
189
+ */
190
+ #needed = new Map<string, Needed[]>();
129
191
  #ready: Promise<void> | undefined;
130
192
  #tail: Promise<unknown> = Promise.resolve();
131
193
 
132
194
  /**
133
195
  * `db`: a database session (`ctx.db`). `history`: the checkpoints a thread
134
196
  * keeps, `all` (the default) or the `latest` only; `serde`: LangGraph's
135
- * serializer, by default its own.
197
+ * serializer, by default its own; `metadata`: added to each checkpoint's
198
+ * metadata (LangGraph's JavaScript runs do not store their config's).
136
199
  */
137
200
  constructor(
138
201
  db: Database,
139
- { history = 'all', serde }: { history?: 'all' | 'latest'; serde?: SerializerProtocol } = {},
202
+ {
203
+ history = 'all',
204
+ serde,
205
+ metadata = {},
206
+ }: { history?: 'all' | 'latest'; serde?: SerializerProtocol; metadata?: Record<string, unknown> } = {},
140
207
  ) {
141
208
  super(serde);
142
209
  this.#db = db;
143
210
  this.#latest = history === 'latest';
211
+ this.#metadata = metadata;
144
212
  }
145
213
 
146
214
  /**
@@ -167,11 +235,10 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
167
235
  const versions = Object.entries(checkpoint.channel_versions ?? {});
168
236
  const values: Record<string, unknown> = {};
169
237
  if (versions.length === 0) return values;
238
+ const [pairsOf, params] = pairs(versions);
170
239
  const rows = await this.#db.values(
171
- `SELECT channel, type, value FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND (${versions
172
- .map(() => '(channel = ? AND version = ?)')
173
- .join(' OR ')})`,
174
- [threadId, ns, ...versions.flatMap(([channel, version]) => [channel, String(version)])],
240
+ `SELECT channel, type, value FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND (channel, version) IN ${pairsOf}`,
241
+ [threadId, ns, ...params],
175
242
  );
176
243
  for (const [channel, type, value] of rows as [string, string, Uint8Array][]) {
177
244
  if (type !== EMPTY) values[channel] = await this.serde.loadsTyped(type, value);
@@ -228,6 +295,46 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
228
295
  versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
229
296
  }
230
297
 
298
+ /**
299
+ * The checkpoints of `threadId` (namespace `ns`) that its latest,
300
+ * `checkpoint`, needs, by id: itself, and the ancestors LangGraph reads to
301
+ * rebuild its delta channels (`getDeltaChannelHistory`), back to the
302
+ * snapshot of each. A checkpoint's metadata counts, for each delta channel,
303
+ * the steps since its snapshot (`counters_since_delta_snapshot`): a channel
304
+ * with no count there was snapshotted at that checkpoint, and one the
305
+ * checkpoint does not hold (`channel_versions`) was never written, so has
306
+ * nothing to rebuild.
307
+ */
308
+ async #kept(tx: DatabaseWriter, threadId: string, ns: string, latest: Needed) {
309
+ // Its parent's, as the last `put` kept them: what it needs is some of them, as its delta channels'
310
+ // snapshots are its parent's, or itself.
311
+ const cached = this.#needed.get(JSON.stringify([threadId, ns]));
312
+ const ancestors = cached?.[0]?.id === latest.parent ? cached : undefined;
313
+ const kept: Needed[] = [];
314
+ let waiting: Set<string> | undefined;
315
+ for (let next: Needed | undefined = latest, i = 0; next !== undefined;) {
316
+ kept.push(next);
317
+ const { counted } = next;
318
+ waiting = waiting === undefined ? counted : new Set([...waiting].filter((channel) => counted.has(channel)));
319
+ if (waiting.size === 0 || next.parent === null) break;
320
+ next = ancestors ? ancestors[i++] : await this.#read(tx, threadId, ns, next.parent);
321
+ }
322
+ return kept;
323
+ }
324
+
325
+ /** Checkpoint `id` of `threadId` (namespace `ns`), as a checkpoint its latest needs, if it is stored. */
326
+ async #read(tx: DatabaseWriter, threadId: string, ns: string, id: string): Promise<Needed | undefined> {
327
+ const rows = await tx.values(
328
+ 'SELECT parent_checkpoint_id, type, checkpoint, metadata FROM restate_langgraph_checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?',
329
+ [threadId, ns, id],
330
+ );
331
+ const row = rows[0] as [string | null, string, Uint8Array, Uint8Array] | undefined;
332
+ if (!row) return undefined;
333
+ const [parent, type, stored, metadata] = row;
334
+ const loaded: Checkpoint = await this.serde.loadsTyped(type, stored);
335
+ return needed(id, parent, loaded, await this.serde.loadsTyped(type, metadata));
336
+ }
337
+
231
338
  getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {
232
339
  return this.#serial(async () => {
233
340
  const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
@@ -289,7 +396,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
289
396
  if (!thread_id) throw new Error('Missing "thread_id" field in passed "config.configurable".');
290
397
  const { channel_values: values, ...rest } = copyCheckpoint(checkpoint);
291
398
  const [type, stored] = await this.serde.dumpsTyped(rest);
292
- const [metadataType, metadataValue] = await this.serde.dumpsTyped(metadata);
399
+ const [metadataType, metadataValue] = await this.serde.dumpsTyped({ ...metadata, ...this.#metadata });
293
400
  if (type !== metadataType) throw new Error('Failed to serialize checkpoint and metadata to the same type.');
294
401
  // The channels this step changed, at their new versions.
295
402
  const changed = await Promise.all(
@@ -298,6 +405,7 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
298
405
  return [channel, String(version), valueType, value];
299
406
  }),
300
407
  );
408
+ let kept: Needed[] | undefined;
301
409
  await this.#db.transaction(async (tx) => {
302
410
  for (const row of changed) {
303
411
  await tx.execute(
@@ -309,8 +417,13 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
309
417
  `INSERT OR REPLACE INTO restate_langgraph_checkpoints (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?)`,
310
418
  [thread_id, checkpoint_ns, checkpoint.id, parentId ?? null, type, stored, metadataValue],
311
419
  );
312
- if (this.#latest) await dropEarlier(tx, thread_id, checkpoint_ns, checkpoint);
420
+ if (!this.#latest) return;
421
+ const latest = needed(checkpoint.id, parentId ?? null, rest, metadata);
422
+ kept = await this.#kept(tx, thread_id, checkpoint_ns, latest);
423
+ await dropEarlier(tx, thread_id, checkpoint_ns, kept);
313
424
  });
425
+ // Once stored: a transaction rolled back keeps the ones before.
426
+ if (kept) this.#needed.set(JSON.stringify([thread_id, checkpoint_ns]), kept);
314
427
  return { configurable: { thread_id, checkpoint_ns, checkpoint_id: checkpoint.id } };
315
428
  });
316
429
  }
@@ -348,17 +461,44 @@ export class SqlCheckpointSaver extends BaseCheckpointSaver {
348
461
  });
349
462
  }
350
463
 
351
- deleteThread(threadId: string): Promise<void> {
464
+ /**
465
+ * Delete checkpoints of `threadIds`: all but the latest of each namespace
466
+ * (`keepLatest`, the default), or all (`delete`), as LangGraph's `prune`.
467
+ * With `keepLatest`, the writes and channel values that only the deleted
468
+ * checkpoints referenced go with them; the latest keeps its pending writes,
469
+ * so a paused run still resumes, and its ancestors back to the snapshot of
470
+ * each of its delta channels (see `#kept`). A namespace is the thread's own
471
+ * (`''`) or a subgraph run's, which keeps its latest checkpoint too.
472
+ */
473
+ prune(threadIds: string[], { strategy = 'keepLatest' }: { strategy?: 'keepLatest' | 'delete' } = {}): Promise<void> {
352
474
  return this.#serial(() =>
353
475
  this.#db.transaction(async (tx) => {
354
- for (const table of [
355
- 'restate_langgraph_checkpoints',
356
- 'restate_langgraph_channel_values',
357
- 'restate_langgraph_writes',
358
- ]) {
359
- await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
476
+ for (const threadId of threadIds) {
477
+ if (strategy === 'delete') {
478
+ for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
479
+ continue;
480
+ }
481
+ const latest = await tx.values(
482
+ 'SELECT c.checkpoint_ns, c.checkpoint_id FROM restate_langgraph_checkpoints c WHERE c.thread_id = ? AND c.checkpoint_id = ' +
483
+ '(SELECT max(l.checkpoint_id) FROM restate_langgraph_checkpoints l WHERE l.thread_id = c.thread_id AND l.checkpoint_ns = c.checkpoint_ns)',
484
+ [threadId],
485
+ );
486
+ for (const [ns, id] of latest) {
487
+ const checkpoint = await this.#read(tx, threadId, String(ns), String(id));
488
+ if (!checkpoint) continue;
489
+ this.#needed.delete(JSON.stringify([threadId, String(ns)]));
490
+ await dropEarlier(tx, threadId, String(ns), await this.#kept(tx, threadId, String(ns), checkpoint));
491
+ }
360
492
  }
361
493
  }),
362
494
  );
363
495
  }
496
+
497
+ deleteThread(threadId: string): Promise<void> {
498
+ return this.#serial(() =>
499
+ this.#db.transaction(async (tx) => {
500
+ for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
501
+ }),
502
+ );
503
+ }
364
504
  }
@@ -0,0 +1,27 @@
1
+ // The handler's context of a graph's run, for this package's prebuilt nodes
2
+ // and Restate tools: the Python SDK's restate/agents/langgraph/_context.py.
3
+ //
4
+ // `langgraph.agent({ graph })` sets it for each run, which leaves LangGraph's
5
+ // run context (`runtime.context`, `config.context`) to the graph: one with a
6
+ // context schema of its own gets its own. A graph that a handler of your own
7
+ // runs, with `invoke(input, { context: ctx })`, has the handler's context as
8
+ // its run context, which the nodes and tools fall back to.
9
+ import { AsyncLocalStorage } from 'node:async_hooks';
10
+ import type * as restate from '@restatedev/sessions';
11
+
12
+ const RUN = new AsyncLocalStorage<restate.SessionContext>();
13
+
14
+ /** Run `body`, a graph's run for the handler of `ctx`: its nodes and tools find it with {@link handlerContext}. */
15
+ export const running = <T>(ctx: restate.SessionContext, body: () => Promise<T>): Promise<T> => RUN.run(ctx, body);
16
+
17
+ /** Whether `value` is a handler's context (a session object's): it has a database and a request. */
18
+ const isContext = (value: unknown): value is restate.SessionContext =>
19
+ typeof value === 'object' && value !== null && 'db' in value && 'request' in value && 'key' in value;
20
+
21
+ /**
22
+ * The handler's context of the graph run in progress, given LangGraph's run
23
+ * context: the one {@link running} set, else the run context itself, for a
24
+ * graph invoked with `context: ctx`; `undefined` if there is neither.
25
+ */
26
+ export const handlerContext = (runContext: unknown): restate.SessionContext | undefined =>
27
+ RUN.getStore() ?? (isContext(runContext) ? runContext : undefined);
@@ -0,0 +1,26 @@
1
+ // LangGraph's own errors that a retry would meet again, which end a turn for
2
+ // good: the Python SDK's restate/agents/langgraph/_errors.py.
3
+ import * as restate from '@restatedev/sessions';
4
+ import { EmptyInputError, GraphRecursionError, InvalidUpdateError } from '@langchain/langgraph';
5
+
6
+ /**
7
+ * The terminal error that ends the turn whose graph run failed with `error`,
8
+ * if a retry cannot help. That is so for the errors that LangGraph's runtime
9
+ * throws itself, rather than a node, a tool or a model:
10
+ *
11
+ * - `GraphRecursionError`: the run took more steps than its `recursionLimit`
12
+ * without finishing (a model that keeps calling tools, say). A retry runs
13
+ * on with a fresh limit, and calls the model again, at each retry.
14
+ * - `InvalidUpdateError`: a step's update does not fit the state (two nodes
15
+ * writing a field that takes one value per step, say). A retry runs the
16
+ * step again, to the same update.
17
+ * - `EmptyInputError`: the run had no input.
18
+ */
19
+ export function terminalOf(error: unknown): restate.TerminalError | undefined {
20
+ let why: string;
21
+ if (error instanceof GraphRecursionError) why = 'the graph stopped at its recursion limit';
22
+ else if (error instanceof InvalidUpdateError) why = 'the graph made an invalid state update';
23
+ else if (error instanceof EmptyInputError) why = 'the graph got no input';
24
+ else return undefined;
25
+ return new restate.TerminalError(`${why}: ${error.message}`);
26
+ }