@restatedev/agents 0.0.0 → 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 +688 -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 +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 +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/dist/common.js ADDED
@@ -0,0 +1,475 @@
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.js';
8
+ import * as log from './log.js';
9
+ import { agentOf, signals, signalsOf } from './signals.js';
10
+ /** `value` for the invocation of `ctx`. */
11
+ export const configured = async (value, ctx) => typeof value === 'function' ? value(ctx) : value;
12
+ /** The prompts each invocation made so far, by its context. */
13
+ const prompts = new WeakMap();
14
+ /**
15
+ * The id of the next prompt of the invocation of `ctx`: the invocation's id,
16
+ * then `<id>:2`, `<id>:3`... A retried attempt makes its prompts in the same
17
+ * order, so each gets the same id again, and its answer.
18
+ */
19
+ export const nextPromptId = (ctx) => {
20
+ const n = (prompts.get(ctx) ?? 0) + 1;
21
+ prompts.set(ctx, n);
22
+ return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
23
+ };
24
+ /** The default model of pi, OpenCode and LangGraph, with OPENAI_API_KEY. */
25
+ export const DEFAULT_MODEL = 'openai/gpt-6-sol';
26
+ /** The default model of Claude agents, with ANTHROPIC_API_KEY. */
27
+ export const CLAUDE_MODEL = 'anthropic/claude-sonnet-5-5';
28
+ /**
29
+ * The model, as `provider/model-id` (such as `openai/gpt-6-sol`):
30
+ * `model`, or else MODEL, or else the framework's default.
31
+ */
32
+ export const modelOf = (model, fallback = DEFAULT_MODEL) => model || process.env.MODEL || fallback;
33
+ /** `provider/model-id` as its provider and model id, split at the first `/` (`openrouter/meta-llama/llama-4`). */
34
+ export const providerOf = (model) => {
35
+ const slash = model.indexOf('/');
36
+ return slash < 0 ? ['', model] : [model.slice(0, slash), model.slice(slash + 1)];
37
+ };
38
+ /**
39
+ * The error code of a message the model's provider refused (a missing or
40
+ * wrong API key, an unknown model): 424, Failed Dependency, as its HTTP
41
+ * status.
42
+ */
43
+ export const REFUSED = 424;
44
+ /** What to check when a model's provider refuses a request. */
45
+ export const CHECK_MODEL = "check the agent's model (its `model` option, or MODEL) and its provider's API key";
46
+ /**
47
+ * An agent's model that it cannot take: not `provider/model-id`, another
48
+ * provider's, or one its framework does not know. Terminal ({@link REFUSED}),
49
+ * wherever it is thrown: a retry takes the same model.
50
+ */
51
+ export class ModelError extends restate.TerminalError {
52
+ constructor(message) {
53
+ super(message, { errorCode: REFUSED });
54
+ this.name = 'ModelError';
55
+ }
56
+ }
57
+ /** `model`, the explicit `model` option of `framework`'s agent, if it is not `provider/model-id`. */
58
+ export const checkModelName = (framework, model) => {
59
+ if (model !== undefined && !/^[^/\s]+\/\S+$/.test(model)) {
60
+ throw new ModelError(`${framework}: the model "${model}" is not provider/model-id, such as openai/gpt-6-sol`);
61
+ }
62
+ };
63
+ /**
64
+ * The model id of `model`, for a framework with only `provider`'s models:
65
+ * `provider/model-id`, or the id alone.
66
+ */
67
+ export const modelIdOf = (model, provider) => {
68
+ const [named, id] = model.includes('/') ? providerOf(model) : [provider, model];
69
+ if (named !== provider || !id) {
70
+ const from = process.env.MODEL === model ? ' (from MODEL)' : '';
71
+ throw new ModelError(`the model "${model}"${from} is not ${provider}'s: this agent takes ${provider}/<model-id>`);
72
+ }
73
+ return id;
74
+ };
75
+ /** A chat message: the request's body as text, or the string it is as JSON (`"Hi"`). */
76
+ export const messageSerde = {
77
+ contentType: 'text/plain',
78
+ serialize: (text) => new TextEncoder().encode(text),
79
+ deserialize: (bytes) => {
80
+ const text = new TextDecoder().decode(bytes);
81
+ try {
82
+ const value = JSON.parse(text);
83
+ return typeof value === 'string' ? value : text;
84
+ }
85
+ catch {
86
+ return text;
87
+ }
88
+ },
89
+ };
90
+ /**
91
+ * What a cancelled turn answers, and each tool call it cut off: the model
92
+ * sees it in the conversation that goes on.
93
+ */
94
+ export const CANCELLED = 'Cancelled: the turn was stopped before it finished.';
95
+ /**
96
+ * What a prompt answers that the model's provider refused for good (see
97
+ * {@link refusal}): the prompt is over, and the model sees it in the
98
+ * conversation that goes on, rather than answer it with the next message.
99
+ */
100
+ export const UNANSWERED = "Unanswered: the model's provider refused the request.";
101
+ /** What stops each turn, by its context: see {@link stopSignalOf}. */
102
+ const turns = new WeakMap();
103
+ /**
104
+ * Why a turn stopped when its attempt ended before it did: Restate suspended
105
+ * the attempt, gave up on it, or lost its connection. Nothing the attempt
106
+ * does after is stored, and the next attempt goes on with the turn, so it
107
+ * stops without answering: unlike a cancellation, nothing is cancelled.
108
+ */
109
+ export class AttemptEnded extends Error {
110
+ constructor() {
111
+ super('the attempt ended before its turn did');
112
+ this.name = 'AttemptEnded';
113
+ }
114
+ }
115
+ /**
116
+ * The signal that stops the turn of `ctx` (of a `chat` handler,
117
+ * `chatHandler`), and an agent's `prompt` stops its framework's work with it.
118
+ * It aborts with a `restate.CancelledError` once Restate cancels the
119
+ * invocation (the turn ends, answered as cancelled), or with an
120
+ * {@link AttemptEnded} once the attempt ends first (the work stops, and
121
+ * answers nothing).
122
+ */
123
+ export const stopSignalOf = (ctx) => turns.get(ctx);
124
+ /** The ids of the messages steered to each turn that its conversation has, by its context. */
125
+ const steerings = new WeakMap();
126
+ /** The agents that run in the background (`background: true`): no one follows them as they work. */
127
+ const background = new Set();
128
+ /** Agent `name` runs in the background: see `background` in object.ts. */
129
+ export const inBackground = (name) => void background.add(name);
130
+ /** What each agent clears beside its database, by its object's name: see {@link onClear}. */
131
+ const clearing = new Map();
132
+ /** What a framework's `messages` view clears beside the agent's database: see {@link alsoClearing}. */
133
+ const viewsClearing = new WeakMap();
134
+ /**
135
+ * The `messages` view `view` of a framework that keeps a conversation apart
136
+ * (OpenCode, in a database of its own): `clear` empties it too, as an agent
137
+ * with this view is cleared.
138
+ */
139
+ export const alsoClearing = (view, clear) => {
140
+ viewsClearing.set(view, clear);
141
+ return view;
142
+ };
143
+ /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
144
+ export const onClear = (name, view) => {
145
+ const clear = view === undefined ? undefined : viewsClearing.get(view);
146
+ if (clear === undefined)
147
+ clearing.delete(name);
148
+ else
149
+ clearing.set(name, clear);
150
+ };
151
+ /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
152
+ export const cleared = async (ctx) => clearing.get(ctx.request.target.service)?.(ctx);
153
+ /** Whether the agent of `ctx` runs in the background. */
154
+ const unfollowed = (ctx) => background.has(ctx.request.target.service);
155
+ /** The `signals` object of the agent of `ctx`. */
156
+ const signalsOfAgent = (ctx) => ctx.rpc(signals, signalsOf(ctx));
157
+ /**
158
+ * The conversation of `ctx` changed (see `watch` in object.ts): its log takes
159
+ * the change (while a framework answers: {@link transcribing}), its revision
160
+ * increases, and the clients that follow it read it again. It is a call to
161
+ * Restate, so it also sends what the handler wrote before, for them to read.
162
+ */
163
+ const publish = async (ctx) => {
164
+ const read = reading.get(ctx);
165
+ if (read)
166
+ await logged(ctx, read);
167
+ await signalsOfAgent(ctx).publish();
168
+ };
169
+ /** A step of a turn of `ctx`: {@link publish} it, unless the agent runs in the background, which publishes the turn's end only. */
170
+ const stepped = async (ctx) => {
171
+ if (!unfollowed(ctx))
172
+ await publish(ctx);
173
+ };
174
+ /**
175
+ * A tool call of the turn of `ctx` starts: {@link publish} it, which forgets
176
+ * the calls whose results are stored (calls.ts) before the tool makes its
177
+ * own. In the background, which publishes the turn's end only, it forgets
178
+ * them alone.
179
+ */
180
+ export async function toolCallStarted(ctx) {
181
+ if (!unfollowed(ctx))
182
+ return publish(ctx);
183
+ const read = reading.get(ctx);
184
+ if (read) {
185
+ const transcript = await read();
186
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
187
+ }
188
+ }
189
+ /**
190
+ * A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish}
191
+ * it, and give `conversation` the messages steered to the turn since, which it
192
+ * does not have yet: its next step takes them. Without a conversation (a
193
+ * framework that takes no steering), they wait for the turn's end.
194
+ */
195
+ export async function toolCallEnded(ctx, conversation) {
196
+ // In the background, no one steers: a message steered anyway is answered after the turn.
197
+ if (unfollowed(ctx))
198
+ return;
199
+ const messages = await signalsOfAgent(ctx).progress(ctx.request.id);
200
+ const taken = steerings.get(ctx);
201
+ if (!taken || !conversation)
202
+ return;
203
+ for (const message of messages.filter((m) => !taken.has(m.id))) {
204
+ if (!(await conversation.has(message.id)))
205
+ await conversation.steer(message);
206
+ taken.add(message.id);
207
+ }
208
+ }
209
+ /**
210
+ * Count the messages steered to the turn of `ctx` that `conversation` has,
211
+ * such as those an earlier attempt gave it. A framework calls it once a
212
+ * prompt is answered; the turn's other messages are answered as messages of
213
+ * their own, when it ends.
214
+ */
215
+ export async function settleSteering(ctx, conversation) {
216
+ const taken = steerings.get(ctx);
217
+ if (!taken)
218
+ return;
219
+ for (const message of await signalsOfAgent(ctx).steering(ctx.request.id)) {
220
+ if (!taken.has(message.id) && (await conversation.has(message.id)))
221
+ taken.add(message.id);
222
+ }
223
+ }
224
+ /** A promise that rejects with `signal`'s reason once it aborts. */
225
+ export const aborted = (signal) => new Promise((_, reject) => {
226
+ if (signal.aborted)
227
+ reject(signal.reason);
228
+ else
229
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
230
+ });
231
+ /**
232
+ * `answer` as a chat handler, which takes its message as plain text or as a
233
+ * JSON string, so that both of these work:
234
+ *
235
+ * curl localhost:8080/assistant/alice/chat -d 'Hi'
236
+ * curl localhost:8080/assistant/alice/chat --json '"Hi"'
237
+ *
238
+ * While it answers, the object's `status` says so (its {@link Turn}). Its
239
+ * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
240
+ * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
241
+ * context, whenever it comes, and cancels the calls its tools made
242
+ * (`cancelCalls(ctx)`): the agent's `prompt`
243
+ * ends the turn, and the handler fails with a `restate.CancelledError`. An
244
+ * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
245
+ * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
246
+ *
247
+ * Messages steered to it (`steer`) go to the agent's conversation at its next
248
+ * tool call ({@link toolCallEnded}); when it ends, those it did not take are
249
+ * answered as messages of their own, unless it was cancelled. It publishes
250
+ * when it starts and ends ({@link publish}), for the clients that follow the
251
+ * conversation.
252
+ */
253
+ export const chatHandler = (answer) => ({
254
+ input: messageSerde,
255
+ accept: '*/*',
256
+ explicitCancellation: true,
257
+ handler: async (ctx, text) => {
258
+ const invocationId = ctx.request.id;
259
+ // The companion knows the turn from here to its close: `status`, `stop` and `steer` ask it.
260
+ await ctx
261
+ .rpc(signals, signalsOf(ctx))
262
+ .start({ agent: agentOf(ctx), turn: { invocationId, since: new Date().toISOString() } });
263
+ const taken = new Set();
264
+ steerings.set(ctx, taken);
265
+ await stepped(ctx);
266
+ const end = async (dropped = false) => {
267
+ ctx
268
+ .send(signals, signalsOf(ctx))
269
+ .close({ agent: agentOf(ctx), turn: invocationId, taken: [...taken], cancelled: dropped });
270
+ await publish(ctx);
271
+ };
272
+ const turn = new AbortController();
273
+ turns.set(ctx, turn.signal);
274
+ void (async () => {
275
+ await cancelled(ctx);
276
+ turn.abort(new restate.CancelledError());
277
+ await cancelCalls(ctx);
278
+ })().catch(() => { });
279
+ // The attempt ends before the turn does: its work stops (a model's
280
+ // request, say), rather than run on for an attempt that can store nothing.
281
+ const attempt = ctx.request.attemptCompletedSignal;
282
+ const attemptEnded = () => turn.abort(new AttemptEnded());
283
+ attempt.addEventListener('abort', attemptEnded, { once: true });
284
+ let answered;
285
+ try {
286
+ answered = await answer(ctx, text);
287
+ // Cancelled once answered: the answer stands.
288
+ }
289
+ catch (error) {
290
+ if (error instanceof restate.TerminalError) {
291
+ await end(error instanceof restate.CancelledError);
292
+ throw error;
293
+ }
294
+ // Any other error fails the attempt, and Restate retries the turn.
295
+ const terminal = refusal(error);
296
+ if (!terminal)
297
+ throw error;
298
+ await end();
299
+ throw terminal;
300
+ }
301
+ finally {
302
+ // An attempt's signal aborts at every attempt's end, the turn's too.
303
+ attempt.removeEventListener('abort', attemptEnded);
304
+ }
305
+ await end();
306
+ return answered;
307
+ },
308
+ });
309
+ /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
310
+ export class ToolError extends Error {
311
+ tool;
312
+ constructor(tool, cause) {
313
+ super(`the tool ${tool} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
314
+ this.name = 'ToolError';
315
+ this.tool = tool;
316
+ }
317
+ }
318
+ /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
319
+ const toolErrors = new WeakSet();
320
+ /**
321
+ * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
322
+ * that failed, whose error is never taken for the model's provider refusing
323
+ * (a tool that calls a model API may fail as one does). `tool()`'s are
324
+ * {@link ToolError}s.
325
+ */
326
+ export function fromTool(error) {
327
+ if (typeof error === 'object' && error !== null)
328
+ toolErrors.add(error);
329
+ }
330
+ /** The Anthropic SDK's errors of a request that fails again however often it is made. */
331
+ const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFoundError', 'BadRequestError']);
332
+ /**
333
+ * Whether `error` is a model provider's refusal that a retry does not change:
334
+ * a missing or wrong API key, an unknown model, a bad request. Other errors
335
+ * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
336
+ */
337
+ function refused(error) {
338
+ if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
339
+ return false;
340
+ if (error instanceof Error && FOR_GOOD.has(error.constructor.name))
341
+ return true;
342
+ return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(String(error));
343
+ }
344
+ /**
345
+ * `error` as a terminal error ({@link REFUSED}), if a retry does not change
346
+ * it: a model the agent cannot take, or its provider's refusal.
347
+ */
348
+ export function refusal(error) {
349
+ if (error instanceof ModelError)
350
+ return error;
351
+ if (error instanceof restate.TerminalError || !refused(error))
352
+ return undefined;
353
+ return new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}. ${String(error)}`, {
354
+ errorCode: REFUSED,
355
+ });
356
+ }
357
+ /**
358
+ * A prompt's stored answer, as the prompt returns it: {@link UNANSWERED},
359
+ * stored as its provider refused it, fails as the prompt did then
360
+ * ({@link REFUSED}), also in a retry after a crash right after it was stored.
361
+ */
362
+ export function storedAnswer(answer) {
363
+ if (answer !== UNANSWERED)
364
+ return answer;
365
+ throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
366
+ }
367
+ /**
368
+ * A conversation as `messages` gives it, built from a framework's transcript:
369
+ * each message is started by `say`, a tool call goes to the assistant's
370
+ * message, and its result to its call. Messages without parts are left out.
371
+ *
372
+ * A message, once given out by `messages()`, is never changed: a change
373
+ * makes a new one in its place. So a framework can keep its transcript and
374
+ * add to it as its conversation grows, and the log stores only the messages
375
+ * that are not the ones it stored last (see log.ts).
376
+ */
377
+ export class Transcript {
378
+ #messages = [];
379
+ /** The message of each tool call, by the call's id: its index. */
380
+ #calls = new Map();
381
+ /** A new message of `role`, with `text` if there is any. */
382
+ say(role, text = '') {
383
+ this.#messages.push({ role, parts: text.trim() ? [{ type: 'text', text }] : [] });
384
+ }
385
+ /** Tool call `id` of the assistant's message. */
386
+ call(id, name, input) {
387
+ if (this.#messages.at(-1)?.role !== 'assistant')
388
+ this.say('assistant');
389
+ const at = this.#messages.length - 1;
390
+ this.#change(at, (parts) => [...parts, { type: 'tool', id, name, input }]);
391
+ this.#calls.set(id, at);
392
+ }
393
+ /** The output of tool call `id`; an error's if the framework says so, or it is a tool's `Error: <message>`. */
394
+ result(id, output, error = false) {
395
+ const at = this.#calls.get(id);
396
+ if (at === undefined)
397
+ return;
398
+ const failed = error || output.startsWith('Error: ');
399
+ this.#change(at, (parts) => parts.map((p) => (p.type === 'tool' && p.id === id ? { ...p, output, ...(failed ? { error: true } : {}) } : p)));
400
+ }
401
+ /**
402
+ * Whether tool call `id` has its output: not an error's, unless it is
403
+ * `failed`, the error the call answered with.
404
+ */
405
+ answered(id, failed) {
406
+ const at = this.#calls.get(id);
407
+ return (at !== undefined &&
408
+ this.#messages[at].parts.some((p) => p.type === 'tool' && p.id === id && p.output !== undefined && (!p.error || p.output === failed)));
409
+ }
410
+ /** Its messages, in order: those with parts. */
411
+ messages() {
412
+ return this.#messages.filter((m) => m.parts.length > 0);
413
+ }
414
+ /** Message `at` with its parts as `change` makes them: a new message, in its place. */
415
+ #change(at, change) {
416
+ const message = this.#messages[at];
417
+ this.#messages[at] = { ...message, parts: change(message.parts) };
418
+ }
419
+ }
420
+ /** The transcript of the turn of each context, while it answers. */
421
+ const reading = new WeakMap();
422
+ /** The log writes of each context, one after another: tool calls in parallel publish at once. */
423
+ const writing = new WeakMap();
424
+ /** The log of the conversation of `ctx` takes its transcript as `read` gives it. */
425
+ function logged(ctx, read) {
426
+ const write = async () => {
427
+ const transcript = await read();
428
+ await log.sync(ctx.db, transcript.messages());
429
+ // The calls whose results the framework stored are made: see calls.ts.
430
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
431
+ };
432
+ const done = (writing.get(ctx) ?? Promise.resolve()).then(write, write);
433
+ writing.set(ctx, done);
434
+ return done;
435
+ }
436
+ /**
437
+ * Run `work`, a framework's turn (or a compaction, a reset), with `read`
438
+ * giving the framework's transcript as it stands, from the framework as
439
+ * `work` holds it open: each publish meanwhile (a tool call's start and end)
440
+ * takes it into the conversation's log, and so does `work`'s end, before the
441
+ * framework closes. `messages` and `sync` read the log.
442
+ */
443
+ export async function transcribing(ctx, read, work) {
444
+ const outer = reading.get(ctx);
445
+ reading.set(ctx, read);
446
+ let failed = false;
447
+ try {
448
+ return await work();
449
+ }
450
+ catch (error) {
451
+ failed = !(error instanceof restate.TerminalError);
452
+ throw error;
453
+ }
454
+ finally {
455
+ try {
456
+ // A failed attempt stores nothing more: its retry runs again.
457
+ if (!failed)
458
+ await logged(ctx, read);
459
+ }
460
+ finally {
461
+ if (outer)
462
+ reading.set(ctx, outer);
463
+ else
464
+ reading.delete(ctx);
465
+ }
466
+ }
467
+ }
468
+ /**
469
+ * The handler of an agent's conversation as clients read it, from its log:
470
+ * a page of it (`{limit, before}`), or what is new or changed since a cursor
471
+ * (`{cursor}`). It is a view: it answers while a message is answered, with
472
+ * what was stored so far, and stores nothing.
473
+ */
474
+ export const messagesHandler = () => async (ctx, request) => log.page(ctx.db, request ?? {});
475
+ //# sourceMappingURL=common.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"common.js","sourceRoot":"","sources":["../src/common.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,4EAA4E;AAC5E,0EAA0E;AAC1E,gDAAgD;AAChD,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,+BAA+B,CAAC;AACvE,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,KAAK,GAAG,MAAM,UAAU,CAAC;AAEhC,OAAO,EAAE,OAAO,EAAc,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAWvE,2CAA2C;AAC3C,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,EAAK,KAAmB,EAAE,GAA2B,EAAc,EAAE,CAClG,OAAO,KAAK,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E,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC"}
@@ -0,0 +1,69 @@
1
+ import * as restate from '@restatedev/sessions';
2
+ import { type ToolDefinition } from '@deepseek-ai/dsh-tools';
3
+ import { type Configure } from '../common.ts';
4
+ import { type Answer } from '../output.ts';
5
+ import { type Definition } from '../object.ts';
6
+ import { type Tool as AnyTool } from '../tools.ts';
7
+ import type { z } from 'zod';
8
+ import { SqlSessionPersistence } from './persistence.ts';
9
+ export { SqlSessionPersistence };
10
+ /** An agent's options: `chat` and `prompt` take them. */
11
+ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
12
+ /**
13
+ * The model, as `provider/model-id`: MODEL, or else deepseek/deepseek-flash.
14
+ * DeepSeek's, or any pi-ai knows, such as `openai/gpt-6-sol`.
15
+ */
16
+ model?: string;
17
+ /** The system prompt: who the agent is, and how it answers. */
18
+ system?: string;
19
+ /** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or the harness's (`defineTool`). */
20
+ tools?: (AnyTool | ToolDefinition)[];
21
+ /**
22
+ * The answer as data: a zod object, whose JSON the agent replies with
23
+ * (checked), and `chat` and `prompt` answer with (see output.ts).
24
+ */
25
+ output?: O;
26
+ }
27
+ /**
28
+ * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
29
+ * of an invocation is a prompt of its own. The session is the object's key.
30
+ * With `output`, it answers with the value the agent replies with (see
31
+ * output.ts), not its text.
32
+ */
33
+ export declare const prompt: <O extends z.ZodObject | undefined = undefined>(ctx: restate.SessionContext, text: string, options?: Options<O>) => Promise<Answer<O>>;
34
+ /**
35
+ * A chat handler: each message an invocation, the session in the object's
36
+ * database, with `options`, or the options a function of the invocation's
37
+ * context gives. It takes the message as plain text (`curl -d 'Hi'`) or as
38
+ * a JSON string (`curl --json '"Hi"'`).
39
+ */
40
+ export declare const chat: <O extends z.ZodObject | undefined = undefined>(options?: Configure<Options<O>>) => {
41
+ input: restate.Serde<string>;
42
+ accept: string;
43
+ explicitCancellation: boolean;
44
+ handler: (ctx: restate.SessionContext, text: string) => Promise<Answer<O>>;
45
+ };
46
+ /**
47
+ * A handler of the conversation as clients read it: a page at a time, or
48
+ * what is new or changed since a cursor, from the log each change writes
49
+ * (log.ts). It answers while a message is answered.
50
+ */
51
+ export declare const messages: () => (ctx: restate.ViewContext, request?: import("../common.ts").MessagesRequest) => Promise<import("../common.ts").Messages>;
52
+ /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
53
+ export declare const agent: <P extends string, O extends z.ZodObject | undefined = undefined>({ name, description, schema, background, ...options }: Options<O> & Definition<P>) => restate.VirtualObjectDefinition<P, {
54
+ signal: (ctx: restate.ViewContext, signal: import("../signals.ts").Signal) => Promise<import("../signals.ts").Resolved>;
55
+ pending: (ctx: restate.ViewContext) => Promise<import("../signals.ts").Waiting[]>;
56
+ status: (ctx: restate.ViewContext) => Promise<import("../object.ts").Status>;
57
+ stop: (ctx: restate.ViewContext) => Promise<import("../object.ts").Stopped>;
58
+ steer: (ctx: restate.ViewContext, text: string) => Promise<import("../signals.ts").Steered>;
59
+ notifications: (ctx: restate.ViewContext) => Promise<import("../signals.ts").Notifications>;
60
+ watch: (ctx: restate.ViewContext, watch: import("../signals.ts").Watch) => Promise<import("../signals.ts").Notifications>;
61
+ } & {
62
+ clear: (ctx: restate.ViewContext) => Promise<import("../object.ts").Stopped>;
63
+ sync: (ctx: restate.ViewContext, { cursor, revision, timeoutSeconds, limit }?: import("../object.ts").SyncRequest) => Promise<import("../object.ts").Synced>;
64
+ } & {
65
+ chat: (ctx: restate.SessionContext, text: string) => Promise<Answer<O>>;
66
+ } & {
67
+ messages: (ctx: restate.ViewContext, request?: import("../common.ts").MessagesRequest) => Promise<import("../common.ts").Messages>;
68
+ }>;
69
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/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