@restatedev/agents 0.0.0 → 0.2.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 +672 -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 +77 -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 +81 -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 +261 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +438 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +68 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +363 -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 +8 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +12 -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 +66 -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 +169 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +221 -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 +100 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +436 -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 +89 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +293 -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 +154 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +256 -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 +71 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +102 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  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 +176 -0
  89. package/src/common.ts +550 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +464 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +24 -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 +319 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +559 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +382 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +386 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +161 -0
package/src/common.ts ADDED
@@ -0,0 +1,550 @@
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, 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 { 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 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>>();
172
+
173
+ /**
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.
177
+ */
178
+ export const alsoClearing = <V extends object>(view: V, clear: (ctx: restate.SessionContext) => Promise<void>) => {
179
+ viewsClearing.set(view, clear);
180
+ return view;
181
+ };
182
+
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);
188
+ };
189
+
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);
192
+
193
+ /** Whether the agent of `ctx` runs in the background. */
194
+ const unfollowed = (ctx: restate.SessionContext) => background.has(ctx.request.target.service);
195
+
196
+ /** The `signals` object of the agent of `ctx`. */
197
+ const signalsOfAgent = (ctx: restate.SessionContext) => ctx.rpc(signals, signalsOf(ctx));
198
+
199
+ /**
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.
204
+ */
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();
209
+ };
210
+
211
+ /** 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) => {
213
+ if (!unfollowed(ctx)) await publish(ctx);
214
+ };
215
+
216
+ /**
217
+ * A tool call of the turn of `ctx` starts: {@link publish} it, which forgets
218
+ * the calls whose results are stored (calls.ts) before the tool makes its
219
+ * own. In the background, which publishes the turn's end only, it forgets
220
+ * them alone.
221
+ */
222
+ export async function toolCallStarted(ctx: restate.SessionContext) {
223
+ 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
+ }
229
+ }
230
+
231
+ /** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
232
+ export async function toolCallEnded(ctx: restate.SessionContext) {
233
+ await stepped(ctx);
234
+ }
235
+
236
+ /** A promise that rejects with `signal`'s reason once it aborts. */
237
+ export const aborted = (signal: AbortSignal) =>
238
+ new Promise<never>((_, reject) => {
239
+ if (signal.aborted) reject(signal.reason);
240
+ else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
241
+ });
242
+
243
+ /**
244
+ * `answer` as a chat handler, which takes its message as plain text or as a
245
+ * JSON string, so that both of these work:
246
+ *
247
+ * curl localhost:8080/assistant/alice/chat -d 'Hi'
248
+ * curl localhost:8080/assistant/alice/chat --json '"Hi"'
249
+ *
250
+ * While it answers, the object's `status` says so (its {@link Turn}). Its
251
+ * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
252
+ * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
253
+ * context, whenever it comes, and cancels the calls its tools made
254
+ * (`cancelCalls(ctx)`): the agent's `prompt`
255
+ * ends the turn, and the handler fails with a `restate.CancelledError`. An
256
+ * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
257
+ * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
258
+ *
259
+ * It publishes when it starts and ends ({@link publish}), for the clients
260
+ * that follow the conversation.
261
+ */
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;
303
+ 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);
308
+ }
309
+ await end();
310
+ return answered;
311
+ },
312
+ });
313
+
314
+ /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
315
+ export class ToolError extends Error {
316
+ readonly tool: string;
317
+ constructor(tool: string, cause: unknown) {
318
+ super(`the tool ${tool} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
319
+ this.name = 'ToolError';
320
+ this.tool = tool;
321
+ }
322
+ }
323
+
324
+ /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
325
+ const toolErrors = new WeakSet<object>();
326
+
327
+ /**
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.
332
+ */
333
+ export function fromTool(error: unknown) {
334
+ if (typeof error === 'object' && error !== null) toolErrors.add(error);
335
+ }
336
+
337
+ /** 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']);
339
+
340
+ /**
341
+ * Whether `error` is a model provider's refusal that a retry does not change:
342
+ * a missing or wrong API key, an unknown model, a bad request. Other errors
343
+ * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
344
+ */
345
+ function refused(error: unknown) {
346
+ if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
347
+ return false;
348
+ if (error instanceof Error && FOR_GOOD.has(error.constructor.name)) return true;
349
+ return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(
350
+ String(error),
351
+ );
352
+ }
353
+
354
+ /**
355
+ * `error` as a terminal error ({@link REFUSED}), if a retry does not change
356
+ * it: a model the agent cannot take, or its provider's refusal.
357
+ */
358
+ export function refusal(error: unknown): restate.TerminalError | undefined {
359
+ if (error instanceof ModelError) return error;
360
+ if (error instanceof restate.TerminalError || !refused(error)) return undefined;
361
+ return new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}. ${String(error)}`, {
362
+ errorCode: REFUSED,
363
+ });
364
+ }
365
+
366
+ /**
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.
370
+ */
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 });
374
+ }
375
+
376
+ /** A message of a conversation, as an agent's `messages` handler returns it. */
377
+ export interface ChatMessage {
378
+ /** Its id, from 0, in the order of the conversation; the same however it changes. `before` takes it. */
379
+ id: number;
380
+ role: 'user' | 'assistant';
381
+ parts: Part[];
382
+ }
383
+
384
+ /**
385
+ * What a message says: text, or a tool call with its output once it ran,
386
+ * and `error: true` if the output is the tool's error (`Error: <message>` of
387
+ * a `restate.TerminalError`, say).
388
+ */
389
+ export type Part =
390
+ | { type: 'text'; text: string }
391
+ | { type: 'tool'; id: string; name: string; input: unknown; output?: string; error?: true };
392
+
393
+ /**
394
+ * Which messages to read: the latest `limit`, or those before a message, for
395
+ * a page of the conversation; or those new or changed since a `cursor`, to
396
+ * follow it.
397
+ */
398
+ export interface MessagesRequest {
399
+ /** At most this many messages (default 50). */
400
+ limit?: number;
401
+ /** The messages before this one (its `id`): older ones, such as for scrolling back. */
402
+ before?: number;
403
+ /** The messages new or changed since this cursor (a page's `cursor`), by when they changed. */
404
+ cursor?: number;
405
+ }
406
+
407
+ /**
408
+ * A page of messages: oldest first; or, with a `cursor`, those new or
409
+ * changed since it, by when they changed. Keep them by `id`: a message comes
410
+ * again once it changed (its tool call's output came, say).
411
+ */
412
+ export interface Messages {
413
+ messages: ChatMessage[];
414
+ /** Whether there are more: older ones, or with a `cursor`, newer ones. */
415
+ more: boolean;
416
+ /** The cursor to read on from: what changes after this page. */
417
+ cursor: number;
418
+ /**
419
+ * The id of the conversation's first message, once it was cleared
420
+ * (`clear`): a client drops the messages it kept from before.
421
+ */
422
+ first?: number;
423
+ }
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 ?? {});
@@ -0,0 +1,110 @@
1
+ # DeepSeek Harness
2
+
3
+ The [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
4
+ (`@deepseek-ai/dsh-*`) is an agent harness built from plugins on
5
+ [cordis](https://www.npmjs.com/package/@deepseek-ai/cordis): an agent loop, a
6
+ model service, a tool registry, and an event-sourced session that is the
7
+ source of truth for everything the agent did. Here the session is in the
8
+ agent's SQL database ([SQL in Restate virtual objects](../../../sessions/README.md)),
9
+ and is the object's key. The integration pins the harness's `next` release
10
+ line, 0.2.1-rc.2, exactly: its packages are release candidates that require
11
+ each other's exact versions.
12
+
13
+ ## Use
14
+
15
+ ```ts
16
+ import { serve } from '@restatedev/agents';
17
+ import * as deepseek from '@restatedev/agents/deepseek';
18
+ import { weather } from './weather.ts';
19
+
20
+ const assistant = deepseek.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
21
+ await serve(assistant);
22
+ ```
23
+
24
+ | Option | What |
25
+ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
26
+ | `model` | `provider/model-id`; or else `MODEL`, or else `deepseek/deepseek-flash` (see below) |
27
+ | `system` | The system prompt |
28
+ | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or the harness's `defineTool`s |
29
+ | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
30
+
31
+ ## Models
32
+
33
+ DeepSeek's models go to DeepSeek, with `DEEPSEEK_API_KEY`. Any other model
34
+ pi-ai knows goes through the harness's pi-ai adapter
35
+ (`@deepseek-ai/dsh-llm-pi-ai`), with its provider's usual key: nothing else
36
+ to set up.
37
+
38
+ ```ts
39
+ deepseek.agent({ name: 'assistant' }); // deepseek/deepseek-flash, with DEEPSEEK_API_KEY
40
+ deepseek.agent({ name: 'assistant', model: 'openai/gpt-6-sol' }); // with OPENAI_API_KEY
41
+ deepseek.agent({ name: 'assistant', model: 'anthropic/claude-sonnet-5-5' }); // with ANTHROPIC_API_KEY
42
+ ```
43
+
44
+ A provider or model pi-ai does not know fails when the agent is defined; a
45
+ missing or wrong key fails the invocation with a terminal error (424).
46
+
47
+ For a session object of your own, `deepseek.chat(options)` is the handler and
48
+ `deepseek.messages()` the view; `options` may be a function of the
49
+ invocation's context (each user's system prompt, say). `deepseek.prompt(ctx,
50
+ text, options)` answers a prompt in a handler of your own, once, however
51
+ often the handler runs; each prompt of an invocation is a prompt of its own.
52
+
53
+ ## Through crashes
54
+
55
+ The persistence ([`persistence.ts`](persistence.ts),
56
+ `SqlSessionPersistence`) keeps each session's header, and its event log, one
57
+ row per event; a flush, the harness's durability barrier, stores what was
58
+ appended before it in one SQL transaction. The handler is not replayed: a
59
+ retried attempt boots the harness again and resumes the session from the
60
+ stored log. The harness does not resume an interrupted turn: resuming closes
61
+ it, and leaves the model to decide what to do about it. So:
62
+
63
+ - **A tool runs only once its call is stored.** The harness's checkpoint
64
+ policy flushes the session before each model request, each tool body and
65
+ each step.
66
+ - **A tool call stored without a result has an unknown outcome.** Resuming
67
+ gives each such call an error result that says so, and tells the model to
68
+ retry only an idempotent operation; the handler then asks the agent to
69
+ continue. A tool that must not run twice needs a way for a retry to name
70
+ the call it retries (the bank agent's `transfer` takes `retryOf`). Restate's own tools
71
+ (`call`, `send`, `workflow`, `subagent`, `signal`) need none: made again
72
+ with the same input, the call is the one the cut-off call made, which
73
+ matters for a long one, such as a wait for an approval, since a suspension
74
+ (after Restate's inactivity timeout) restarts the handler too.
75
+ - **A tool's error fails the attempt**, and Restate retries it; a
76
+ `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
77
+ model. The failed attempt stores nothing more, so its retry finds the call
78
+ without a result, as above.
79
+ - **A failed turn fails the attempt**: a model request that failed, or a
80
+ checkpoint that could not store the log, and Restate retries.
81
+ - **A message is answered once per invocation**: the message carries the
82
+ invocation id, and a retried attempt returns the answer of the turn that
83
+ finished it. A message that a crash interrupted is finished before the next
84
+ one starts.
85
+
86
+ ## Run
87
+
88
+ ```sh
89
+ cd packages/examples && DEEPSEEK_API_KEY=… node basic/deepseek.ts
90
+ cd packages/examples && MODEL=openai/gpt-6-sol OPENAI_API_KEY=… node basic/deepseek.ts # on GPT
91
+ ```
92
+
93
+ With a Restate server, and the agent registered with it: see
94
+ [Run an example](../../../examples/README.md#run-an-example).
95
+
96
+ ## Tests
97
+
98
+ The tests run on a scripted model, [`test/fakes/deepseek.ts`](../../test/fakes/deepseek.ts),
99
+ which makes a fresh tool call id for every call, as a model does
100
+ (`pnpm --filter @restatedev/agents test deepseek`, from the repository root):
101
+
102
+ - [`test/deepseek.test.ts`](../../test/deepseek.test.ts):
103
+ each point above, with crashes that stop an attempt in a tool call, or
104
+ at any of its state requests; and
105
+ `messages`. Without the checkpoint policy four of its tests fail, and with
106
+ a transfer tool that ignores `retryOf` three do.
107
+ - [`test/deepseek.ts`](../../test/deepseek.ts): the
108
+ bank agent, whose `transfer` uses `retryOf`, or its own call id, as the
109
+ transfer id, through crashes in [the crash test](../../../e2e/crash.ts)
110
+ (`pnpm --filter e2e crash`): every message moves money exactly once.