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