@restatedev/agents 0.0.0 → 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +688 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +78 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +83 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +67 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
package/README.md CHANGED
@@ -1,4 +1,690 @@
1
1
  # @restatedev/agents
2
2
 
3
- A placeholder: the package is being released from
4
- https://github.com/restatedev/sdk-sessions. Install a later version.
3
+ Durable agents on Restate: an agent of one of five frameworks (pi, OpenCode,
4
+ LangGraph, Claude, the DeepSeek Harness) in a Restate virtual object, its
5
+ conversation in the object's own SQL database. A crash, a restart or a
6
+ person who takes a day to approve changes nothing: each message is answered
7
+ once, and each tool call is made once.
8
+
9
+ - [Start here](#start-here)
10
+ - [Choose a framework](#choose-a-framework)
11
+ - [Calling an agent](#calling-an-agent)
12
+ - [Tools](#tools)
13
+ - [Signals](#signals)
14
+ - [Models](#models)
15
+ - [Your own session object](#your-own-session-object)
16
+ - [Build your own](#build-your-own)
17
+ - [Words](#words)
18
+
19
+ ## Start here
20
+
21
+ A chat agent with a tool, the whole of
22
+ [`examples/basic/chat.ts`](../examples/basic/chat.ts):
23
+
24
+ ```ts
25
+ import { serve, tool } from '@restatedev/agents';
26
+ import * as pi from '@restatedev/agents/pi';
27
+ import { z } from 'zod';
28
+
29
+ const weather = tool({
30
+ name: 'get_weather',
31
+ description: 'The current weather in a city.',
32
+ input: z.object({ city: z.string() }),
33
+ run: ({ city }) => `Sunny and 21°C in ${city}`, // a stand-in for a real weather API
34
+ });
35
+
36
+ const assistant = pi.agent({ name: 'assistant', tools: [weather] });
37
+
38
+ await serve(assistant);
39
+ ```
40
+
41
+ Run it, from [`packages/examples/`](../examples/README.md), after
42
+ `pnpm install && pnpm build` at the repository's root
43
+ ([Build your own](#build-your-own)):
44
+
45
+ ```sh
46
+ OPENAI_API_KEY=… node basic/chat.ts # the agent, on port 9080
47
+ npx @restatedev/restate-server # Restate, in another terminal
48
+ npx @restatedev/restate deployments register http://localhost:9080 # tell Restate where the agent is
49
+ curl localhost:8080/assistant/alice/chat -d 'Hi, I am Alice. Is it warm in Lisbon?'
50
+ curl localhost:8080/assistant/alice/chat -d 'What is my name?'
51
+ curl localhost:8080/assistant/alice/messages # the conversation so far
52
+ ```
53
+
54
+ `assistant` is a virtual object: each key (`alice`, `bob`) is a
55
+ conversation of its own, with a database of its own, and answers one
56
+ message at a time. `serve` serves it on PORT (default 9080), with the
57
+ `signals` object every agent uses (its waits and steering); an endpoint of
58
+ your own (`restate.serve`, `restate.endpoint()`) binds `signals` too.
59
+ `RESTATE_SERVE_ONLY=triage,planner` serves only the services it names, so
60
+ that one program (or image) deploys in parts; `signals` too, in one of them
61
+ (`RESTATE_SERVE_ONLY=triage,planner,signals`): the agents reach it through
62
+ Restate, wherever it is.
63
+
64
+ ## Choose a framework
65
+
66
+ The same agent runs on each of them: `agent({ name, ...options })`, with
67
+ the handler `chat` (a message in, the answer out), and the views
68
+ `messages` (the conversation so far), `status` (what it is doing), `stop`
69
+ and `steer` (the message it answers), `clear` (forget it all), `sync`,
70
+ `notifications` and `watch` (to follow it), and `signal` and `pending`
71
+ ([Signals](#signals)).
72
+
73
+ | Import | Framework | Choose it when |
74
+ | --------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------------------------- |
75
+ | [`@restatedev/agents/pi`](src/pi/README.md) | pi-durable | You want the default: any provider, coding tools on request, and its Harness (compact, reset) |
76
+ | [`@restatedev/agents/opencode`](src/opencode/README.md) | OpenCode 2.0, embedded | You want a coding agent: OpenCode's own tools (read, edit, bash, grep...) in a directory |
77
+ | [`@restatedev/agents/langgraph`](src/langgraph/README.md) | LangGraph | You use LangChain: its tools, or a chat model of your own |
78
+ | [`@restatedev/agents/claude`](src/claude/README.md) | the Anthropic SDK's tool runner | You want Claude with nothing in between: the lightest, the API's own messages |
79
+ | [`@restatedev/agents/deepseek`](src/deepseek/README.md) | DeepSeek Harness | You want DeepSeek's harness: DeepSeek's models, or any pi-ai knows |
80
+
81
+ Each framework's packages are optional peer dependencies of
82
+ @restatedev/agents: a project installs @restatedev/agents, whose required peers
83
+ (@restatedev/sessions, which brings the Restate SDK, and zod) npm and pnpm
84
+ install with it, and the packages of the frameworks it imports, so that
85
+ `@restatedev/agents/pi` brings pi alone:
86
+
87
+ ```sh
88
+ npm install @restatedev/agents @earendil-works/pi-durable @earendil-works/pi-ai @earendil-works/chord # pi
89
+ npm install @restatedev/agents @anthropic-ai/sdk # Claude
90
+ npm install @restatedev/agents @langchain/core @langchain/langgraph @langchain/langgraph-checkpoint \
91
+ @langchain/openai # LangGraph, and the provider of its models: or @langchain/anthropic
92
+ npm install @restatedev/agents @opencode/core@2.0.32 @opencode/plugin@2.0.32 @opencode/sdk@2.0.32 \
93
+ @opencode/server@2.0.32 effect@4.0.1 # OpenCode, which pins its packages, and effect
94
+ npm install @restatedev/agents @earendil-works/pi-ai @deepseek-ai/cordis \
95
+ @deepseek-ai/{dsh-agent,dsh-agent-loop,dsh-llm,dsh-llm-deepseek-api-key,dsh-llm-pi-ai,dsh-session}@0.2.1-rc.2 \
96
+ @deepseek-ai/{dsh-session-checkpoint-policy,dsh-session-persistence,dsh-session-projection}@0.2.1-rc.2 \
97
+ @deepseek-ai/{dsh-system-prompt,dsh-tools}@0.2.1-rc.2 # DeepSeek
98
+ ```
99
+
100
+ OpenCode is pinned: @restatedev/agents stores its tables in the object's
101
+ database, as its version lays them out. A subpath whose packages are
102
+ missing fails as it is imported, naming the first it lacks. The packages
103
+ are not published yet:
104
+ [`pnpm --filter e2e packaging`](../e2e/packaging.ts) installs them from
105
+ their tarballs, with pi alone. In this repository the frameworks' packages
106
+ are @restatedev/agents' development dependencies, so every example runs as it is.
107
+
108
+ Every framework takes `model`, `system`, `tools` and `output` (a
109
+ [structured answer](#structured-answers)); pi and OpenCode take a
110
+ `workspace` too, a directory for their coding tools. `system` is the whole
111
+ system prompt for Claude and LangGraph, and is added to the framework's own
112
+ (which tells the model about its tools) for pi, OpenCode and DeepSeek.
113
+
114
+ Every agent takes these too, beside its framework's options:
115
+
116
+ | Option | What |
117
+ | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
118
+ | `description` | What it is, for the UI, and for a parent's model: `subagent(agent)` tells it |
119
+ | `background` | It works unwatched (a subagent, say): its turn tells its `signals` at its end only, not at each step, so a follower sees each turn once it ended, and a steer waits for the end |
120
+ | `schema` | Tables of your own in its database ([Build your own](#build-your-own)) |
121
+
122
+ ## Calling an agent
123
+
124
+ Through Restate's ingress (port 8080), the request's body is the message,
125
+ as text or as a JSON string, and the response is the answer, as a JSON
126
+ string:
127
+
128
+ ```sh
129
+ curl localhost:8080/assistant/alice/chat -d 'Hi, I am Alice' # "Hello Alice! ..."
130
+ ```
131
+
132
+ A key answers one message at a time: a message sent while another is
133
+ answered waits for it. A message that fails for good answers with an error:
134
+ HTTP 424 if the model's provider refused it (a missing or wrong API key, an
135
+ unknown model), 500 otherwise. A refused message is over: the next message
136
+ is answered on its own, not after it.
137
+
138
+ **Send now, fetch the answer later.** A turn can take longer than an HTTP
139
+ request should wait (a tool that waits for a person, say). Add `/send` to
140
+ send without waiting: the response has the invocation's id, and
141
+ `/restate/invocation/<id>/attach` waits for its answer, as often as you
142
+ like:
143
+
144
+ ```sh
145
+ curl localhost:8080/assistant/alice/chat/send -d 'Plan my week' # {"invocationId": "inv_1f…", ...}
146
+ curl localhost:8080/restate/invocation/inv_1f…/attach # the answer, once there is one
147
+ ```
148
+
149
+ **Stop a turn.** `stop` stops the message being answered, such as for a
150
+ UI's Stop button: it cancels its invocation (the one `status` says), and
151
+ answers its id, or null if no message was answered. Messages to `chat`
152
+ queue: the agent answers one at a time, in the order they came, and a
153
+ stopped turn makes way for the next one waiting. So to interrupt with a new
154
+ message, send it after `stop`: it is answered once the stopped turn ended,
155
+ after any messages already waiting.
156
+
157
+ ```sh
158
+ curl localhost:8080/assistant/alice/stop # {"stopped": "inv_1f…"}
159
+ curl localhost:8080/assistant/alice/chat -d 'Actually, plan only Monday'
160
+ ```
161
+
162
+ `stop` is Restate's cancellation, as Restate's admin API (port 9070) cancels
163
+ any invocation by its id: `curl -X PATCH localhost:9070/invocations/inv_1f…/cancel`.
164
+
165
+ The turn ends cancelled whenever the cancellation comes (during a model
166
+ request too), and the agent does not go on: each framework stops its turn
167
+ and records the cut-off tool calls as cancelled, in its own way, and the
168
+ next message starts afresh. The calls its tools made (a wait for an
169
+ approval, a sub-agent's task, a workflow) are cancelled with it. `chat`
170
+ uses Restate's explicit cancellation for this (`explicitCancellation: true`,
171
+ with `cancelled(ctx)` and `cancelCalls(ctx)` of `@restatedev/sessions/internal`).
172
+
173
+ An attempt that ends before its turn does, while its process lives on
174
+ (Restate suspended it, gave up on it, or lost its connection), stops its
175
+ work too, a model's request included: it can store nothing more, and the
176
+ next attempt goes on with the turn, which is not cancelled.
177
+
178
+ **Steer a turn.** `steer` adds to the message being answered, such as for
179
+ a message typed while the agent works: the agent takes it at its next tool
180
+ call, as its framework steers a turn (pi-durable's, OpenCode's and the
181
+ DeepSeek Harness's steering), and goes on with it. `steer` answers with
182
+ the invocation that answers the message (to attach to), and whether it
183
+ steers one:
184
+
185
+ ```sh
186
+ curl localhost:8080/assistant/alice/steer -d 'Only Monday, please' # {"invocationId": "inv_1f…", "steered": true}
187
+ ```
188
+
189
+ A turn that ends before it takes a message (no tool call came) answers it
190
+ as a message of its own, once it ended; with no message answered, `steer`
191
+ is a message of its own (`"steered": false`, and its invocation). Claude's
192
+ and LangGraph's turns take no steering: their messages are answered next.
193
+ A stopped turn answers none of them.
194
+
195
+ A steered message waits in the agent's `signals` object (`steer`), and the
196
+ turn reads it there after each tool call (`steering`), and gives it to the
197
+ framework by its id, which the framework keeps: a retried attempt neither
198
+ loses nor repeats one.
199
+
200
+ **Forget a conversation.** `clear` starts a key over, such as for a UI's
201
+ New chat button: it stops the message being answered (as `stop`), then
202
+ forgets the conversation, the key's database, and what its
203
+ `signals` hold (waits, kept signals, steered messages). It answers as `stop`
204
+ does. The next message starts anew; its ids and cursors go on from where
205
+ the forgotten conversation got to, so a follower (`follow`, `sync`) reads on,
206
+ and drops the messages it kept from before `first` (which a page and each
207
+ change of `follow` give).
208
+
209
+ ```sh
210
+ curl localhost:8080/assistant/alice/clear # {"stopped": null}
211
+ ```
212
+
213
+ A message sent before `clear` is answered first, then forgotten too.
214
+
215
+ **Send again safely.** A caller that may send a message again (after a
216
+ timeout, say) gives it an idempotency key: the same key is the same
217
+ invocation, answered once, however often it is sent. Its answer is also at
218
+ the key:
219
+
220
+ ```sh
221
+ curl localhost:8080/assistant/alice/chat/send -H 'idempotency-key: msg-1' -d 'Plan my week'
222
+ curl localhost:8080/restate/invocation/assistant/alice/chat/msg-1/attach
223
+ ```
224
+
225
+ **The conversation** is `messages`, a page at a time, for a chat UI: what
226
+ was said, in order, with the tool calls the agent made and their outputs.
227
+ Without a body, it is the latest 50 messages:
228
+
229
+ ```sh
230
+ curl localhost:8080/assistant/alice/messages
231
+ ```
232
+
233
+ ```json
234
+ {
235
+ "messages": [
236
+ { "id": 0, "role": "user", "parts": [{ "type": "text", "text": "Weather in Paris?" }] },
237
+ {
238
+ "id": 1,
239
+ "role": "assistant",
240
+ "parts": [
241
+ { "type": "tool", "id": "toolu_01", "name": "weather", "input": { "city": "Paris" }, "output": "18°C, sunny" }
242
+ ]
243
+ },
244
+ { "id": 2, "role": "assistant", "parts": [{ "type": "text", "text": "18°C and sunny." }] }
245
+ ],
246
+ "more": false,
247
+ "cursor": 4
248
+ }
249
+ ```
250
+
251
+ The conversation as clients read it is a log in the object's database,
252
+ which each change the agent publishes goes into. A message's `id` never
253
+ changes; `cursor` is where the log is now. `limit` caps a page; `before` an
254
+ id gives older messages (scrolling back, while `more` says there are older
255
+ ones still); and `cursor` gives the messages new or changed since it, by
256
+ when they changed, with the next cursor: a message that grew (a tool call
257
+ with its output) comes again, with its `id`. A compacted or reset
258
+ conversation keeps what was said, and the summary or handoff after it (the
259
+ model's context is what changed):
260
+
261
+ ```sh
262
+ curl localhost:8080/assistant/alice/messages --json '{"limit": 20, "before": 40}'
263
+ curl localhost:8080/assistant/alice/messages --json '{"cursor": 4}'
264
+ ```
265
+
266
+ It answers at once, also while a message is answered: with the tool calls
267
+ made so far.
268
+
269
+ **What it is doing.** `status` says which message the agent answers, if
270
+ any (its invocation id, to attach to its answer, and since when), and what
271
+ its tools wait for ([Signals](#signals)). The message is in the agent's
272
+ `signals` object, which `chat` tells when it starts, and when it answers or
273
+ fails for good (Restate's UI shows it there):
274
+
275
+ ```sh
276
+ curl localhost:8080/support/alice/status
277
+ ```
278
+
279
+ ```json
280
+ {
281
+ "answering": { "invocationId": "inv_1f…", "since": "2026-10-17T15:00:00.000Z" },
282
+ "waiting": [
283
+ { "id": "inv_1f…:toolu_01", "name": "approval", "input": { "order": "103" }, "since": "2026-10-17T15:00:02.000Z" }
284
+ ]
285
+ }
286
+ ```
287
+
288
+ In a tool part, `error: true` says the output is the tool's error (`Error:
289
+ <message>`), for a UI to show it as one.
290
+
291
+ **Follow it.** Instead of polling `messages` and `status`, a UI waits for
292
+ the next change with `sync`: given the `revision` of its last sync, it
293
+ answers once something changed (a message or tool call stored, a wait, a
294
+ turn's start and end), or at its timeout (50 s by default, at most 60), with
295
+ the new revision, the `status`, and the messages since its `cursor`, in one
296
+ request. It waits in Restate, holding no process; sent again with the same
297
+ idempotency key, it joins the same wait. `follow()` of
298
+ `@restatedev/agents/client` (below) is a loop of syncs:
299
+
300
+ ```sh
301
+ curl localhost:8080/support/alice/sync --json '{}' # {"revision": 7, "cursor": 31, "status": ..., "messages": [...], "more": false}
302
+ curl localhost:8080/support/alice/sync --json '{"cursor": 31, "revision": 7}' # the same, once something changed
303
+ ```
304
+
305
+ `notifications` and `watch({ revision })` are the revision alone, and
306
+ the wait alone. The model's reply comes whole, with its message: there is no
307
+ token streaming.
308
+
309
+ **From code.** From a Restate handler, through the agent's definition:
310
+
311
+ ```ts
312
+ const answer = await ctx.rpc(assistant, 'alice').chat('Hi, I am Alice');
313
+ ```
314
+
315
+ From any other code, a web app included, with Restate's own client
316
+ ([`@restatedev/restate-sdk-clients`](https://docs.restate.dev/develop/ts/clients)).
317
+ `agent(name)` of `@restatedev/agents/client` is the agent's definition as the
318
+ client takes it: its name, typed with an agent's handlers. It imports
319
+ Restate's client and nothing of the agent's code or the SDK, so a web app
320
+ bundles it as it is:
321
+
322
+ ```ts
323
+ import * as clients from '@restatedev/restate-sdk-clients';
324
+ import { agent } from '@restatedev/agents/client';
325
+
326
+ const restate = clients.connect({ url: 'http://localhost:8080' });
327
+ const alice = restate.objectClient(agent('assistant'), 'alice');
328
+
329
+ const sent = await restate
330
+ .objectSendClient(agent('assistant'), 'alice')
331
+ .chat('Plan my week', clients.rpc.sendOpts({ idempotencyKey: 'msg-1' }));
332
+ const { answering, waiting } = await alice.status(); // while it works
333
+ await alice.steer('Only Monday, please'); // typed while it works
334
+ await alice.stop(); // the Stop button
335
+ const { messages } = await alice.messages({ limit: 20 }); // the tool calls so far
336
+ const answer = await restate.result(sent); // once it answered
337
+ ```
338
+
339
+ `follow(restate, agent(name), key)` gives the conversation as it changes:
340
+ what the agent is doing, and the messages new or changed since the last
341
+ time (a message may come again, changed, such as a tool call with its
342
+ output: keep them by `id`), until its `signal` aborts. A network failure
343
+ does not end it, and a wait it retries joins the one already parked in
344
+ Restate:
345
+
346
+ ```ts
347
+ import { agent, follow } from '@restatedev/agents/client';
348
+
349
+ const stop = new AbortController();
350
+ const messages = new Map<number, ChatMessage>();
351
+ for await (const change of follow(restate, agent('assistant'), 'alice', { signal: stop.signal })) {
352
+ for (const m of change.messages) messages.set(m.id, m);
353
+ render(change.status, [...messages.values()]);
354
+ }
355
+ ```
356
+
357
+ Each change has `waiting` too, what the agent waits for, and `asText(message)`
358
+ is a message to read, as a terminal shows it: its text, and its tool calls
359
+ with their outputs.
360
+
361
+ `@restatedev/agents/client` also has the types of what the handlers answer
362
+ (`Messages`, `Status`, `Waiting`...); `agent<H>(name)` types a session
363
+ object of your own with its handlers `H`.
364
+ [`examples/ui`](../examples/ui/app.ts) is a chat page on it: the
365
+ conversation as the agent works, its approvals, steering and Stop.
366
+
367
+ ## Tools
368
+
369
+ Any agent's `tools` take the tools of `@restatedev/agents`, which work the same
370
+ in every framework, and a framework's own tools:
371
+
372
+ ```ts
373
+ import { call, send, signal, subagent, tool, workflow } from '@restatedev/agents';
374
+ ```
375
+
376
+ | Tool | What the model gets |
377
+ | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
378
+ | `tool({ name, description, input, run })` | A tool of your own: `input` is a zod object; `run(input, { ctx, callId, idempotencyKey })` returns text or JSON, or a promise of it |
379
+ | `call(target, handler, { description, input?, key? })` | Calls a handler of a service, virtual object or workflow, and answers with its result. Of an object, the model chooses the key, unless `key` gives it |
380
+ | `send(target, handler, { description, input?, key?, delay? })` | Sends to a handler without waiting: a one-way call, after `delay` if given |
381
+ | `workflow(target, { description, input?, key? })` | Runs a workflow to the end, and answers with its result: a workflow of its own per tool call, unless `key` gives its id |
382
+ | `signal(name, { description, input? })` | Waits for a signal (a person's approval, another system's result) without holding a process, and answers with its value ([Signals](#signals)) |
383
+ | `subagent(agent, { description?, handler?, name? })` | Hands a named task to another agent (of any framework), keyed `<this key>.<task>`, and answers with its answer: the same name continues the task. Its description is the agent's, by default |
384
+
385
+ Handler names are checked against the target's handlers: a typo does not
386
+ compile. A `key` is a string, or a function of the invocation's context
387
+ that gives one.
388
+
389
+ **Errors.** A `restate.TerminalError` that a tool throws, or that a handler
390
+ it calls fails with (an unknown order, say), is the tool's answer to the
391
+ model, `Error: <message>`, and the agent goes on. So are arguments that do
392
+ not fit the tool's `input` (`run` never sees them), and a call of a tool the
393
+ agent does not have: the model's to fix. Any other error fails the attempt,
394
+ and Restate retries it: the tool call runs again.
395
+
396
+ **Once.** A crash runs an unfinished tool call again with the same call id.
397
+ A tool that must not run twice passes its `idempotencyKey` on (made of the
398
+ invocation's id and the call id), as Restate's tools do with each call they
399
+ make: run again, it is the same call. OpenCode and the DeepSeek Harness tell
400
+ the model that a cut-off tool call was interrupted instead, and the model
401
+ makes it again as a new tool call: Restate's tools then make the same call,
402
+ if the input is the same (so a wait for an approval outlasts a restart), and
403
+ so is a call that answered just before the crash, until the framework has
404
+ stored its result. They keep these calls in the object's database (the
405
+ table `restate_agent_calls`) for this. A tool of your own needs a way for the model to name the call it
406
+ retries (see their READMEs).
407
+
408
+ **Tools for each invocation** (each user's, say) come with the options of
409
+ `chat`: `pi.chat(async (ctx) => ({ tools: await toolsOf(ctx) }))`.
410
+
411
+ ## Signals
412
+
413
+ A `signal()` tool waits for a value from outside: a person's approval, say.
414
+ With an `input`, the model says what it waits for:
415
+
416
+ ```ts
417
+ signal('approval', {
418
+ description: 'Wait for a manager to approve a refund.',
419
+ input: z.object({ order: z.string(), amount: z.number() }),
420
+ });
421
+ ```
422
+
423
+ Every agent (every `sessionObject()`) has the views `pending`, which lists
424
+ its waits, and `signal`, which resolves one; both answer at once, while the agent
425
+ waits. Each wait has an id, the signal's name, the model's `input` and when
426
+ it started:
427
+
428
+ ```sh
429
+ curl localhost:8080/support/alice/pending
430
+ ```
431
+
432
+ ```json
433
+ [
434
+ {
435
+ "id": "inv_1f…:toolu_01",
436
+ "name": "approval",
437
+ "input": { "order": "103", "amount": 30 },
438
+ "since": "2026-10-17T15:00:00.000Z"
439
+ }
440
+ ]
441
+ ```
442
+
443
+ `signal` resolves the wait of an `id`, or else the oldest wait for a `name`,
444
+ and answers `{"resolved": <its id>}`, or `{"resolved": null}` if none
445
+ waited. A signal no one waits for is dropped, so a stale approval approves
446
+ nothing later; with `"keep": true` it is kept for the next wait for its
447
+ name:
448
+
449
+ ```sh
450
+ curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
451
+ curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved", "keep": true}'
452
+ ```
453
+
454
+ A wait ends with its agent's invocation: a cancelled one leaves `pending`.
455
+ The waits are kept by the `signals` object, keyed `<agent>:<key>`, which
456
+ `serve` serves beside the agents. See
457
+ [`examples/intermediate/support.ts`](../examples/intermediate/support.ts).
458
+
459
+ ## Structured answers
460
+
461
+ With `output`, a zod object, an agent answers with data rather than text:
462
+ its reply is its answer, as JSON of the schema (which its system prompt
463
+ asks for, with the schema), and `chat` answers with the value, checked
464
+ against the schema: the answer is the call's return value, as with any
465
+ handler. Every framework takes it.
466
+
467
+ ```ts
468
+ const Plan = z.object({ summary: z.string(), parts: z.array(z.string()) });
469
+ const planner = claude.agent({ name: 'planner', output: Plan });
470
+
471
+ const plan = await ctx.rpc(planner, 'ENG-1').chat('Plan the work on ENG-1'); // a Plan
472
+ ```
473
+
474
+ A reply that is not such JSON (a code fence around it is fine) is answered
475
+ with what is wrong with it, once, for the model to reply again; then the
476
+ invocation fails, with a terminal error. A retried attempt resumes the
477
+ conversation, and reads the same reply. In a handler of your own, `prompt(ctx, text, {
478
+ output })` answers with it too. As a subagent's, the parent's model gets it
479
+ as JSON.
480
+
481
+ ## Webhooks
482
+
483
+ `webhook()` takes another system's webhooks (Linear's, GitHub's...) into
484
+ agents: a service whose `webhook` handler checks each delivery's signature,
485
+ and delivers it to the agents of `route`, at once (the other system does not
486
+ wait for the agent):
487
+
488
+ ```ts
489
+ import { serve, webhook } from '@restatedev/agents';
490
+
491
+ const issues = webhook({
492
+ name: 'linear', // at /linear/webhook
493
+ auth: { header: 'linear-signature', secret: process.env.LINEAR_WEBHOOK_SECRET! },
494
+ idempotencyHeader: 'linear-delivery', // a delivery sent again reaches the same message
495
+ route: [triage],
496
+ key: ({ data }) => data.identifier, // its conversation; undefined drops it
497
+ });
498
+ await serve(issues, triage);
499
+ ```
500
+
501
+ | Option | What |
502
+ | ------------------- | -------------------------------------------------------------------------------------------- |
503
+ | `name` | The service: `/<name>/webhook` |
504
+ | `auth` | `{ header, secret }`: the HMAC-SHA256 of the body, in hex (or `sha256=…`); else 401 |
505
+ | `idempotencyHeader` | The header of the delivery's id, which a delivery sent again has too |
506
+ | `route` | The agents each delivery goes to |
507
+ | `key` | The agents' key, from the body (its JSON), or undefined to drop it; by default, the delivery |
508
+ | `message` | What of the body the agents read; by default, all of it |
509
+ | `description` | What it is, for the UI |
510
+
511
+ A delivery goes through the agent's `signals`, which knows what the agent is
512
+ doing: to the message it answers, if it answers one, which takes it at its
513
+ next step (as `steer`); else as a message of its own (as `chat`). A turn
514
+ that ends, or is stopped, before it takes it answers it after: a delivery is
515
+ never dropped, as a steer to a stopped turn is.
516
+
517
+ The same delivery is yours from any handler (a session object's, or a
518
+ service's or workflow's of the SDK), for events of other kinds (a queue, a
519
+ schedule): `deliver(ctx, agent, key, text, { idempotencyKey })`.
520
+ Every `sessionObject()` and `agent()` knows its companion,
521
+ `companionOf(agent, key)` (its `signals` object and key), so whoever holds an
522
+ agent can reach it.
523
+
524
+ The agent's message says where it comes from, with the body as JSON:
525
+
526
+ ```
527
+ <webhook name="linear" delivery="5d2…">
528
+ { "action": "create", "type": "Issue", "data": { … } }
529
+ </webhook>
530
+ ```
531
+
532
+ The handler's metadata says what it is, for the admin API and the UI:
533
+ `restate-agents.kind` (`webhook`), `.routes` (`triage`), `.auth`
534
+ (`hmac-sha256:linear-signature`) and `.idempotency-header`. See
535
+ [`examples/advanced/factory`](../examples/advanced/factory/README.md).
536
+
537
+ ## Models
538
+
539
+ Every agent's `model` is `provider/model-id`, or else the `MODEL`
540
+ environment variable, or else OpenAI's `openai/gpt-6-sol`, with
541
+ `OPENAI_API_KEY` (Anthropic's `anthropic/claude-sonnet-5-5`, with
542
+ `ANTHROPIC_API_KEY`, for Claude; DeepSeek's `deepseek/deepseek-flash`, with
543
+ `DEEPSEEK_API_KEY`, for the DeepSeek Harness):
544
+
545
+ ```ts
546
+ pi.agent({ name: 'assistant', model: 'anthropic/claude-sonnet-5-5' }); // with ANTHROPIC_API_KEY
547
+ ```
548
+
549
+ pi, OpenCode and the DeepSeek Harness take any provider they know (the
550
+ DeepSeek Harness, pi-ai's); LangGraph OpenAI's and Anthropic's models (and
551
+ any LangChain chat model, as `model`); Claude Anthropic's.
552
+
553
+ A wrong model fails at once: a model that is not `provider/model-id`, or
554
+ another provider's for an agent of one provider's models, when the agent is
555
+ defined; a missing or wrong API key, or a model the provider does not know,
556
+ with a terminal error that says what to check, rather than retries while
557
+ the caller waits.
558
+
559
+ ## Your own session object
560
+
561
+ `agent()` is a session object with `chat` and `messages`. For more, make
562
+ the session object yourself, with `sessionObject()`, and put your own
563
+ handlers beside the framework's. Here, an assistant whose tools keep facts
564
+ in its own table (a shorter
565
+ [`examples/basic/memory.ts`](../examples/basic/memory.ts)):
566
+
567
+ ```ts
568
+ import { sessionObject, serve, tool } from '@restatedev/agents';
569
+ import * as pi from '@restatedev/agents/pi';
570
+ import { z } from 'zod';
571
+
572
+ const remember = tool({
573
+ name: 'remember',
574
+ description: 'Remember a fact about the user.',
575
+ input: z.object({ fact: z.string() }),
576
+ run: async ({ fact }, { ctx }) => {
577
+ await ctx.db.execute('INSERT OR IGNORE INTO facts VALUES (?)', [fact]);
578
+ return 'remembered';
579
+ },
580
+ });
581
+
582
+ const assistant = sessionObject({
583
+ name: 'assistant',
584
+ schema: ['CREATE TABLE facts (fact TEXT PRIMARY KEY)'], // tables of your own, beside the agent's (optional)
585
+ handlers: {
586
+ chat: pi.chat({ tools: [remember] }),
587
+ },
588
+ views: {
589
+ messages: pi.messages(),
590
+ facts: (ctx) => ctx.db.query('SELECT fact FROM facts'),
591
+ },
592
+ });
593
+
594
+ await serve(assistant);
595
+ ```
596
+
597
+ Your tables share the database with the agent's, whose names all start with
598
+ `restate_` (`restate_pi_tasks`, `restate_claude_messages`,
599
+ `restate_agent_log`...): any other name is yours. OpenCode's tables are in a
600
+ database of their own, beside it, as OpenCode boots only on a database that
601
+ is empty or its own.
602
+
603
+ **Options for each invocation.** `chat` takes options, or a function of the
604
+ invocation's context that gives them: each user's model and persona from
605
+ the object's database, say ([`examples/intermediate/harness.ts`](../examples/intermediate/harness.ts)):
606
+
607
+ ```ts
608
+ const options = async (ctx: restate.SessionContext): Promise<pi.Options> => {
609
+ const { model, persona } = await settingsOf(ctx);
610
+ return { model, system: persona ?? 'You are a helpful assistant.', tools: [clock] };
611
+ };
612
+
613
+ chat: pi.chat(options),
614
+ ```
615
+
616
+ **A handler of your own.** `prompt(ctx, text, options)` answers a prompt in
617
+ any handler, once, however often the handler runs; each prompt of an
618
+ invocation is a prompt of its own. `chatHandler(answer)` makes a handler
619
+ that takes its message as `chat` does (text, or a JSON string):
620
+
621
+ ```ts
622
+ summarize: chatHandler(async (ctx, topic) => pi.prompt(ctx, `Summarize what we said about ${topic}`)),
623
+ ```
624
+
625
+ pi and OpenCode also have `withPi(ctx, options, work)` and
626
+ `withOpenCode(ctx, options, work)`, for more than a prompt: the Harness's own
627
+ API, such as compacting the conversation (see their READMEs).
628
+
629
+ **What `sessionObject()` sets up.** `ctx.db` in every handler; retries for weeks
630
+ (50 ms after a crash, then twice as long each time, up to 10 s apart), since
631
+ each attempt resumes from the database; and the SQL storage hidden from the
632
+ journal in Restate's UI. Its `options` (such as `retryPolicy`) and
633
+ `metadata` add to these. It is a `restate.sessionObject` of
634
+ [`@restatedev/sessions`](../sessions/README.md): `handlers` run one at a time per
635
+ key, and `views` beside them. Its own cannot be named `signal`, `pending`,
636
+ `status`, `stop`, `steer`, `notifications` or `watch`, views every agent's
637
+ session object has, nor `sync`, `clear` or `erase`, which an agent has (one with a
638
+ `messages` view). A view of yours reads the database too: `ctx.db` is the
639
+ database as committed, beside a message being answered.
640
+
641
+ ## Build your own
642
+
643
+ `@restatedev/agents` is not published: it runs on
644
+ [`@restatedev/sessions`](../sessions/README.md) (SQL in virtual objects, with its
645
+ Node.js addon), which this repository builds.
646
+ Build them once, at the repository's root, with `pnpm install && pnpm build`:
647
+ it needs Rust (for the addon), Node 24 or later, and pnpm (see
648
+ [Build and test](../../README.md#build-and-test)).
649
+
650
+ Then the quickest start is a file in [`packages/examples/`](../examples/README.md),
651
+ whose package has `@restatedev/agents`, the SDK and zod. Or a package of your own
652
+ in the pnpm workspace: a directory under `packages/`
653
+ ([`pnpm-workspace.yaml`](../../pnpm-workspace.yaml)), with
654
+
655
+ ```json
656
+ {
657
+ "type": "module",
658
+ "dependencies": { "@restatedev/restate-sdk": "1.18.2", "@restatedev/agents": "workspace:*", "zod": "4.6.5" }
659
+ }
660
+ ```
661
+
662
+ and `pnpm install`. Node runs
663
+ TypeScript as it is: `node agent.ts`.
664
+
665
+ ## Tests
666
+
667
+ [`test/`](test) has each framework's agent on a scripted model
668
+ ([`test/fakes/`](test/fakes/fakes.ts)), which needs no API key, through
669
+ crashes of the handler, and each framework's storage on a database in memory,
670
+ with the framework's own conformance suite where it has one
671
+ ([`test/storage/`](test/storage)). Each framework's README lists its own.
672
+
673
+ ```sh
674
+ pnpm --filter @restatedev/agents test # all of them, without a Restate server
675
+ pnpm --filter @restatedev/agents test langgraph # one framework's
676
+ ```
677
+
678
+ The same agents run against a real Restate server, through crashes, in
679
+ [the crash test](../e2e/README.md).
680
+
681
+ ## Words
682
+
683
+ - **Object, key.** A Restate virtual object: `assistant/alice` is the
684
+ object `assistant`'s key `alice`, with its own conversation and database,
685
+ answering one message at a time.
686
+ - **Invocation.** One call of a handler: a message to `chat`. Restate runs
687
+ it until it completes, through crashes and restarts.
688
+ - **Attempt.** One run of an invocation. A crash ends an attempt, and
689
+ Restate starts another, which resumes from the database: what an
690
+ invocation does "once" is done once however many attempts it takes.