@restatedev/agents 0.2.0 → 0.4.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 +89 -49
  2. package/dist/calls.d.ts +29 -8
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +79 -18
  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 +238 -156
  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 +161 -71
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +277 -226
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -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 +323 -107
  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 +234 -180
  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 -40
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +75 -7
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +154 -27
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +110 -24
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +271 -183
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +354 -247
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +385 -138
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +337 -193
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +178 -48
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -79
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +235 -31
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -145
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -193
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
package/src/common.ts CHANGED
@@ -1,13 +1,12 @@
1
1
  // What the frameworks share: their options (`Configure`, the model), the
2
2
  // ids of an invocation's prompts, the `chat` handler with its turn (status,
3
- // cancellation, publishing for the clients that follow it), and
4
- // the `messages` handler with its `Transcript`.
3
+ // cancellation, publishing for the clients that follow it), and what the
4
+ // conversation of turns (conversation.ts) takes: its notes, window and
5
+ // budget.
5
6
  import * as restate from '@restatedev/sessions';
6
- import { cancelCalls, cancelled } from '@restatedev/sessions/internal';
7
- import { settle } from './calls.ts';
8
- import * as log from './log.ts';
9
- import type { Said } from './log.ts';
10
- import { signals, signalsOf } from './signals.ts';
7
+ import { cancelCalls, cancelled, definitionOf, Link, ScopeKey } from '@restatedev/sessions/internal';
8
+ import { settleCalls } from './calls.ts';
9
+ import { type Published, type Steer, signals, signalsOf } from './signals.ts';
11
10
 
12
11
  /**
13
12
  * A value, or a function of the invocation's context that gives it: the
@@ -23,7 +22,7 @@ export const configured = async <T>(value: Configure<T>, ctx: restate.SessionCon
23
22
  typeof value === 'function' ? (value as (ctx: restate.SessionContext) => T | Promise<T>)(ctx) : value;
24
23
 
25
24
  /** The prompts each invocation made so far, by its context. */
26
- const prompts = new WeakMap<object, number>();
25
+ const PROMPTS = new ScopeKey<number>('nextPromptId');
27
26
 
28
27
  /**
29
28
  * The id of the next prompt of the invocation of `ctx`: the invocation's id,
@@ -31,12 +30,12 @@ const prompts = new WeakMap<object, number>();
31
30
  * order, so each gets the same id again, and its answer.
32
31
  */
33
32
  export const nextPromptId = (ctx: restate.SessionContext) => {
34
- const n = (prompts.get(ctx) ?? 0) + 1;
35
- prompts.set(ctx, n);
33
+ const n = (PROMPTS.get(ctx) ?? 0) + 1;
34
+ PROMPTS.set(ctx, n);
36
35
  return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
37
36
  };
38
37
 
39
- /** The default model of pi, OpenCode and LangGraph, with OPENAI_API_KEY. */
38
+ /** The default model of pi and LangGraph, with OPENAI_API_KEY. */
40
39
  export const DEFAULT_MODEL = 'openai/gpt-6-sol';
41
40
 
42
41
  /** The default model of Claude agents, with ANTHROPIC_API_KEY. */
@@ -111,6 +110,12 @@ export const messageSerde: restate.Serde<string> = {
111
110
  },
112
111
  };
113
112
 
113
+ /**
114
+ * What an empty answer says, as the model sees it later in the conversation:
115
+ * a provider's API may refuse an empty text (Anthropic's does).
116
+ */
117
+ export const NO_ANSWER = '(no answer)';
118
+
114
119
  /**
115
120
  * What a cancelled turn answers, and each tool call it cut off: the model
116
121
  * sees it in the conversation that goes on.
@@ -124,8 +129,63 @@ export const CANCELLED = 'Cancelled: the turn was stopped before it finished.';
124
129
  */
125
130
  export const UNANSWERED = "Unanswered: the model's provider refused the request.";
126
131
 
132
+ /**
133
+ * What a turn whose invocation ended without answering it (killed, say)
134
+ * answers, and each tool call it cut off: the next message, or the companion
135
+ * once it finds the invocation gone (`settle`), closes it with this.
136
+ */
137
+ export const ENDED = 'Ended: the turn ended before it finished, and was not answered.';
138
+
139
+ /** The result of a tool call a stopped turn cut off once its Restate call had answered: it happened. */
140
+ export const RETURNED_UNRECORDED =
141
+ "Done, but the turn was stopped before this call's result was recorded: it did happen, so check its effect before doing it again.";
142
+
143
+ /**
144
+ * What a stopped turn records as the result of its tool call `callId`, which
145
+ * has none: `text` (cancelled, say), unless the call's Restate call answered
146
+ * (`outcomes` of calls.ts), which the model would take for undone, and do
147
+ * again: then the error it answered with, or {@link RETURNED_UNRECORDED}.
148
+ */
149
+ export function cutOffResult(outcomes: ReadonlyMap<string, string | undefined>, callId: string, text: string) {
150
+ if (!outcomes.has(callId)) return text;
151
+ return outcomes.get(callId) ?? RETURNED_UNRECORDED;
152
+ }
153
+
154
+ /** How many of the latest answered turns the model sees whole (with their tool calls and results), or `'all'`. */
155
+ export type Window = number | 'all';
156
+
157
+ /** The window by default: the previous turn's tool calls and results stay in view, for a follow-up. */
158
+ export const WINDOW: Window = 1;
159
+
160
+ /** How many tokens of the turns before the window the model sees, by default, counted as 4 characters each. */
161
+ export const BUDGET = 32_000;
162
+
163
+ /** How an agent summarizes earlier turns: from the request ({@link SUMMARIZE} and the turns, as text) to the summary. */
164
+ export type Summarize = (ctx: restate.SessionContext, request: string) => Promise<string>;
165
+
166
+ /** What a request to summarize earlier turns starts with, before the turns themselves. */
167
+ export const SUMMARIZE =
168
+ "Summarize the conversation below, for the assistant who carries it on: keep the facts, names, numbers, decisions, the user's preferences, and what is still open. Answer with the summary only.\n\n";
169
+
170
+ /**
171
+ * What a turn checks its answer with: nothing if the answer is what was
172
+ * asked for, else the message that asks the model again, once, within the
173
+ * turn (`answerOnce`'s `check`). With `last`, the model was asked again
174
+ * already: a check that throws a terminal error then fails the turn, which
175
+ * is closed with it.
176
+ */
177
+ export type Check = (answer: string, last?: boolean) => string | undefined;
178
+
179
+ /** `window`, if it is one: a whole number of turns (0 or more), or `'all'`. */
180
+ export function checkWindow(window: Window): Window {
181
+ if (window !== 'all' && !(Number.isInteger(window) && window >= 0)) {
182
+ throw new Error(`window must be a number of turns (0 or more) or 'all', not ${JSON.stringify(window)}`);
183
+ }
184
+ return window;
185
+ }
186
+
127
187
  /** The message a `chat` handler is answering: its invocation, and when it started. */
128
- export interface Turn {
188
+ export interface Answering {
129
189
  /** The invocation's id: `/restate/invocation/<id>/attach` waits for its answer. */
130
190
  invocationId: string;
131
191
  /** When it started, as an ISO date. */
@@ -133,7 +193,7 @@ export interface Turn {
133
193
  }
134
194
 
135
195
  /** What stops each turn, by its context: see {@link stopSignalOf}. */
136
- const turns = new WeakMap<object, AbortSignal>();
196
+ const TURN = new ScopeKey<AbortSignal>('stopSignalOf');
137
197
 
138
198
  /**
139
199
  * Why a turn stopped when its attempt ended before it did: Restate suspended
@@ -156,60 +216,122 @@ export class AttemptEnded extends Error {
156
216
  * {@link AttemptEnded} once the attempt ends first (the work stops, and
157
217
  * answers nothing).
158
218
  */
159
- export const stopSignalOf = (ctx: object): AbortSignal | undefined => turns.get(ctx);
160
-
161
- /** The agents that run in the background (`background: true`): no one follows them as they work. */
162
- const background = new Set<string>();
163
-
164
- /** Agent `name` runs in the background: see `background` in object.ts. */
165
- export const inBackground = (name: string) => void background.add(name);
166
-
167
- /** What each agent clears beside its database, by its object's name: see {@link onClear}. */
168
- const clearing = new Map<string, (ctx: restate.SessionContext) => Promise<void>>();
169
-
170
- /** What a framework's `messages` view clears beside the agent's database: see {@link alsoClearing}. */
171
- const viewsClearing = new WeakMap<object, (ctx: restate.SessionContext) => Promise<void>>();
219
+ export const stopSignalOf = (ctx: restate.SessionContext): AbortSignal | undefined => TURN.get(ctx);
172
220
 
173
221
  /**
174
- * The `messages` view `view` of a framework that keeps a conversation apart
175
- * (OpenCode, in a database of its own): `clear` empties it too, as an agent
176
- * with this view is cleared.
222
+ * An agent's settings: whether it runs in the background (`background:
223
+ * true`: no one follows it as it works), and, for an agent on the
224
+ * conversation of turns (conversation.ts), its framework's items, how much
225
+ * of the conversation its model sees (`window` and `budget`), and how it
226
+ * summarizes the earliest turns (`summarize`).
177
227
  */
178
- export const alsoClearing = <V extends object>(view: V, clear: (ctx: restate.SessionContext) => Promise<void>) => {
179
- viewsClearing.set(view, clear);
180
- return view;
228
+ export interface Settings {
229
+ background: boolean;
230
+ /** The items of its framework, if it keeps the conversation of turns (its `messages` view is `conversationView`'s). */
231
+ items?: object;
232
+ window: Window;
233
+ budget: number;
234
+ summarize?: Summarize;
235
+ }
236
+
237
+ /** An agent's settings, on its definition. */
238
+ const AGENT = new Link<Settings>('an agent');
239
+
240
+ /** The items of a framework's `messages` view on the conversation of turns. */
241
+ export const ITEMS = new Link<object>('restate-agents.items');
242
+
243
+ /** `definition` is an agent's, with these settings: its framework's items, if it is on the conversation of turns. */
244
+ export const isAgent = <D extends object>(
245
+ definition: D,
246
+ {
247
+ background = false,
248
+ items = undefined as object | undefined,
249
+ window = WINDOW as Window,
250
+ budget = BUDGET,
251
+ summarize = undefined as Summarize | undefined,
252
+ },
253
+ ) => {
254
+ return AGENT.on(definition, {
255
+ background,
256
+ items,
257
+ window,
258
+ budget,
259
+ summarize,
260
+ });
181
261
  };
182
262
 
183
- /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
184
- export const onClear = (name: string, view: object | undefined) => {
185
- const clear = view === undefined ? undefined : viewsClearing.get(view);
186
- if (clear === undefined) clearing.delete(name);
187
- else clearing.set(name, clear);
263
+ /** The settings of the agent of `ctx`, if it is one. */
264
+ const agentOf = (ctx: restate.SessionContext) => {
265
+ const definition = definitionOf(ctx);
266
+ return definition && AGENT.of(definition);
188
267
  };
189
268
 
190
- /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
191
- export const cleared = async (ctx: restate.SessionContext) => clearing.get(ctx.request.target.service)?.(ctx);
269
+ /** The settings of the agent of `ctx`: the defaults, for an object that is no agent. */
270
+ export const settingsOf = (ctx: restate.SessionContext): Settings =>
271
+ agentOf(ctx) ?? { background: false, window: WINDOW, budget: BUDGET };
192
272
 
193
273
  /** Whether the agent of `ctx` runs in the background. */
194
- const unfollowed = (ctx: restate.SessionContext) => background.has(ctx.request.target.service);
274
+ const unfollowed = (ctx: restate.SessionContext) => agentOf(ctx)?.background === true;
195
275
 
196
276
  /** The `signals` object of the agent of `ctx`. */
197
277
  const signalsOfAgent = (ctx: restate.SessionContext) => ctx.rpc(signals, signalsOf(ctx));
198
278
 
199
279
  /**
200
- * The conversation of `ctx` changed (see `watch` in object.ts): its log takes
201
- * the change (while a framework answers: {@link transcribing}), its revision
202
- * increases, and the clients that follow it read it again. It is a call to
203
- * Restate, so it also sends what the handler wrote before, for them to read.
280
+ * The messages steered to a `chat` turn that it has not taken yet, as the
281
+ * companion last published them. The companion answers them to every
282
+ * `publish`, which a turn makes at each tool call's start and end: so the
283
+ * turn knows of them without a call of its own, and finds them at its next
284
+ * step (`takeSteers`). The newest revision wins, as tool calls that run at
285
+ * once publish at once.
204
286
  */
205
- const publish = async (ctx: restate.SessionContext) => {
206
- const read = reading.get(ctx);
207
- if (read) await logged(ctx, read);
208
- await signalsOfAgent(ctx).publish();
287
+ export class Inbox {
288
+ revision = -1;
289
+ messages: Steer[] = [];
290
+ readonly #listeners = new Set<() => void>();
291
+
292
+ /** Keep what `publish` answered, if it is newer than what is kept, and tell the listeners if it lists messages. */
293
+ saw(published: Published | undefined) {
294
+ if (typeof published !== 'object' || published === null) return;
295
+ const revision = published.revision ?? -1;
296
+ if (revision <= this.revision) return;
297
+ this.revision = revision;
298
+ this.messages = [...(published.steering ?? [])];
299
+ if (this.messages.length > 0) for (const listener of this.#listeners) listener();
300
+ }
301
+
302
+ /**
303
+ * Call `listener` after each publish that lists messages, until the
304
+ * returned function is called: for a framework that takes steered
305
+ * messages through an inbox of its own (pi's, DeepSeek's), handed to it as
306
+ * they come.
307
+ */
308
+ listen(listener: () => void): () => void {
309
+ this.#listeners.add(listener);
310
+ return () => this.#listeners.delete(listener);
311
+ }
312
+ }
313
+
314
+ const INBOX = new ScopeKey<Inbox>('inbox');
315
+
316
+ /** The inbox of the `chat` turn running on `ctx`, if it takes steered messages: none outside one. */
317
+ export const inboxOf = (ctx: restate.SessionContext) => INBOX.get(ctx);
318
+
319
+ /**
320
+ * The conversation of `ctx` changed (see `watch` in object.ts): its revision
321
+ * increases, and the clients that follow it read it again; while a framework
322
+ * answers ({@link answering}), the calls whose results it stored are
323
+ * forgotten first. It is a call to Restate, so it also sends what the
324
+ * handler wrote before, for them to read.
325
+ */
326
+ export const publish = async (ctx: restate.SessionContext) => {
327
+ const stored = ANSWERING.get(ctx);
328
+ if (stored) await settled(ctx, stored);
329
+ const published = await signalsOfAgent(ctx).publish();
330
+ INBOX.get(ctx)?.saw(published);
209
331
  };
210
332
 
211
333
  /** A step of a turn of `ctx`: {@link publish} it, unless the agent runs in the background, which publishes the turn's end only. */
212
- const stepped = async (ctx: restate.SessionContext) => {
334
+ export const stepped = async (ctx: restate.SessionContext) => {
213
335
  if (!unfollowed(ctx)) await publish(ctx);
214
336
  };
215
337
 
@@ -221,11 +343,8 @@ const stepped = async (ctx: restate.SessionContext) => {
221
343
  */
222
344
  export async function toolCallStarted(ctx: restate.SessionContext) {
223
345
  if (!unfollowed(ctx)) return publish(ctx);
224
- const read = reading.get(ctx);
225
- if (read) {
226
- const transcript = await read();
227
- await settle(ctx, (id, failed) => transcript.answered(id, failed));
228
- }
346
+ const stored = ANSWERING.get(ctx);
347
+ if (stored) await settled(ctx, stored);
229
348
  }
230
349
 
231
350
  /** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
@@ -233,6 +352,49 @@ export async function toolCallEnded(ctx: restate.SessionContext) {
233
352
  await stepped(ctx);
234
353
  }
235
354
 
355
+ /** Whether a tool call's result is stored: `stored(callId, failed)`, `failed` the error the call answered with. */
356
+ export type Stored = (callId: string, failed?: string) => boolean;
357
+
358
+ /** What the attempt's turn has stored, while it answers (see {@link answering}). */
359
+ const ANSWERING = new ScopeKey<Stored>('answering');
360
+
361
+ /** The attempt's latest settling of calls: one after another, as parallel tool calls publish at once. */
362
+ const SETTLING = new ScopeKey<Promise<void>>('settling');
363
+
364
+ /** Forget the calls whose results the conversation stored (calls.ts), after any settling before. */
365
+ function settled(ctx: restate.SessionContext, stored: Stored): Promise<void> {
366
+ const settle = () => settleCalls(ctx, stored);
367
+ const done = (SETTLING.get(ctx) ?? Promise.resolve()).then(settle, settle);
368
+ SETTLING.set(ctx, done);
369
+ return done;
370
+ }
371
+
372
+ /**
373
+ * Run `work`, a framework's turn on the conversation of turns, forgetting
374
+ * the calls whose results it stores as it goes: each publish while it runs
375
+ * (a tool call's start and end), and its end, forget the Restate calls of
376
+ * the tool calls whose results `stored` says are stored (calls.ts).
377
+ */
378
+ export async function answering<T>(ctx: restate.SessionContext, stored: Stored, work: () => Promise<T>): Promise<T> {
379
+ const outer = ANSWERING.get(ctx);
380
+ ANSWERING.set(ctx, stored);
381
+ let failed = false;
382
+ try {
383
+ return await work();
384
+ } catch (error) {
385
+ failed = !(error instanceof restate.TerminalError);
386
+ throw error;
387
+ } finally {
388
+ try {
389
+ // A failed attempt stores nothing more: its retry runs again.
390
+ if (!failed) await settled(ctx, stored);
391
+ } finally {
392
+ if (outer) ANSWERING.set(ctx, outer);
393
+ else ANSWERING.delete(ctx);
394
+ }
395
+ }
396
+ }
397
+
236
398
  /** A promise that rejects with `signal`'s reason once it aborts. */
237
399
  export const aborted = (signal: AbortSignal) =>
238
400
  new Promise<never>((_, reject) => {
@@ -240,6 +402,22 @@ export const aborted = (signal: AbortSignal) =>
240
402
  else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
241
403
  });
242
404
 
405
+ /** A `chat` handler's answer to a message: a framework's prompt, say. */
406
+ export type Chat<A = unknown> = (ctx: restate.SessionContext, message: string) => Promise<A>;
407
+
408
+ /**
409
+ * Whether a `chat` handler's turns take steered messages: for every message,
410
+ * or for each, as the invocation's context says (a framework's options that
411
+ * a function gives, say).
412
+ */
413
+ export type Steers = boolean | ((ctx: restate.SessionContext) => boolean | Promise<boolean>);
414
+
415
+ /** What makes a `chat` handler (`chatHandler`): its answer, and whether it takes steered messages. */
416
+ const CHAT = new Link<{ answer: Chat; steers: Steers }>('restate-agents.chat');
417
+
418
+ /** The answer of `entry`, a handler that `chatHandler` made, and whether it takes steered messages. */
419
+ export const chatOf = (entry: object) => CHAT.of(entry);
420
+
243
421
  /**
244
422
  * `answer` as a chat handler, which takes its message as plain text or as a
245
423
  * JSON string, so that both of these work:
@@ -247,7 +425,7 @@ export const aborted = (signal: AbortSignal) =>
247
425
  * curl localhost:8080/assistant/alice/chat -d 'Hi'
248
426
  * curl localhost:8080/assistant/alice/chat --json '"Hi"'
249
427
  *
250
- * While it answers, the object's `status` says so (its {@link Turn}). Its
428
+ * While it answers, the object's `status` says so (its {@link Answering}). Its
251
429
  * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
252
430
  * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
253
431
  * context, whenever it comes, and cancels the calls its tools made
@@ -258,58 +436,91 @@ export const aborted = (signal: AbortSignal) =>
258
436
  *
259
437
  * It publishes when it starts and ends ({@link publish}), for the clients
260
438
  * that follow the conversation.
439
+ *
440
+ * As the `chat` handler of an agent, it also answers each message sent to
441
+ * the agent's `steer` view that no turn took, as a turn of its own (the
442
+ * private `steered` handler). With `steers` (a framework's integration says
443
+ * so), its turns take steered messages at their steps (`takeSteers`).
261
444
  */
262
- export const chatHandler = <A = string>(answer: (ctx: restate.SessionContext, message: string) => Promise<A>) => ({
263
- input: messageSerde,
264
- accept: '*/*',
265
- explicitCancellation: true,
266
- handler: async (ctx: restate.SessionContext, text: string): Promise<A> => {
267
- const invocationId = ctx.request.id;
268
- // The companion knows the turn from here to its close: `status` and `stop` ask it.
269
- await ctx.rpc(signals, signalsOf(ctx)).start({ invocationId, since: new Date().toISOString() });
270
- await stepped(ctx);
271
- // The log takes the turn's last change, then the companion closes the
272
- // turn, which publishes it: one revision. The close is a call the turn
273
- // waits for, so that it is done before the turn ends (see `awaitTurn`).
274
- const end = async () => {
275
- const read = reading.get(ctx);
276
- if (read) await logged(ctx, read);
277
- await signalsOfAgent(ctx).close(invocationId);
278
- };
279
- const turn = new AbortController();
280
- turns.set(ctx, turn.signal);
281
- void (async () => {
282
- await cancelled(ctx);
283
- turn.abort(new restate.CancelledError());
284
- await cancelCalls(ctx);
285
- })().catch(() => {});
286
- // The attempt ends before the turn does: its work stops (a model's
287
- // request, say), rather than run on for an attempt that can store nothing.
288
- const attempt = ctx.request.attemptCompletedSignal;
289
- const attemptEnded = () => turn.abort(new AttemptEnded());
290
- attempt.addEventListener('abort', attemptEnded, { once: true });
291
- let answered: A;
292
- try {
293
- answered = await answer(ctx, text);
294
- // Cancelled once answered: the answer stands.
295
- } catch (error) {
296
- if (error instanceof restate.TerminalError) {
297
- await end();
298
- throw error;
299
- }
300
- // Any other error fails the attempt, and Restate retries the turn.
301
- const terminal = refusal(error);
302
- if (!terminal) throw error;
445
+ export const chatHandler = <A = string>(answer: Chat<A>, { steers = false }: { steers?: Steers } = {}) =>
446
+ CHAT.on(
447
+ {
448
+ input: messageSerde,
449
+ accept: '*/*',
450
+ explicitCancellation: true,
451
+ handler: (ctx: restate.SessionContext, text: string): Promise<A> => chatTurn(ctx, text, answer, steers),
452
+ },
453
+ { answer, steers },
454
+ );
455
+
456
+ /**
457
+ * Answer `text` as a turn of the agent of `ctx`, with `answer`: the body of a
458
+ * `chat` handler ({@link chatHandler}), and of `steered`. With `steers`, the
459
+ * turn takes the messages steered to it at its steps (unless the agent runs
460
+ * in the background).
461
+ */
462
+ export async function chatTurn<A>(
463
+ ctx: restate.SessionContext,
464
+ text: string,
465
+ answer: Chat<A>,
466
+ steers: Steers = false,
467
+ ): Promise<A> {
468
+ const invocationId = ctx.request.id;
469
+ // The companion knows the turn from here to its close: `status` and `stop` ask it.
470
+ // An agent on the conversation of turns has `settle`: the companion sends it
471
+ // this turn, should its invocation be gone without closing it.
472
+ const settles = agentOf(ctx)?.items !== undefined;
473
+ const steering = !unfollowed(ctx) && (typeof steers === 'function' ? await steers(ctx) : steers);
474
+ // Before the first publish, which may answer messages steered to the turn already (a retried attempt's).
475
+ if (steering) INBOX.set(ctx, new Inbox());
476
+ await ctx.rpc(signals, signalsOf(ctx)).start({
477
+ invocationId,
478
+ since: new Date().toISOString(),
479
+ ...(settles ? { settles } : {}),
480
+ ...(steering ? { steers: steering } : {}),
481
+ });
482
+ await stepped(ctx);
483
+ // The log takes the turn's last change, then the companion closes the
484
+ // turn, which publishes it: one revision. The close is a call the turn
485
+ // waits for, so that it is done before the turn ends (see `awaitTurn`).
486
+ const end = async () => {
487
+ const stored = ANSWERING.get(ctx);
488
+ if (stored) await settled(ctx, stored);
489
+ await signalsOfAgent(ctx).close(invocationId);
490
+ };
491
+ const turn = new AbortController();
492
+ TURN.set(ctx, turn.signal);
493
+ void (async () => {
494
+ await cancelled(ctx);
495
+ turn.abort(new restate.CancelledError());
496
+ await cancelCalls(ctx);
497
+ })().catch(() => {});
498
+ // The attempt ends before the turn does: its work stops (a model's
499
+ // request, say), rather than run on for an attempt that can store nothing.
500
+ const attempt = ctx.request.attemptCompletedSignal;
501
+ const attemptEnded = () => turn.abort(new AttemptEnded());
502
+ attempt.addEventListener('abort', attemptEnded, { once: true });
503
+ let answered: A;
504
+ try {
505
+ answered = await answer(ctx, text);
506
+ // Cancelled once answered: the answer stands.
507
+ } catch (error) {
508
+ if (error instanceof restate.TerminalError) {
303
509
  await end();
304
- throw terminal;
305
- } finally {
306
- // An attempt's signal aborts at every attempt's end, the turn's too.
307
- attempt.removeEventListener('abort', attemptEnded);
510
+ throw error;
308
511
  }
512
+ // Any other error fails the attempt, and Restate retries the turn.
513
+ const terminal = refusalOf(ctx, error);
514
+ if (!terminal) throw error;
309
515
  await end();
310
- return answered;
311
- },
312
- });
516
+ throw terminal;
517
+ } finally {
518
+ // An attempt's signal aborts at every attempt's end, the turn's too.
519
+ attempt.removeEventListener('abort', attemptEnded);
520
+ }
521
+ await end();
522
+ return answered;
523
+ }
313
524
 
314
525
  /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
315
526
  export class ToolError extends Error {
@@ -321,21 +532,26 @@ export class ToolError extends Error {
321
532
  }
322
533
  }
323
534
 
324
- /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
325
- const toolErrors = new WeakSet<object>();
535
+ /** The errors the attempt's framework tools (not `tool()`'s) failed with: see {@link fromTool}. */
536
+ const TOOL_ERRORS = new ScopeKey<WeakSet<object>>('fromTool');
326
537
 
327
538
  /**
328
- * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
329
- * that failed, whose error is never taken for the model's provider refusing
330
- * (a tool that calls a model API may fail as one does). `tool()`'s are
331
- * {@link ToolError}s.
539
+ * `error` is a tool's, in the attempt of `ctx`: a framework's own tool
540
+ * (Claude's, LangChain's...) that failed, whose error is never taken for
541
+ * the model's provider refusing (a tool that calls a model API may fail as
542
+ * one does). `tool()`'s are {@link ToolError}s.
332
543
  */
333
- export function fromTool(error: unknown) {
334
- if (typeof error === 'object' && error !== null) toolErrors.add(error);
544
+ export function fromTool(ctx: restate.SessionContext, error: unknown) {
545
+ if (typeof error === 'object' && error !== null) TOOL_ERRORS.of(ctx, () => new WeakSet()).add(error);
335
546
  }
336
547
 
337
548
  /** The Anthropic SDK's errors of a request that fails again however often it is made. */
338
- const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFoundError', 'BadRequestError']);
549
+ const FOR_GOOD: ReadonlySet<string> = new Set([
550
+ 'AuthenticationError',
551
+ 'PermissionDeniedError',
552
+ 'NotFoundError',
553
+ 'BadRequestError',
554
+ ]);
339
555
 
340
556
  /**
341
557
  * Whether `error` is a model provider's refusal that a retry does not change:
@@ -343,14 +559,19 @@ const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFo
343
559
  * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
344
560
  */
345
561
  function refused(error: unknown) {
346
- if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
347
- return false;
562
+ if (error instanceof ToolError) return false;
348
563
  if (error instanceof Error && FOR_GOOD.has(error.constructor.name)) return true;
349
564
  return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(
350
565
  String(error),
351
566
  );
352
567
  }
353
568
 
569
+ /** {@link refusal}, but not of an error a framework's tool failed with in the attempt of `ctx` ({@link fromTool}). */
570
+ export function refusalOf(ctx: restate.SessionContext, error: unknown): restate.TerminalError | undefined {
571
+ const failedTool = typeof error === 'object' && error !== null && TOOL_ERRORS.get(ctx)?.has(error);
572
+ return failedTool ? undefined : refusal(error);
573
+ }
574
+
354
575
  /**
355
576
  * `error` as a terminal error ({@link REFUSED}), if a retry does not change
356
577
  * it: a model the agent cannot take, or its provider's refusal.
@@ -364,13 +585,20 @@ export function refusal(error: unknown): restate.TerminalError | undefined {
364
585
  }
365
586
 
366
587
  /**
367
- * A prompt's stored answer, as the prompt returns it: {@link UNANSWERED},
368
- * stored as its provider refused it, fails as the prompt did then
369
- * ({@link REFUSED}), also in a retry after a crash right after it was stored.
588
+ * A prompt's stored answer, as the prompt returns it, by how its turn ended
589
+ * (`status`): a turn refused ({@link UNANSWERED}) fails with
590
+ * {@link REFUSED}, one failed for good with its error, one cancelled with
591
+ * the cancellation, one another invocation ended with its note; so that a
592
+ * retry after a crash right after the close fails as the prompt did.
370
593
  */
371
- export function storedAnswer(answer: string): string {
372
- if (answer !== UNANSWERED) return answer;
373
- throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
594
+ export function storedAnswer(answer: string, status = 'answered'): string {
595
+ if (status === 'refused') {
596
+ throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
597
+ }
598
+ if (status === 'cancelled') throw new restate.CancelledError();
599
+ if (status === 'failed') throw new restate.TerminalError(answer.replace(/^Error: /, ''));
600
+ if (status === 'ended') throw new restate.TerminalError(answer);
601
+ return answer;
374
602
  }
375
603
 
376
604
  /** A message of a conversation, as an agent's `messages` handler returns it. */
@@ -396,6 +624,12 @@ export type Part =
396
624
  * follow it.
397
625
  */
398
626
  export interface MessagesRequest {
627
+ /**
628
+ * `full` (the default): every message, with its tool calls; `summary`:
629
+ * each turn's message of the user and its answer, under the ids they have
630
+ * in the full view.
631
+ */
632
+ view?: 'full' | 'summary';
399
633
  /** At most this many messages (default 50). */
400
634
  limit?: number;
401
635
  /** The messages before this one (its `id`): older ones, such as for scrolling back. */
@@ -421,130 +655,3 @@ export interface Messages {
421
655
  */
422
656
  first?: number;
423
657
  }
424
-
425
- /**
426
- * A conversation as `messages` gives it, built from a framework's transcript:
427
- * each message is started by `say`, a tool call goes to the assistant's
428
- * message, and its result to its call. Messages without parts are left out.
429
- *
430
- * A message, once given out by `messages()`, is never changed: a change
431
- * makes a new one in its place. So a framework can keep its transcript and
432
- * add to it as its conversation grows, and the log stores only the messages
433
- * that are not the ones it stored last (see log.ts).
434
- */
435
- export class Transcript {
436
- #messages: Said[] = [];
437
- /** The message of each tool call, by the call's id: its index. */
438
- #calls = new Map<string, number>();
439
-
440
- /** A new message of `role`, with `text` if there is any. */
441
- say(role: ChatMessage['role'], text = '') {
442
- this.#messages.push({ role, parts: text.trim() ? [{ type: 'text', text }] : [] });
443
- }
444
-
445
- /** Tool call `id` of the assistant's message. */
446
- call(id: string, name: string, input: unknown) {
447
- if (this.#messages.at(-1)?.role !== 'assistant') this.say('assistant');
448
- const at = this.#messages.length - 1;
449
- this.#change(at, (parts) => [...parts, { type: 'tool', id, name, input }]);
450
- this.#calls.set(id, at);
451
- }
452
-
453
- /** The output of tool call `id`; an error's if the framework says so, or it is a tool's `Error: <message>`. */
454
- result(id: string, output: string, error = false) {
455
- const at = this.#calls.get(id);
456
- if (at === undefined) return;
457
- const failed = error || output.startsWith('Error: ');
458
- this.#change(at, (parts) =>
459
- parts.map((p) => (p.type === 'tool' && p.id === id ? { ...p, output, ...(failed ? { error: true } : {}) } : p)),
460
- );
461
- }
462
-
463
- /**
464
- * Whether tool call `id` has its output: not an error's, unless it is
465
- * `failed`, the error the call answered with.
466
- */
467
- answered(id: string, failed?: string) {
468
- const at = this.#calls.get(id);
469
- return (
470
- at !== undefined &&
471
- this.#messages[at]!.parts.some(
472
- (p) => p.type === 'tool' && p.id === id && p.output !== undefined && (!p.error || p.output === failed),
473
- )
474
- );
475
- }
476
-
477
- /** Its messages, in order: those with parts. */
478
- messages(): Said[] {
479
- return this.#messages.filter((m) => m.parts.length > 0);
480
- }
481
-
482
- /** Message `at` with its parts as `change` makes them: a new message, in its place. */
483
- #change(at: number, change: (parts: Part[]) => Part[]) {
484
- const message = this.#messages[at]!;
485
- this.#messages[at] = { ...message, parts: change(message.parts) };
486
- }
487
- }
488
-
489
- /**
490
- * A framework's transcript as it stands, while it answers (see
491
- * {@link transcribing}): a new one, or the one it keeps and adds to.
492
- */
493
- export type Read = () => Promise<Transcript>;
494
-
495
- /** The transcript of the turn of each context, while it answers. */
496
- const reading = new WeakMap<object, Read>();
497
-
498
- /** The log writes of each context, one after another: tool calls in parallel publish at once. */
499
- const writing = new WeakMap<object, Promise<void>>();
500
-
501
- /** The log of the conversation of `ctx` takes its transcript as `read` gives it. */
502
- function logged(ctx: restate.SessionContext, read: Read): Promise<void> {
503
- const write = async () => {
504
- const transcript = await read();
505
- await log.sync(ctx.db, transcript.messages());
506
- // The calls whose results the framework stored are made: see calls.ts.
507
- await settle(ctx, (id, failed) => transcript.answered(id, failed));
508
- };
509
- const done = (writing.get(ctx) ?? Promise.resolve()).then(write, write);
510
- writing.set(ctx, done);
511
- return done;
512
- }
513
-
514
- /**
515
- * Run `work`, a framework's turn (or a compaction, a reset), with `read`
516
- * giving the framework's transcript as it stands, from the framework as
517
- * `work` holds it open: each publish meanwhile (a tool call's start and end)
518
- * takes it into the conversation's log, and so does `work`'s end, before the
519
- * framework closes. `messages` and `sync` read the log.
520
- */
521
- export async function transcribing<T>(ctx: restate.SessionContext, read: Read, work: () => Promise<T>): Promise<T> {
522
- const outer = reading.get(ctx);
523
- reading.set(ctx, read);
524
- let failed = false;
525
- try {
526
- return await work();
527
- } catch (error) {
528
- failed = !(error instanceof restate.TerminalError);
529
- throw error;
530
- } finally {
531
- try {
532
- // A failed attempt stores nothing more: its retry runs again.
533
- if (!failed) await logged(ctx, read);
534
- } finally {
535
- if (outer) reading.set(ctx, outer);
536
- else reading.delete(ctx);
537
- }
538
- }
539
- }
540
-
541
- /**
542
- * The handler of an agent's conversation as clients read it, from its log:
543
- * a page of it (`{limit, before}`), or what is new or changed since a cursor
544
- * (`{cursor}`). It is a view: it answers while a message is answered, with
545
- * what was stored so far, and stores nothing.
546
- */
547
- export const messagesHandler =
548
- () =>
549
- async (ctx: restate.ViewContext, request?: MessagesRequest): Promise<Messages> =>
550
- log.page(ctx.db, request ?? {});