@restatedev/agents 0.3.0 → 0.5.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 (136) hide show
  1. package/README.md +107 -53
  2. package/dist/calls.d.ts +29 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +232 -151
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +478 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1256 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +322 -106
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +227 -171
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +123 -35
  64. package/dist/object.js.map +1 -1
  65. package/dist/opencode/db.d.ts +51 -10
  66. package/dist/opencode/db.d.ts.map +1 -1
  67. package/dist/opencode/db.js +122 -34
  68. package/dist/opencode/db.js.map +1 -1
  69. package/dist/opencode/index.d.ts +105 -21
  70. package/dist/opencode/index.d.ts.map +1 -1
  71. package/dist/opencode/index.js +827 -279
  72. package/dist/opencode/index.js.map +1 -1
  73. package/dist/output.d.ts +15 -7
  74. package/dist/output.d.ts.map +1 -1
  75. package/dist/output.js +44 -26
  76. package/dist/output.js.map +1 -1
  77. package/dist/pi/index.d.ts +39 -11
  78. package/dist/pi/index.d.ts.map +1 -1
  79. package/dist/pi/index.js +281 -77
  80. package/dist/pi/index.js.map +1 -1
  81. package/dist/pi/storage.d.ts +29 -4
  82. package/dist/pi/storage.d.ts.map +1 -1
  83. package/dist/pi/storage.js +18 -6
  84. package/dist/pi/storage.js.map +1 -1
  85. package/dist/signals.d.ts +74 -4
  86. package/dist/signals.d.ts.map +1 -1
  87. package/dist/signals.js +144 -15
  88. package/dist/signals.js.map +1 -1
  89. package/dist/steering.d.ts +31 -0
  90. package/dist/steering.d.ts.map +1 -0
  91. package/dist/steering.js +45 -0
  92. package/dist/steering.js.map +1 -0
  93. package/dist/tools.d.ts +28 -0
  94. package/dist/tools.d.ts.map +1 -1
  95. package/dist/tools.js +34 -5
  96. package/dist/tools.js.map +1 -1
  97. package/package.json +42 -13
  98. package/src/calls.ts +107 -15
  99. package/src/claude/README.md +41 -20
  100. package/src/claude/index.ts +266 -178
  101. package/src/client.ts +14 -3
  102. package/src/common.ts +317 -232
  103. package/src/conversation.ts +1547 -0
  104. package/src/deepseek/README.md +78 -11
  105. package/src/deepseek/index.ts +384 -137
  106. package/src/deepseek/persistence.ts +11 -8
  107. package/src/index.ts +13 -4
  108. package/src/langgraph/README.md +115 -25
  109. package/src/langgraph/checkpointer.ts +168 -28
  110. package/src/langgraph/context.ts +27 -0
  111. package/src/langgraph/errors.ts +26 -0
  112. package/src/langgraph/graph.ts +396 -0
  113. package/src/langgraph/index.ts +326 -181
  114. package/src/langgraph/nodes.ts +243 -0
  115. package/src/messages.ts +244 -0
  116. package/src/object.ts +169 -38
  117. package/src/opencode/README.md +172 -66
  118. package/src/opencode/db.ts +204 -40
  119. package/src/opencode/index.ts +1010 -325
  120. package/src/output.ts +52 -31
  121. package/src/pi/README.md +18 -3
  122. package/src/pi/index.ts +346 -78
  123. package/src/pi/storage.ts +20 -7
  124. package/src/signals.ts +225 -19
  125. package/src/steering.ts +67 -0
  126. package/src/tools.ts +61 -8
  127. package/dist/claude/conversation.d.ts +0 -33
  128. package/dist/claude/conversation.d.ts.map +0 -1
  129. package/dist/claude/conversation.js +0 -95
  130. package/dist/claude/conversation.js.map +0 -1
  131. package/dist/log.d.ts +0 -29
  132. package/dist/log.d.ts.map +0 -1
  133. package/dist/log.js +0 -146
  134. package/dist/log.js.map +0 -1
  135. package/src/claude/conversation.ts +0 -114
  136. package/src/log.ts +0 -194
@@ -1,6 +1,7 @@
1
1
  // Claude agents in Restate virtual objects, on the tool runner of the
2
- // Anthropic SDK (`client.beta.messages.toolRunner`): the conversation is in
3
- // the object's database (conversation.ts).
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`).
4
5
  //
5
6
  // const assistant = claude.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
6
7
  //
@@ -12,48 +13,54 @@
12
13
  // with ANTHROPIC_API_KEY.
13
14
  //
14
15
  // The handler is not replayed: a retried attempt (a crash, a lost connection)
15
- // runs again from the start, and starts the runner with the stored messages:
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):
16
19
  // - Each reply of the model is stored before its tools run, and their results
17
20
  // before the next request. So a crash during the tools resumes them with the
18
21
  // same tool call ids (`callId(context)`), without asking the model again,
19
- // and a tool passes the id on to stay idempotent.
20
- // - A tool's error fails the attempt, which Restate retries (by default the
21
- // runner hands it to the model as the tool's result).
22
- // - A message is answered once per invocation: its answer is stored with the
23
- // model's last reply, and a retried attempt returns it.
24
- // - A reply cut off at `maxTokens`, or declined, ends the prompt: its tool
25
- // calls do not run, and the handler fails with a terminal error.
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).
26
34
  import * as restate from '@restatedev/sessions';
27
35
  import { ScopeKey } from '@restatedev/sessions/internal';
28
36
  import Anthropic from '@anthropic-ai/sdk';
37
+ import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod';
29
38
  import type { BetaRunnableTool, BetaToolRunContext } from '@anthropic-ai/sdk/lib/tools/BetaRunnableTool';
39
+ import { ToolError } from '@anthropic-ai/sdk/lib/tools/ToolError';
30
40
  import {
31
- aborted,
32
- AttemptEnded,
33
- CANCELLED,
34
41
  chatHandler,
35
42
  CLAUDE_MODEL,
36
43
  type Configure,
37
44
  configured,
38
45
  fromTool,
39
- messagesHandler,
40
46
  modelIdOf,
41
47
  modelOf,
42
- nextPromptId,
43
- refusalOf,
48
+ RETURNED_UNRECORDED,
44
49
  stopSignalOf,
45
- storedAnswer,
50
+ type Summarize,
46
51
  toolCallEnded,
47
52
  toolCallStarted,
48
- transcribing,
49
- Transcript,
50
- UNANSWERED,
53
+ NO_ANSWER,
51
54
  } from '../common.ts';
52
- import { type Answer, withOutput } from '../output.ts';
55
+ import { answerOnce, type Items, type Parsed, type Run } from '../conversation.ts';
56
+ import { takeSteers } from '../steering.ts';
57
+ import { conversationView } from '../messages.ts';
58
+ import { type Answer, withChecked } from '../output.ts';
53
59
  import type { z } from 'zod';
54
60
  import { type Definition, sessionObject } from '../object.ts';
55
61
  import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
56
- import { Conversation } from './conversation.ts';
62
+
63
+ type MessageParam = Anthropic.Beta.Messages.BetaMessageParam;
57
64
 
58
65
  /** The id of the tool call a tool runs for: the runner always passes it. */
59
66
  export const callId = (context?: BetaToolRunContext) => {
@@ -61,10 +68,88 @@ export const callId = (context?: BetaToolRunContext) => {
61
68
  return context.toolUse.id;
62
69
  };
63
70
 
71
+ /**
72
+ * `messages` as the API takes them: it refuses an empty text, and an
73
+ * assistant's message with no content but the last. The model may reply
74
+ * with nothing (stored as it came): sent back, such a reply says so.
75
+ */
76
+ const sendable = (messages: MessageParam[]): MessageParam[] =>
77
+ messages.map((m) => {
78
+ if (m.role !== 'assistant') return m;
79
+ if (typeof m.content === 'string') return m.content.trim() ? m : { ...m, content: NO_ANSWER };
80
+ const content = m.content.filter((b) => b.type !== 'text' || b.text.trim() !== '');
81
+ if (content.length === 0) return { ...m, content: NO_ANSWER };
82
+ return content.length === m.content.length ? m : { ...m, content };
83
+ });
84
+
85
+ /** The text of stored content, without its tool calls and results. */
86
+ const storedText = (content: string | readonly { type: string; text?: string }[] | undefined) =>
87
+ typeof content === 'string' ? content : (content ?? []).flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('');
88
+
89
+ /**
90
+ * Claude's items: the SDK's messages, as JSON. A user's text is said by the
91
+ * user, an assistant's by the assistant, and its `tool_use` blocks are its
92
+ * calls; a `tool_result` is a result. A server tool's blocks (and a
93
+ * `system` message) say nothing: they leave no open call the API would
94
+ * refuse a result for.
95
+ */
96
+ export const items: Items<MessageParam> = {
97
+ dump: (message) => JSON.stringify(message),
98
+ load: (stored) => {
99
+ // Only a message of the API's (a role and its content): another framework's row is not one.
100
+ const message = JSON.parse(stored) as MessageParam;
101
+ const { role, content, ...rest } = message;
102
+ if ((role !== 'user' && role !== 'assistant') || (typeof content !== 'string' && !Array.isArray(content)))
103
+ throw new Error('not a message of the Claude API (a role and its content)');
104
+ if (Object.keys(rest).length > 0)
105
+ throw new Error(`not a message of the Claude API: ${Object.keys(rest).join(', ')}`);
106
+ return message;
107
+ },
108
+ prompt: (text) => ({ role: 'user', content: text }),
109
+ // The API refuses an empty text: an empty answer, as the model sees it later, says so.
110
+ reply: (text) => ({ role: 'assistant', content: text.trim() ? text : NO_ANSWER }),
111
+ // Every result of a reply in one message, as the API wants them.
112
+ results: (results) =>
113
+ results.length === 0
114
+ ? []
115
+ : [
116
+ {
117
+ role: 'user',
118
+ content: results.map(([call, output]) => ({
119
+ type: 'tool_result' as const,
120
+ tool_use_id: call.id,
121
+ content: output,
122
+ ...(output === RETURNED_UNRECORDED ? {} : { is_error: true }),
123
+ })),
124
+ },
125
+ ],
126
+ read: (message): Parsed => {
127
+ if (message.role !== 'user' && message.role !== 'assistant') return {};
128
+ const { role, content } = message;
129
+ if (typeof content === 'string') return { said: [role, content] };
130
+ const texts = content.filter((b) => b.type === 'text');
131
+ const calls = content.flatMap((b) => (b.type === 'tool_use' ? [{ id: b.id, name: b.name, input: b.input }] : []));
132
+ const results = content.flatMap((b) =>
133
+ b.type === 'tool_result'
134
+ ? [{ id: b.tool_use_id, output: storedText(b.content as never), error: b.is_error === true }]
135
+ : [],
136
+ );
137
+ // Each reply of the model is a message of its own, its tool calls' too (as
138
+ // the views gave them before); a message of results only says nothing.
139
+ const said = role === 'assistant' || texts.length > 0;
140
+ return {
141
+ ...(said ? { said: [role, texts.map((b) => b.text).join('')] as ['user' | 'assistant', string] } : {}),
142
+ calls,
143
+ results,
144
+ };
145
+ },
146
+ };
147
+
64
148
  /**
65
149
  * `tools`, whose errors fail the attempt: the runner would hand a thrown error
66
150
  * to the model as the tool's result, so each one is kept, for `check()` to
67
- * throw once the tools ran.
151
+ * throw once the tools ran. The SDK's `ToolError` is for the model: the
152
+ * runner hands it over as the tool's result.
68
153
  */
69
154
  function failing(ctx: restate.SessionContext, tools: BetaRunnableTool[]) {
70
155
  let failure: unknown;
@@ -75,6 +160,7 @@ function failing(ctx: restate.SessionContext, tools: BetaRunnableTool[]) {
75
160
  try {
76
161
  return await tool.run(args, context);
77
162
  } catch (e) {
163
+ if (e instanceof ToolError) throw e;
78
164
  fromTool(ctx, e);
79
165
  failure ??= e;
80
166
  throw e;
@@ -100,84 +186,104 @@ interface Agent {
100
186
  effort?: Effort;
101
187
  system?: string;
102
188
  tools: BetaRunnableTool[];
189
+ /** The JSON schema of `output`, asked for natively: the API holds the final reply to it. */
190
+ format?: Anthropic.Beta.Messages.BetaJSONOutputFormat;
103
191
  }
104
192
 
105
193
  /**
106
- * Run prompt `id` of `conversation` until it is answered, from its stored
107
- * messages; each round of tool calls published as it starts and ends (for
108
- * the clients that follow the conversation).
194
+ * The run of `agent` on the conversation: from the stored turn on, each
195
+ * reply stored before its tools run, and their results after; each round of
196
+ * tool calls published as it starts and ends (for the clients that follow
197
+ * the conversation). At each step (before a request that follows the
198
+ * prompt or the tools' results), it takes the messages steered to the turn
199
+ * (`takeSteers`): the request then goes out from the conversation's
200
+ * history, which has them after the tools' results.
109
201
  */
110
- async function run(
111
- ctx: restate.SessionContext,
112
- { client, model, maxTokens, effort, system, tools: all }: Agent,
113
- conversation: Conversation,
114
- id: string,
115
- signal?: AbortSignal,
116
- ) {
117
- const { tools, check } = failing(ctx, all);
118
- const runner = client.beta.messages.toolRunner(
119
- {
120
- model,
121
- max_tokens: maxTokens,
122
- ...(effort === undefined ? {} : { output_config: { effort } }),
123
- ...(system === undefined ? {} : { system }),
124
- tools,
125
- messages: await conversation.messages(),
126
- },
127
- { signal },
128
- );
129
- // A reply whose tools did not finish (a crash): run them, with the same ids,
130
- // once the calls whose results are stored are settled, as for any reply:
131
- // else one of its calls could take the id of an identical call answered before.
132
- if (runner.params.messages.at(-1)?.role === 'assistant') {
133
- await toolCallStarted(ctx);
134
- const results = await runner.generateToolResponse();
135
- check();
136
- if (results) {
137
- await conversation.append(id, [results]);
138
- runner.pushMessages(results);
139
- }
140
- await toolCallEnded(ctx);
141
- }
142
- for await (const message of runner) {
143
- const reply: Anthropic.Beta.Messages.BetaMessageParam = { role: 'assistant', content: message.content };
144
- // A reply that cannot go on ends the prompt, whose tool calls do not run.
145
- const stopped = stoppedShort(message, maxTokens);
146
- if (stopped) {
147
- await conversation.close(id, stopped.text, reply);
148
- throw new restate.TerminalError(stopped.error);
149
- }
150
- if (!message.content.some((c) => c.type === 'tool_use')) {
151
- await conversation.append(id, [reply], textOf(message.content));
152
- return;
202
+ const runOf =
203
+ (ctx: restate.SessionContext, agent: Agent): Run<MessageParam> =>
204
+ async (conversation) => {
205
+ const { client, model, maxTokens, effort, system, format } = agent;
206
+ const turn = conversation.turn;
207
+ for (;;) {
208
+ // A stored final reply is the answer: the model is not asked for it again.
209
+ const final = turn.finalReply();
210
+ if (final !== undefined) return final;
211
+ // A paused reply goes back as the last message, which a steered one would not leave it.
212
+ if (turn.entries.at(-1)!.parsed?.said?.[0] !== 'assistant') await takeSteers(ctx, conversation);
213
+ const { tools, check } = failing(ctx, agent.tools);
214
+ const runner = client.beta.messages.toolRunner(
215
+ {
216
+ model,
217
+ max_tokens: maxTokens,
218
+ ...(effort === undefined && format === undefined ? {} : { output_config: { effort, format } }),
219
+ ...(system === undefined ? {} : { system }),
220
+ tools,
221
+ messages: sendable(conversation.history()),
222
+ },
223
+ { signal: stopSignalOf(ctx) },
224
+ );
225
+ /** A step: the messages steered to the turn go into the next request, after the tools' results. */
226
+ const step = async () => {
227
+ if ((await takeSteers(ctx, conversation)).length === 0) return;
228
+ // The runner leaves the history to its caller, who changed it: the reply, its results and the messages.
229
+ runner.setMessagesParams((params) => ({ ...params, messages: sendable(conversation.history()) }));
230
+ };
231
+ // A reply whose tools did not finish (a crash): run them, with the same
232
+ // ids, once the calls whose results are stored are settled, as for any
233
+ // reply: else one of its calls could take the id of an identical call
234
+ // answered before.
235
+ if (turn.openCalls().length > 0) {
236
+ await toolCallStarted(ctx);
237
+ const results = await runner.generateToolResponse();
238
+ check();
239
+ if (results) {
240
+ await turn.append(results);
241
+ runner.pushMessages(results);
242
+ }
243
+ await toolCallEnded(ctx);
244
+ await step();
245
+ }
246
+ let paused = false;
247
+ for await (const message of runner) {
248
+ // A reply that cannot go on ends the turn, whose tool calls do not run.
249
+ const stopped = stoppedShort(message, maxTokens);
250
+ if (stopped) throw new restate.TerminalError(stopped);
251
+ const said: MessageParam = { role: 'assistant', content: message.content };
252
+ // Paused (a server tool's long turn): a step of the turn, not a reply to
253
+ // end it with, and the model goes on from it.
254
+ if (message.stop_reason === 'pause_turn') {
255
+ await turn.append(said);
256
+ paused = true;
257
+ break;
258
+ }
259
+ await turn.appendReply([said]);
260
+ if (!message.content.some((c) => c.type === 'tool_use')) return textOf(message.content);
261
+ await toolCallStarted(ctx);
262
+ const results = await runner.generateToolResponse();
263
+ check();
264
+ if (results) await turn.append(results);
265
+ await toolCallEnded(ctx);
266
+ await step();
267
+ }
268
+ if (!paused) throw new Error('the tool runner ended without a reply');
153
269
  }
154
- // The reply first, then its tools.
155
- await conversation.append(id, [reply]);
156
- await toolCallStarted(ctx);
157
- const results = await runner.generateToolResponse();
158
- check();
159
- if (results) await conversation.append(id, [results]);
160
- await toolCallEnded(ctx);
161
- }
162
- }
270
+ };
163
271
 
164
272
  /**
165
273
  * Why the model's `message` stopped short of a reply to go on from: cut off
166
- * at `maxTokens` (its text, or a tool call's input, unfinished), or declined.
274
+ * at `maxTokens` (its text, or a tool call's input, unfinished), declined, or
275
+ * past the model's context window: a terminal error's message.
167
276
  */
168
277
  function stoppedShort(message: Anthropic.Beta.Messages.BetaMessage, maxTokens: number) {
169
278
  if (message.stop_reason === 'max_tokens') {
170
- return {
171
- text: `Cut off: the reply reached ${maxTokens} tokens before it ended.`,
172
- error: `the model's reply reached maxTokens (${maxTokens}) before it ended: raise the agent's maxTokens`,
173
- };
279
+ return `the model's reply reached maxTokens (${maxTokens}) before it ended: raise the agent's maxTokens`;
174
280
  }
175
281
  if (message.stop_reason === 'refusal') {
176
282
  const category = message.stop_details?.category;
177
- return {
178
- text: 'Declined: the model did not answer.',
179
- error: `the model declined to answer${category ? ` (${category})` : ''}`,
180
- };
283
+ return `the model declined to answer${category ? ` (${category})` : ''}`;
284
+ }
285
+ if (message.stop_reason === 'model_context_window_exceeded') {
286
+ return "the conversation outgrew the model's context window: lower the agent's window or budget";
181
287
  }
182
288
  return undefined;
183
289
  }
@@ -217,86 +323,75 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
217
323
  * (checked), and `chat` and `prompt` answer with (see output.ts).
218
324
  */
219
325
  output?: O;
326
+ /**
327
+ * Whether the model is asked for `output` natively, with the API's
328
+ * structured outputs (`output_config.format`: the JSON schema the API
329
+ * holds the final reply to), rather than in the prompt (default: if the
330
+ * model has them, as Claude's have since the 4.5 models). A schema the API
331
+ * cannot take (too complex, say) refuses the message: `false` asks in the
332
+ * prompt instead.
333
+ */
334
+ nativeOutput?: boolean;
220
335
  }
221
336
 
337
+ /**
338
+ * The Claude models with structured outputs: of each family, the 4.5 models
339
+ * and later (and Mythos Preview); not Claude 3, Opus 4 and 4.1, or Sonnet 4.
340
+ */
341
+ const STRUCTURED_OUTPUTS =
342
+ /claude-(?:(?:opus|sonnet|haiku)-4-[5-9](?!\d)|(?:opus|sonnet|haiku|fable|mythos)-(?:[5-9]|[1-9]\d)|mythos-preview)/;
343
+
344
+ /** Whether an agent of `options` asks the model for its `output` natively (see `nativeOutput`). */
345
+ const asksNatively = ({ model, output, nativeOutput }: Options) =>
346
+ output !== undefined &&
347
+ (nativeOutput ?? STRUCTURED_OUTPUTS.test(modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic')));
348
+
349
+ /**
350
+ * `output`'s JSON schema, as the API takes it (the SDK's helper's): what the
351
+ * API does not take (a string's `minLength`, say) goes to a description, and
352
+ * is left to the check of the reply.
353
+ */
354
+ const formatOf = (output: z.ZodObject): Anthropic.Beta.Messages.BetaJSONOutputFormat => {
355
+ const { type, schema } = betaZodOutputFormat(output);
356
+ return { type, schema };
357
+ };
358
+
222
359
  /** The client of an agent without one of its own, on the context of the turn it answers. */
223
360
  const CLIENT = new ScopeKey<Anthropic>('the Anthropic client');
224
361
 
225
- /** {@link prompt}, answering with the agent's text. */
226
- const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
227
- transcribing(
228
- ctx,
229
- () => transcribe(ctx),
230
- () => answerOnce(ctx, text, options),
231
- );
232
-
233
- const answerOnce = async (
234
- ctx: restate.SessionContext,
235
- text: string,
236
- { model: named, system, tools = [], client, maxTokens = 16_000, effort }: Options,
237
- ): Promise<string> => {
238
- const agent = {
362
+ /** The agent of `options`, for the turn of `ctx`. */
363
+ const agentOf = (ctx: restate.SessionContext, options: Options): Agent => {
364
+ const { model, system, tools = [], client, maxTokens = 16_000, effort, output } = options;
365
+ return {
239
366
  client: client ?? CLIENT.of(ctx, () => new Anthropic()),
240
- model: modelIdOf(modelOf(named, CLAUDE_MODEL), 'anthropic'),
367
+ model: modelIdOf(modelOf(model, CLAUDE_MODEL), 'anthropic'),
241
368
  maxTokens,
242
369
  effort,
243
370
  system,
244
371
  tools: tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
372
+ ...(output !== undefined && asksNatively(options) ? { format: formatOf(output) } : {}),
245
373
  };
246
- const id = nextPromptId(ctx);
247
- const conversation = await Conversation.open(ctx.db);
248
- for (;;) {
249
- const answer = await conversation.answer(id);
250
- if (answer !== undefined) return storedAnswer(answer);
251
- // Finish an interrupted prompt first (this one's, after a crash), then
252
- // start this one.
253
- let pending = await conversation.pending();
254
- if (pending === undefined) {
255
- await conversation.append(id, [{ role: 'user', content: text }]);
256
- pending = id;
257
- }
258
- const turn = stopSignalOf(ctx);
259
- try {
260
- const running = run(ctx, agent, conversation, pending, turn);
261
- running.catch(() => {});
262
- await (turn ? Promise.race([running, aborted(turn)]) : running);
263
- } catch (error) {
264
- // The attempt ended: it stops, and the next attempt goes on with the prompt.
265
- if (turn?.reason instanceof AttemptEnded) throw turn.reason;
266
- // Cancelled: the prompt ends, and the next one starts afresh.
267
- if (turn?.aborted || error instanceof restate.CancelledError) {
268
- await conversation.cancel(pending, CANCELLED);
269
- throw turn?.aborted ? turn.reason : error;
270
- }
271
- // An earlier prompt that ended (cut off, or declined): this one goes on.
272
- if (
273
- pending !== id &&
274
- error instanceof restate.TerminalError &&
275
- (await conversation.answer(pending)) !== undefined
276
- ) {
277
- continue;
278
- }
279
- // Refused for good (a wrong API key): the prompt ends unanswered, and
280
- // fails as terminal. An earlier one's, this one goes on.
281
- const refused = refusalOf(ctx, error);
282
- if (!refused) throw error;
283
- await conversation.close(pending, UNANSWERED);
284
- if (pending === id) throw refused;
285
- }
286
- }
287
374
  };
288
375
 
289
376
  /**
290
377
  * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
291
378
  * of an invocation is a prompt of its own.
292
379
  * With `output`, it answers with the value the agent replies with (see
293
- * output.ts), not its text.
380
+ * output.ts), not its text: a reply that is not one is asked again within
381
+ * its turn, once. A model with structured outputs is asked for it natively
382
+ * (`nativeOutput`), else in the prompt.
294
383
  */
295
- export const prompt = <O extends z.ZodObject | undefined = undefined>(
384
+ export const prompt = async <O extends z.ZodObject | undefined = undefined>(
296
385
  ctx: restate.SessionContext,
297
386
  text: string,
298
387
  options: Options<O> = {},
299
- ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
388
+ ): Promise<Answer<O>> =>
389
+ withChecked(
390
+ text,
391
+ options,
392
+ (t, o, check, reminder) => answerOnce(ctx, t, items, runOf(ctx, agentOf(ctx, o)), { check, reminder }),
393
+ asksNatively(options),
394
+ ) as Promise<Answer<O>>;
300
395
 
301
396
  /**
302
397
  * A chat handler: each message an invocation, the conversation in the
@@ -306,45 +401,32 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
306
401
  */
307
402
  export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
308
403
  if (typeof options === 'object') modelIdOf(modelOf(options.model, CLAUDE_MODEL), 'anthropic');
309
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
404
+ return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
310
405
  };
311
406
 
312
- /** The text of stored content, without its tool calls and results. */
313
- const storedText = (content: string | readonly { type: string; text?: string }[] | undefined) =>
314
- typeof content === 'string' ? content : (content ?? []).flatMap((b) => (b.type === 'text' ? [b.text] : [])).join('');
315
-
316
407
  /**
317
- * A handler of the conversation as clients read it: a page at a time, or
318
- * what is new or changed since a cursor, from the log each change writes
319
- * (log.ts). It answers while a message is answered.
408
+ * A view of the conversation as clients read it: a page at a time, or what
409
+ * is new or changed since a cursor; `view: 'summary'` for each turn's
410
+ * message and answer. It answers while a message is answered.
320
411
  */
321
- export const messages = () => messagesHandler();
412
+ export const messages = () => conversationView(items);
322
413
 
323
414
  /**
324
- * The transcript of each session's conversation (`ctx.db`, one per
325
- * attempt), as far as it was read: the conversation only grows, so each
326
- * read adds the messages stored since.
415
+ * How an agent of `options` summarizes the earliest turns, past its budget:
416
+ * with its own client and model (`agent()` gives it; for an object of your
417
+ * own, `sessionObject`'s `summarize`).
327
418
  */
328
- const TRANSCRIPT = new ScopeKey<{ seq: number; transcript: Transcript }>('the transcript');
329
-
330
- /** The conversation in the database of `ctx`, as `messages` gives it. */
331
- const transcribe = async (ctx: restate.SessionContext): Promise<Transcript> => {
332
- const { db } = ctx;
333
- const read = TRANSCRIPT.of(ctx, () => ({ seq: 0, transcript: new Transcript() }));
334
- const { transcript } = read;
335
- for (const [seq, m] of await (await Conversation.open(db)).since(read.seq)) {
336
- read.seq = seq;
337
- if (m.role === 'system') continue;
338
- transcript.say(m.role, storedText(m.content));
339
- if (typeof m.content === 'string') continue;
340
- for (const block of m.content) {
341
- if (block.type === 'tool_use') transcript.call(block.id, block.name, block.input);
342
- if (block.type === 'tool_result')
343
- transcript.result(block.tool_use_id, storedText(block.content), block.is_error === true);
344
- }
345
- }
346
- return transcript;
347
- };
419
+ export const summarizer =
420
+ (options: Options = {}): Summarize =>
421
+ async (ctx, request) => {
422
+ const { client, model, maxTokens } = agentOf(ctx, { ...options, tools: [] });
423
+ const message = await client.beta.messages.create({
424
+ model,
425
+ max_tokens: maxTokens,
426
+ messages: [{ role: 'user', content: request }],
427
+ });
428
+ return textOf(message.content);
429
+ };
348
430
 
349
431
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
350
432
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -352,6 +434,9 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
352
434
  description,
353
435
  schema,
354
436
  background,
437
+ window,
438
+ budget,
439
+ summarize,
355
440
  ...options
356
441
  }: Options<O> & Definition<P>) =>
357
442
  sessionObject({
@@ -359,6 +444,9 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
359
444
  description,
360
445
  schema,
361
446
  background,
447
+ window,
448
+ budget,
449
+ summarize: summarize ?? summarizer(options),
362
450
  handlers: { chat: chat(options) },
363
451
  views: { messages: messages() },
364
452
  });
package/src/client.ts CHANGED
@@ -14,11 +14,12 @@
14
14
  // for await (const { status, messages } of follow(restate, agent('assistant'), 'alice')) { ... }
15
15
  import * as clients from '@restatedev/restate-sdk-clients';
16
16
  import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
17
- import type { ChatMessage, Messages, MessagesRequest, Part, Turn } from './common.ts';
17
+ import type { Answering, ChatMessage, Messages, MessagesRequest, Part } from './common.ts';
18
18
  import type { Status, Stopped, Synced, SyncRequest } from './object.ts';
19
- import type { Notifications, Resolved, Signal, Waiting, Watch } from './signals.ts';
19
+ import type { Notifications, Resolved, Signal, Steered, Steering, Waiting, Watch } from './signals.ts';
20
20
 
21
21
  export type {
22
+ Answering,
22
23
  ChatMessage,
23
24
  Messages,
24
25
  MessagesRequest,
@@ -27,10 +28,11 @@ export type {
27
28
  Resolved,
28
29
  Signal,
29
30
  Status,
31
+ Steered,
32
+ Steering,
30
33
  Stopped,
31
34
  Synced,
32
35
  SyncRequest,
33
- Turn,
34
36
  Waiting,
35
37
  Watch,
36
38
  };
@@ -39,6 +41,15 @@ export type {
39
41
  export interface Agent {
40
42
  /** Answer `message`. */
41
43
  chat(ctx: unknown, message: string): Promise<string>;
44
+ /**
45
+ * Send `message` while the agent answers another: the turn being answered
46
+ * takes it at its next step (once its model's tool calls have their
47
+ * results), and its answer covers it; else it is answered as a turn of its
48
+ * own, after the messages before it. Either way it is answered once: send
49
+ * it with an idempotency key, made once per message, so that sending it
50
+ * again is the same message.
51
+ */
52
+ steer(ctx: unknown, message: string): Promise<Steered>;
42
53
  /** The conversation, a page at a time, or what is new or changed since a cursor, also while a message is answered. */
43
54
  messages(ctx: unknown, request?: MessagesRequest): Promise<Messages>;
44
55
  /** The conversation since a cursor, the status and the revision; with `revision`, once there is a newer one. */