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