@restatedev/agents 0.3.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 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  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 +232 -151
  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 +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  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 +322 -106
  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 +227 -171
  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 +121 -35
  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 +74 -4
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +144 -15
  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 +107 -15
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +266 -178
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +317 -232
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +384 -137
  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 +326 -181
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +167 -38
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -78
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +225 -19
  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 -146
  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 -194
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
@@ -0,0 +1,396 @@
1
+ // An agent whose `chat` runs a LangGraph graph of your own:
2
+ // `langgraph.agent({ name, graph })`, as the Python SDK's
3
+ // restate/agents/langgraph/_graph.py.
4
+ //
5
+ // The graph's state has LangGraph's `messages` (`MessagesAnnotation`), and
6
+ // each message to the agent is a run of the graph on the key's thread, with
7
+ // the message as a new `HumanMessage`:
8
+ //
9
+ // - The graph's checkpoints are in the key's database (`SqlCheckpointSaver`),
10
+ // stored before each step runs (`durability: 'sync'`), and the prebuilt
11
+ // nodes (nodes.ts) and the tools of `tools()` get the handler's context
12
+ // there (context.ts). LangGraph's run context is the graph's own (`context`),
13
+ // else the handler's. A retried attempt resumes the run it cut off. A run
14
+ // that finishes prunes the thread to the latest checkpoint of each
15
+ // namespace, and what LangGraph rebuilds its delta channels from.
16
+ // - Any error of the run fails the attempt, and Restate retries it: none is
17
+ // taken for a model provider's refusal, as the built-in agent's model's
18
+ // can be, since a graph's models, tools and nodes are all its own. A
19
+ // `TerminalError` ends the turn, and so do LangGraph's own errors that a
20
+ // retry would meet again (errors.ts). A run that an invalid update ended
21
+ // leaves writes that LangGraph cannot apply: the next message starts its
22
+ // run from the checkpoint before them, as a new run discards them.
23
+ // - After each step, the AI and tool messages the step added are copied into
24
+ // the agent's conversation, by their ids, so that the `messages` view (and
25
+ // `watch`) shows the run as it goes. They are the messages after the run's
26
+ // prompt; if the graph trimmed the prompt away, those whose ids the
27
+ // conversation does not have. With `durability: 'sync'`, LangGraph streams
28
+ // a step's state only once its checkpoint is stored, so the conversation
29
+ // never gets ahead of the checkpoints; a crash between a checkpoint and its
30
+ // copy is made up by the next step's state, as messages are copied by id.
31
+ // The conversation is a log: a message the graph removes or edits later
32
+ // stays as it was copied.
33
+ // - The answer is the text of the run's last AI message. A graph that writes
34
+ // a `structuredResponse` in the run (LangChain's `createAgent` with a
35
+ // `responseFormat`) answers with it instead, as JSON, which `output`
36
+ // validates; one left from an earlier run is not the answer.
37
+ // - LangGraph's `interrupt()` waits for a signal: each pending interrupt is
38
+ // a wait named `interrupt`, which the agent's `pending` view lists with the
39
+ // interrupt's value, and which `signal` resolves (by the wait's id, or as
40
+ // the oldest `interrupt`). The run then resumes with `new Command({ resume
41
+ // })`, the signal's value as `interrupt()`'s result. The turn waits without
42
+ // holding a process; a retried attempt joins the same waits. Static
43
+ // breakpoints (`interruptBefore`, `interruptAfter`) have nothing to wait
44
+ // for: a compiled graph with them is refused, and a run that stops at a
45
+ // subgraph's fails.
46
+ // - A stopped run is not resumed: the next message starts a run of its own,
47
+ // from the state the graph had stored. What closed the stopped (or
48
+ // refused, or failed) run in the conversation comes first in the new run's
49
+ // input: the results of its cut-off tool calls, and the note that ends it,
50
+ // so that the graph's model knows. So does that run's message, if the graph
51
+ // never stored it.
52
+ //
53
+ // The graph's state is its own: its models read the state, not the
54
+ // conversation, so the agent's `window`, `budget` and `summarize` do not
55
+ // reach them. Trimming the state is the graph's job (a node that returns a
56
+ // `RemoveMessage` for each message to drop, say).
57
+ import * as restate from '@restatedev/sessions';
58
+ import { AIMessage, type BaseMessage, HumanMessage, ToolMessage } from '@langchain/core/messages';
59
+ import { mapStoredMessagesToChatMessages } from '@langchain/core/messages';
60
+ import type { RunnableConfig } from '@langchain/core/runnables';
61
+ import { Command, InvalidUpdateError, type Pregel, type StateSnapshot, StateGraph } from '@langchain/langgraph';
62
+ import { fromTool, stepped, stopSignalOf } from '../common.ts';
63
+ import type { Conversation, Run, Turn } from '../conversation.ts';
64
+ import { signals, signalsOf } from '../signals.ts';
65
+ import { SqlCheckpointSaver } from './checkpointer.ts';
66
+ import { running } from './context.ts';
67
+ import { terminalOf } from './errors.ts';
68
+
69
+ /** A graph of your own: a `StateGraph` (not compiled), or a compiled one such as LangChain's `createAgent` makes. */
70
+ export type AnyGraph =
71
+ // oxlint-disable-next-line typescript/no-explicit-any -- any graph's state, update, nodes and context
72
+ | StateGraph<any, any, any, any, any, any, any, any, any, any>
73
+ // oxlint-disable-next-line typescript/no-explicit-any -- any compiled graph's
74
+ | Pregel<any, any, any, any, any, any, any, any, any, any, any>;
75
+
76
+ /** The graph's thread: there is one per key, as the key's database is its own. */
77
+ export const THREAD_ID = 'chat';
78
+ const THREAD = { configurable: { thread_id: THREAD_ID } };
79
+
80
+ /** Why a graph with static breakpoints is refused, and a run stopped at a subgraph's fails. */
81
+ export const BREAKPOINTS =
82
+ 'static breakpoints (interruptBefore, interruptAfter) stop a run with nothing to wait for, and leave its tool ' +
83
+ 'calls without results: pause the graph with interrupt() instead, which waits for a signal';
84
+
85
+ /**
86
+ * Throw a `TypeError` if `graph` has no `messages` in its state, or is
87
+ * compiled with static breakpoints. A subgraph's static breakpoints are found
88
+ * when one stops a run, which then fails: LangGraph has no public way to find
89
+ * every subgraph (a node may call one it makes).
90
+ */
91
+ export function check(graph: AnyGraph) {
92
+ if (!('messages' in (graph.channels as object))) {
93
+ throw new TypeError("the graph's state has no messages: build it on LangGraph's MessagesAnnotation");
94
+ }
95
+ if (!(graph instanceof StateGraph) && (graph.interruptBefore?.length || graph.interruptAfter?.length)) {
96
+ throw new TypeError(BREAKPOINTS);
97
+ }
98
+ }
99
+
100
+ /** A compiled graph, as the run uses it: untyped, as the graph is the user's. */
101
+ interface App {
102
+ checkpointer: SqlCheckpointSaver;
103
+ getState(config: RunnableConfig): Promise<StateSnapshot>;
104
+ stream(input: unknown, options: Record<string, unknown>): Promise<AsyncIterable<Record<string, unknown>>>;
105
+ }
106
+
107
+ /** `graph` compiled with its checkpoints in `saver`. */
108
+ function compiled(graph: AnyGraph, saver: SqlCheckpointSaver): App {
109
+ if (graph instanceof StateGraph) return graph.compile({ checkpointer: saver }) as unknown as App;
110
+ // A copy, as `withConfig` makes one: the graph is shared by every key's runs.
111
+ const Compiled = graph.constructor as new (fields: object) => App;
112
+ // oxlint-disable-next-line typescript/no-misused-spread -- the graph's fields, as its constructor takes them
113
+ return new Compiled({ ...graph, checkpointer: saver });
114
+ }
115
+
116
+ /** The key, in each checkpoint's metadata, of the prompt whose run made it: the run's input may be trimmed away. */
117
+ const PROMPT = 'restate_prompt';
118
+ /** The state field of a structured answer, as LangChain's `createAgent` writes it. */
119
+ const STRUCTURED = 'structuredResponse';
120
+ /** The key, in each checkpoint's metadata, of the version the structured answer's channel had as its run began. */
121
+ const STRUCTURED_BEFORE = 'restate_structured_version';
122
+ /** The prefixes of the ids of the messages that the conversation gave the graph, rather than the graph made. */
123
+ const CARRIED = ['prompt:', 'closed:'];
124
+
125
+ /** The ids of the graph's messages that the conversation has: those copied from it. */
126
+ const knownOf = (conversation: Conversation<BaseMessage>) =>
127
+ new Set(conversation.entries.flatMap((e) => (e.item.id === undefined ? [] : [e.item.id])));
128
+
129
+ /** The version of the graph's structured answer's channel, which changes each time it is written. */
130
+ async function structuredVersion(app: App): Promise<string> {
131
+ const stored = await app.checkpointer.getTuple(THREAD);
132
+ return String(stored?.checkpoint.channel_versions[STRUCTURED] ?? '');
133
+ }
134
+
135
+ /**
136
+ * The run's answer: the JSON of the structured answer it wrote, else its last
137
+ * AI message's text. A structured answer counts only if the run wrote it (its
138
+ * channel's version is not `before`): the state keeps an earlier run's. The
139
+ * text is read from the conversation, a log, as the graph may have trimmed
140
+ * its own history (the run's input and answer included).
141
+ */
142
+ async function answerOf(app: App, turn: Turn<BaseMessage>, state: Record<string, unknown>, before: string) {
143
+ const structured = state[STRUCTURED];
144
+ if (structured !== undefined && structured !== null && (await structuredVersion(app)) !== before) {
145
+ return JSON.stringify(structured);
146
+ }
147
+ const replies = turn.items.flatMap((e) => (AIMessage.isInstance(e.item) && e.item.id !== undefined ? [e.item] : []));
148
+ return replies.at(-1)?.text ?? '';
149
+ }
150
+
151
+ /**
152
+ * Copy the AI and tool messages of `messages` (the graph's state) that the
153
+ * conversation does not have yet: those after the run's prompt (whose id is
154
+ * `prompt`), as the state holds the earlier turns too; if the graph trimmed
155
+ * the prompt away, those whose ids are not `known`. `known` is the ids the
156
+ * conversation has, which this adds to; the messages the conversation gave
157
+ * the graph are not copied back. Then publish.
158
+ */
159
+ async function copied(
160
+ ctx: restate.SessionContext,
161
+ turn: Turn<BaseMessage>,
162
+ known: Set<string>,
163
+ messages: readonly BaseMessage[],
164
+ prompt: string,
165
+ ) {
166
+ const at = messages.findIndex((m) => m.id === prompt);
167
+ const fresh = messages
168
+ .slice(at + 1)
169
+ .filter(
170
+ (m) =>
171
+ (AIMessage.isInstance(m) || ToolMessage.isInstance(m)) &&
172
+ m.id !== undefined &&
173
+ !known.has(m.id) &&
174
+ !CARRIED.some((prefix) => m.id!.startsWith(prefix)),
175
+ );
176
+ for (const message of fresh) {
177
+ if (AIMessage.isInstance(message)) await turn.appendReply([message]);
178
+ else await turn.append(message);
179
+ known.add(message.id!);
180
+ }
181
+ if (fresh.length > 0) await stepped(ctx);
182
+ }
183
+
184
+ /** The id of a turn's prompt, as a `HumanMessage` in the graph: the conversation's id of the turn. */
185
+ const promptIdOf = (turn: Turn<BaseMessage>) => `prompt:${turn.id}`;
186
+
187
+ /** `message` with the id `id`. */
188
+ const withId = (message: BaseMessage, id: string): BaseMessage => {
189
+ const stored = message.toDict();
190
+ return mapStoredMessagesToChatMessages([{ ...stored, data: { ...stored.data, id } }])[0]!;
191
+ };
192
+
193
+ /**
194
+ * What the conversation has of the previous prompt's run that the graph does
195
+ * not: what closed the run, if it was stopped, refused or failed (the results
196
+ * of its cut-off tool calls and the note that ends it, which only the
197
+ * conversation has: copied messages have the graph's ids, these have none),
198
+ * and the previous prompt itself, if the graph never stored it (its run
199
+ * copied nothing). Each gets an id of its own, so that it is carried once.
200
+ */
201
+ function closing(
202
+ conversation: Conversation<BaseMessage>,
203
+ turn: Turn<BaseMessage>,
204
+ messages: readonly BaseMessage[],
205
+ ): BaseMessage[] {
206
+ const turns = conversation.turns;
207
+ const at = turns.indexOf(turn);
208
+ if (at <= 0) return [];
209
+ const previous = turns[at - 1]!;
210
+ const known = new Set(messages.map((m) => m.id));
211
+ const copiedAny = previous.items.some((e) => e.item.id !== undefined);
212
+ // Only a turn the conversation closed (stopped, refused, failed, ended) has messages the graph lacks.
213
+ const closed = previous.status !== undefined && previous.status !== 'answered';
214
+ const carried: BaseMessage[] = [];
215
+ for (const entry of previous.entries) {
216
+ const item = entry.item;
217
+ if (entry.prompt !== undefined) {
218
+ if (!copiedAny && !known.has(promptIdOf(previous))) {
219
+ carried.push(new HumanMessage({ content: item.text, id: promptIdOf(previous) }));
220
+ }
221
+ } else if (closed && !HumanMessage.isInstance(item) && item.id === undefined && !known.has(`closed:${entry.n}`)) {
222
+ carried.push(withId(item, `closed:${entry.n}`));
223
+ }
224
+ }
225
+ return carried;
226
+ }
227
+
228
+ /** The name of the signal that answers LangGraph's `interrupt()`. */
229
+ export const INTERRUPT = 'interrupt';
230
+
231
+ /**
232
+ * The pending interrupts of the run, each once: LangGraph keeps each on the
233
+ * task whose step raised it, a subgraph's included, and each graph above that
234
+ * task lists it again, under the same id.
235
+ */
236
+ function interruptsOf(snapshot: StateSnapshot) {
237
+ const pending = new Map<string, { id: string; value?: unknown }>();
238
+ for (const task of snapshot.tasks) {
239
+ for (const interrupted of task.interrupts ?? []) {
240
+ if (interrupted.id !== undefined && !pending.has(interrupted.id)) {
241
+ pending.set(interrupted.id, { id: interrupted.id, value: interrupted.value });
242
+ }
243
+ }
244
+ }
245
+ return [...pending.values()];
246
+ }
247
+
248
+ /**
249
+ * How many resume values the thread's pending writes hold: one more each
250
+ * time an `interrupt()` is answered, until its step ends. LangGraph gives an
251
+ * interrupt the id of its task's namespace, so a node's second `interrupt()`
252
+ * has its first's id: the count tells them apart.
253
+ */
254
+ async function resumesOf(ctx: restate.SessionContext, saver: SqlCheckpointSaver) {
255
+ const rows = await ctx.db.values(
256
+ "SELECT type, value FROM restate_langgraph_writes WHERE thread_id = ? AND channel = '__resume__'",
257
+ [THREAD_ID],
258
+ );
259
+ let count = 0;
260
+ for (const [type, value] of rows) {
261
+ const resumes: unknown = await saver.serde.loadsTyped(String(type), value as Uint8Array);
262
+ count += Array.isArray(resumes) ? resumes.length : 1;
263
+ }
264
+ return count;
265
+ }
266
+
267
+ /**
268
+ * Wait for a signal for each pending interrupt of `snapshot`, and return
269
+ * their values by interrupt id, or `undefined` if none is pending. Each
270
+ * wait's id is the turn's invocation id (the same in each attempt), the
271
+ * interrupt's id, and the count of resume values stored (see
272
+ * {@link resumesOf}): a retried attempt joins the same waits, and a turn that
273
+ * ends without them has them closed, as the companion closes the waits whose
274
+ * ids start with the turn's.
275
+ */
276
+ async function resumed(ctx: restate.SessionContext, saver: SqlCheckpointSaver, snapshot: StateSnapshot) {
277
+ const pending = interruptsOf(snapshot);
278
+ if (pending.length === 0) return undefined;
279
+ const resumes = await resumesOf(ctx, saver);
280
+ const values = await Promise.all(
281
+ pending.map(({ id, value }) => {
282
+ const waitId = `${ctx.request.id}:interrupt:${id}:${resumes}`;
283
+ // As JSON, which the companion stores: the state may hold class instances.
284
+ const input = value === undefined ? undefined : (JSON.parse(JSON.stringify(value)) as unknown);
285
+ return ctx
286
+ .rpc(signals, signalsOf(ctx), { idempotencyKey: waitId })
287
+ .wait({ id: waitId, name: INTERRUPT, ...(input === undefined ? {} : { input }) });
288
+ }),
289
+ );
290
+ return Object.fromEntries(pending.map(({ id }, i) => [id, values[i]]));
291
+ }
292
+
293
+ /** Whether a run stopped with steps to go and no interrupt: at a static breakpoint. */
294
+ const atBreakpoint = (paused: StateSnapshot) =>
295
+ paused.next.length > 0 && !paused.tasks.some((task) => (task.interrupts ?? []).length > 0);
296
+
297
+ /**
298
+ * The state of the graph's thread: where it stopped, and why (its tasks'
299
+ * interrupts). If the writes of the last step's tasks do not fit the state
300
+ * (an invalid update), it is the state of the checkpoint itself, which
301
+ * LangGraph shows without them: a run with new input discards them.
302
+ */
303
+ async function storedState(app: App): Promise<StateSnapshot> {
304
+ try {
305
+ return await app.getState(THREAD);
306
+ } catch (error) {
307
+ if (!(error instanceof InvalidUpdateError)) throw error;
308
+ const latest = await app.checkpointer.getTuple(THREAD);
309
+ if (!latest) throw error;
310
+ return app.getState(latest.config);
311
+ }
312
+ }
313
+
314
+ /**
315
+ * The run of a prompt: the graph's, on the key's thread, from the prompt to
316
+ * its answer. `context` is the graph's run context, if not the handler's.
317
+ */
318
+ export const graphRun =
319
+ (ctx: restate.SessionContext, graph: AnyGraph, context?: unknown): Run<BaseMessage> =>
320
+ (conversation) =>
321
+ running(ctx, () => runGraph(ctx, graph, context ?? ctx, conversation));
322
+
323
+ async function runGraph(
324
+ ctx: restate.SessionContext,
325
+ graph: AnyGraph,
326
+ context: unknown,
327
+ conversation: Conversation<BaseMessage>,
328
+ ): Promise<string> {
329
+ const turn = conversation.turn;
330
+ // The run's input: the turn's prompt, or the message that asked again within the turn, under an id of its own.
331
+ const step = turn.latestAsk();
332
+ const promptId = step === turn.prompt ? promptIdOf(turn) : `${promptIdOf(turn)}:again:${step.n}`;
333
+ const app = compiled(graph, new SqlCheckpointSaver(ctx.db));
334
+ const snapshot = await storedState(app);
335
+ let values = snapshot.values as Record<string, unknown>;
336
+ const messages = (values.messages ?? []) as BaseMessage[];
337
+ const known = knownOf(conversation);
338
+ const metadata = (snapshot.metadata ?? {}) as Record<string, unknown>;
339
+ const asked = metadata[PROMPT] === promptId;
340
+ const stamped = metadata[STRUCTURED_BEFORE];
341
+ const before = asked ? (typeof stamped === 'string' ? stamped : '') : await structuredVersion(app);
342
+ // Each checkpoint of the run names its prompt, so that a retried attempt finds the run it cut off, and the
343
+ // version its structured answer had before it.
344
+ const saver = new SqlCheckpointSaver(ctx.db, { metadata: { [PROMPT]: promptId, [STRUCTURED_BEFORE]: before } });
345
+ const run = compiled(graph, saver);
346
+ const options = {
347
+ ...THREAD,
348
+ context,
349
+ durability: 'sync',
350
+ streamMode: 'values',
351
+ signal: stopSignalOf(ctx),
352
+ };
353
+ if (asked && snapshot.next.length === 0) {
354
+ // The run had finished, but its answer was not stored: that is the answer, rather than run again.
355
+ await copied(ctx, turn, known, messages, promptId);
356
+ await saver.prune([THREAD_ID]);
357
+ return answerOf(run, turn, values, before);
358
+ }
359
+ // A run cut off by a crash is resumed: first by the signals its pending interrupts wait for, if any. A new
360
+ // message (or one after a stopped run) starts a run, after what closed the previous run.
361
+ let start: unknown;
362
+ if (asked) {
363
+ const resumes = await resumed(ctx, saver, await storedState(run));
364
+ start = resumes === undefined ? null : new Command({ resume: resumes });
365
+ } else {
366
+ const prompt = new HumanMessage({ content: step.item.text, id: promptId });
367
+ const closed = step === turn.prompt ? closing(conversation, turn, messages) : [];
368
+ start = { messages: [...closed, prompt] };
369
+ }
370
+ for (;;) {
371
+ try {
372
+ for await (const state of await run.stream(start, options)) {
373
+ values = state;
374
+ await copied(ctx, turn, known, (state.messages ?? []) as BaseMessage[], promptId);
375
+ }
376
+ } catch (error) {
377
+ // LangGraph's own error, which a retry would meet again: a run past its recursion limit, say.
378
+ const terminal = terminalOf(error);
379
+ if (terminal) throw terminal;
380
+ // No refusal, whatever its name: a graph's models, tools and nodes are all its own.
381
+ fromTool(ctx, error);
382
+ throw error;
383
+ }
384
+ // The run stops at its interrupts: it goes on with the signals that answer them.
385
+ const paused = await storedState(run);
386
+ const resumes = await resumed(ctx, saver, paused);
387
+ if (resumes === undefined) {
388
+ // At a subgraph's static breakpoint, which check() does not look for: fail, rather than answer half done.
389
+ if (atBreakpoint(paused)) throw new restate.TerminalError(BREAKPOINTS);
390
+ // Only the latest checkpoint of each namespace is read again; a paused or cut-off run keeps it too.
391
+ await saver.prune([THREAD_ID]);
392
+ return answerOf(run, turn, values, before);
393
+ }
394
+ start = new Command({ resume: resumes });
395
+ }
396
+ }