@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
package/README.md CHANGED
@@ -1,817 +1,198 @@
1
1
  # @restatedev/agents
2
2
 
3
- Durable agents on Restate: an agent of one of six frameworks (pi,
4
- LangGraph, Claude, the DeepSeek Harness, OpenCode, agentlib) in a Restate virtual
5
- object, its conversation in the object's own SQL database (agentlib's, in
6
- its key/value state, journaled). A crash, a restart or a
7
- person who takes a day to approve changes nothing: each message is answered
8
- once, and each tool call is made once.
9
-
10
- - [Start here](#start-here)
11
- - [Choose a framework](#choose-a-framework)
12
- - [Calling an agent](#calling-an-agent)
13
- - [Tools](#tools)
14
- - [Signals](#signals)
15
- - [The companion](#the-companion)
16
- - [Models](#models)
17
- - [Your own session object](#your-own-session-object)
18
- - [Build your own](#build-your-own)
19
- - [Words](#words)
20
- - [The conversation of turns](docs/README.md): how a message is answered,
21
- retried, stopped or killed, how the conversation is stored, what the model
22
- sees, and what a client sees meanwhile
23
-
24
- ## Start here
25
-
26
- A chat agent with a tool, the whole of
27
- [`examples/basic/chat.ts`](../examples/basic/chat.ts):
28
-
29
- ```ts
30
- import { serve, tool } from '@restatedev/agents';
31
- import * as pi from '@restatedev/agents/pi';
32
- import { z } from 'zod';
33
-
34
- const weather = tool({
35
- name: 'get_weather',
36
- description: 'The current weather in a city.',
37
- input: z.object({ city: z.string() }),
38
- run: ({ city }) => `Sunny and 21°C in ${city}`, // a stand-in for a real weather API
39
- });
40
-
41
- const assistant = pi.agent({ name: 'assistant', tools: [weather] });
42
-
43
- await serve(assistant);
44
- ```
45
-
46
- Run it, from [`packages/examples/`](../examples/README.md), after
47
- `pnpm install && pnpm build` at the repository's root
48
- ([Build your own](#build-your-own)):
49
-
50
- ```sh
51
- OPENAI_API_KEY=… node basic/chat.ts # the agent, on port 9080
52
- npx @restatedev/restate-server # Restate, in another terminal
53
- npx @restatedev/restate deployments register http://localhost:9080 # tell Restate where the agent is
54
- curl localhost:8080/assistant/alice/chat -d 'Hi, I am Alice. Is it warm in Lisbon?'
55
- curl localhost:8080/assistant/alice/chat -d 'What is my name?'
56
- curl localhost:8080/assistant/alice/messages # the conversation so far
57
- ```
58
-
59
- `assistant` is a virtual object: each key (`alice`, `bob`) is a
60
- conversation of its own, with a database of its own, and answers one
61
- message at a time. `serve` (@restatedev/sessions' `restate.serve`) serves it
62
- on PORT (default 9080), with the agent's companion: a virtual object of
63
- the agent's own, named `<agent>.prebuilt.restate`
64
- (`assistant.prebuilt.restate`) and keyed as the agent (`alice`), which
65
- keeps its waits and what it is doing ([The companion](#the-companion)).
66
- Each agent brings its companion with it: you never name it. An endpoint of
67
- your own binds what `served([assistant])` lists (the agents with their
68
- companions): `restate.endpoint()`, or the SDK's `restate.serve({ services:
69
- served([...]), port })`. `RESTATE_SERVE_ONLY=triage,planner` serves only
70
- the services it names, each agent with its companion, so that one program
71
- (or image) deploys in parts.
72
-
73
- On Restate Cloud, where the program connects out rather than being called
74
- in, use this package's `connect` (@restatedev/sessions'):
75
- `connect({ services: [assistant], name: 'assistant-v1' })` brings each
76
- agent's companion as `serve` does. The Restate SDK's own `connect` does
77
- not: it binds the agents alone, and the first tool that waits has nothing
78
- to wait on.
79
-
80
- ## Choose a framework
81
-
82
- The same agent runs on each of them: `agent({ name, ...options })`, with
83
- the handler `chat` (a message in, the answer out), and the views
84
- `messages` (the conversation so far), `status` (what it is doing), `steer`
85
- (add to the message it answers), `stop` (the message it answers), `clear`
86
- (forget it all), `sync`,
87
- `notifications` and `watch` (to follow it), and `signal` and `pending`
88
- ([Signals](#signals)).
89
-
90
- | Import | Framework | Choose it when |
91
- | --------------------------------------------------------- | ------------------------------- | --------------------------------------------------------------------------------------------- |
92
- | [`@restatedev/agents/pi`](src/pi/README.md) | pi-durable | You want the default: any provider, coding tools on request, and its Harness (compact, reset) |
93
- | [`@restatedev/agents/langgraph`](src/langgraph/README.md) | LangGraph | You use LangChain: its tools, a chat model of your own, or a graph of your own |
94
- | [`@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 |
95
- | [`@restatedev/agents/deepseek`](src/deepseek/README.md) | DeepSeek Harness | You want DeepSeek's harness: DeepSeek's models, or any pi-ai knows |
96
- | [`@restatedev/agents/opencode`](src/opencode/README.md) | OpenCode | You want OpenCode's agent: its own coding tools in a workspace, any provider it serves |
97
- | [`@restatedev/agents/agentlib`](src/agentlib/README.md) | agentlib (Restate's own) | You want Restate's agent library: its tools, journaled on the classic Restate SDK, not in SQL |
98
-
99
- Each framework's packages are optional peer dependencies of
100
- @restatedev/agents: a project installs @restatedev/agents, whose required peers
101
- (@restatedev/sessions, which brings the Restate SDK, and zod) npm and pnpm
102
- install with it, and the packages of the frameworks it imports, so that
103
- `@restatedev/agents/pi` brings pi alone:
104
-
105
- ```sh
106
- npm install @restatedev/agents @earendil-works/{pi-durable,pi-ai,chord}@1.5.2 # pi
107
- npm install @restatedev/agents @anthropic-ai/sdk # Claude
108
- npm install @restatedev/agents @langchain/core @langchain/langgraph @langchain/langgraph-checkpoint \
109
- @langchain/openai # LangGraph, and the provider of its models: or @langchain/anthropic
110
- npm install @restatedev/agents @earendil-works/pi-ai@1.5.2 @deepseek-ai/cordis \
111
- @deepseek-ai/{dsh-agent,dsh-agent-loop,dsh-llm,dsh-llm-deepseek-api-key,dsh-llm-pi-ai,dsh-session}@0.2.2-rc.2 \
112
- @deepseek-ai/{dsh-session-checkpoint-policy,dsh-session-persistence,dsh-session-projection}@0.2.2-rc.2 \
113
- @deepseek-ai/{dsh-system-prompt,dsh-tools,dsh-tool-executor-native,dsh-user-approval}@0.2.2-rc.2 \
114
- @deepseek-ai/{dsh-commands,dsh-compaction,dsh-compaction-basic,dsh-compaction-tool-result-pruner,dsh-token-meter}@0.2.2-rc.2 # DeepSeek
115
- npm install @restatedev/agents @opencode/{core,sdk,server,plugin}@2.2.7 effect@4.1.0 # OpenCode, on Node 24
116
- npm install @restatedev/agents @restatedev/agentlib@0.2.0 @restatedev/restate-sdk-gen@1.18.2 \
117
- @restatedev/restate-sdk@1.18.2 @ai-sdk/openai # agentlib, and the provider of its models: or @ai-sdk/anthropic
118
- ```
119
-
120
- pi's packages are on 1.5 (`~1.5.2`): pi changes its API in minor releases
121
- (1.5 dropped pi-ai's `Type`, and changed pi-durable's storage), so a minor
122
- newer than the one @restatedev/agents is tested on is not taken.
123
- A subpath whose packages are missing fails as it is imported, naming the
124
- first it lacks. The packages are not published yet:
125
- [`pnpm --filter e2e packaging`](../e2e/packaging.ts) installs them from
126
- their tarballs, with pi alone. In this repository the frameworks' packages
127
- are @restatedev/agents' development dependencies, so every example runs as it is.
128
-
129
- Every framework takes `model`, `system`, `tools` and `output` (a
130
- [structured answer](#structured-answers)); pi and OpenCode take a
131
- `workspace` too, a directory for their coding tools. `system` is the whole
132
- system prompt for Claude and LangGraph, and is added to the framework's own
133
- (which tells the model about its tools) for pi, DeepSeek and OpenCode.
134
-
135
- **OpenCode** runs embedded in the handler, on Node 24 (its sources do not
136
- load on Node 22), and keeps its own history in a database of the key's own,
137
- beside the object's: each turn holds copies of what OpenCode stored of it.
138
- A crashed attempt's turn is resumed by OpenCode; a killed invocation's turn
139
- is closed, never finished, without asking the model (OpenCode's resume
140
- budget), and the next prompt tells the model how it ended and which of its
141
- calls did happen. With a `workspace`, the agent has OpenCode's own coding
142
- tools, but for its subagent and question tools, and its shell runs no
143
- background jobs; what OpenCode's rules ask about (a read of a `.env` file)
144
- is denied, or, with `approval: true`, waits for a person's approval. A
145
- provider's outage is asked again as pi does (its `retry` option), and
146
- never ends the turn. Not there yet: a change of `model` for a key that has
147
- a session already ([its README](src/opencode/README.md)).
148
-
149
- **agentlib** runs on the classic Restate SDK, not in a session object: its
150
- `chat` is journaled, and a crash replays it, so that a model call or a tool
151
- call that finished is not made again; its conversation is in the object's
152
- key/value state. It has every agent's handlers and views, and their
153
- companion, and takes the tools of `@restatedev/agents` below beside
154
- agentlib's own (`asyncTool`, `serviceTool`, `agentTool`, MCP's...), though a
155
- `tool()` of its own has no `ctx.db`; and neither `schema`, `window` nor
156
- `budget`, which are the SQL database's: `history` keeps its conversation
157
- short ([its README](src/agentlib/README.md)).
158
-
159
- Every agent takes these too, beside its framework's options:
160
-
161
- | Option | What |
162
- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
163
- | `description` | What it is, for the UI, and for a parent's model: `subagent(agent)` tells it |
164
- | `background` | It works unwatched (a subagent, say): its turn tells its companion at its end only, not at each step, so a follower sees each turn once it ended |
165
- | `schema` | Tables of your own in its database ([Build your own](#build-your-own)) |
166
- | `window` | How many of the latest answered turns its model sees whole, with their tool calls and results (default 1), or `'all'` |
167
- | `budget` | How many tokens of the turns before the window its model sees, as their messages and answers (default 32 000); `summarize` summarizes the rest |
168
-
169
- `window` and `budget` bound what Claude's and LangGraph's model is sent
170
- ([what the model gets](docs/conversation.md)); pi, the DeepSeek Harness and
171
- OpenCode keep their own history, and compact it themselves; agentlib's
172
- `history` summarizes its own. An object holds one
173
- framework's conversation: its turns are that framework's messages.
174
-
175
- ## Calling an agent
176
-
177
- Through Restate's ingress (port 8080), the request's body is the message,
178
- as text or as a JSON string, and the response is the answer, as a JSON
179
- string:
180
-
181
- ```sh
182
- curl localhost:8080/assistant/alice/chat -d 'Hi, I am Alice' # "Hello Alice! ..."
183
- ```
184
-
185
- A key answers one message at a time: a message sent while another is
186
- answered waits for it ([turn semantics](docs/turns.md) spells out how a
187
- turn starts, ends, and is retried). A message that fails for good answers with an error:
188
- HTTP 424 if the model's provider refused it (a missing or wrong API key, an
189
- unknown model), 500 otherwise. A refused message is over: the next message
190
- is answered on its own, not after it.
191
-
192
- **Send now, fetch the answer later.** A turn can take longer than an HTTP
193
- request should wait (a tool that waits for a person, say). Add `/send` to
194
- send without waiting: the response has the invocation's id, and
195
- `/restate/invocation/<id>/attach` waits for its answer, as often as you
196
- like:
197
-
198
- ```sh
199
- curl localhost:8080/assistant/alice/chat/send -d 'Plan my week' # {"invocationId": "inv_1f…", ...}
200
- curl localhost:8080/restate/invocation/inv_1f…/attach # the answer, once there is one
201
- ```
202
-
203
- **Stop a turn.** `stop` stops the message being answered, such as for a
204
- UI's Stop button: it cancels its invocation (the one `status` says), and
205
- answers its id, or null if no message was answered. Messages to `chat`
206
- queue: the agent answers one at a time, in the order they came, and a
207
- stopped turn makes way for the next one waiting. So to interrupt with a new
208
- message, send it after `stop`: it is answered once the stopped turn ended,
209
- after any messages already waiting.
210
-
211
- ```sh
212
- curl localhost:8080/assistant/alice/stop # {"stopped": "inv_1f…"}
213
- curl localhost:8080/assistant/alice/chat -d 'Actually, plan only Monday'
214
- ```
215
-
216
- `stop` is Restate's cancellation, as Restate's admin API (port 9070) cancels
217
- any invocation by its id: `curl -X PATCH localhost:9070/invocations/inv_1f…/cancel`.
218
-
219
- The turn ends cancelled whenever the cancellation comes (during a model
220
- request too), and the agent does not go on: each framework stops its turn
221
- and records the cut-off tool calls as cancelled, in its own way, and the
222
- next message starts afresh. The calls its tools made (a wait for an
223
- approval, a sub-agent's task, a workflow) are cancelled with it. `chat`
224
- uses Restate's explicit cancellation for this (`explicitCancellation: true`,
225
- with `cancelled(ctx)` and `cancelCalls(ctx)` of `@restatedev/sessions/internal`).
226
-
227
- A cancellation reaches the turn's work at once while Restate keeps the
228
- turn's input open. Restate closes it once the turn has sent and received
229
- nothing for the inactivity timeout (a minute by default: a long model
230
- request, or a slow tool). The turn works on, and a cancellation then reaches
231
- it at its next step, when it next commits or calls. For turns whose steps
232
- take longer, raise Restate's inactivity timeout (the server's
233
- `worker.invoker.inactivity-timeout`).
234
-
235
- An attempt that ends before its turn does, while its process lives on
236
- (Restate suspended it, gave up on it, or lost its connection), stops its
237
- work too, a model's request included: it can store nothing more, and the
238
- next attempt goes on with the turn, which is not cancelled.
239
-
240
- **A message while it works.** A message sent to `chat` while the agent
241
- answers another waits for it: Restate answers a key's messages one at a
242
- time, in order. To add to the message being answered ("use Celsius", "skip
243
- Friday"), send it to `steer`: the turn takes it at its next step (once the
244
- model's tool calls have their results, before its next request), and its
245
- answer covers it. A message that comes too late for a step (the model is
246
- writing its final answer, say) is answered as a turn of its own, right after
247
- the turn, before the messages sent after it; so is one sent with no turn
248
- being answered. Either way it is answered once: send it with an idempotency
249
- key, so that a request sent again is the same message.
250
-
251
- ```sh
252
- curl localhost:8080/assistant/alice/chat/send -d 'Plan my week'
253
- curl localhost:8080/assistant/alice/steer -H 'idempotency-key: 7f3c…' -d 'Skip Friday' # {"id": "inv_…", "turn": "inv_1f…"}
254
- ```
255
-
256
- `steer` answers the message's id and the turn that holds it for its next
257
- step, or `turn: null` if it is answered as a turn of its own; `status`
258
- lists the messages the turn holds and has not taken yet (`steering`). A
259
- turn takes at most 16. Claude and LangGraph's built-in agent take them
260
- before each model request that follows a round of tool calls; pi, DeepSeek
261
- and OpenCode through their own inboxes; a LangGraph graph of your own, and a
262
- background agent, take none ([Steering a turn](docs/turns.md#steering-a-turn)).
263
- To change course outright, stop the turn (`stop`) and send the message that
264
- replaces it.
265
-
266
- **Forget a conversation.** `clear` starts a key over, such as for a UI's
267
- New chat button: it stops the message being answered (as `stop`), then
268
- forgets the conversation, the key's database, and what its
269
- companion holds (waits and kept signals). It answers as `stop`
270
- does. The next message starts anew; its ids and cursors go on from where
271
- the forgotten conversation got to, so a follower (`follow`, `sync`) reads on,
272
- and drops the messages it kept from before `first` (which a page and each
273
- change of `follow` give).
274
-
275
- ```sh
276
- curl localhost:8080/assistant/alice/clear # {"stopped": null}
277
- ```
278
-
279
- A message sent before `clear` is answered first, then forgotten too.
280
-
281
- **Send again safely.** A caller that may send a message again (after a
282
- timeout, say) gives it an idempotency key: the same key is the same
283
- invocation, answered once, however often it is sent. Its answer is also at
284
- the key:
285
-
286
- ```sh
287
- curl localhost:8080/assistant/alice/chat/send -H 'idempotency-key: msg-1' -d 'Plan my week'
288
- curl localhost:8080/restate/invocation/assistant/alice/chat/msg-1/attach
289
- ```
290
-
291
- **The conversation** is `messages`, a page at a time, for a chat UI: what
292
- was said, in order, with the tool calls the agent made and their outputs.
293
- Without a body, it is the latest 50 messages:
294
-
295
- ```sh
296
- curl localhost:8080/assistant/alice/messages
297
- ```
298
-
299
- ```json
300
- {
301
- "messages": [
302
- { "id": 0, "role": "user", "parts": [{ "type": "text", "text": "Weather in Paris?" }] },
303
- {
304
- "id": 1,
305
- "role": "assistant",
306
- "parts": [
307
- { "type": "tool", "id": "toolu_01", "name": "weather", "input": { "city": "Paris" }, "output": "18°C, sunny" }
308
- ]
309
- },
310
- { "id": 2, "role": "assistant", "parts": [{ "type": "text", "text": "18°C and sunny." }] }
311
- ],
312
- "more": false,
313
- "cursor": 4
314
- }
315
- ```
316
-
317
- The conversation as clients read it is the agent's conversation of turns,
318
- in the object's database ([docs/conversation.md](docs/conversation.md)). A
319
- message's `id` is its position, and never changes; `cursor` is where the
320
- conversation is now. `limit` caps a page; `before` an id gives older
321
- messages (scrolling back, while `more` says there are older ones still);
322
- and `cursor` gives the messages new or changed since it, by when they
323
- changed, with the next cursor: a message that grew (a tool call with its
324
- output) comes again, with its `id`. `view: "summary"` gives each turn's
325
- message and answer alone, under the same ids. A conversation whose earliest
326
- turns are summarized, or that the framework compacted, keeps every turn as
327
- it was said (only the model's context changed):
328
-
329
- ```sh
330
- curl localhost:8080/assistant/alice/messages --json '{"limit": 20, "before": 40}'
331
- curl localhost:8080/assistant/alice/messages --json '{"cursor": 4}'
332
- ```
333
-
334
- It answers at once, also while a message is answered: with the tool calls
335
- made so far.
336
-
337
- **What it is doing.** `status` says which message the agent answers, if
338
- any (its invocation id, to attach to its answer, and since when), and what
339
- its tools wait for ([Signals](#signals)). The message is in the agent's
340
- companion (`support.prebuilt.restate`, key `alice`), which `chat` tells
341
- when it starts, and when it answers or fails for good (Restate's UI shows it
342
- there):
343
-
344
- ```sh
345
- curl localhost:8080/support/alice/status
346
- ```
347
-
348
- ```json
349
- {
350
- "answering": { "invocationId": "inv_1f…", "since": "2026-10-17T15:00:00.000Z" },
351
- "waiting": [
352
- { "id": "inv_1f…:toolu_01", "name": "approval", "input": { "order": "103" }, "since": "2026-10-17T15:00:02.000Z" }
353
- ]
354
- }
355
- ```
356
-
357
- In a tool part, `error: true` says the output is the tool's error (`Error:
358
- <message>`), for a UI to show it as one.
359
-
360
- **Follow it.** Instead of polling `messages` and `status`, a UI waits for
361
- the next change with `sync`: given the `revision` of its last sync, it
362
- answers once something changed (a message or tool call stored, a wait, a
363
- turn's start and end), or at its timeout (50 s by default, at most 60), with
364
- the new revision, the `status`, and the messages since its `cursor`, in one
365
- request. It waits in Restate, holding no process; sent again with the same
366
- idempotency key, it joins the same wait. `follow()` of
367
- `@restatedev/agents/client` (below) is a loop of syncs:
368
-
369
- ```sh
370
- curl localhost:8080/support/alice/sync --json '{}' # {"revision": 7, "cursor": 31, "status": ..., "messages": [...], "more": false}
371
- curl localhost:8080/support/alice/sync --json '{"cursor": 31, "revision": 7}' # the same, once something changed
372
- ```
373
-
374
- `notifications` and `watch({ revision })` are the revision alone, and
375
- the wait alone. The model's reply comes whole, with its message: there is no
376
- token streaming.
377
-
378
- **From code.** From a Restate handler, through the agent's definition:
379
-
380
- ```ts
381
- const answer = await ctx.rpc(assistant, 'alice').chat('Hi, I am Alice');
382
- ```
383
-
384
- From any other code, a web app included, with Restate's own client
385
- ([`@restatedev/restate-sdk-clients`](https://docs.restate.dev/develop/ts/clients)).
386
- `agent(name)` of `@restatedev/agents/client` is the agent's definition as the
387
- client takes it: its name, typed with an agent's handlers. It imports
388
- Restate's client and nothing of the agent's code or the SDK, so a web app
389
- bundles it as it is:
390
-
391
- ```ts
392
- import * as clients from '@restatedev/restate-sdk-clients';
393
- import { agent } from '@restatedev/agents/client';
394
-
395
- const restate = clients.connect({ url: 'http://localhost:8080' });
396
- const alice = restate.objectClient(agent('assistant'), 'alice');
397
-
398
- const sent = await restate
399
- .objectSendClient(agent('assistant'), 'alice')
400
- .chat('Plan my week', clients.rpc.sendOpts({ idempotencyKey: 'msg-1' }));
401
- const { answering, waiting } = await alice.status(); // while it works
402
- await alice.stop(); // the Stop button
403
- const { messages } = await alice.messages({ limit: 20 }); // the tool calls so far
404
- const answer = await restate.result(sent); // once it answered
405
- ```
406
-
407
- `follow(restate, agent(name), key)` gives the conversation as it changes:
408
- what the agent is doing, and the messages new or changed since the last
409
- time (a message may come again, changed, such as a tool call with its
410
- output: keep them by `id`), until its `signal` aborts. A network failure
411
- does not end it, and a wait it retries joins the one already parked in
412
- Restate:
413
-
414
- ```ts
415
- import { agent, follow } from '@restatedev/agents/client';
416
-
417
- const stop = new AbortController();
418
- const messages = new Map<number, ChatMessage>();
419
- for await (const change of follow(restate, agent('assistant'), 'alice', { signal: stop.signal })) {
420
- for (const m of change.messages) messages.set(m.id, m);
421
- render(change.status, [...messages.values()]);
422
- }
423
- ```
424
-
425
- Each change has `waiting` too, what the agent waits for, and `asText(message)`
426
- is a message to read, as a terminal shows it: its text, and its tool calls
427
- with their outputs.
428
-
429
- `@restatedev/agents/client` also has the types of what the handlers answer
430
- (`Messages`, `Status`, `Waiting`...); `agent<H>(name)` types a session
431
- object of your own with its handlers `H`.
432
- [`examples/ui`](../examples/ui/app.ts) is a chat page on it: the
433
- conversation as the agent works, its approvals and Stop.
434
-
435
- ## Tools
436
-
437
- Any agent's `tools` take the tools of `@restatedev/agents`, which work the same
438
- in every framework, and a framework's own tools:
439
-
440
- ```ts
441
- import { call, send, signal, subagent, tool, workflow } from '@restatedev/agents';
442
- ```
443
-
444
- | Tool | What the model gets |
445
- | -------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
446
- | `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 |
447
- | `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 |
448
- | `send(target, handler, { description, input?, key?, delay? })` | Sends to a handler without waiting: a one-way call, after `delay` if given |
449
- | `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 |
450
- | `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)) |
451
- | `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 |
452
-
453
- Handler names are checked against the target's handlers: a typo does not
454
- compile. A `key` is a string, or a function of the invocation's context
455
- that gives one.
456
-
457
- **Errors.** A `restate.TerminalError` that a tool throws, or that a handler
458
- it calls fails with (an unknown order, say), is the tool's answer to the
459
- model, `Error: <message>`, and the agent goes on. So are arguments that do
460
- not fit the tool's `input` (`run` never sees them), and a call of a tool the
461
- agent does not have: the model's to fix. Any other error fails the attempt,
462
- and Restate retries it: the tool call runs again.
463
-
464
- **Once.** A crash runs an unfinished tool call again with the same call id.
465
- A tool that must not run twice passes its `idempotencyKey` on (made of the
466
- invocation's id and the call id), as Restate's tools do with each call they
467
- make: run again, it is the same call. A workflow's `run` is the exception:
468
- Restate runs it once per workflow id, and refuses a second call of it
469
- whatever its idempotency key. Restate's `workflow` tool (and `call` of a
470
- workflow's `run`) calls it without a key, and waits for the run by the
471
- call's invocation id: run again, the refused call's invocation id is the
472
- run's. A tool of your own that runs a workflow does the same (`start` and
473
- `attach` of `@restatedev/sessions/internal`), with a workflow id that a run
474
- again gets too (made of the agent's key and the `callId`, as `workflow`'s
475
- is). The DeepSeek Harness and OpenCode tell
476
- the model that a cut-off tool call was interrupted instead, and the model
477
- makes it again as a new tool call: Restate's tools then make the same call,
478
- if the input is the same (so a wait for an approval outlasts a restart), and
479
- so is a call that answered just before the crash, until the framework has
480
- stored its result. They keep these calls in the object's database (the
481
- table `restate_agent_calls`) for this. A tool of your own needs a way for the model to name the call it
482
- retries (see their READMEs).
483
-
484
- **Long work.** Restate shuts an attempt down when it has heard nothing
485
- from it for its inactivity timeout (a minute, by default), and a new attempt
486
- runs the turn from where it was stored. Every agent keeps the model's
487
- requests alive, however long they take, and so do the built-in tools of
488
- OpenCode and pi (a shell, file edits), which work on the machine. A tool of
489
- your own is not kept alive, so a wait for a call or a signal holds no
490
- process: one that works for longer than the timeout sets `keepalive: true`
491
- (`tool({ ..., keepalive: true })`), or it is cut off by every attempt, and
492
- keeps long waits on Restate out of its `run`.
493
-
494
- **Tools for each invocation** (each user's, say) come with the options of
495
- `chat`: `pi.chat(async (ctx) => ({ tools: await toolsOf(ctx) }))`.
496
-
497
- ## Signals
498
-
499
- A `signal()` tool waits for a value from outside: a person's approval, say.
500
- With an `input`, the model says what it waits for:
501
-
502
- ```ts
503
- signal('approval', {
504
- description: 'Wait for a manager to approve a refund.',
505
- input: z.object({ order: z.string(), amount: z.number() }),
506
- });
507
- ```
508
-
509
- Every agent (every `sessionObject()`) has the views `pending`, which lists
510
- its waits, and `signal`, which resolves one; both answer at once, while the agent
511
- waits. Each wait has an id, the signal's name, the model's `input` and when
512
- it started:
513
-
514
- ```sh
515
- curl localhost:8080/support/alice/pending
516
- ```
517
-
518
- ```json
519
- [
520
- {
521
- "id": "inv_1f…:toolu_01",
522
- "name": "approval",
523
- "input": { "order": "103", "amount": 30 },
524
- "since": "2026-10-17T15:00:00.000Z"
525
- }
526
- ]
527
- ```
528
-
529
- `signal` resolves the wait of an `id`, or else the oldest wait for a `name`,
530
- and answers `{"resolved": <its id>}`, or `{"resolved": null}` if none
531
- waited. A signal no one waits for is dropped, so a stale approval approves
532
- nothing later; with `"keep": true` it is kept for the next wait for its
533
- name:
534
-
535
- ```sh
536
- curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
537
- curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved", "keep": true}'
538
- ```
539
-
540
- A DeepSeek agent's tool calls that need a person's approval (its `approval`
541
- option) wait the same way, for the signal `approval`: see
542
- [its README](src/deepseek/README.md#approvals). So do an OpenCode agent's
543
- with `approval: true`, those its permission rules ask about: see
544
- [its README](src/opencode/README.md#permissions). So do an agentlib agent's
545
- that its `approval` option names: see
546
- [its README](src/agentlib/README.md#approvals-and-signals).
547
-
548
- A wait ends with its agent's invocation: a cancelled or killed one leaves `pending`.
549
- The waits are kept by the agent's companion, `<agent>.prebuilt.restate`
550
- keyed as the agent, which `serve` serves beside it. See
551
- [`examples/intermediate/support.ts`](../examples/intermediate/support.ts).
552
-
553
- ## The companion
554
-
555
- Each agent brings a companion of its own: a virtual object named
556
- `<agent>.prebuilt.restate`, the agent's name as it is (agent `support`
557
- has `support.prebuilt.restate`), keyed as the agent (`support/alice`'s
558
- is `support.prebuilt.restate/alice`). It keeps what the agent's key is
559
- doing: the message it answers, the waits of its tools, the messages steered
560
- to it, and the revision a follower waits on. `serve` serves it with the
561
- agent, without your naming it (Restate refuses names that start with
562
- `restate`, so the name ends with it instead). Clients never call it: its
563
- handlers are private to Restate's ingress, and the agent's own views
564
- (`status`, `pending`, `signal`, `steer`, `stop`, `watch`, `sync`) ask it.
565
-
566
- Up to 0.5, every agent shared one `signals` object, keyed `<agent>:<key>`.
567
- Upgrading leaves its state behind: the turns in flight, pending waits and
568
- kept signals, and the revision do not carry over to the new companions
569
- (the revision starts again from 0: a client that kept a later one should
570
- follow anew). Upgrade with no turn running and
571
- no wait pending, and remove the `signals` service from Restate once no
572
- deployment serves it.
573
-
574
- ## Structured answers
575
-
576
- With `output`, a zod object, an agent answers with data rather than text:
577
- its reply is its answer, as JSON of the schema, and `chat` answers with the
578
- value, checked against the schema: the answer is the call's return value,
579
- as with any handler. Every framework takes it. Claude asks the model for it
580
- natively where the model has structured outputs (the API's
581
- `output_config.format`, which holds the reply to the schema), or as its
582
- `nativeOutput` says; otherwise, and in the other frameworks, the system
583
- prompt asks for it, with the schema, and the model is reminded of it after
584
- each prompt, though `messages` shows the prompt as it was asked.
3
+ pi on [`@restatedev/sessions`](../sessions/README.md). The integration is
4
+ pi-durable's own storage moved into a session object's database (`ctx.db`),
5
+ plus the little a turn needs to survive a crash in a handler and to stop when
6
+ it is cancelled. You write a plain `restate.sessionObject`, open pi over
7
+ `ctx.db` with the integration, and use pi as its own docs describe. pi keeps
8
+ its own history.
9
+
10
+ The guide to the integration, page by page, starts at [`docs/README.md`](../../docs/README.md).
11
+
12
+ The entry is `@restatedev/agents/pi`. pi's packages are peer dependencies:
13
+ install `@earendil-works/pi-durable` `~1.7.0`, `@earendil-works/pi-ai`
14
+ `~1.7.0` and `@earendil-works/chord` `~1.7.0` beside `@restatedev/sessions`,
15
+ so that your code and the integration share them.
16
+
17
+ pi's providers read the model's key from the environment of the process that
18
+ serves the session object, not from Restate: `openaiProvider()` reads
19
+ `OPENAI_API_KEY`, and each other provider of `@earendil-works/pi-ai` its own
20
+ variable ([the model's key](../../docs/agents/pi.md#the-models-key)).
21
+
22
+ A handler is not replayed: a retried attempt runs from its first line,
23
+ against what the database holds. What the integration settles:
24
+
25
+ - **The attempt is kept alive while a model answers or a tool runs.** Each
26
+ model request and each tool call, a call of Restate's (`ctx.rpc`) the tool
27
+ makes included, runs in `ctx.stoppable`, with nothing written in the tool;
28
+ otherwise Restate shuts the attempt down after a minute without activity,
29
+ and the request is made again, or the tool's work done again. A tool is
30
+ kept alive for its whole length unless it awaits in `ctx.suspendable`: a
31
+ tool that only waits on another service writes
32
+ `await ctx.suspendable(() => ctx.rpc(...).handler(...))`, and while that
33
+ call is pending its scope keeps nothing alive, so an invocation with
34
+ nothing else at work may suspend on the call.
35
+ - **A retried attempt finds the turn it was in**, by the turn's request id
36
+ (by default `ctx.request.id`), instead of asking for it again. A tool that
37
+ calls another object passes an idempotency key made of the request's id
38
+ and the tool call's id.
39
+ - **A cancelled turn stops.** A cancellation (a Stop button: a view that
40
+ calls `ctx.cancel`, see
41
+ [cancelling an invocation](../sessions/README.md#cancelling-an-invocation))
42
+ aborts the model request or the tool in flight at once, through the
43
+ scope's stop signal, and the framework stops its run. What it stores as it
44
+ stops is stored, and the turn ends as cancelled (`[409] Cancelled`)
45
+ promptly. A cancellation during a tool's call to another object cancels
46
+ that call's invocation and ends the turn the same way; no model request is
47
+ answered after it. The next message takes one model request, which holds
48
+ the cancelled message. A tool that ignores the signal runs to its end: pi
49
+ waits for it, then ends the turn as cancelled.
50
+ - **An attempt that ends mid-request stops too:** its request is aborted,
51
+ and the retried attempt asks again. pi counts each such cut-off with the
52
+ model's errors against its retry policy: a request cut off four times ends
53
+ the turn unanswered.
54
+
55
+ So a tool's call to another object does not suspend the invocation, unless
56
+ the tool awaits it in `ctx.suspendable`. A call outside a
57
+ tool, `ctx.working` and `ctx.stoppable`, or in `ctx.suspendable`, that
58
+ outlives Restate's inactivity timeout (a minute) suspends the invocation,
59
+ holding no process; a cancellation then ends the turn but not that call (a
60
+ [known limit](../sessions/README.md#known-limits)).
61
+
62
+ What a turn does, rule by rule, what the tests show of it and what it
63
+ assumes of Restate, pi and you is specified in
64
+ [`docs/semantics.md`](../../docs/semantics.md).
65
+
66
+ ## pi
67
+
68
+ Example: [`basic/pi.ts`](../examples/basic/pi.ts).
69
+
70
+ `withPi(options)` is configured once, at module scope, and runs each
71
+ invocation's closure:
585
72
 
586
73
  ```ts
587
- const Plan = z.object({ summary: z.string(), parts: z.array(z.string()) });
588
- const planner = claude.agent({ name: 'planner', output: Plan });
589
-
590
- const plan = await ctx.rpc(planner, 'ENG-1').chat('Plan the work on ENG-1'); // a Plan
591
- ```
592
-
593
- A reply that is not such JSON (a code fence around it is fine; asked
594
- natively, the API holds it to the schema's types, not to checks such as a
595
- string's `max`) is answered with what is wrong with it, once, for the model
596
- to reply again; then the invocation fails, with a terminal error, and the
597
- conversation shows its turn failed, with that error. A retried attempt
598
- resumes the conversation, and reads the same reply. In a handler of your
599
- own, `prompt(ctx, text, { output })` answers with it too. As a subagent's,
600
- the parent's model gets it as JSON.
601
-
602
- ## Webhooks
603
-
604
- `webhook()` takes another system's webhooks (Linear's, GitHub's...) into
605
- agents: a service whose `webhook` handler checks each delivery's signature,
606
- and delivers it to the agents of `route`, at once (the other system does not
607
- wait for the agent):
74
+ const pi = withPi({ models, agent: { model }, tools: (ctx) => [transfer(ctx)] });
75
+
76
+ chat: (ctx, message: string) => pi(ctx, ({ ask }) => ask(message)),
77
+ history: (ctx) => pi(ctx, ({ messages }) => messages()),
78
+ ```
79
+
80
+ `options` are pi's `Harness.open` options without `registry` and `readOnly`,
81
+ `tools`, the root conversation's `agent`, and a chord `context` (default
82
+ `BACKGROUND_CONTEXT`). `tools(ctx)` is called once per invocation, with its
83
+ `ctx`, and its tools are installed in the invocation's registry as one
84
+ extension, `withPi.tools`. A tool decided per call can also be installed in
85
+ the closure, in its `registry`. `agent` (the model, the instructions, …) is
86
+ what a key's conversation is created with, by its first `ask`; a
87
+ conversation that exists keeps its own, and pi's `configure` on the root,
88
+ through `harness()`, changes it
89
+ ([the agent of a conversation](../../docs/agents/pi.md#the-agent-of-a-conversation)).
90
+ The closure gets, fresh for each invocation:
91
+
92
+ - `registry`: pi's registry, the option's tools in it; install more before the first `ask` or `harness()`.
93
+ - `ask(message, { requestId })`: a turn of the root conversation, submitted to pi under `requestId` (default: the
94
+ invocation id); returns the answer's text.
95
+ - `messages()`: the root conversation's messages, `[]` before its first turn; resumes nothing.
96
+ - `harness()`: pi's Harness, opened for writing; `ask` uses the same one.
97
+
98
+ Exported types: `PiOptions`, `Pi`, `AskOptions`.
99
+
100
+ From the first `ask` or `harness()`, pi may run a tool call a crash cut off.
101
+ `ask` submits the message under its request id, so a retry waits for the
102
+ same run. One id is one submission, as pi keeps them: in one attempt, a
103
+ second `ask` under an id the conversation holds (the default id twice, in
104
+ one closure or in closures of any factories, or one explicit id twice) gets
105
+ the first's answer, or the first's `unanswered: …` error, and stores
106
+ nothing, so a second turn in one invocation passes another `requestId`;
107
+ across attempts the same id is the retry; across
108
+ invocations an id the conversation holds returns that submission's answer,
109
+ which makes a message under an id of the caller's own idempotent. The id
110
+ must be the same on every attempt: one made at random makes a retry a
111
+ second turn of the message. Ask one after the other, from one closure at a
112
+ time: pi queues asks made at once, and when the first fails it keeps the
113
+ second queued, which then never settles; two closures at once open two
114
+ Harnesses on one storage, which pi does not support
115
+ ([pi](../../docs/agents/pi.md#the-request-id)). A run that
116
+ does not end `done` is a `TerminalError` whose message names pi's reason
117
+ only (`unanswered: model_error`); the provider's message, which can echo what
118
+ the request carried, is on the span `withPi.ask` in Restate's UI, which ends
119
+ with `unanswered: <reason>: <detail>`. A tool that throws, a `TerminalError`
120
+ included, does not end the turn: pi answers the call with an error result
121
+ the model sees, and the run goes on. A background compaction pi started that
122
+ is still running when the closure ends is aborted, and the next turn runs it
123
+ again ([limits](../../docs/agents/limits.md)). Two turns in one invocation
124
+ ([`pi-teller.ts`](../examples/docs/pi-teller.ts)):
608
125
 
609
126
  ```ts
610
- import { serve, webhook } from '@restatedev/agents';
611
-
612
- const issues = webhook({
613
- name: 'linear', // at /linear/webhook
614
- auth: { header: 'linear-signature', secret: process.env.LINEAR_WEBHOOK_SECRET! },
615
- idempotencyHeader: 'linear-delivery', // a delivery sent again reaches the same message
616
- route: [triage],
617
- key: ({ data }) => data.identifier, // its conversation; undefined drops it
618
- });
619
- await serve(issues, triage);
620
- ```
621
-
622
- | Option | What |
623
- | ------------------- | -------------------------------------------------------------------------------------------- |
624
- | `name` | The service: `/<name>/webhook` |
625
- | `auth` | `{ header, secret }`: the HMAC-SHA256 of the body, in hex (or `sha256=…`); else 401 |
626
- | `idempotencyHeader` | The header of the delivery's id, which a delivery sent again has too |
627
- | `route` | The agents each delivery goes to |
628
- | `key` | The agents' key, from the body (its JSON), or undefined to drop it; by default, the delivery |
629
- | `message` | What of the body the agents read; by default, all of it |
630
- | `description` | What it is, for the UI |
631
-
632
- A delivery is a message of its own to the agent's `chat`, which it answers
633
- after the message it works on, if any, also one that is stopped: a delivery
634
- is never dropped.
635
-
636
- The same delivery is yours from any handler (a session object's, or a
637
- service's or workflow's of the SDK), for events of other kinds (a queue, a
638
- schedule): `deliver(ctx, agent, key, text, { idempotencyKey })`.
639
- Every `sessionObject()` and `agent()` brings its own companion,
640
- `companionOf(agent)` (the object `<agent>.prebuilt.restate`, at the
641
- agent's own keys), which `deliver` and `webhook` check for.
642
-
643
- The agent's message says where it comes from, with the body as JSON:
644
-
645
- ```
646
- <webhook name="linear" delivery="5d2…">
647
- { "action": "create", "type": "Issue", "data": { … } }
648
- </webhook>
649
- ```
650
-
651
- The handler's metadata says what it is, for the admin API and the UI:
652
- `restate-agents.kind` (`webhook`), `.routes` (`triage`), `.auth`
653
- (`hmac-sha256:linear-signature`) and `.idempotency-header`. See
654
- [`examples/advanced/factory`](../examples/advanced/factory/README.md).
655
-
656
- ## Models
657
-
658
- Every agent's `model` is `provider/model-id`, or else the `MODEL`
659
- environment variable, or else OpenAI's `openai/gpt-6-sol`, with
660
- `OPENAI_API_KEY` (Anthropic's `anthropic/claude-sonnet-5-5`, with
661
- `ANTHROPIC_API_KEY`, for Claude; DeepSeek's `deepseek/deepseek-flash`, with
662
- `DEEPSEEK_API_KEY`, for the DeepSeek Harness):
663
-
664
- ```ts
665
- pi.agent({ name: 'assistant', model: 'anthropic/claude-sonnet-5-5' }); // with ANTHROPIC_API_KEY
666
- ```
667
-
668
- pi, the DeepSeek Harness and OpenCode take any provider they know (the
669
- DeepSeek Harness, pi-ai's; OpenCode, its own providers'); LangGraph OpenAI's
670
- and Anthropic's models (and any LangChain chat model, as `model`); Claude
671
- Anthropic's.
672
-
673
- A wrong model fails at once: a model that is not `provider/model-id`, or
674
- another provider's for an agent of one provider's models, when the agent is
675
- defined; a missing or wrong API key, or a model the provider does not know,
676
- with a terminal error that says what to check, rather than retries while
677
- the caller waits.
678
-
679
- ## Your own session object
680
-
681
- `agent()` is a session object with `chat` and `messages`. For more, make
682
- the session object yourself, with `sessionObject()`, and put your own
683
- handlers beside the framework's. Here, an assistant whose tools keep facts
684
- in its own table (a shorter
685
- [`examples/basic/memory.ts`](../examples/basic/memory.ts)):
686
-
687
- ```ts
688
- import { sessionObject, serve, tool } from '@restatedev/agents';
689
- import * as pi from '@restatedev/agents/pi';
690
- import { z } from 'zod';
691
-
692
- const remember = tool({
693
- name: 'remember',
694
- description: 'Remember a fact about the user.',
695
- input: z.object({ fact: z.string() }),
696
- run: async ({ fact }, { ctx }) => {
697
- await ctx.db.execute('INSERT OR IGNORE INTO facts VALUES (?)', [fact]);
698
- return 'remembered';
699
- },
700
- });
701
-
702
- const assistant = sessionObject({
703
- name: 'assistant',
704
- schema: ['CREATE TABLE facts (fact TEXT PRIMARY KEY)'], // tables of your own, beside the agent's (optional)
705
- handlers: {
706
- chat: pi.chat({ tools: [remember] }),
707
- },
708
- views: {
709
- messages: pi.messages(),
710
- facts: (ctx) => ctx.db.query('SELECT fact FROM facts'),
711
- },
712
- });
713
-
714
- await serve(assistant);
715
- ```
716
-
717
- Your tables share the database with the agent's, whose names all start with
718
- `restate_` (`restate_agent_turns`, `restate_agent_items`,
719
- `restate_pi_tasks`...): any other name is yours.
720
-
721
- **Options for each invocation.** `chat` takes options, or a function of the
722
- invocation's context that gives them: each user's model and persona from
723
- the object's database, say ([`examples/intermediate/harness.ts`](../examples/intermediate/harness.ts)):
724
-
725
- ```ts
726
- const options = async (ctx: restate.SessionContext): Promise<pi.Options> => {
727
- const { model, persona } = await settingsOf(ctx);
728
- return { model, system: persona ?? 'You are a helpful assistant.', tools: [clock] };
729
- };
730
-
731
- chat: pi.chat(options),
732
- ```
733
-
734
- **A handler of your own.** `prompt(ctx, text, options)` answers a prompt in
735
- any handler, once, however often the handler runs; each prompt of an
736
- invocation is a prompt of its own. `chatHandler(answer)` makes a handler
737
- that takes its message as `chat` does (text, or a JSON string):
738
-
739
- ```ts
740
- summarize: chatHandler(async (ctx, topic) => pi.prompt(ctx, `Summarize what we said about ${topic}`)),
741
- ```
742
-
743
- `chatHandler` is what tells the companion of the turn: `status` shows it,
744
- `stop` stops it, `steer` reaches it, and its steps are published for
745
- followers. A `prompt()` in a handler without it stores its turn and
746
- publishes nothing (a follower sees it with the next publish); a `signal`
747
- tool still waits, as the object's companion keeps the wait. A session
748
- object of `@restatedev/sessions` has no companion: a `prompt()` there
749
- stores its turns too, but a wait for a signal fails the turn, and a
750
- `chatHandler` the message, with a terminal error that says so
751
- ([A turn outside a `chat` turn](docs/turns.md#a-turn-outside-a-chat-turn)).
752
-
753
- pi also has `withPi(ctx, options, work)`, for more than a prompt: the Harness's own
754
- API, such as compacting the conversation (see its README).
755
-
756
- **What `sessionObject()` sets up.** `ctx.db` in every handler; retries for weeks
757
- (50 ms after a crash, then twice as long each time, up to 10 s apart), since
758
- each attempt resumes from the database; and the SQL storage hidden from the
759
- journal in Restate's UI. Its `options` (such as `retryPolicy`) and
760
- `metadata` add to these. It is a `restate.sessionObject` of
761
- [`@restatedev/sessions`](../sessions/README.md): `handlers` run one at a time per
762
- key, and `views` beside them. Its own cannot be named `signal`, `pending`,
763
- `status`, `stop`, `notifications` or `watch`, views every agent's
764
- session object has, nor `sync`, `clear`, `steer`, `erase`, `settle`, `compact`
765
- or `steered`, which an agent has (one with a `messages` view). A view of yours reads the database too: `ctx.db` is the
766
- database as committed, beside a message being answered.
767
-
768
- ## Build your own
769
-
770
- `@restatedev/agents` is not published: it runs on
771
- [`@restatedev/sessions`](../sessions/README.md) (SQL in virtual objects, with its
772
- Node.js addon), which this repository builds.
773
- Build them once, at the repository's root, with `pnpm install && pnpm build`:
774
- it needs Rust (for the addon), Node 24 or later, and pnpm (see
775
- [Build and test](../../README.md#build-and-test)).
776
-
777
- Then the quickest start is a file in [`packages/examples/`](../examples/README.md),
778
- whose package has `@restatedev/agents`, the SDK and zod. Or a package of your own
779
- in the pnpm workspace: a directory under `packages/`
780
- ([`pnpm-workspace.yaml`](../../pnpm-workspace.yaml)), with
781
-
782
- ```json
783
- {
784
- "type": "module",
785
- "dependencies": { "@restatedev/restate-sdk": "1.18.2", "@restatedev/agents": "workspace:*", "zod": "4.6.5" }
786
- }
787
- ```
788
-
789
- and `pnpm install`. Node runs
790
- TypeScript as it is: `node agent.ts`.
127
+ confirm: (ctx, message: string) =>
128
+ pi(ctx, async ({ ask }) => {
129
+ const answer = await ask(message);
130
+ const check = await ask('In one line: which accounts and amounts did you just move?', {
131
+ requestId: `${ctx.request.id}:check`,
132
+ });
133
+ return { answer, check };
134
+ }),
135
+ ```
136
+
137
+ `messages()` reads through a read-only Harness, which runs nothing, unless this invocation has opened pi for
138
+ writing; on a key never written it commits pi's storage migrations, and after a closure of the same attempt that
139
+ opened pi for writing and wrote nothing, the writer row. `harness()` keeps model requests and tool calls alive
140
+ and stops them on a cancellation (`keptModels`, `keptTools`), sets
141
+ `restartLimit: Infinity` unless your `settings` give one (pi parks work after
142
+ 5 crashes otherwise), and aborts a run another invocation left (`abortLeft`).
143
+
144
+ Nothing is opened until the closure uses it, and what was opened is closed
145
+ when the closure ends. History is read in a handler, not a view: pi-durable's
146
+ storage migrates its tables as it opens, and a view's database refuses writes.
147
+
148
+ The pieces, for a need the factory does not cover: `openSqlKvStorage`,
149
+ `SqlKvDatabase`, `keptModels`, `keptTools`, `abortLeft`.
150
+
151
+ - `openSqlKvStorage(ctx.db)`: pi-durable's storage, each pi commit one
152
+ transaction of the session (`SqlKvDatabase`, chord's SQLite facade over it).
153
+ - `keptModels(ctx, models)`: the model registry, each request kept alive.
154
+ - `registry: keptTools(ctx, registry)` as the Harness opens: every tool of
155
+ the registry kept alive.
156
+ - From pi itself: submit with a `requestId` that is the same on every attempt (`ctx.request.id`); declare tools
157
+ `replay: 'safe'`, so a tool a crash cut off runs again with the same call
158
+ id.
159
+ - A tool that awaits its call in `ctx.suspendable` lets the invocation
160
+ suspend on it: the tool's `execute` runs inside its scope, which stops
161
+ counting while the call is pending. When the call answers, the next
162
+ attempt resumes the run and runs the tool again with the same call id, and
163
+ its idempotency key reaches the same invocation; the model is not asked
164
+ again for the reply that called the tool. What the tool did before the
165
+ `ctx.suspendable` is done again.
166
+ - A crash in a tool resumes the turn without asking the model again.
167
+ - **Stopping a turn:** `keptModels` gives each request the stop signal
168
+ beside pi's own, and `keptTools` gives it to each tool as its chord
169
+ context's `abortSignal`; pi commits an aborted request as the run's
170
+ failure, and the submission ends unanswered, as cancelled.
171
+ `abortLeft(ctx, harness, context)` before the turn: a run another
172
+ invocation left (cancelled while nothing could stop it, crashed as it
173
+ stopped) is aborted, not resumed; this invocation's own is, whatever its
174
+ request id. The history holds the cancelled message with no reply.
175
+ `abortLeft` tells them apart by the table `restate_withpi_writer`, which
176
+ pi's next writing commit after it fills with the invocation id.
177
+ `abortLeft(ctx, harness, context, db)` reads and records it on `db`, by
178
+ default `ctx.db`: give it the database you gave `openSqlKvStorage` (the
179
+ same object, not a wrapper of it).
180
+
181
+ ## Tables
182
+
183
+ The integration's tables are `restate_pi_*` (pi's) and `restate_withpi_writer` (which invocation last wrote pi's
184
+ storage) in `ctx.db`. Give yours other names: a table of yours named `restate_withpi_writer` with another shape fails every turn.
791
185
 
792
186
  ## Tests
793
187
 
794
- [`test/`](test) has each framework's agent on a scripted model
795
- ([`test/fakes/`](test/fakes/fakes.ts)), which needs no API key, through
796
- crashes of the handler, and each framework's storage on a database in memory,
797
- with the framework's own conformance suite where it has one
798
- ([`test/storage/`](test/storage)). Each framework's README lists its own.
799
-
800
- ```sh
801
- pnpm --filter @restatedev/agents test # all of them, without a Restate server
802
- pnpm --filter @restatedev/agents test langgraph # one framework's
803
- ```
804
-
805
- The same agents run against a real Restate server, through crashes, in
806
- [the crash test](../e2e/README.md).
807
-
808
- ## Words
809
-
810
- - **Object, key.** A Restate virtual object: `assistant/alice` is the
811
- object `assistant`'s key `alice`, with its own conversation and database,
812
- answering one message at a time.
813
- - **Invocation.** One call of a handler: a message to `chat`. Restate runs
814
- it until it completes, through crashes and restarts.
815
- - **Attempt.** One run of an invocation. A crash ends an attempt, and
816
- Restate starts another, which resumes from the database: what an
817
- invocation does "once" is done once however many attempts it takes.
188
+ `pnpm --filter @restatedev/agents test`: on scripted models (`test/fakes/`), a
189
+ turn whose attempt dies in a tool call and is finished by the next attempt,
190
+ turns stopped during a model request and a tool's call (`test/stop.test.ts`),
191
+ a long tool kept alive and stopped (`test/tools.test.ts`), and a tool
192
+ awaiting its call in `ctx.suspendable` (`test/suspendable.test.ts`);
193
+ pi-durable's storage suite; and a check that the entry reaches only pi's
194
+ packages. `test/slow.ts` is a session object whose model takes
195
+ `SLOW_SECONDS` (default 75) to answer, with a tool whose call takes
196
+ `SLOW_TOOL_SECONDS` (in `ctx.suspendable` with `SLOW_TOOL_SUSPENDS=1`) or
197
+ that works `SLOW_WORK_SECONDS`, for a real server (give `PORT`;
198
+ `NO_KEEPALIVE=1` turns the keep-alive off).