@restatedev/agents 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +189 -808
  2. package/dist/pi/factory.d.ts +73 -0
  3. package/dist/pi/factory.d.ts.map +1 -0
  4. package/dist/pi/factory.js +145 -0
  5. package/dist/pi/factory.js.map +1 -0
  6. package/dist/pi/index.d.ts +5 -129
  7. package/dist/pi/index.d.ts.map +1 -1
  8. package/dist/pi/index.js +31 -571
  9. package/dist/pi/index.js.map +1 -1
  10. package/dist/pi/keepalive.d.ts +3 -16
  11. package/dist/pi/keepalive.d.ts.map +1 -1
  12. package/dist/pi/keepalive.js +38 -41
  13. package/dist/pi/keepalive.js.map +1 -1
  14. package/dist/pi/left.d.ts +16 -0
  15. package/dist/pi/left.d.ts.map +1 -0
  16. package/dist/pi/left.js +23 -0
  17. package/dist/pi/left.js.map +1 -0
  18. package/dist/pi/storage.d.ts +19 -76
  19. package/dist/pi/storage.d.ts.map +1 -1
  20. package/dist/pi/storage.js +50 -368
  21. package/dist/pi/storage.js.map +1 -1
  22. package/dist/pi/tools.d.ts +12 -0
  23. package/dist/pi/tools.d.ts.map +1 -0
  24. package/dist/pi/tools.js +70 -0
  25. package/dist/pi/tools.js.map +1 -0
  26. package/package.json +11 -254
  27. package/src/pi/factory.ts +231 -0
  28. package/src/pi/index.ts +31 -759
  29. package/src/pi/keepalive.ts +46 -56
  30. package/src/pi/left.ts +52 -0
  31. package/src/pi/storage.ts +75 -409
  32. package/src/pi/tools.ts +78 -0
  33. package/dist/agentlib/agent.d.ts +0 -32
  34. package/dist/agentlib/agent.d.ts.map +0 -1
  35. package/dist/agentlib/agent.js +0 -174
  36. package/dist/agentlib/agent.js.map +0 -1
  37. package/dist/agentlib/index.d.ts +0 -5
  38. package/dist/agentlib/index.d.ts.map +0 -1
  39. package/dist/agentlib/index.js +0 -15
  40. package/dist/agentlib/index.js.map +0 -1
  41. package/dist/agentlib/messages.d.ts +0 -39
  42. package/dist/agentlib/messages.d.ts.map +0 -1
  43. package/dist/agentlib/messages.js +0 -177
  44. package/dist/agentlib/messages.js.map +0 -1
  45. package/dist/agentlib/model.d.ts +0 -31
  46. package/dist/agentlib/model.d.ts.map +0 -1
  47. package/dist/agentlib/model.js +0 -140
  48. package/dist/agentlib/model.js.map +0 -1
  49. package/dist/agentlib/options.d.ts +0 -58
  50. package/dist/agentlib/options.d.ts.map +0 -1
  51. package/dist/agentlib/options.js +0 -2
  52. package/dist/agentlib/options.js.map +0 -1
  53. package/dist/agentlib/runtime.d.ts +0 -37
  54. package/dist/agentlib/runtime.d.ts.map +0 -1
  55. package/dist/agentlib/runtime.js +0 -216
  56. package/dist/agentlib/runtime.js.map +0 -1
  57. package/dist/agentlib/state.d.ts +0 -114
  58. package/dist/agentlib/state.d.ts.map +0 -1
  59. package/dist/agentlib/state.js +0 -52
  60. package/dist/agentlib/state.js.map +0 -1
  61. package/dist/agentlib/steering.d.ts +0 -23
  62. package/dist/agentlib/steering.d.ts.map +0 -1
  63. package/dist/agentlib/steering.js +0 -48
  64. package/dist/agentlib/steering.js.map +0 -1
  65. package/dist/agentlib/tools.d.ts +0 -33
  66. package/dist/agentlib/tools.d.ts.map +0 -1
  67. package/dist/agentlib/tools.js +0 -245
  68. package/dist/agentlib/tools.js.map +0 -1
  69. package/dist/agentlib/turn.d.ts +0 -82
  70. package/dist/agentlib/turn.d.ts.map +0 -1
  71. package/dist/agentlib/turn.js +0 -253
  72. package/dist/agentlib/turn.js.map +0 -1
  73. package/dist/calls.d.ts +0 -90
  74. package/dist/calls.d.ts.map +0 -1
  75. package/dist/calls.js +0 -235
  76. package/dist/calls.js.map +0 -1
  77. package/dist/claude/index.d.ts +0 -106
  78. package/dist/claude/index.d.ts.map +0 -1
  79. package/dist/claude/index.js +0 -386
  80. package/dist/claude/index.js.map +0 -1
  81. package/dist/client.d.ts +0 -90
  82. package/dist/client.d.ts.map +0 -1
  83. package/dist/client.js +0 -88
  84. package/dist/client.js.map +0 -1
  85. package/dist/common.d.ts +0 -410
  86. package/dist/common.d.ts.map +0 -1
  87. package/dist/common.js +0 -563
  88. package/dist/common.js.map +0 -1
  89. package/dist/companion.d.ts +0 -286
  90. package/dist/companion.d.ts.map +0 -1
  91. package/dist/companion.js +0 -463
  92. package/dist/companion.js.map +0 -1
  93. package/dist/conversation.d.ts +0 -576
  94. package/dist/conversation.d.ts.map +0 -1
  95. package/dist/conversation.js +0 -1476
  96. package/dist/conversation.js.map +0 -1
  97. package/dist/deepseek/barriers.d.ts +0 -11
  98. package/dist/deepseek/barriers.d.ts.map +0 -1
  99. package/dist/deepseek/barriers.js +0 -36
  100. package/dist/deepseek/barriers.js.map +0 -1
  101. package/dist/deepseek/index.d.ts +0 -97
  102. package/dist/deepseek/index.d.ts.map +0 -1
  103. package/dist/deepseek/index.js +0 -603
  104. package/dist/deepseek/index.js.map +0 -1
  105. package/dist/deepseek/persistence.d.ts +0 -83
  106. package/dist/deepseek/persistence.d.ts.map +0 -1
  107. package/dist/deepseek/persistence.js +0 -262
  108. package/dist/deepseek/persistence.js.map +0 -1
  109. package/dist/index.d.ts +0 -14
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -17
  112. package/dist/index.js.map +0 -1
  113. package/dist/langgraph/checkpointer.d.ts +0 -52
  114. package/dist/langgraph/checkpointer.d.ts.map +0 -1
  115. package/dist/langgraph/checkpointer.js +0 -477
  116. package/dist/langgraph/checkpointer.js.map +0 -1
  117. package/dist/langgraph/context.d.ts +0 -10
  118. package/dist/langgraph/context.d.ts.map +0 -1
  119. package/dist/langgraph/context.js +0 -21
  120. package/dist/langgraph/context.js.map +0 -1
  121. package/dist/langgraph/errors.d.ts +0 -16
  122. package/dist/langgraph/errors.d.ts.map +0 -1
  123. package/dist/langgraph/errors.js +0 -30
  124. package/dist/langgraph/errors.js.map +0 -1
  125. package/dist/langgraph/graph.d.ts +0 -25
  126. package/dist/langgraph/graph.d.ts.map +0 -1
  127. package/dist/langgraph/graph.js +0 -378
  128. package/dist/langgraph/graph.js.map +0 -1
  129. package/dist/langgraph/index.d.ts +0 -119
  130. package/dist/langgraph/index.d.ts.map +0 -1
  131. package/dist/langgraph/index.js +0 -325
  132. package/dist/langgraph/index.js.map +0 -1
  133. package/dist/langgraph/keepalive.d.ts +0 -16
  134. package/dist/langgraph/keepalive.d.ts.map +0 -1
  135. package/dist/langgraph/keepalive.js +0 -51
  136. package/dist/langgraph/keepalive.js.map +0 -1
  137. package/dist/langgraph/nodes.d.ts +0 -71
  138. package/dist/langgraph/nodes.d.ts.map +0 -1
  139. package/dist/langgraph/nodes.js +0 -148
  140. package/dist/langgraph/nodes.js.map +0 -1
  141. package/dist/messages.d.ts +0 -18
  142. package/dist/messages.d.ts.map +0 -1
  143. package/dist/messages.js +0 -182
  144. package/dist/messages.js.map +0 -1
  145. package/dist/object.d.ts +0 -213
  146. package/dist/object.d.ts.map +0 -1
  147. package/dist/object.js +0 -309
  148. package/dist/object.js.map +0 -1
  149. package/dist/opencode/db.d.ts +0 -81
  150. package/dist/opencode/db.d.ts.map +0 -1
  151. package/dist/opencode/db.js +0 -249
  152. package/dist/opencode/db.js.map +0 -1
  153. package/dist/opencode/index.d.ts +0 -184
  154. package/dist/opencode/index.d.ts.map +0 -1
  155. package/dist/opencode/index.js +0 -1079
  156. package/dist/opencode/index.js.map +0 -1
  157. package/dist/output.d.ts +0 -25
  158. package/dist/output.d.ts.map +0 -1
  159. package/dist/output.js +0 -99
  160. package/dist/output.js.map +0 -1
  161. package/dist/pi/commits.d.ts +0 -6
  162. package/dist/pi/commits.d.ts.map +0 -1
  163. package/dist/pi/commits.js +0 -3
  164. package/dist/pi/commits.js.map +0 -1
  165. package/dist/steering.d.ts +0 -32
  166. package/dist/steering.d.ts.map +0 -1
  167. package/dist/steering.js +0 -45
  168. package/dist/steering.js.map +0 -1
  169. package/dist/tools.d.ts +0 -267
  170. package/dist/tools.d.ts.map +0 -1
  171. package/dist/tools.js +0 -305
  172. package/dist/tools.js.map +0 -1
  173. package/dist/webhook.d.ts +0 -71
  174. package/dist/webhook.d.ts.map +0 -1
  175. package/dist/webhook.js +0 -102
  176. package/dist/webhook.js.map +0 -1
  177. package/src/agentlib/README.md +0 -229
  178. package/src/agentlib/agent.ts +0 -216
  179. package/src/agentlib/index.ts +0 -16
  180. package/src/agentlib/messages.ts +0 -207
  181. package/src/agentlib/model.ts +0 -156
  182. package/src/agentlib/options.ts +0 -62
  183. package/src/agentlib/runtime.ts +0 -252
  184. package/src/agentlib/state.ts +0 -93
  185. package/src/agentlib/steering.ts +0 -53
  186. package/src/agentlib/tools.ts +0 -355
  187. package/src/agentlib/turn.ts +0 -302
  188. package/src/calls.ts +0 -330
  189. package/src/claude/README.md +0 -107
  190. package/src/claude/index.ts +0 -487
  191. package/src/client.ts +0 -187
  192. package/src/common.ts +0 -766
  193. package/src/companion.ts +0 -675
  194. package/src/conversation.ts +0 -1799
  195. package/src/deepseek/README.md +0 -202
  196. package/src/deepseek/barriers.ts +0 -63
  197. package/src/deepseek/index.ts +0 -740
  198. package/src/deepseek/persistence.ts +0 -337
  199. package/src/index.ts +0 -41
  200. package/src/langgraph/README.md +0 -199
  201. package/src/langgraph/checkpointer.ts +0 -614
  202. package/src/langgraph/context.ts +0 -27
  203. package/src/langgraph/errors.ts +0 -26
  204. package/src/langgraph/graph.ts +0 -422
  205. package/src/langgraph/index.ts +0 -500
  206. package/src/langgraph/keepalive.ts +0 -58
  207. package/src/langgraph/nodes.ts +0 -247
  208. package/src/messages.ts +0 -244
  209. package/src/object.ts +0 -454
  210. package/src/opencode/README.md +0 -249
  211. package/src/opencode/db.ts +0 -387
  212. package/src/opencode/index.ts +0 -1339
  213. package/src/output.ts +0 -116
  214. package/src/pi/README.md +0 -174
  215. package/src/pi/commits.ts +0 -7
  216. package/src/steering.ts +0 -68
  217. package/src/tools.ts +0 -515
  218. package/src/webhook.ts +0 -161
@@ -1,229 +0,0 @@
1
- # agentlib
2
-
3
- [agentlib](https://github.com/restatedev/agentlib) (`@restatedev/agentlib`)
4
- is Restate's own agent library: an agent's loop as an operation of Restate's
5
- generator SDK (`@restatedev/restate-sdk-gen`), with its tools, steering,
6
- interruption, approvals, guardrails, compaction and limits. Restate journals
7
- each model call and tool call it makes, and replays them.
8
-
9
- Unlike the other frameworks here, an agentlib agent runs on the classic
10
- Restate SDK, not in a session object: a virtual object whose `chat` handler
11
- is journaled, and replayed after a crash, so that a model call or a tool
12
- call that finished is not made again. Its conversation is in the object's
13
- key/value state, not in a SQL database. It has the handlers and views of
14
- every agent (`chat`, `messages`, `status`, `steer`, `stop`, `clear`, `sync`,
15
- `signal`, `pending`, `notifications`, `watch`) and their companion, so that
16
- a client (`@restatedev/agents/client`, `follow`) follows it as it follows
17
- any other.
18
-
19
- ## Use
20
-
21
- ```ts
22
- import { serve, tool } from '@restatedev/agents';
23
- import * as agentlib from '@restatedev/agents/agentlib';
24
- import { z } from 'zod';
25
-
26
- const weather = tool({
27
- name: 'get_weather',
28
- description: 'The current weather in a city.',
29
- input: z.object({ city: z.string() }),
30
- run: ({ city }) => `Sunny and 21°C in ${city}`,
31
- });
32
-
33
- const assistant = agentlib.agent({
34
- name: 'assistant',
35
- system: 'Answer briefly.',
36
- tools: [weather],
37
- });
38
- await serve(assistant);
39
- ```
40
-
41
- The same `weather` works in an agent of any framework here; agentlib's own
42
- tools work too, beside it.
43
-
44
- See [`examples/basic/agentlib.ts`](../../../examples/basic/agentlib.ts),
45
- with a transfer that waits for an approval.
46
-
47
- ```sh
48
- npm install @restatedev/agents @restatedev/agentlib@0.2.0 @restatedev/restate-sdk-gen@1.18.2 \
49
- @restatedev/restate-sdk@1.18.2 @ai-sdk/openai # or @ai-sdk/anthropic
50
- ```
51
-
52
- | Option | What |
53
- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
54
- | `model` | `openai/model-id` or `anthropic/model-id` (with `@ai-sdk/openai` or `@ai-sdk/anthropic`), or else `MODEL`, or else `openai/gpt-6-sol`; or a model of agentlib (`aiModel` of `@restatedev/agentlib/provider` for any provider of the AI SDK, `journaledModel` for one of your own) |
55
- | `system` | The instructions (the system prompt): a text, or agentlib's function of the run's context that gives one |
56
- | `tools` | The tools of `@restatedev/agents` (`tool()`, `call`, `send`, `workflow`, `signal`, `subagent`), as every agent takes them, and agentlib's own (`asyncTool`, `serviceTool`, `agentTool`, `handoff`, MCP's...) by the name the model calls them: `[weather, { transfer: asyncTool(...) }]` |
57
- | `approval` | The tools of `@restatedev/agents` that wait for a person's approval before they run: their names, or a function of a call ([Approvals and signals](#approvals-and-signals)) |
58
- | `history` | How the conversation the model gets stays short from turn to turn: `{ maxMessages, maxChars, retainMessages, model }`, or `false` ([A long conversation](#a-long-conversation)) |
59
- | `output` | A zod schema: the answer as data, which `chat` answers with |
60
- | `description` | What it is, for the UI, and for a parent's model: `subagent(agent)` tells it |
61
- | `background` | It works unwatched (a subagent, say): its turn tells its companion at its end only, and takes no steered messages |
62
- | `options` | Options of the object, beside the ones set here (its `retryPolicy`, as every agent's; its state preloads only `meta` and `taken`) |
63
-
64
- Every other option of agentlib's `agent()` goes to it as it is:
65
- `maxSteps`, `maxToolCalls`, `maxOutputTokens`, `compaction`,
66
- `contextWindow`, `toolResults`, `skills`, `finalize`, and the guardrails
67
- `beforeRun`, `beforeStep`, `beforeTool`, `afterTool` and `afterRun`.
68
-
69
- ## Tools
70
-
71
- An agentlib agent takes the tools of `@restatedev/agents`, as every agent
72
- does, and makes each agentlib's own, its calls the generator SDK's on the
73
- classic SDK's context of its invocation:
74
-
75
- | Tool | In an agentlib agent |
76
- | ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
77
- | `call(target, handler, …)` | A call of the handler, by its typed definition (a session object's, an agent's, or any of the classic SDK's): journaled, so a crash replays its answer; stopping the turn cancels it |
78
- | `send(target, handler, …)` | A send, journaled: made once |
79
- | `workflow(target, …)` | A run of the workflow, to its end: a workflow of its own per tool call, unless `key` gives its id; stopping the turn cancels it |
80
- | `signal(name, …)` | A wait for the signal, which `pending` lists and `signal` resolves |
81
- | `subagent(agent)` | A task for an agent of any framework (a pi agent, another agentlib agent...), at its key `<this key>.<task name>`: the same name continues the task; stopping the turn stops the sub-agent's turn |
82
- | `tool({ name, description, input, run })` | `run`, as a journaled step (agentlib's `asyncTool` is one too): a crash replays its result, and an error that is no terminal error fails the attempt, which Restate retries |
83
-
84
- As in every agent, arguments that do not fit a tool's `input` are the
85
- model's to fix, and a terminal error (the tool's own, or a handler's it
86
- calls) is the tool's answer, which the model sees. A `tool()`'s `run` gets
87
- `ctx.key` and `ctx.request`, its `callId` and `idempotencyKey`, but no
88
- `ctx.db` (an agentlib agent has no SQL database) and no `ctx.rpc` or
89
- `ctx.send`: its calls are Restate's tools above, or agentlib's own. A
90
- `tool()` that reaches for them fails the turn, saying so. A `key` given
91
- as a function gets that context too, as a journaled step.
92
-
93
- An agent of another framework hands an agentlib agent a task with
94
- `subagent(assistant)`, as any agent; `deliver` and `webhook` send it
95
- messages as they send any agent's.
96
-
97
- agentlib's own `serviceTool`, and the generator SDK's typed `client`, take
98
- the generator SDK's descriptors (`iface`, `service`, `object`), which a
99
- definition of the classic SDK (a session object, an agent) is not: for
100
- those, `call` and `subagent` above.
101
-
102
- ## Through crashes
103
-
104
- A crash, a restart, a deployment or a suspension replays `chat`'s journal:
105
- each model call (`aiModel` journals it, as a `run`) and each tool call that
106
- finished returns what it returned, without being made again, and the run
107
- goes on from where it got to. A tool's own I/O is journaled as agentlib
108
- journals it (`asyncTool`'s `execute` is a `run`, with `callId` for an
109
- idempotency key). [`e2e/agentlib.ts`](../../../e2e/agentlib.ts) kills the
110
- service mid-turn and checks that the model was asked once per step.
111
-
112
- agentlib saves a turn's messages when its run ends; until then, `messages`
113
- shows the turn as it goes: its message, its tool calls with their results,
114
- and the messages steered to it. Once the turn ends, its messages are as the
115
- run saved them (the model's text beside its tool calls, and its answer,
116
- come then), under the same ids.
117
-
118
- ## Approvals and signals
119
-
120
- `approval` names the tools of `@restatedev/agents` whose calls wait for a
121
- person's approval before they run (or is a function of a call, `{ name,
122
- args }`, that says whether it does), as the DeepSeek Harness's option does:
123
-
124
- ```ts
125
- agentlib.agent({ name: 'assistant', tools: [weather, transfer], approval: ['transfer'] });
126
- ```
127
-
128
- Such a call waits for the signal `approval`, as do agentlib's own tools
129
- with `needsApproval`, its `humanApprovalTool`, and a tool's
130
- `context.approve`: `pending` lists the wait, with the tool and its input,
131
- and `signal` approves it (`true`, `{"approved": true}`, or a text such as
132
- `approved`, `yes` or `ok`) or denies it (anything else), and the model is
133
- told it was denied.
134
-
135
- ```sh
136
- curl localhost:8080/assistant/alice/pending
137
- # [{"id": "inv_1f…:assistant:approval:call_01:0", "name": "approval", "input": {"tool": "transfer", "input": {"to": "Bob", "euros": 50}}, "since": "…"}]
138
- curl localhost:8080/assistant/alice/signal --json '{"name": "approval", "value": "approved"}'
139
- ```
140
-
141
- ## Steering and stopping
142
-
143
- A message sent to `steer` while a turn runs reaches the run as agentlib's
144
- steering (`controls.steering`) at the turn's next publish (a tool call's
145
- start or end): agentlib places it after the current round of tool calls,
146
- and the model answers it in the same turn. One that comes too late (the
147
- model writes its final answer) is answered as a turn of its own, after the
148
- turn. `stop` cancels the turn's invocation, as for every agent: the run
149
- ends cancelled, with its open tool calls, and the next turn's model sees
150
- the turn's message, the messages steered to it that it took, and that it
151
- ended `Cancelled: …` (not its tool calls, whose results may be missing).
152
-
153
- ## Models
154
-
155
- `openai/…` and `anthropic/…` are agentlib's `aiModel` on the AI SDK's
156
- provider (`@ai-sdk/openai`, on OpenAI's Responses API, and
157
- `@ai-sdk/anthropic`), loaded when the first message comes. Any other
158
- provider of the AI SDK works as a model you give:
159
-
160
- ```ts
161
- import { aiModel } from '@restatedev/agentlib/provider';
162
- import { google } from '@ai-sdk/google';
163
-
164
- agentlib.agent({ name: 'assistant', model: aiModel({ model: google('<model-id>') }) });
165
- ```
166
-
167
- A provider's refusal that a retry does not change (a missing or wrong API
168
- key, an unknown model, a request it rejects: an answer 4xx) ends the message
169
- with HTTP 424, as for every agent, and the conversation shows it unanswered.
170
- Any other failure of a model by name (an outage, a rate limit) fails the attempt, and Restate retries it, as
171
- for every agent: the model has no retry limit of its own. A model you give
172
- retries as you set it (`aiModel`'s `retry`; agentlib's default is 3
173
- attempts, then the message fails, `Failed: …`). An `anthropic/…` model is
174
- sent the tools' schemas without their numbers' bounds, which the tools still
175
- check: agentlib 0.1.0 asked Anthropic for strict tools, which it refuses with
176
- bounded numbers (agentlib's own `read_tool_result` has them).
177
-
178
- ## A long conversation
179
-
180
- The model gets the conversation as agentlib's `LazyStateConversation` keeps
181
- it: at a turn's start, once its messages since the last summary pass 64
182
- (or 64 000 characters), the earliest are summarized by the agent's model,
183
- and the latest 12 stay as they are, from a message of the user's on. The
184
- summary is kept, and the turns after build on it, so the model's input
185
- stays bounded, and so does what each turn loads. `history` sets it:
186
-
187
- ```ts
188
- agentlib.agent({
189
- name: 'assistant',
190
- history: { maxMessages: 200, maxChars: 200_000, retainMessages: 40 },
191
- });
192
- agentlib.agent({ name: 'assistant', history: false }); // the whole conversation, every turn
193
- ```
194
-
195
- `history`'s `model` summarizes with another model than the agent's (a
196
- cheaper one, say). `messages` keeps every turn as it was said, whatever
197
- the model gets. Within a turn, agentlib's own `compaction` and
198
- `contextWindow` keep a long run within the model's window.
199
-
200
- ## State
201
-
202
- The conversation is in the object's state: the model's, in chunks of 32
203
- (`t/<n>`) with its count and summary (`t/meta`), and the messages as
204
- clients read them, one key each (`c/<id>`), beside `meta`. An invocation
205
- starts with `meta`, `taken` and `t/meta` alone, and reads the rest as it
206
- needs it: `messages`, a page; `chat`, the messages since the summary. Each
207
- read is journaled with what it read, as any state read of a journaled
208
- handler is: a turn's journal has the conversation it loaded.
209
-
210
- ## Not here
211
-
212
- - **`window`, `budget`, `summarize`, `schema`** (the conversation of turns,
213
- and tables of your own): there is no SQL database; `history` keeps a
214
- long conversation short ([A long conversation](#a-long-conversation)).
215
- - **`ctx.db`, `ctx.rpc` and `ctx.send` in a `tool()`**: see [Tools](#tools).
216
- - **A killed turn** (out of retries, or killed by an operator) is closed by
217
- the next message, `Ended: …`, not by the companion as it finds it gone.
218
-
219
- ## Packages
220
-
221
- `@restatedev/agentlib` (0.1.x) and `@restatedev/restate-sdk-gen`
222
- (1.18.2, the SDK @restatedev/sessions pins) are optional peer
223
- dependencies, as are `@ai-sdk/openai` and `@ai-sdk/anthropic`. agentlib
224
- runs on the copy of `@restatedev/restate-sdk` it finds, which must be
225
- @restatedev/sessions' own (1.18.2): install `@restatedev/restate-sdk@1.18.2`
226
- with it, as above, and npm installs one for all of them. On two copies (npm
227
- puts a newer SDK beside sessions' own for agentlib, without it), an agent
228
- refuses to start, saying so; `@restatedev/agents` asks for no SDK of its
229
- own, so a project of another framework keeps whichever SDK it has.
@@ -1,216 +0,0 @@
1
- // The agentlib agent's virtual object: `chat`, which answers with agentlib's
2
- // run, and the handlers and views that every agent here has.
3
- import { GuardrailError } from '@restatedev/agentlib';
4
- import { sdk as restate } from '@restatedev/sessions/internal';
5
- import { type Messages, type MessagesRequest, messageSerde } from '../common.ts';
6
- import {
7
- type Notifications,
8
- type Resolved,
9
- type Signal,
10
- type Steer,
11
- type Steered,
12
- type Waiting,
13
- type Watch,
14
- withCompanion,
15
- } from '../companion.ts';
16
- import type { Status, Stopped, Synced, SyncRequest } from '../object.ts';
17
- import { readMessages } from './messages.ts';
18
- import type { Definition, Options } from './options.ts';
19
- import { Runtime } from './runtime.ts';
20
- import {
21
- callOwn,
22
- companionAt,
23
- CONVERSATION_META,
24
- emptyMeta,
25
- META,
26
- type Meta,
27
- TAKEN,
28
- } from './state.ts';
29
-
30
- type Exclusive = restate.ObjectContext;
31
- type Shared = restate.ObjectSharedContext;
32
-
33
- /**
34
- * The options of every agentlib agent's object. An invocation starts with
35
- * the small keys only, not the whole conversation (each message is a key of
36
- * its own). It retries as every agent does: soon after a failure, then twice
37
- * as long each time, up to 10 seconds apart, for weeks.
38
- */
39
- const OPTIONS = {
40
- state: { preload: [META, TAKEN, CONVERSATION_META] },
41
- retryPolicy: {
42
- initialInterval: 50,
43
- exponentiationFactor: 2,
44
- maxInterval: 10_000,
45
- maxAttempts: 100_000,
46
- },
47
- } satisfies restate.ObjectOptions;
48
-
49
- /** A handler that takes a message as plain text or as a JSON string. */
50
- const TEXT_INPUT = { input: messageSerde, accept: '*/*' };
51
-
52
- /**
53
- * An agent of agentlib: a virtual object `name` of the classic Restate SDK,
54
- * with one conversation per key, in its state. `chat` answers a message with
55
- * agentlib's run of the agent, journaled: after a crash, Restate replays it,
56
- * so a model call or a tool call that finished is not made again. It has the
57
- * views of every agent, and its companion, which `serve` serves beside it.
58
- *
59
- * A tool call that needs approval waits for the signal `approval`: `pending`
60
- * lists it, and `signal` approves it (`true`, `"approved"`, `{ "approved":
61
- * true }`) or denies it (anything else).
62
- */
63
- export function agent<P extends string, O = string>(definition: Options<O> & Definition<P>) {
64
- const { name, description, background = false, options, metadata, ...agentOptions } = definition;
65
- checkOneSdk(name);
66
- const runtime = new Runtime<O>(name, background, agentOptions);
67
-
68
- const object = restate.object({
69
- name,
70
- description,
71
- metadata,
72
- handlers: {
73
- chat: restate.handlers.object.exclusive(TEXT_INPUT, (ctx: Exclusive, text: string) =>
74
- runtime.answer(ctx, text),
75
- ),
76
- steered: restate.handlers.object.exclusive(
77
- { ingressPrivate: true },
78
- (ctx: Exclusive, message: Steer) => answerSteered(runtime, ctx, message),
79
- ),
80
- erase: restate.handlers.object.exclusive({ ingressPrivate: true }, erase),
81
- messages: restate.handlers.object.shared(messages),
82
- status: restate.handlers.object.shared(status),
83
- pending: restate.handlers.object.shared(pending),
84
- signal: restate.handlers.object.shared(signal),
85
- stop: restate.handlers.object.shared(stop),
86
- clear: restate.handlers.object.shared(clear),
87
- steer: restate.handlers.object.shared(TEXT_INPUT, steer),
88
- notifications: restate.handlers.object.shared(notifications),
89
- watch: restate.handlers.object.shared(watch),
90
- sync: restate.handlers.object.shared(sync),
91
- },
92
- options: { ...OPTIONS, ...options },
93
- });
94
- return withCompanion(object);
95
- }
96
-
97
- /**
98
- * Checks that agentlib runs on the same copy of the Restate SDK as
99
- * @restatedev/sessions. With two copies, agentlib's terminal errors are not
100
- * the SDK's `TerminalError`, so a failed turn would look retryable.
101
- */
102
- function checkOneSdk(name: string) {
103
- // Anywhere up the chain: agentlib's errors may have their own base (0.2.0's
104
- // `GuardrailError` extends `ToolError`).
105
- if (GuardrailError.prototype instanceof restate.TerminalError) return;
106
- throw new Error(
107
- `${name}: @restatedev/agentlib runs on another copy of @restatedev/restate-sdk ` +
108
- 'than @restatedev/sessions. Install @restatedev/restate-sdk@1.18.2 ' +
109
- '(the version @restatedev/sessions pins) beside them.',
110
- );
111
- }
112
-
113
- // The private handlers.
114
-
115
- /**
116
- * A message steered to a turn (`steer`), which the companion sent here as it
117
- * came, so that it keeps its place in the key's queue: answered as a turn of
118
- * its own, unless the turn it was steered to took it.
119
- */
120
- async function answerSteered<O>(runtime: Runtime<O>, ctx: Exclusive, { id, text }: Steer) {
121
- const taken = (await ctx.get<string[]>(TAKEN)) ?? [];
122
- if (!taken.includes(id)) {
123
- await runtime.answer(ctx, text);
124
- return;
125
- }
126
- const left = taken.filter((other) => other !== id);
127
- if (left.length > 0) ctx.set(TAKEN, left);
128
- else ctx.clear(TAKEN);
129
- }
130
-
131
- /**
132
- * `clear`'s work, once the messages before it are answered: forgets the
133
- * conversation. Its ids go on from where they got to.
134
- */
135
- async function erase(ctx: Exclusive) {
136
- const meta = (await ctx.get<Meta>(META)) ?? emptyMeta();
137
- const next = meta.chats + (meta.live?.n ?? 0);
138
- ctx.clearAll();
139
- const cleared: Meta = { chats: next, cursor: meta.cursor + 1, first: next };
140
- ctx.set(META, cleared);
141
- await companionAt(ctx).reset();
142
- }
143
-
144
- // The views: they run beside the turn being answered.
145
-
146
- /** The conversation, a page at a time, or what is new or changed since a cursor. */
147
- async function messages(ctx: Shared, request?: MessagesRequest | null): Promise<Messages> {
148
- return readMessages(ctx, request ?? {});
149
- }
150
-
151
- /** What the agent is doing: the message it answers, its waits, and the messages steered to it. */
152
- async function status(ctx: Shared): Promise<Status> {
153
- return companionAt(ctx).status();
154
- }
155
-
156
- /** The waits of the agent's tools. */
157
- async function pending(ctx: Shared): Promise<Waiting[]> {
158
- return companionAt(ctx).pending();
159
- }
160
-
161
- /** Resolves the wait of an id, or else the oldest wait for a name. */
162
- async function signal(ctx: Shared, wanted: Signal): Promise<Resolved> {
163
- return companionAt(ctx).resolve(wanted);
164
- }
165
-
166
- /** Cancels the invocation of the message being answered, and says which one, if any. */
167
- async function stop(ctx: Shared): Promise<Stopped> {
168
- const turn = (await companionAt(ctx).status()).answering;
169
- if (!turn) return { stopped: null };
170
- ctx.cancel(restate.InvocationIdParser.fromString(turn.invocationId));
171
- return { stopped: turn.invocationId };
172
- }
173
-
174
- /** Stops the message being answered, then forgets the conversation. */
175
- async function clear(ctx: Shared): Promise<Stopped> {
176
- const stopped = await stop(ctx);
177
- await callOwn(ctx, 'erase');
178
- return stopped;
179
- }
180
-
181
- /**
182
- * Sends a message to the turn being answered, which takes it at its next
183
- * step. Otherwise it is answered as a turn of its own.
184
- */
185
- async function steer(ctx: Shared, text: string): Promise<Steered> {
186
- return companionAt(ctx).steer({ id: ctx.request().id, text });
187
- }
188
-
189
- /** The conversation's revision. */
190
- async function notifications(ctx: Shared): Promise<Notifications> {
191
- return companionAt(ctx).notifications();
192
- }
193
-
194
- /** The revision, once there is one newer than `revision`, or at the timeout. */
195
- async function watch(ctx: Shared, request: Watch): Promise<Notifications> {
196
- return companionAt(ctx).watch(request);
197
- }
198
-
199
- /**
200
- * The conversation since a cursor, the status and the revision. With
201
- * `revision`, it waits until there is a newer one.
202
- */
203
- async function sync(ctx: Shared, request?: SyncRequest | null): Promise<Synced> {
204
- const { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view } = request ?? {};
205
- if (revision !== undefined) await companionAt(ctx).watch({ revision, timeoutSeconds });
206
-
207
- // The revision first: a change after it shows in the next sync.
208
- const now = await companionAt(ctx).notifications();
209
- const current = await companionAt(ctx).status();
210
- // A call of its own: it reads the state as it is now, while this view
211
- // read its state as it started.
212
- const page: MessagesRequest = { cursor, limit };
213
- if (view) page.view = view;
214
- const changed = await callOwn<Messages>(ctx, 'messages', page);
215
- return { revision: now.revision, status: current, ...changed };
216
- }
@@ -1,16 +0,0 @@
1
- // @restatedev/agents/agentlib: an agent of Restate's agentlib
2
- // (@restatedev/agentlib) in a virtual object of the classic Restate SDK,
3
- // journaled and replayed, with the handlers and views of every agent here.
4
- //
5
- // const assistant = agentlib.agent({ name: 'assistant', tools: [weather] });
6
- // await serve(assistant);
7
- //
8
- // The modules: agent.ts (the object, its handlers and views), runtime.ts (a
9
- // turn, from start to end), turn.ts (a turn's messages and the model's
10
- // conversation), steering.ts, messages.ts (the messages clients read),
11
- // model.ts, tools.ts (the tools of @restatedev/agents, made agentlib's), and
12
- // state.ts (the object's state).
13
- export { agent } from './agent.ts';
14
- export { DEFAULT_MODEL } from './model.ts';
15
- export type { Definition, Options } from './options.ts';
16
- export type { AgentlibContext, AgentlibTool, Approval, Tools } from './tools.ts';
@@ -1,207 +0,0 @@
1
- // The agentlib agent's messages as clients read them: rendered from
2
- // agentlib's messages, kept one per key (`c/<id>`), and paged by the
3
- // `messages` view.
4
- import type { Message } from '@restatedev/agentlib';
5
- import { sdk as restate } from '@restatedev/sessions/internal';
6
- import type { ChatMessage, Messages, MessagesRequest, Part } from '../common.ts';
7
- import { emptyMeta, entryKey, META, type Meta } from './state.ts';
8
-
9
- type ToolPart = Extract<Part, { type: 'tool' }>;
10
- type ToolResult = Extract<Message, { role: 'tool' }>['result'];
11
-
12
- /** A message as clients read it, without its id (that is its key), as the agent stores it. */
13
- export interface Entry {
14
- role: ChatMessage['role'];
15
- parts: Part[];
16
- /** The cursor of the message's latest change. */
17
- at: number;
18
- /** It is its turn's message from the user (`view: 'summary'` shows these). */
19
- prompt?: true;
20
- /** It is its turn's answer (`view: 'summary'` shows these). */
21
- answer?: true;
22
- }
23
-
24
- /** An entry before it is stored, without its cursor. */
25
- export type Rendered = Omit<Entry, 'at'>;
26
-
27
- /** Returns what a tool's result says, as a tool part's output. */
28
- export function outputOf(result: ToolResult): Pick<ToolPart, 'output' | 'error'> {
29
- switch (result.status) {
30
- case 'success': {
31
- const { output } = result;
32
- return { output: typeof output === 'string' ? output : JSON.stringify(output) };
33
- }
34
- case 'error':
35
- return { output: `Error: ${result.message}`, error: true };
36
- case 'denied':
37
- return { output: `Denied: ${result.message}`, error: true };
38
- case 'cancelled':
39
- return { output: `Cancelled: ${result.message}`, error: true };
40
- case 'pending':
41
- default:
42
- return {};
43
- }
44
- }
45
-
46
- /** A message steered to a turn, as agentlib notes it in the conversation. */
47
- export function steeringNote(message: string): string {
48
- return JSON.stringify({ source: 'agent-runtime', type: 'steering', message });
49
- }
50
-
51
- /** Returns a user message's text: for agentlib's steering note, the steered message. */
52
- export function userText(content: string): string {
53
- if (!content.startsWith('{')) return content;
54
- try {
55
- const note = JSON.parse(content) as { source?: unknown; type?: unknown; message?: unknown };
56
- const steering = note.source === 'agent-runtime' && note.type === 'steering';
57
- if (steering && typeof note.message === 'string') return note.message;
58
- } catch {
59
- // Not JSON: the user's own text.
60
- }
61
- return content;
62
- }
63
-
64
- /**
65
- * Renders a turn's messages of agentlib as clients read them: each reply
66
- * with its tool calls, each call with its result as its output. The first
67
- * message is the turn's prompt, and the last reply its answer.
68
- */
69
- export function render(messages: readonly Message[]): Rendered[] {
70
- const rendered: Rendered[] = [];
71
- const callParts = new Map<string, ToolPart>();
72
-
73
- for (const message of messages) {
74
- switch (message.role) {
75
- case 'user':
76
- rendered.push({ role: 'user', parts: [{ type: 'text', text: userText(message.content) }] });
77
- break;
78
- case 'assistant': {
79
- const parts: Part[] = [];
80
- if (message.content) parts.push({ type: 'text', text: message.content });
81
- for (const call of message.calls ?? []) {
82
- const part: ToolPart = { type: 'tool', id: call.id, name: call.name, input: call.input };
83
- callParts.set(call.id, part);
84
- parts.push(part);
85
- }
86
- if (parts.length === 0) parts.push({ type: 'text', text: '' });
87
- rendered.push({ role: 'assistant', parts });
88
- break;
89
- }
90
- case 'tool': {
91
- const part = callParts.get(message.callId);
92
- if (part) Object.assign(part, outputOf(message.result));
93
- break;
94
- }
95
- }
96
- }
97
-
98
- const first = rendered[0];
99
- if (first?.role === 'user') first.prompt = true;
100
- const last = rendered.at(-1);
101
- if (last?.role === 'assistant') last.answer = true;
102
- return rendered;
103
- }
104
-
105
- /** How many messages one read of the `messages` view fetches at once. */
106
- const BATCH = 25;
107
-
108
- type View = restate.ObjectSharedContext;
109
-
110
- /**
111
- * Reads the entry `id`. At runtime, `get` returns a RestatePromise, although
112
- * its type says Promise.
113
- */
114
- function readEntry(ctx: View, id: number) {
115
- return ctx.get<Entry>(entryKey(id)) as unknown as restate.RestatePromise<Entry | null>;
116
- }
117
-
118
- /** Reads the entries of `ids` at once. A missing entry is `null`. */
119
- function readEntries(ctx: View, ids: number[]) {
120
- return restate.RestatePromise.all(ids.map((id) => readEntry(ctx, id)));
121
- }
122
-
123
- /** Yields the ids from `from` down to `to` (included), newest first, a batch at a time. */
124
- function* batches(from: number, to: number): Generator<number[]> {
125
- for (let id = from; id >= to; id -= BATCH) {
126
- const size = Math.min(BATCH, id - to + 1);
127
- yield Array.from({ length: size }, (_, i) => id - i);
128
- }
129
- }
130
-
131
- const chatMessage = (id: number, entry: Entry): ChatMessage => ({
132
- id,
133
- role: entry.role,
134
- parts: entry.parts,
135
- });
136
-
137
- /** Whether `entry` belongs in the view that `request` asks for. */
138
- function inView(request: MessagesRequest, entry: Entry): boolean {
139
- if (request.view !== 'summary') return true;
140
- return entry.prompt === true || entry.answer === true;
141
- }
142
-
143
- /** The `messages` view: a page of the conversation, or what changed since a cursor. */
144
- export async function readMessages(ctx: View, request: MessagesRequest = {}): Promise<Messages> {
145
- const meta = (await ctx.get<Meta>(META)) ?? emptyMeta();
146
- const page =
147
- request.cursor === undefined
148
- ? await pageBefore(ctx, meta, request)
149
- : await changedSince(ctx, meta, request);
150
- if (meta.first !== undefined) page.first = meta.first;
151
- return page;
152
- }
153
-
154
- /** The id after the conversation's last message (the turn being answered included). */
155
- const endOf = (meta: Meta) => meta.chats + (meta.live?.n ?? 0);
156
-
157
- /** The latest messages before `request.before` (by default, the end), at most `request.limit`. */
158
- async function pageBefore(ctx: View, meta: Meta, request: MessagesRequest): Promise<Messages> {
159
- const first = meta.first ?? 0;
160
- const limit = request.limit ?? 50;
161
- const messages: ChatMessage[] = [];
162
- // The oldest id read so far: there are more if older ids are left.
163
- let oldest = Math.min(request.before ?? endOf(meta), endOf(meta));
164
-
165
- reading: for (const ids of batches(oldest - 1, first)) {
166
- const entries = await readEntries(ctx, ids);
167
- for (const [i, id] of ids.entries()) {
168
- if (messages.length >= limit) break reading;
169
- oldest = id;
170
- const entry = entries[i];
171
- if (entry && inView(request, entry)) messages.push(chatMessage(id, entry));
172
- }
173
- }
174
-
175
- return { messages: messages.toReversed(), more: oldest > first, cursor: meta.cursor };
176
- }
177
-
178
- /**
179
- * The messages new or changed since `request.cursor`, in the order they
180
- * changed, at most `request.limit`. An ended turn's messages are rewritten
181
- * in order as it ends, so the scan stops at the first message, older than
182
- * the turn being answered, that did not change.
183
- */
184
- async function changedSince(ctx: View, meta: Meta, request: MessagesRequest): Promise<Messages> {
185
- const cursor = request.cursor ?? 0;
186
- const limit = request.limit ?? 50;
187
- const liveFrom = meta.live?.from ?? endOf(meta);
188
- const changed: [number, Entry][] = [];
189
-
190
- scanning: for (const ids of batches(endOf(meta) - 1, meta.first ?? 0)) {
191
- const entries = await readEntries(ctx, ids);
192
- for (const [i, id] of ids.entries()) {
193
- const entry = entries[i];
194
- if (!entry) continue;
195
- if (entry.at > cursor) changed.push([id, entry]);
196
- else if (id < liveFrom) break scanning;
197
- }
198
- }
199
-
200
- const ordered = changed
201
- .toSorted(([, a], [, b]) => a.at - b.at)
202
- .filter(([, entry]) => inView(request, entry));
203
- const page = ordered.slice(0, limit);
204
- const more = ordered.length > limit;
205
- const next = more ? page.at(-1)![1].at : meta.cursor;
206
- return { messages: page.map(([id, entry]) => chatMessage(id, entry)), more, cursor: next };
207
- }