@restatedev/agents 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +689 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +78 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +83 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +67 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +224 -3
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
@@ -0,0 +1,364 @@
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).
4
+ //
5
+ // const assistant = claude.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
6
+ //
7
+ // or a handler of an object of your own: `handlers: { chat: claude.chat() }`,
8
+ // with options for each invocation: `claude.chat(async (ctx) => ({ system }))`,
9
+ // or a prompt of your own handler: `claude.prompt(ctx, text, options)`
10
+ //
11
+ // The model is `model`, or else MODEL, or else anthropic/claude-sonnet-5-5,
12
+ // with ANTHROPIC_API_KEY.
13
+ //
14
+ // 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
+ // - Each reply of the model is stored before its tools run, and their results
17
+ // before the next request. So a crash during the tools resumes them with the
18
+ // 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.
26
+ import * as restate from '@restatedev/sessions';
27
+ import type { Database } from '@restatedev/sessions';
28
+ import Anthropic from '@anthropic-ai/sdk';
29
+ import type { BetaRunnableTool, BetaToolRunContext } from '@anthropic-ai/sdk/lib/tools/BetaRunnableTool';
30
+ import {
31
+ aborted,
32
+ AttemptEnded,
33
+ CANCELLED,
34
+ chatHandler,
35
+ CLAUDE_MODEL,
36
+ type Configure,
37
+ configured,
38
+ fromTool,
39
+ messagesHandler,
40
+ modelIdOf,
41
+ modelOf,
42
+ nextPromptId,
43
+ refusal,
44
+ stopSignalOf,
45
+ storedAnswer,
46
+ toolCallEnded,
47
+ toolCallStarted,
48
+ transcribing,
49
+ Transcript,
50
+ UNANSWERED,
51
+ } from '../common.ts';
52
+ import { type Answer, withOutput } from '../output.ts';
53
+ import type { z } from 'zod';
54
+ import { type Definition, sessionObject } from '../object.ts';
55
+ import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
56
+ import { Conversation } from './conversation.ts';
57
+
58
+ /** The id of the tool call a tool runs for: the runner always passes it. */
59
+ export const callId = (context?: BetaToolRunContext) => {
60
+ if (!context) throw new Error('a tool call without its context');
61
+ return context.toolUse.id;
62
+ };
63
+
64
+ /**
65
+ * `tools`, whose errors fail the attempt: the runner would hand a thrown error
66
+ * to the model as the tool's result, so each one is kept, for `check()` to
67
+ * throw once the tools ran.
68
+ */
69
+ function failing(tools: BetaRunnableTool[]) {
70
+ let failure: unknown;
71
+ return {
72
+ tools: tools.map((tool): BetaRunnableTool => ({
73
+ ...tool,
74
+ run: async (args, context) => {
75
+ try {
76
+ return await tool.run(args, context);
77
+ } catch (e) {
78
+ fromTool(e);
79
+ failure ??= e;
80
+ throw e;
81
+ }
82
+ },
83
+ })),
84
+ check: () => {
85
+ if (failure !== undefined) throw failure;
86
+ },
87
+ };
88
+ }
89
+
90
+ const textOf = (content: Anthropic.Beta.Messages.BetaContentBlock[]) =>
91
+ content
92
+ .filter((c) => c.type === 'text')
93
+ .map((c) => c.text)
94
+ .join('');
95
+
96
+ interface Agent {
97
+ client: Anthropic;
98
+ model: string;
99
+ maxTokens: number;
100
+ effort?: Effort;
101
+ system?: string;
102
+ tools: BetaRunnableTool[];
103
+ }
104
+
105
+ /**
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).
109
+ */
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(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;
153
+ }
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
+ }
163
+
164
+ /**
165
+ * 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.
167
+ */
168
+ function stoppedShort(message: Anthropic.Beta.Messages.BetaMessage, maxTokens: number) {
169
+ 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
+ };
174
+ }
175
+ if (message.stop_reason === 'refusal') {
176
+ 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
+ };
181
+ }
182
+ return undefined;
183
+ }
184
+
185
+ /** `t` as a tool of the Anthropic SDK's tool runner: `t.run` checks the model's arguments itself. */
186
+ const native = (t: AnyTool, ctx: restate.SessionContext): BetaRunnableTool => ({
187
+ type: 'custom',
188
+ name: t.name,
189
+ description: t.description,
190
+ input_schema: jsonSchemaOf(t) as Anthropic.Beta.Messages.BetaTool.InputSchema,
191
+ parse: (args) => args,
192
+ run: (args, context) => t.run(args, { ctx, callId: callId(context) }),
193
+ });
194
+
195
+ /** How much effort the model puts into a reply (Anthropic's `output_config.effort`). */
196
+ export type Effort = 'low' | 'medium' | 'high' | 'xhigh' | 'max';
197
+
198
+ /** An agent's options: `chat` and `prompt` take them. */
199
+ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
200
+ /** The model, as `anthropic/model-id`: MODEL, or else anthropic/claude-sonnet-5-5. */
201
+ model?: string;
202
+ /** The system prompt. */
203
+ system?: string;
204
+ /** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or the SDK's (such as `betaZodTool`s). */
205
+ tools?: (AnyTool | BetaRunnableTool)[];
206
+ /** The client of the Anthropic API: by default one with ANTHROPIC_API_KEY. */
207
+ client?: Anthropic;
208
+ /**
209
+ * The most tokens of each of the model's replies (default 16000). A reply
210
+ * cut off there ends its prompt, which fails (a terminal error).
211
+ */
212
+ maxTokens?: number;
213
+ /** How much effort the model puts into each reply: more is more thorough, and slower (default: the model's). */
214
+ effort?: Effort;
215
+ /**
216
+ * The answer as data: a zod object, whose JSON the agent replies with
217
+ * (checked), and `chat` and `prompt` answer with (see output.ts).
218
+ */
219
+ output?: O;
220
+ }
221
+
222
+ /** The client of the agents without one of their own, made when first used. */
223
+ let shared: Anthropic | undefined;
224
+
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.db),
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 = {
239
+ client: client ?? (shared ??= new Anthropic()),
240
+ model: modelIdOf(modelOf(named, CLAUDE_MODEL), 'anthropic'),
241
+ maxTokens,
242
+ effort,
243
+ system,
244
+ tools: tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
245
+ };
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 = refusal(error);
282
+ if (!refused) throw error;
283
+ await conversation.close(pending, UNANSWERED);
284
+ if (pending === id) throw refused;
285
+ }
286
+ }
287
+ };
288
+
289
+ /**
290
+ * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
291
+ * of an invocation is a prompt of its own.
292
+ * With `output`, it answers with the value the agent replies with (see
293
+ * output.ts), not its text.
294
+ */
295
+ export const prompt = <O extends z.ZodObject | undefined = undefined>(
296
+ ctx: restate.SessionContext,
297
+ text: string,
298
+ options: Options<O> = {},
299
+ ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
300
+
301
+ /**
302
+ * A chat handler: each message an invocation, the conversation in the
303
+ * object's database, with `options`, or the options a function of the
304
+ * invocation's context gives. It takes the message as plain text
305
+ * (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
306
+ */
307
+ export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
308
+ if (typeof options === 'object') modelIdOf(modelOf(options.model, CLAUDE_MODEL), 'anthropic');
309
+ return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
310
+ };
311
+
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
+ /**
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.
320
+ */
321
+ export const messages = () => messagesHandler();
322
+
323
+ /**
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.
327
+ */
328
+ const transcripts = new WeakMap<Database, { seq: number; transcript: Transcript }>();
329
+
330
+ /** The conversation in `db`, as `messages` gives it. */
331
+ const transcribe = async (db: Database): Promise<Transcript> => {
332
+ const read = transcripts.get(db) ?? { seq: 0, transcript: new Transcript() };
333
+ transcripts.set(db, read);
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
+ };
348
+
349
+ /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
350
+ export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
351
+ name,
352
+ description,
353
+ schema,
354
+ background,
355
+ ...options
356
+ }: Options<O> & Definition<P>) =>
357
+ sessionObject({
358
+ name,
359
+ description,
360
+ schema,
361
+ background,
362
+ handlers: { chat: chat(options) },
363
+ views: { messages: messages() },
364
+ });
package/src/client.ts ADDED
@@ -0,0 +1,179 @@
1
+ // An agent 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
+ import type { VirtualObjectDefinition } from '@restatedev/restate-sdk-core';
17
+ import type { ChatMessage, Messages, MessagesRequest, Part, Turn } from './common.ts';
18
+ import type { Status, Stopped, Synced, SyncRequest } from './object.ts';
19
+ import type { Notifications, Resolved, Signal, Steered, Waiting, Watch } from './signals.ts';
20
+
21
+ export type {
22
+ ChatMessage,
23
+ Messages,
24
+ MessagesRequest,
25
+ Notifications,
26
+ Part,
27
+ Resolved,
28
+ Signal,
29
+ Status,
30
+ Steered,
31
+ Stopped,
32
+ Synced,
33
+ SyncRequest,
34
+ Turn,
35
+ Waiting,
36
+ Watch,
37
+ };
38
+
39
+ /** The handlers of an agent (`agent()` of any framework), as Restate's client calls them. */
40
+ export interface Agent {
41
+ /** Answer `message`. */
42
+ chat(ctx: unknown, message: string): Promise<string>;
43
+ /** The conversation, a page at a time, or what is new or changed since a cursor, also while a message is answered. */
44
+ messages(ctx: unknown, request?: MessagesRequest): Promise<Messages>;
45
+ /** The conversation since a cursor, the status and the revision; with `revision`, once there is a newer one. */
46
+ sync(ctx: unknown, request?: SyncRequest): Promise<Synced>;
47
+ /** What the agent is doing: the message it answers, and what its tools wait for. */
48
+ status(ctx: unknown): Promise<Status>;
49
+ /** Stop the message it answers: cancel its invocation. */
50
+ stop(ctx: unknown): Promise<Stopped>;
51
+ /** Forget the conversation (stopping the message it answers): its database and state too. */
52
+ clear(ctx: unknown): Promise<Stopped>;
53
+ /** Add `message` to the message it answers, at its next tool call (or answer it as a message of its own). */
54
+ steer(ctx: unknown, message: string): Promise<Steered>;
55
+ /** What its tools wait for. */
56
+ pending(ctx: unknown): Promise<Waiting[]>;
57
+ /** Resolve a wait: by its id, or the oldest for a name. */
58
+ signal(ctx: unknown, signal: Signal): Promise<Resolved>;
59
+ /** The revision of its conversation, which each change increases. */
60
+ notifications(ctx: unknown): Promise<Notifications>;
61
+ /** The revision, once there is one newer than `revision`, or at the timeout. */
62
+ watch(ctx: unknown, watch: Watch): Promise<Notifications>;
63
+ }
64
+
65
+ /**
66
+ * The agent `name`, as Restate's client takes it: its name, typed with the
67
+ * handlers of an agent (or `H`, an object of your own's).
68
+ */
69
+ export const agent = <H = Agent, P extends string = string>(name: P) => ({ name }) as VirtualObjectDefinition<P, H>;
70
+
71
+ /** What {@link follow} gives each time the conversation changes. */
72
+ export interface Followed {
73
+ /** What the agent is doing now. */
74
+ status: Status;
75
+ /**
76
+ * The messages new or changed since the last time, by when they changed: a
77
+ * message may come again, changed (a tool call with its output, say), with
78
+ * its `id`, which a UI keeps them by, and orders them by.
79
+ */
80
+ messages: ChatMessage[];
81
+ /**
82
+ * The id of the conversation's first message: one kept from before is
83
+ * gone (`clear` forgot it), and a UI drops it.
84
+ */
85
+ first: number;
86
+ /** Where this leaves off: `follow(..., { cursor })` carries on from here, later or elsewhere. */
87
+ cursor: number;
88
+ /** What the agent's tools wait for now (`status.waiting`). */
89
+ waiting: Waiting[];
90
+ }
91
+
92
+ /**
93
+ * `message` to read, such as in a terminal: its text after its role, and
94
+ * each tool call on a line of its own, with its output (`…` until it has one).
95
+ */
96
+ export const asText = ({ role, parts }: ChatMessage) =>
97
+ parts
98
+ .map((part) =>
99
+ part.type === 'text'
100
+ ? `${role}: ${part.text}`
101
+ : ` ${part.name}(${JSON.stringify(part.input)}) -> ${part.output ?? '…'}`,
102
+ )
103
+ .join('\n');
104
+
105
+ /** Where {@link follow} starts, and what stops it. */
106
+ export interface FollowOptions {
107
+ /** The messages new or changed since this cursor (a page's, or a `Followed`'s); by default, all of them. */
108
+ cursor?: number;
109
+ /** Following ends once it aborts. */
110
+ signal?: AbortSignal;
111
+ /** How long one wait for a change lasts at most, in seconds (default 50). */
112
+ timeoutSeconds?: number;
113
+ }
114
+
115
+ /** Whether a retry may answer: a network failure, Restate's (5xx) or too many requests (429); not a 4xx. */
116
+ const transient = (error: unknown) =>
117
+ !(error instanceof clients.HttpCallError) || error.status >= 500 || error.status === 429;
118
+
119
+ /**
120
+ * One `sync` of `followed`, tried again a second later with the same
121
+ * idempotency key until it answers, unless its error would last; undefined
122
+ * once `signal` aborts.
123
+ */
124
+ async function syncRetried(
125
+ followed: clients.IngressClient<Agent>,
126
+ request: SyncRequest,
127
+ signal: AbortSignal | undefined,
128
+ ): Promise<Synced | undefined> {
129
+ const opts = clients.rpc.opts<SyncRequest, Synced>({ signal, idempotencyKey: crypto.randomUUID() });
130
+ for (;;) {
131
+ if (signal?.aborted) return undefined;
132
+ try {
133
+ return await followed.sync(request, opts);
134
+ } catch (error) {
135
+ if (signal?.aborted) return undefined;
136
+ if (!transient(error)) throw error;
137
+ console.warn('follow: retrying', error);
138
+ await new Promise((resolve) => setTimeout(resolve, 1000));
139
+ }
140
+ }
141
+ }
142
+
143
+ /**
144
+ * The conversation of the agent `definition` (such as `agent('assistant')`)
145
+ * with key `key`, as it changes, through `ingress` (Restate's client): what
146
+ * the agent is doing and the messages so far, then each change, until
147
+ * `signal` aborts.
148
+ *
149
+ * Each change is one `sync`, which waits in Restate for the next. A network
150
+ * failure (or Restate's, restarting) does not end it: it tries again, and a
151
+ * sync it retries keeps its idempotency key, so it joins the one already
152
+ * waiting.
153
+ */
154
+ export async function* follow(
155
+ ingress: clients.Ingress,
156
+ definition: VirtualObjectDefinition<string, Agent>,
157
+ key: string,
158
+ { cursor = 0, signal, timeoutSeconds = 50 }: FollowOptions = {},
159
+ ): AsyncGenerator<Followed, void, void> {
160
+ const followed = ingress.objectClient(definition, key);
161
+ let revision: number | undefined;
162
+ for (;;) {
163
+ const synced = await syncRetried(followed, { cursor, revision, timeoutSeconds }, signal);
164
+ if (!synced) return;
165
+ // Nothing changed (the wait timed out): wait again.
166
+ if (synced.revision !== revision || synced.messages.length > 0) {
167
+ yield {
168
+ status: synced.status,
169
+ messages: synced.messages,
170
+ first: synced.first ?? 0,
171
+ cursor: synced.cursor,
172
+ waiting: synced.status.waiting,
173
+ };
174
+ }
175
+ cursor = synced.cursor;
176
+ // With more to read, at once; else once something changes.
177
+ revision = synced.more ? undefined : synced.revision;
178
+ }
179
+ }