@restatedev/agents 0.11.2 → 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 -241
  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 -333
  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,386 +0,0 @@
1
- // Claude agents in Restate virtual objects, on the tool runner of the
2
- // Anthropic SDK (`client.beta.messages.toolRunner`): the conversation is the
3
- // object's conversation of turns (../conversation.ts), whose items are the
4
- // SDK's messages (`BetaMessageParam`).
5
- //
6
- // const assistant = claude.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
7
- //
8
- // or a handler of an object of your own: `handlers: { chat: claude.chat() }`,
9
- // with options for each invocation: `claude.chat(async (ctx) => ({ system }))`,
10
- // or a prompt of your own handler: `claude.prompt(ctx, text, options)`
11
- //
12
- // The model is `model`, or else MODEL, or else anthropic/claude-sonnet-5-5,
13
- // with ANTHROPIC_API_KEY.
14
- //
15
- // The handler is not replayed: a retried attempt (a crash, a lost connection)
16
- // runs again from the start, and starts the runner with what the model sees
17
- // of the conversation (`history()`: the earlier turns as their prompts and
18
- // answers, the latest whole):
19
- // - Each reply of the model is stored before its tools run, and their results
20
- // before the next request. So a crash during the tools resumes them with the
21
- // same tool call ids (`callId(context)`), without asking the model again,
22
- // and a tool passes the id on to stay idempotent. A stored final reply is
23
- // the answer: the model is not asked for it again.
24
- // - A tool's error fails the attempt, which Restate retries; but the SDK's
25
- // `ToolError`, which is meant for the model, is the tool's result.
26
- // - A message is answered once per invocation (`answerOnce`).
27
- // - A reply cut off at `maxTokens`, declined, or past the model's context
28
- // window ends the turn: its tool calls do not run, and the handler fails
29
- // with a terminal error.
30
- // - With `output`, a model with structured outputs is asked for it natively:
31
- // each request of the run has its JSON schema (`output_config.format`),
32
- // which holds the final reply to it, and tool calls go on as before. The
33
- // reply is checked all the same (output.ts).
34
- import * as restate from '@restatedev/sessions';
35
- import { ScopeKey } from '@restatedev/sessions/internal';
36
- import Anthropic from '@anthropic-ai/sdk';
37
- import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod';
38
- import { ToolError } from '@anthropic-ai/sdk/lib/tools/ToolError';
39
- import { chatHandler, CLAUDE_MODEL, configured, fromTool, keepAlive, modelIdOf, modelOf, RETURNED_UNRECORDED, toolCallStarted, stopSignalOf, NO_ANSWER, } from '../common.js';
40
- import { answerOnce } from '../conversation.js';
41
- import { takeSteers } from '../steering.js';
42
- import { conversationView } from '../messages.js';
43
- import { withChecked } from '../output.js';
44
- import { sessionObject } from '../object.js';
45
- import { isTool, jsonSchemaOf } from '../tools.js';
46
- /** The id of the tool call a tool runs for: the runner always passes it. */
47
- export const callId = (context) => {
48
- if (!context)
49
- throw new Error('a tool call without its context');
50
- return context.toolUse.id;
51
- };
52
- /**
53
- * `messages` as the API takes them: it refuses an empty text, and an
54
- * assistant's message with no content but the last. The model may reply
55
- * with nothing (stored as it came): sent back, such a reply says so.
56
- */
57
- const sendable = (messages) => messages.map((m) => {
58
- if (m.role !== 'assistant')
59
- return m;
60
- if (typeof m.content === 'string')
61
- return m.content.trim() ? m : { ...m, content: NO_ANSWER };
62
- const content = m.content.filter((b) => b.type !== 'text' || b.text.trim() !== '');
63
- if (content.length === 0)
64
- return { ...m, content: NO_ANSWER };
65
- return content.length === m.content.length ? m : { ...m, content };
66
- });
67
- /** The text of stored content, without its tool calls and results. */
68
- const storedText = (content) => typeof content === 'string' ? content : (content ?? []).flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('');
69
- /**
70
- * Claude's items: the SDK's messages, as JSON. A user's text is said by the
71
- * user, an assistant's by the assistant, and its `tool_use` blocks are its
72
- * calls; a `tool_result` is a result. A server tool's blocks (and a
73
- * `system` message) say nothing: they leave no open call the API would
74
- * refuse a result for.
75
- */
76
- export const items = {
77
- dump: (message) => JSON.stringify(message),
78
- load: (stored) => {
79
- // Only a message of the API's (a role and its content): another framework's row is not one.
80
- const message = JSON.parse(stored);
81
- const { role, content, ...rest } = message;
82
- if ((role !== 'user' && role !== 'assistant') || (typeof content !== 'string' && !Array.isArray(content)))
83
- throw new Error('not a message of the Claude API (a role and its content)');
84
- if (Object.keys(rest).length > 0)
85
- throw new Error(`not a message of the Claude API: ${Object.keys(rest).join(', ')}`);
86
- return message;
87
- },
88
- prompt: (text) => ({ role: 'user', content: text }),
89
- // The API refuses an empty text: an empty answer, as the model sees it later, says so.
90
- reply: (text) => ({ role: 'assistant', content: text.trim() ? text : NO_ANSWER }),
91
- // Every result of a reply in one message, as the API wants them.
92
- results: (results) => results.length === 0
93
- ? []
94
- : [
95
- {
96
- role: 'user',
97
- content: results.map(([call, output]) => ({
98
- type: 'tool_result',
99
- tool_use_id: call.id,
100
- content: output,
101
- ...(output === RETURNED_UNRECORDED ? {} : { is_error: true }),
102
- })),
103
- },
104
- ],
105
- read: (message) => {
106
- if (message.role !== 'user' && message.role !== 'assistant')
107
- return {};
108
- const { role, content } = message;
109
- if (typeof content === 'string')
110
- return { said: [role, content] };
111
- const texts = content.filter((b) => b.type === 'text');
112
- const calls = content.flatMap((b) => (b.type === 'tool_use' ? [{ id: b.id, name: b.name, input: b.input }] : []));
113
- const results = content.flatMap((b) => b.type === 'tool_result'
114
- ? [{ id: b.tool_use_id, output: storedText(b.content), error: b.is_error === true }]
115
- : []);
116
- // Each reply of the model is a message of its own, its tool calls' too (as
117
- // the views gave them before); a message of results only says nothing.
118
- const said = role === 'assistant' || texts.length > 0;
119
- return {
120
- ...(said ? { said: [role, texts.map((b) => b.text).join('')] } : {}),
121
- calls,
122
- results,
123
- };
124
- },
125
- };
126
- /**
127
- * `tools`, whose errors fail the attempt: the runner would hand a thrown error
128
- * to the model as the tool's result, so each one is kept, for `check()` to
129
- * throw once the tools ran. The SDK's `ToolError` is for the model: the
130
- * runner hands it over as the tool's result.
131
- */
132
- function failing(ctx, tools) {
133
- let failure;
134
- return {
135
- tools: tools.map((tool) => ({
136
- ...tool,
137
- run: async (args, context) => {
138
- try {
139
- return await tool.run(args, context);
140
- }
141
- catch (e) {
142
- if (e instanceof ToolError)
143
- throw e;
144
- fromTool(ctx, e);
145
- failure ??= e;
146
- throw e;
147
- }
148
- },
149
- })),
150
- check: () => {
151
- if (failure !== undefined)
152
- throw failure;
153
- },
154
- };
155
- }
156
- const textOf = (content) => content
157
- .filter((c) => c.type === 'text')
158
- .map((c) => c.text)
159
- .join('');
160
- /**
161
- * The run of `agent` on the conversation: from the stored turn on, each
162
- * reply with tool calls stored before its tools run, and their results
163
- * after; each such write published as it commits, by the conversation (for
164
- * the clients that follow it), and the final reply stored with the answer. At each step (before a request that follows the
165
- * prompt or the tools' results), it takes the messages steered to the turn
166
- * (`takeSteers`): the request then goes out from the conversation's
167
- * history, which has them after the tools' results.
168
- */
169
- const runOf = (ctx, agent) => async (conversation) => {
170
- const { client, model, maxTokens, effort, system, format } = agent;
171
- const turn = conversation.turn;
172
- for (;;) {
173
- // A stored final reply is the answer: the model is not asked for it again.
174
- const final = turn.finalReply();
175
- if (final !== undefined)
176
- return final;
177
- // A paused reply goes back as the last message, which a steered one would not leave it.
178
- if (turn.entries.at(-1).parsed?.said?.[0] !== 'assistant')
179
- await takeSteers(ctx, conversation);
180
- const { tools, check } = failing(ctx, agent.tools);
181
- const runner = client.beta.messages.toolRunner({
182
- model,
183
- max_tokens: maxTokens,
184
- ...(effort === undefined && format === undefined ? {} : { output_config: { effort, format } }),
185
- ...(system === undefined ? {} : { system }),
186
- tools,
187
- messages: sendable(conversation.history()),
188
- // The conversation is the session's: each request carries all of it, as stored, and no message thread
189
- // of the API's holds a copy that a crash or a steered message would leave behind.
190
- thread: false,
191
- }, { signal: stopSignalOf(ctx) });
192
- /** A step: the messages steered to the turn go into the next request, after the tools' results. */
193
- const step = async () => {
194
- if ((await takeSteers(ctx, conversation)).length === 0)
195
- return;
196
- // The runner leaves the history to its caller, who changed it: the reply, its results and the messages.
197
- runner.setMessagesParams((params) => ({ ...params, messages: sendable(conversation.history()) }));
198
- };
199
- // A reply whose tools did not finish (a crash): run them, with the same
200
- // ids, once the calls whose results are stored are settled, as for any
201
- // reply: else one of its calls could take the id of an identical call
202
- // answered before.
203
- if (turn.openCalls().length > 0) {
204
- await toolCallStarted(ctx);
205
- const results = await runner.generateToolResponse();
206
- check();
207
- if (results) {
208
- await turn.append(results);
209
- runner.pushMessages(results);
210
- }
211
- await step();
212
- }
213
- let paused = false;
214
- for await (const message of requests(ctx, runner)) {
215
- // A reply that cannot go on ends the turn, whose tool calls do not run.
216
- const stopped = stoppedShort(message, maxTokens);
217
- if (stopped)
218
- throw new restate.TerminalError(stopped);
219
- const said = { role: 'assistant', content: message.content };
220
- // Paused (a server tool's long turn): a step of the turn, not a reply to
221
- // end it with, and the model goes on from it.
222
- if (message.stop_reason === 'pause_turn') {
223
- // Stored before the model goes on: a crash in a server tool's long turn goes on from it, rather than
224
- // ask the whole of it again.
225
- await turn.append(said);
226
- await conversation.flush();
227
- paused = true;
228
- break;
229
- }
230
- // A reply with tool calls commits, and is published, before its tools run; the final reply commits with
231
- // the turn's answer.
232
- await turn.appendReply([said]);
233
- if (!message.content.some((c) => c.type === 'tool_use'))
234
- return textOf(message.content);
235
- await toolCallStarted(ctx);
236
- const results = await runner.generateToolResponse();
237
- check();
238
- if (results)
239
- await turn.append(results);
240
- await step();
241
- }
242
- if (!paused)
243
- throw new Error('the tool runner ended without a reply');
244
- }
245
- };
246
- /**
247
- * `runner`'s replies, each model request kept alive: from the moment the
248
- * loop asks for the next reply until it arrives (the runner does not stream,
249
- * so the reply is the whole response), however it ends: an error, or the turn
250
- * stopped. The tools run outside it: the loop runs them (`generateToolResponse`)
251
- * before it asks again, and the runner then finds their results done.
252
- */
253
- async function* requests(ctx, runner) {
254
- const replies = runner[Symbol.asyncIterator]();
255
- try {
256
- for (;;) {
257
- const release = keepAlive(ctx);
258
- let next;
259
- try {
260
- next = await replies.next();
261
- }
262
- finally {
263
- release();
264
- }
265
- if (next.done)
266
- return;
267
- yield next.value;
268
- }
269
- }
270
- finally {
271
- // Ends the runner's loop (its span and its stream) when the caller leaves it early, as a final reply does.
272
- await replies.return?.();
273
- }
274
- }
275
- /**
276
- * Why the model's `message` stopped short of a reply to go on from: cut off
277
- * at `maxTokens` (its text, or a tool call's input, unfinished), declined, or
278
- * past the model's context window: a terminal error's message.
279
- */
280
- function stoppedShort(message, maxTokens) {
281
- if (message.stop_reason === 'max_tokens') {
282
- return `the model's reply reached maxTokens (${maxTokens}) before it ended: raise the agent's maxTokens`;
283
- }
284
- if (message.stop_reason === 'refusal') {
285
- const category = message.stop_details?.category;
286
- return `the model declined to answer${category ? ` (${category})` : ''}`;
287
- }
288
- if (message.stop_reason === 'model_context_window_exceeded') {
289
- return "the conversation outgrew the model's context window: lower the agent's window or budget";
290
- }
291
- return undefined;
292
- }
293
- /** `t` as a tool of the Anthropic SDK's tool runner: `t.run` checks the model's arguments itself. */
294
- const native = (t, ctx) => ({
295
- type: 'custom',
296
- name: t.name,
297
- description: t.description,
298
- input_schema: jsonSchemaOf(t),
299
- parse: (args) => args,
300
- run: (args, context) => t.run(args, { ctx, callId: callId(context) }),
301
- });
302
- /**
303
- * The Claude models with structured outputs: of each family, the 4.5 models
304
- * and later (and Mythos Preview); not Claude 3, Opus 4 and 4.1, or Sonnet 4.
305
- */
306
- const STRUCTURED_OUTPUTS = /claude-(?:(?:opus|sonnet|haiku)-4-[5-9](?!\d)|(?:opus|sonnet|haiku|fable|mythos)-(?:[5-9]|[1-9]\d)|mythos-preview)/;
307
- /** Whether an agent of `options` asks the model for its `output` natively (see `nativeOutput`). */
308
- const asksNatively = ({ model, output, nativeOutput }) => output !== undefined &&
309
- (nativeOutput ?? STRUCTURED_OUTPUTS.test(modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic')));
310
- /**
311
- * `output`'s JSON schema, as the API takes it (the SDK's helper's): what the
312
- * API does not take (a string's `minLength`, say) goes to a description, and
313
- * is left to the check of the reply.
314
- */
315
- const formatOf = (output) => {
316
- const { type, schema } = betaZodOutputFormat(output);
317
- return { type, schema };
318
- };
319
- /** The client of an agent without one of its own, on the context of the turn it answers. */
320
- const CLIENT = new ScopeKey('the Anthropic client');
321
- /** The agent of `options`, for the turn of `ctx`. */
322
- const agentOf = (ctx, options) => {
323
- const { model, system, tools = [], client, maxTokens = 16_000, effort, output } = options;
324
- return {
325
- client: client ?? CLIENT.of(ctx, () => new Anthropic()),
326
- model: modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic'),
327
- maxTokens,
328
- effort,
329
- system,
330
- tools: tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
331
- ...(output !== undefined && asksNatively(options) ? { format: formatOf(output) } : {}),
332
- };
333
- };
334
- /**
335
- * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
336
- * of an invocation is a prompt of its own.
337
- * With `output`, it answers with the value the agent replies with (see
338
- * output.ts), not its text: a reply that is not one is asked again within
339
- * its turn, once. A model with structured outputs is asked for it natively
340
- * (`nativeOutput`), else in the prompt.
341
- */
342
- export const prompt = async (ctx, text, options = {}) => withChecked(text, options, (t, o, check, reminder) => answerOnce(ctx, t, items, runOf(ctx, agentOf(ctx, o)), { check, reminder }), asksNatively(options));
343
- /**
344
- * A chat handler: each message an invocation, the conversation in the
345
- * object's database, with `options`, or the options a function of the
346
- * invocation's context gives. It takes the message as plain text
347
- * (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
348
- */
349
- export const chat = (options = {}) => {
350
- if (typeof options === 'object')
351
- modelIdOf(modelOf(options.model, CLAUDE_MODEL), 'anthropic');
352
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
353
- };
354
- /**
355
- * A view of the conversation as clients read it: a page at a time, or what
356
- * is new or changed since a cursor; `view: 'summary'` for each turn's
357
- * message and answer. It answers while a message is answered.
358
- */
359
- export const messages = () => conversationView(items);
360
- /**
361
- * How an agent of `options` summarizes the earliest turns, past its budget:
362
- * with its own client and model (`agent()` gives it; for an object of your
363
- * own, `sessionObject`'s `summarize`).
364
- */
365
- export const summarizer = (options = {}) => async (ctx, request) => {
366
- const { client, model, maxTokens } = agentOf(ctx, { ...options, tools: [] });
367
- const message = await ctx.working(() => client.beta.messages.create({
368
- model,
369
- max_tokens: maxTokens,
370
- messages: [{ role: 'user', content: request }],
371
- }));
372
- return textOf(message.content);
373
- };
374
- /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
375
- export const agent = ({ name, description, schema, background, window, budget, summarize, ...options }) => sessionObject({
376
- name,
377
- description,
378
- schema,
379
- background,
380
- window,
381
- budget,
382
- summarize: summarize ?? summarizer(options),
383
- handlers: { chat: chat(options) },
384
- views: { messages: messages() },
385
- });
386
- //# sourceMappingURL=index.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/claude/index.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,6EAA6E;AAC7E,2EAA2E;AAC3E,uCAAuC;AACvC,EAAE;AACF,wGAAwG;AACxG,EAAE;AACF,8EAA8E;AAC9E,gFAAgF;AAChF,uEAAuE;AACvE,EAAE;AACF,4EAA4E;AAC5E,0BAA0B;AAC1B,EAAE;AACF,8EAA8E;AAC9E,4EAA4E;AAC5E,2EAA2E;AAC3E,8BAA8B;AAC9B,8EAA8E;AAC9E,+EAA+E;AAC/E,4EAA4E;AAC5E,4EAA4E;AAC5E,qDAAqD;AACrD,2EAA2E;AAC3E,qEAAqE;AACrE,8DAA8D;AAC9D,0EAA0E;AAC1E,2EAA2E;AAC3E,2BAA2B;AAC3B,6EAA6E;AAC7E,0EAA0E;AAC1E,2EAA2E;AAC3E,+CAA+C;AAC/C,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,QAAQ,EAAE,MAAM,+BAA+B,CAAC;AACzD,OAAO,SAAS,MAAM,mBAAmB,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AAEzE,OAAO,EAAE,SAAS,EAAE,MAAM,uCAAuC,CAAC;AAClE,OAAO,EACL,WAAW,EACX,YAAY,EAEZ,UAAU,EACV,QAAQ,EACR,SAAS,EACT,SAAS,EACT,OAAO,EACP,mBAAmB,EACnB,eAAe,EACf,YAAY,EAEZ,SAAS,GACV,MAAM,cAAc,CAAC;AACtB,OAAO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C,QAAQ,CAAC,MAAM,CAAC;QAC1B,KAAK;QACL,UAAU,EAAE,SAAS;QACrB,QAAQ,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;KAC/C,CAAC,CACH,CAAC;IACF,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC,CAAC;AAEJ,6HAA6H;AAC7H,MAAM,CAAC,MAAM,KAAK,GAAG,CAAkE,EACrF,IAAI,EACJ,WAAW,EACX,MAAM,EACN,UAAU,EACV,MAAM,EACN,MAAM,EACN,SAAS,EACT,GAAG,OAAO,EACiB,EAAE,EAAE,CAC/B,aAAa,CAAC;IACZ,IAAI;IACJ,WAAW;IACX,MAAM;IACN,UAAU;IACV,MAAM;IACN,MAAM;IACN,SAAS,EAAE,SAAS,IAAI,UAAU,CAAC,OAAO,CAAC;IAC3C,QAAQ,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE;IACjC,KAAK,EAAE,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE;CAChC,CAAC,CAAC"}
package/dist/client.d.ts DELETED
@@ -1,90 +0,0 @@
1
- import * as clients from '@restatedev/restate-sdk-clients';
2
- import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
3
- import type { Answering, ChatMessage, Messages, MessagesRequest, Part } from './common.ts';
4
- import type { Status, Stopped, Synced, SyncRequest } from './object.ts';
5
- import type { Notifications, Resolved, Signal, Steered, Steering, Waiting, Watch } from './companion.ts';
6
- export type { Answering, ChatMessage, Messages, MessagesRequest, Notifications, Part, Resolved, Signal, Status, Steered, Steering, Stopped, Synced, SyncRequest, Waiting, Watch, };
7
- /** The handlers of an agent (`agent()` of any framework), as Restate's client calls them. */
8
- export interface Agent {
9
- /** Answer `message`. */
10
- chat(ctx: unknown, message: string): Promise<string>;
11
- /**
12
- * Send `message` while the agent answers another: the turn being answered
13
- * takes it at its next step (once its model's tool calls have their
14
- * results), and its answer covers it; else it is answered as a turn of its
15
- * own, after the messages before it. Either way it is answered once: send
16
- * it with an idempotency key, made once per message, so that sending it
17
- * again is the same message.
18
- */
19
- steer(ctx: unknown, message: string): Promise<Steered>;
20
- /** The conversation, a page at a time, or what is new or changed since a cursor, also while a message is answered. */
21
- messages(ctx: unknown, request?: MessagesRequest): Promise<Messages>;
22
- /** The conversation since a cursor, the status and the revision; with `revision`, once there is a newer one. */
23
- sync(ctx: unknown, request?: SyncRequest): Promise<Synced>;
24
- /** What the agent is doing: the message it answers, and what its tools wait for. */
25
- status(ctx: unknown): Promise<Status>;
26
- /** Stop the message it answers: cancel its invocation. */
27
- stop(ctx: unknown): Promise<Stopped>;
28
- /** Forget the conversation (stopping the message it answers): its database and state too. */
29
- clear(ctx: unknown): Promise<Stopped>;
30
- /** What its tools wait for. */
31
- pending(ctx: unknown): Promise<Waiting[]>;
32
- /** Resolve a wait: by its id, or the oldest for a name. */
33
- signal(ctx: unknown, signal: Signal): Promise<Resolved>;
34
- /** The revision of its conversation, which each change increases. */
35
- notifications(ctx: unknown): Promise<Notifications>;
36
- /** The revision, once there is one newer than `revision`, or at the timeout. */
37
- watch(ctx: unknown, watch: Watch): Promise<Notifications>;
38
- }
39
- /**
40
- * The agent `name`, as Restate's client takes it: its name, typed with the
41
- * handlers of an agent (or `H`, an object of your own's).
42
- */
43
- export declare const agent: <H = Agent, P extends string = string>(name: P) => VirtualObjectDefinition<P, H>;
44
- /** What {@link follow} gives each time the conversation changes. */
45
- export interface Followed {
46
- /** What the agent is doing now. */
47
- status: Status;
48
- /**
49
- * The messages new or changed since the last time, by when they changed: a
50
- * message may come again, changed (a tool call with its output, say), with
51
- * its `id`, which a UI keeps them by, and orders them by.
52
- */
53
- messages: ChatMessage[];
54
- /**
55
- * The id of the conversation's first message: one kept from before is
56
- * gone (`clear` forgot it), and a UI drops it.
57
- */
58
- first: number;
59
- /** Where this leaves off: `follow(..., { cursor })` carries on from here, later or elsewhere. */
60
- cursor: number;
61
- /** What the agent's tools wait for now (`status.waiting`). */
62
- waiting: Waiting[];
63
- }
64
- /**
65
- * `message` to read, such as in a terminal: its text after its role, and
66
- * each tool call on a line of its own, with its output (`…` until it has one).
67
- */
68
- export declare const asText: ({ role, parts }: ChatMessage) => string;
69
- /** Where {@link follow} starts, and what stops it. */
70
- export interface FollowOptions {
71
- /** The messages new or changed since this cursor (a page's, or a `Followed`'s); by default, all of them. */
72
- cursor?: number;
73
- /** Following ends once it aborts. */
74
- signal?: AbortSignal;
75
- /** How long one wait for a change lasts at most, in seconds (default 50). */
76
- timeoutSeconds?: number;
77
- }
78
- /**
79
- * The conversation of the agent `definition` (such as `agent('assistant')`)
80
- * with key `key`, as it changes, through `ingress` (Restate's client): what
81
- * the agent is doing and the messages so far, then each change, until
82
- * `signal` aborts.
83
- *
84
- * Each change is one `sync`, which waits in Restate for the next. A network
85
- * failure (or Restate's, restarting) does not end it: it tries again, and a
86
- * sync it retries keeps its idempotency key, so it joins the one already
87
- * waiting.
88
- */
89
- export declare function follow(ingress: clients.Ingress, definition: VirtualObjectDefinition<string, Agent>, key: string, { cursor, signal, timeoutSeconds }?: FollowOptions): AsyncGenerator<Followed, void, void>;
90
- //# sourceMappingURL=client.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;AAC3D,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AAC5E,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,aAAa,CAAC;AAC3F,OAAO,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AACxE,OAAO,KAAK,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,QAAQ,EA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ent for Restate's client (@restatedev/restate-sdk-clients), from a
2
- // chat UI or any other code: the agent's definition as the client takes it,
3
- // its name and the types of its handlers, and the types of what they answer;
4
- // and `follow`, which follows its conversation as it changes. It imports
5
- // Restate's client, and nothing of the agent's code or the SDK, so a web app
6
- // bundles it as it is.
7
- //
8
- // import * as clients from '@restatedev/restate-sdk-clients';
9
- // import { agent, follow } from '@restatedev/agents/client';
10
- //
11
- // const restate = clients.connect({ url: 'http://localhost:8080' });
12
- // const alice = restate.objectClient(agent('assistant'), 'alice');
13
- // const { messages } = await alice.messages({ limit: 20 });
14
- // for await (const { status, messages } of follow(restate, agent('assistant'), 'alice')) { ... }
15
- import * as clients from '@restatedev/restate-sdk-clients';
16
- /**
17
- * The agent `name`, as Restate's client takes it: its name, typed with the
18
- * handlers of an agent (or `H`, an object of your own's).
19
- */
20
- export const agent = (name) => ({ name });
21
- /**
22
- * `message` to read, such as in a terminal: its text after its role, and
23
- * each tool call on a line of its own, with its output (`…` until it has one).
24
- */
25
- export const asText = ({ role, parts }) => parts
26
- .map((part) => part.type === 'text'
27
- ? `${role}: ${part.text}`
28
- : ` ${part.name}(${JSON.stringify(part.input)}) -> ${part.output ?? '…'}`)
29
- .join('\n');
30
- /** Whether a retry may answer: a network failure, Restate's (5xx) or too many requests (429); not a 4xx. */
31
- const transient = (error) => !(error instanceof clients.HttpCallError) || error.status >= 500 || error.status === 429;
32
- /**
33
- * One `sync` of `followed`, tried again a second later with the same
34
- * idempotency key until it answers, unless its error would last; undefined
35
- * once `signal` aborts.
36
- */
37
- async function syncRetried(followed, request, signal) {
38
- const opts = clients.rpc.opts({ signal, idempotencyKey: crypto.randomUUID() });
39
- for (;;) {
40
- if (signal?.aborted)
41
- return undefined;
42
- try {
43
- return await followed.sync(request, opts);
44
- }
45
- catch (error) {
46
- if (signal?.aborted)
47
- return undefined;
48
- if (!transient(error))
49
- throw error;
50
- console.warn('follow: retrying', error);
51
- await new Promise((resolve) => setTimeout(resolve, 1000));
52
- }
53
- }
54
- }
55
- /**
56
- * The conversation of the agent `definition` (such as `agent('assistant')`)
57
- * with key `key`, as it changes, through `ingress` (Restate's client): what
58
- * the agent is doing and the messages so far, then each change, until
59
- * `signal` aborts.
60
- *
61
- * Each change is one `sync`, which waits in Restate for the next. A network
62
- * failure (or Restate's, restarting) does not end it: it tries again, and a
63
- * sync it retries keeps its idempotency key, so it joins the one already
64
- * waiting.
65
- */
66
- export async function* follow(ingress, definition, key, { cursor = 0, signal, timeoutSeconds = 50 } = {}) {
67
- const followed = ingress.objectClient(definition, key);
68
- let revision;
69
- for (;;) {
70
- const synced = await syncRetried(followed, { cursor, revision, timeoutSeconds }, signal);
71
- if (!synced)
72
- return;
73
- // Nothing changed (the wait timed out): wait again.
74
- if (synced.revision !== revision || synced.messages.length > 0) {
75
- yield {
76
- status: synced.status,
77
- messages: synced.messages,
78
- first: synced.first ?? 0,
79
- cursor: synced.cursor,
80
- waiting: synced.status.waiting,
81
- };
82
- }
83
- cursor = synced.cursor;
84
- // With more to read, at once; else once something changes.
85
- revision = synced.more ? undefined : synced.revision;
86
- }
87
- }
88
- //# sourceMappingURL=client.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,4EAA4E;AAC5E,6EAA6E;AAC7E,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,EAAE;AACF,gEAAgE;AAChE,+DAA+D;AAC/D,EAAE;AACF,uEAAuE;AACvE,qEAAqE;AACrE,8DAA8D;AAC9D,mGAAmG;AACnG,OAAO,KAAK,OAAO,MAAM,iCAAiC,CAAC;AA0D3D;;;GAGG;AACH,MAAM,CAAC,MAAM,KAAK,GAAG,CAAuC,IAAO,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAkC,CAAC;AAuBpH;;;GAGG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CAAC,EAAE,IAAI,EAAE,KAAK,EAA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