@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
package/src/common.ts ADDED
@@ -0,0 +1,593 @@
1
+ // What the frameworks share: their options (`Configure`, the model), the
2
+ // ids of an invocation's prompts, the `chat` handler with its turn (status,
3
+ // cancellation, steering, publishing for the clients that follow it), and
4
+ // the `messages` handler with its `Transcript`.
5
+ 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 { agentOf, type Steer, signals, signalsOf } from './signals.ts';
11
+
12
+ /**
13
+ * A value, or a function of the invocation's context that gives it: the
14
+ * same for every message, or each user's (from the object's database, say).
15
+ *
16
+ * pi.chat({ model: 'openai/gpt-6-sol' })
17
+ * pi.chat(async (ctx) => ({ model: await userModel(ctx) }))
18
+ */
19
+ export type Configure<T> = T | ((ctx: restate.SessionContext) => T | Promise<T>);
20
+
21
+ /** `value` for the invocation of `ctx`. */
22
+ export const configured = async <T>(value: Configure<T>, ctx: restate.SessionContext): Promise<T> =>
23
+ typeof value === 'function' ? (value as (ctx: restate.SessionContext) => T | Promise<T>)(ctx) : value;
24
+
25
+ /** The prompts each invocation made so far, by its context. */
26
+ const prompts = new WeakMap<object, number>();
27
+
28
+ /**
29
+ * The id of the next prompt of the invocation of `ctx`: the invocation's id,
30
+ * then `<id>:2`, `<id>:3`... A retried attempt makes its prompts in the same
31
+ * order, so each gets the same id again, and its answer.
32
+ */
33
+ export const nextPromptId = (ctx: restate.SessionContext) => {
34
+ const n = (prompts.get(ctx) ?? 0) + 1;
35
+ prompts.set(ctx, n);
36
+ return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
37
+ };
38
+
39
+ /** The default model of pi, OpenCode and LangGraph, with OPENAI_API_KEY. */
40
+ export const DEFAULT_MODEL = 'openai/gpt-6-sol';
41
+
42
+ /** The default model of Claude agents, with ANTHROPIC_API_KEY. */
43
+ export const CLAUDE_MODEL = 'anthropic/claude-sonnet-5-5';
44
+
45
+ /**
46
+ * The model, as `provider/model-id` (such as `openai/gpt-6-sol`):
47
+ * `model`, or else MODEL, or else the framework's default.
48
+ */
49
+ export const modelOf = (model: string | undefined, fallback = DEFAULT_MODEL) => model || process.env.MODEL || fallback;
50
+
51
+ /** `provider/model-id` as its provider and model id, split at the first `/` (`openrouter/meta-llama/llama-4`). */
52
+ export const providerOf = (model: string): [provider: string, id: string] => {
53
+ const slash = model.indexOf('/');
54
+ return slash < 0 ? ['', model] : [model.slice(0, slash), model.slice(slash + 1)];
55
+ };
56
+
57
+ /**
58
+ * The error code of a message the model's provider refused (a missing or
59
+ * wrong API key, an unknown model): 424, Failed Dependency, as its HTTP
60
+ * status.
61
+ */
62
+ export const REFUSED = 424;
63
+
64
+ /** What to check when a model's provider refuses a request. */
65
+ export const CHECK_MODEL = "check the agent's model (its `model` option, or MODEL) and its provider's API key";
66
+
67
+ /**
68
+ * An agent's model that it cannot take: not `provider/model-id`, another
69
+ * provider's, or one its framework does not know. Terminal ({@link REFUSED}),
70
+ * wherever it is thrown: a retry takes the same model.
71
+ */
72
+ export class ModelError extends restate.TerminalError {
73
+ constructor(message: string) {
74
+ super(message, { errorCode: REFUSED });
75
+ this.name = 'ModelError';
76
+ }
77
+ }
78
+
79
+ /** `model`, the explicit `model` option of `framework`'s agent, if it is not `provider/model-id`. */
80
+ export const checkModelName = (framework: string, model: string | undefined) => {
81
+ if (model !== undefined && !/^[^/\s]+\/\S+$/.test(model)) {
82
+ throw new ModelError(`${framework}: the model "${model}" is not provider/model-id, such as openai/gpt-6-sol`);
83
+ }
84
+ };
85
+
86
+ /**
87
+ * The model id of `model`, for a framework with only `provider`'s models:
88
+ * `provider/model-id`, or the id alone.
89
+ */
90
+ export const modelIdOf = (model: string, provider: string) => {
91
+ const [named, id] = model.includes('/') ? providerOf(model) : [provider, model];
92
+ if (named !== provider || !id) {
93
+ const from = process.env.MODEL === model ? ' (from MODEL)' : '';
94
+ throw new ModelError(`the model "${model}"${from} is not ${provider}'s: this agent takes ${provider}/<model-id>`);
95
+ }
96
+ return id;
97
+ };
98
+
99
+ /** A chat message: the request's body as text, or the string it is as JSON (`"Hi"`). */
100
+ export const messageSerde: restate.Serde<string> = {
101
+ contentType: 'text/plain',
102
+ serialize: (text) => new TextEncoder().encode(text),
103
+ deserialize: (bytes) => {
104
+ const text = new TextDecoder().decode(bytes);
105
+ try {
106
+ const value: unknown = JSON.parse(text);
107
+ return typeof value === 'string' ? value : text;
108
+ } catch {
109
+ return text;
110
+ }
111
+ },
112
+ };
113
+
114
+ /**
115
+ * What a cancelled turn answers, and each tool call it cut off: the model
116
+ * sees it in the conversation that goes on.
117
+ */
118
+ export const CANCELLED = 'Cancelled: the turn was stopped before it finished.';
119
+
120
+ /**
121
+ * What a prompt answers that the model's provider refused for good (see
122
+ * {@link refusal}): the prompt is over, and the model sees it in the
123
+ * conversation that goes on, rather than answer it with the next message.
124
+ */
125
+ export const UNANSWERED = "Unanswered: the model's provider refused the request.";
126
+
127
+ /** The message a `chat` handler is answering: its invocation, and when it started. */
128
+ export interface Turn {
129
+ /** The invocation's id: `/restate/invocation/<id>/attach` waits for its answer. */
130
+ invocationId: string;
131
+ /** When it started, as an ISO date. */
132
+ since: string;
133
+ }
134
+
135
+ /** What stops each turn, by its context: see {@link stopSignalOf}. */
136
+ const turns = new WeakMap<object, AbortSignal>();
137
+
138
+ /**
139
+ * Why a turn stopped when its attempt ended before it did: Restate suspended
140
+ * the attempt, gave up on it, or lost its connection. Nothing the attempt
141
+ * does after is stored, and the next attempt goes on with the turn, so it
142
+ * stops without answering: unlike a cancellation, nothing is cancelled.
143
+ */
144
+ export class AttemptEnded extends Error {
145
+ constructor() {
146
+ super('the attempt ended before its turn did');
147
+ this.name = 'AttemptEnded';
148
+ }
149
+ }
150
+
151
+ /**
152
+ * The signal that stops the turn of `ctx` (of a `chat` handler,
153
+ * `chatHandler`), and an agent's `prompt` stops its framework's work with it.
154
+ * It aborts with a `restate.CancelledError` once Restate cancels the
155
+ * invocation (the turn ends, answered as cancelled), or with an
156
+ * {@link AttemptEnded} once the attempt ends first (the work stops, and
157
+ * answers nothing).
158
+ */
159
+ export const stopSignalOf = (ctx: object): AbortSignal | undefined => turns.get(ctx);
160
+
161
+ /** The ids of the messages steered to each turn that its conversation has, by its context. */
162
+ const steerings = new WeakMap<object, Set<string>>();
163
+
164
+ /** A framework's conversation, while it answers a message: what steering needs of it. */
165
+ export interface Steerable {
166
+ /** Give it `message`, for its next step: once, by the message's id, however often it is given. */
167
+ steer(message: Steer): Promise<void>;
168
+ /** Whether it has message `id`: given in this attempt, or an earlier one. */
169
+ has(id: string): Promise<boolean>;
170
+ }
171
+
172
+ /** The agents that run in the background (`background: true`): no one follows them as they work. */
173
+ const background = new Set<string>();
174
+
175
+ /** Agent `name` runs in the background: see `background` in object.ts. */
176
+ export const inBackground = (name: string) => void background.add(name);
177
+
178
+ /** What each agent clears beside its database, by its object's name: see {@link onClear}. */
179
+ const clearing = new Map<string, (ctx: restate.SessionContext) => Promise<void>>();
180
+
181
+ /** What a framework's `messages` view clears beside the agent's database: see {@link alsoClearing}. */
182
+ const viewsClearing = new WeakMap<object, (ctx: restate.SessionContext) => Promise<void>>();
183
+
184
+ /**
185
+ * The `messages` view `view` of a framework that keeps a conversation apart
186
+ * (OpenCode, in a database of its own): `clear` empties it too, as an agent
187
+ * with this view is cleared.
188
+ */
189
+ export const alsoClearing = <V extends object>(view: V, clear: (ctx: restate.SessionContext) => Promise<void>) => {
190
+ viewsClearing.set(view, clear);
191
+ return view;
192
+ };
193
+
194
+ /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
195
+ export const onClear = (name: string, view: object | undefined) => {
196
+ const clear = view === undefined ? undefined : viewsClearing.get(view);
197
+ if (clear === undefined) clearing.delete(name);
198
+ else clearing.set(name, clear);
199
+ };
200
+
201
+ /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
202
+ export const cleared = async (ctx: restate.SessionContext) => clearing.get(ctx.request.target.service)?.(ctx);
203
+
204
+ /** Whether the agent of `ctx` runs in the background. */
205
+ const unfollowed = (ctx: restate.SessionContext) => background.has(ctx.request.target.service);
206
+
207
+ /** The `signals` object of the agent of `ctx`. */
208
+ const signalsOfAgent = (ctx: restate.SessionContext) => ctx.rpc(signals, signalsOf(ctx));
209
+
210
+ /**
211
+ * The conversation of `ctx` changed (see `watch` in object.ts): its log takes
212
+ * the change (while a framework answers: {@link transcribing}), its revision
213
+ * increases, and the clients that follow it read it again. It is a call to
214
+ * Restate, so it also sends what the handler wrote before, for them to read.
215
+ */
216
+ const publish = async (ctx: restate.SessionContext) => {
217
+ const read = reading.get(ctx);
218
+ if (read) await logged(ctx, read);
219
+ await signalsOfAgent(ctx).publish();
220
+ };
221
+
222
+ /** A step of a turn of `ctx`: {@link publish} it, unless the agent runs in the background, which publishes the turn's end only. */
223
+ const stepped = async (ctx: restate.SessionContext) => {
224
+ if (!unfollowed(ctx)) await publish(ctx);
225
+ };
226
+
227
+ /**
228
+ * A tool call of the turn of `ctx` starts: {@link publish} it, which forgets
229
+ * the calls whose results are stored (calls.ts) before the tool makes its
230
+ * own. In the background, which publishes the turn's end only, it forgets
231
+ * them alone.
232
+ */
233
+ export async function toolCallStarted(ctx: restate.SessionContext) {
234
+ if (!unfollowed(ctx)) return publish(ctx);
235
+ const read = reading.get(ctx);
236
+ if (read) {
237
+ const transcript = await read();
238
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
239
+ }
240
+ }
241
+
242
+ /**
243
+ * A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish}
244
+ * it, and give `conversation` the messages steered to the turn since, which it
245
+ * does not have yet: its next step takes them. Without a conversation (a
246
+ * framework that takes no steering), they wait for the turn's end.
247
+ */
248
+ export async function toolCallEnded(ctx: restate.SessionContext, conversation?: Steerable) {
249
+ // In the background, no one steers: a message steered anyway is answered after the turn.
250
+ if (unfollowed(ctx)) return;
251
+ const messages = await signalsOfAgent(ctx).progress(ctx.request.id);
252
+ const taken = steerings.get(ctx);
253
+ if (!taken || !conversation) return;
254
+ for (const message of messages.filter((m) => !taken.has(m.id))) {
255
+ if (!(await conversation.has(message.id))) await conversation.steer(message);
256
+ taken.add(message.id);
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Count the messages steered to the turn of `ctx` that `conversation` has,
262
+ * such as those an earlier attempt gave it. A framework calls it once a
263
+ * prompt is answered; the turn's other messages are answered as messages of
264
+ * their own, when it ends.
265
+ */
266
+ export async function settleSteering(ctx: restate.SessionContext, conversation: Pick<Steerable, 'has'>) {
267
+ const taken = steerings.get(ctx);
268
+ if (!taken) return;
269
+ for (const message of await signalsOfAgent(ctx).steering(ctx.request.id)) {
270
+ if (!taken.has(message.id) && (await conversation.has(message.id))) taken.add(message.id);
271
+ }
272
+ }
273
+
274
+ /** A promise that rejects with `signal`'s reason once it aborts. */
275
+ export const aborted = (signal: AbortSignal) =>
276
+ new Promise<never>((_, reject) => {
277
+ if (signal.aborted) reject(signal.reason);
278
+ else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
279
+ });
280
+
281
+ /**
282
+ * `answer` as a chat handler, which takes its message as plain text or as a
283
+ * JSON string, so that both of these work:
284
+ *
285
+ * curl localhost:8080/assistant/alice/chat -d 'Hi'
286
+ * curl localhost:8080/assistant/alice/chat --json '"Hi"'
287
+ *
288
+ * While it answers, the object's `status` says so (its {@link Turn}). Its
289
+ * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
290
+ * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
291
+ * context, whenever it comes, and cancels the calls its tools made
292
+ * (`cancelCalls(ctx)`): the agent's `prompt`
293
+ * ends the turn, and the handler fails with a `restate.CancelledError`. An
294
+ * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
295
+ * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
296
+ *
297
+ * Messages steered to it (`steer`) go to the agent's conversation at its next
298
+ * tool call ({@link toolCallEnded}); when it ends, those it did not take are
299
+ * answered as messages of their own, unless it was cancelled. It publishes
300
+ * when it starts and ends ({@link publish}), for the clients that follow the
301
+ * conversation.
302
+ */
303
+ export const chatHandler = <A = string>(answer: (ctx: restate.SessionContext, message: string) => Promise<A>) => ({
304
+ input: messageSerde,
305
+ accept: '*/*',
306
+ explicitCancellation: true,
307
+ handler: async (ctx: restate.SessionContext, text: string): Promise<A> => {
308
+ const invocationId = ctx.request.id;
309
+ // The companion knows the turn from here to its close: `status`, `stop` and `steer` ask it.
310
+ await ctx
311
+ .rpc(signals, signalsOf(ctx))
312
+ .start({ agent: agentOf(ctx), turn: { invocationId, since: new Date().toISOString() } });
313
+ const taken = new Set<string>();
314
+ steerings.set(ctx, taken);
315
+ await stepped(ctx);
316
+ const end = async (dropped = false) => {
317
+ ctx
318
+ .send(signals, signalsOf(ctx))
319
+ .close({ agent: agentOf(ctx), turn: invocationId, taken: [...taken], cancelled: dropped });
320
+ await publish(ctx);
321
+ };
322
+ const turn = new AbortController();
323
+ turns.set(ctx, turn.signal);
324
+ void (async () => {
325
+ await cancelled(ctx);
326
+ turn.abort(new restate.CancelledError());
327
+ await cancelCalls(ctx);
328
+ })().catch(() => {});
329
+ // The attempt ends before the turn does: its work stops (a model's
330
+ // request, say), rather than run on for an attempt that can store nothing.
331
+ const attempt = ctx.request.attemptCompletedSignal;
332
+ const attemptEnded = () => turn.abort(new AttemptEnded());
333
+ attempt.addEventListener('abort', attemptEnded, { once: true });
334
+ let answered: A;
335
+ try {
336
+ answered = await answer(ctx, text);
337
+ // Cancelled once answered: the answer stands.
338
+ } catch (error) {
339
+ if (error instanceof restate.TerminalError) {
340
+ await end(error instanceof restate.CancelledError);
341
+ throw error;
342
+ }
343
+ // Any other error fails the attempt, and Restate retries the turn.
344
+ const terminal = refusal(error);
345
+ if (!terminal) throw error;
346
+ await end();
347
+ throw terminal;
348
+ } finally {
349
+ // An attempt's signal aborts at every attempt's end, the turn's too.
350
+ attempt.removeEventListener('abort', attemptEnded);
351
+ }
352
+ await end();
353
+ return answered;
354
+ },
355
+ });
356
+
357
+ /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
358
+ export class ToolError extends Error {
359
+ readonly tool: string;
360
+ constructor(tool: string, cause: unknown) {
361
+ super(`the tool ${tool} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
362
+ this.name = 'ToolError';
363
+ this.tool = tool;
364
+ }
365
+ }
366
+
367
+ /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
368
+ const toolErrors = new WeakSet<object>();
369
+
370
+ /**
371
+ * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
372
+ * that failed, whose error is never taken for the model's provider refusing
373
+ * (a tool that calls a model API may fail as one does). `tool()`'s are
374
+ * {@link ToolError}s.
375
+ */
376
+ export function fromTool(error: unknown) {
377
+ if (typeof error === 'object' && error !== null) toolErrors.add(error);
378
+ }
379
+
380
+ /** The Anthropic SDK's errors of a request that fails again however often it is made. */
381
+ const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFoundError', 'BadRequestError']);
382
+
383
+ /**
384
+ * Whether `error` is a model provider's refusal that a retry does not change:
385
+ * a missing or wrong API key, an unknown model, a bad request. Other errors
386
+ * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
387
+ */
388
+ function refused(error: unknown) {
389
+ if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
390
+ return false;
391
+ if (error instanceof Error && FOR_GOOD.has(error.constructor.name)) return true;
392
+ return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(
393
+ String(error),
394
+ );
395
+ }
396
+
397
+ /**
398
+ * `error` as a terminal error ({@link REFUSED}), if a retry does not change
399
+ * it: a model the agent cannot take, or its provider's refusal.
400
+ */
401
+ export function refusal(error: unknown): restate.TerminalError | undefined {
402
+ if (error instanceof ModelError) return error;
403
+ if (error instanceof restate.TerminalError || !refused(error)) return undefined;
404
+ return new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}. ${String(error)}`, {
405
+ errorCode: REFUSED,
406
+ });
407
+ }
408
+
409
+ /**
410
+ * A prompt's stored answer, as the prompt returns it: {@link UNANSWERED},
411
+ * stored as its provider refused it, fails as the prompt did then
412
+ * ({@link REFUSED}), also in a retry after a crash right after it was stored.
413
+ */
414
+ export function storedAnswer(answer: string): string {
415
+ if (answer !== UNANSWERED) return answer;
416
+ throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
417
+ }
418
+
419
+ /** A message of a conversation, as an agent's `messages` handler returns it. */
420
+ export interface ChatMessage {
421
+ /** Its id, from 0, in the order of the conversation; the same however it changes. `before` takes it. */
422
+ id: number;
423
+ role: 'user' | 'assistant';
424
+ parts: Part[];
425
+ }
426
+
427
+ /**
428
+ * What a message says: text, or a tool call with its output once it ran,
429
+ * and `error: true` if the output is the tool's error (`Error: <message>` of
430
+ * a `restate.TerminalError`, say).
431
+ */
432
+ export type Part =
433
+ | { type: 'text'; text: string }
434
+ | { type: 'tool'; id: string; name: string; input: unknown; output?: string; error?: true };
435
+
436
+ /**
437
+ * Which messages to read: the latest `limit`, or those before a message, for
438
+ * a page of the conversation; or those new or changed since a `cursor`, to
439
+ * follow it.
440
+ */
441
+ export interface MessagesRequest {
442
+ /** At most this many messages (default 50). */
443
+ limit?: number;
444
+ /** The messages before this one (its `id`): older ones, such as for scrolling back. */
445
+ before?: number;
446
+ /** The messages new or changed since this cursor (a page's `cursor`), by when they changed. */
447
+ cursor?: number;
448
+ }
449
+
450
+ /**
451
+ * A page of messages: oldest first; or, with a `cursor`, those new or
452
+ * changed since it, by when they changed. Keep them by `id`: a message comes
453
+ * again once it changed (its tool call's output came, say).
454
+ */
455
+ export interface Messages {
456
+ messages: ChatMessage[];
457
+ /** Whether there are more: older ones, or with a `cursor`, newer ones. */
458
+ more: boolean;
459
+ /** The cursor to read on from: what changes after this page. */
460
+ cursor: number;
461
+ /**
462
+ * The id of the conversation's first message, once it was cleared
463
+ * (`clear`): a client drops the messages it kept from before.
464
+ */
465
+ first?: number;
466
+ }
467
+
468
+ /**
469
+ * A conversation as `messages` gives it, built from a framework's transcript:
470
+ * each message is started by `say`, a tool call goes to the assistant's
471
+ * message, and its result to its call. Messages without parts are left out.
472
+ *
473
+ * A message, once given out by `messages()`, is never changed: a change
474
+ * makes a new one in its place. So a framework can keep its transcript and
475
+ * add to it as its conversation grows, and the log stores only the messages
476
+ * that are not the ones it stored last (see log.ts).
477
+ */
478
+ export class Transcript {
479
+ #messages: Said[] = [];
480
+ /** The message of each tool call, by the call's id: its index. */
481
+ #calls = new Map<string, number>();
482
+
483
+ /** A new message of `role`, with `text` if there is any. */
484
+ say(role: ChatMessage['role'], text = '') {
485
+ this.#messages.push({ role, parts: text.trim() ? [{ type: 'text', text }] : [] });
486
+ }
487
+
488
+ /** Tool call `id` of the assistant's message. */
489
+ call(id: string, name: string, input: unknown) {
490
+ if (this.#messages.at(-1)?.role !== 'assistant') this.say('assistant');
491
+ const at = this.#messages.length - 1;
492
+ this.#change(at, (parts) => [...parts, { type: 'tool', id, name, input }]);
493
+ this.#calls.set(id, at);
494
+ }
495
+
496
+ /** The output of tool call `id`; an error's if the framework says so, or it is a tool's `Error: <message>`. */
497
+ result(id: string, output: string, error = false) {
498
+ const at = this.#calls.get(id);
499
+ if (at === undefined) return;
500
+ const failed = error || output.startsWith('Error: ');
501
+ this.#change(at, (parts) =>
502
+ parts.map((p) => (p.type === 'tool' && p.id === id ? { ...p, output, ...(failed ? { error: true } : {}) } : p)),
503
+ );
504
+ }
505
+
506
+ /**
507
+ * Whether tool call `id` has its output: not an error's, unless it is
508
+ * `failed`, the error the call answered with.
509
+ */
510
+ answered(id: string, failed?: string) {
511
+ const at = this.#calls.get(id);
512
+ return (
513
+ at !== undefined &&
514
+ this.#messages[at]!.parts.some(
515
+ (p) => p.type === 'tool' && p.id === id && p.output !== undefined && (!p.error || p.output === failed),
516
+ )
517
+ );
518
+ }
519
+
520
+ /** Its messages, in order: those with parts. */
521
+ messages(): Said[] {
522
+ return this.#messages.filter((m) => m.parts.length > 0);
523
+ }
524
+
525
+ /** Message `at` with its parts as `change` makes them: a new message, in its place. */
526
+ #change(at: number, change: (parts: Part[]) => Part[]) {
527
+ const message = this.#messages[at]!;
528
+ this.#messages[at] = { ...message, parts: change(message.parts) };
529
+ }
530
+ }
531
+
532
+ /**
533
+ * A framework's transcript as it stands, while it answers (see
534
+ * {@link transcribing}): a new one, or the one it keeps and adds to.
535
+ */
536
+ export type Read = () => Promise<Transcript>;
537
+
538
+ /** The transcript of the turn of each context, while it answers. */
539
+ const reading = new WeakMap<object, Read>();
540
+
541
+ /** The log writes of each context, one after another: tool calls in parallel publish at once. */
542
+ const writing = new WeakMap<object, Promise<void>>();
543
+
544
+ /** The log of the conversation of `ctx` takes its transcript as `read` gives it. */
545
+ function logged(ctx: restate.SessionContext, read: Read): Promise<void> {
546
+ const write = async () => {
547
+ const transcript = await read();
548
+ await log.sync(ctx.db, transcript.messages());
549
+ // The calls whose results the framework stored are made: see calls.ts.
550
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
551
+ };
552
+ const done = (writing.get(ctx) ?? Promise.resolve()).then(write, write);
553
+ writing.set(ctx, done);
554
+ return done;
555
+ }
556
+
557
+ /**
558
+ * Run `work`, a framework's turn (or a compaction, a reset), with `read`
559
+ * giving the framework's transcript as it stands, from the framework as
560
+ * `work` holds it open: each publish meanwhile (a tool call's start and end)
561
+ * takes it into the conversation's log, and so does `work`'s end, before the
562
+ * framework closes. `messages` and `sync` read the log.
563
+ */
564
+ export async function transcribing<T>(ctx: restate.SessionContext, read: Read, work: () => Promise<T>): Promise<T> {
565
+ const outer = reading.get(ctx);
566
+ reading.set(ctx, read);
567
+ let failed = false;
568
+ try {
569
+ return await work();
570
+ } catch (error) {
571
+ failed = !(error instanceof restate.TerminalError);
572
+ throw error;
573
+ } finally {
574
+ try {
575
+ // A failed attempt stores nothing more: its retry runs again.
576
+ if (!failed) await logged(ctx, read);
577
+ } finally {
578
+ if (outer) reading.set(ctx, outer);
579
+ else reading.delete(ctx);
580
+ }
581
+ }
582
+ }
583
+
584
+ /**
585
+ * The handler of an agent's conversation as clients read it, from its log:
586
+ * a page of it (`{limit, before}`), or what is new or changed since a cursor
587
+ * (`{cursor}`). It is a view: it answers while a message is answered, with
588
+ * what was stored so far, and stores nothing.
589
+ */
590
+ export const messagesHandler =
591
+ () =>
592
+ async (ctx: restate.ViewContext, request?: MessagesRequest): Promise<Messages> =>
593
+ log.page(ctx.db, request ?? {});