@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/dist/common.js ADDED
@@ -0,0 +1,438 @@
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.js';
8
+ import * as log from './log.js';
9
+ import { 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 agents that run in the background (`background: true`): no one follows them as they work. */
125
+ const background = new Set();
126
+ /** Agent `name` runs in the background: see `background` in object.ts. */
127
+ export const inBackground = (name) => void background.add(name);
128
+ /** What each agent clears beside its database, by its object's name: see {@link onClear}. */
129
+ const clearing = new Map();
130
+ /** What a framework's `messages` view clears beside the agent's database: see {@link alsoClearing}. */
131
+ const viewsClearing = new WeakMap();
132
+ /**
133
+ * The `messages` view `view` of a framework that keeps a conversation apart
134
+ * (OpenCode, in a database of its own): `clear` empties it too, as an agent
135
+ * with this view is cleared.
136
+ */
137
+ export const alsoClearing = (view, clear) => {
138
+ viewsClearing.set(view, clear);
139
+ return view;
140
+ };
141
+ /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
142
+ export const onClear = (name, view) => {
143
+ const clear = view === undefined ? undefined : viewsClearing.get(view);
144
+ if (clear === undefined)
145
+ clearing.delete(name);
146
+ else
147
+ clearing.set(name, clear);
148
+ };
149
+ /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
150
+ export const cleared = async (ctx) => clearing.get(ctx.request.target.service)?.(ctx);
151
+ /** Whether the agent of `ctx` runs in the background. */
152
+ const unfollowed = (ctx) => background.has(ctx.request.target.service);
153
+ /** The `signals` object of the agent of `ctx`. */
154
+ const signalsOfAgent = (ctx) => ctx.rpc(signals, signalsOf(ctx));
155
+ /**
156
+ * The conversation of `ctx` changed (see `watch` in object.ts): its log takes
157
+ * the change (while a framework answers: {@link transcribing}), its revision
158
+ * increases, and the clients that follow it read it again. It is a call to
159
+ * Restate, so it also sends what the handler wrote before, for them to read.
160
+ */
161
+ const publish = async (ctx) => {
162
+ const read = reading.get(ctx);
163
+ if (read)
164
+ await logged(ctx, read);
165
+ await signalsOfAgent(ctx).publish();
166
+ };
167
+ /** A step of a turn of `ctx`: {@link publish} it, unless the agent runs in the background, which publishes the turn's end only. */
168
+ const stepped = async (ctx) => {
169
+ if (!unfollowed(ctx))
170
+ await publish(ctx);
171
+ };
172
+ /**
173
+ * A tool call of the turn of `ctx` starts: {@link publish} it, which forgets
174
+ * the calls whose results are stored (calls.ts) before the tool makes its
175
+ * own. In the background, which publishes the turn's end only, it forgets
176
+ * them alone.
177
+ */
178
+ export async function toolCallStarted(ctx) {
179
+ if (!unfollowed(ctx))
180
+ return publish(ctx);
181
+ const read = reading.get(ctx);
182
+ if (read) {
183
+ const transcript = await read();
184
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
185
+ }
186
+ }
187
+ /** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
188
+ export async function toolCallEnded(ctx) {
189
+ await stepped(ctx);
190
+ }
191
+ /** A promise that rejects with `signal`'s reason once it aborts. */
192
+ export const aborted = (signal) => new Promise((_, reject) => {
193
+ if (signal.aborted)
194
+ reject(signal.reason);
195
+ else
196
+ signal.addEventListener('abort', () => reject(signal.reason), { once: true });
197
+ });
198
+ /**
199
+ * `answer` as a chat handler, which takes its message as plain text or as a
200
+ * JSON string, so that both of these work:
201
+ *
202
+ * curl localhost:8080/assistant/alice/chat -d 'Hi'
203
+ * curl localhost:8080/assistant/alice/chat --json '"Hi"'
204
+ *
205
+ * While it answers, the object's `status` says so (its {@link Turn}). Its
206
+ * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
207
+ * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
208
+ * context, whenever it comes, and cancels the calls its tools made
209
+ * (`cancelCalls(ctx)`): the agent's `prompt`
210
+ * ends the turn, and the handler fails with a `restate.CancelledError`. An
211
+ * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
212
+ * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
213
+ *
214
+ * It publishes when it starts and ends ({@link publish}), for the clients
215
+ * that follow the conversation.
216
+ */
217
+ export const chatHandler = (answer) => ({
218
+ input: messageSerde,
219
+ accept: '*/*',
220
+ explicitCancellation: true,
221
+ handler: async (ctx, text) => {
222
+ const invocationId = ctx.request.id;
223
+ // The companion knows the turn from here to its close: `status` and `stop` ask it.
224
+ await ctx.rpc(signals, signalsOf(ctx)).start({ invocationId, since: new Date().toISOString() });
225
+ await stepped(ctx);
226
+ // The log takes the turn's last change, then the companion closes the
227
+ // turn, which publishes it: one revision. The close is a call the turn
228
+ // waits for, so that it is done before the turn ends (see `awaitTurn`).
229
+ const end = async () => {
230
+ const read = reading.get(ctx);
231
+ if (read)
232
+ await logged(ctx, read);
233
+ await signalsOfAgent(ctx).close(invocationId);
234
+ };
235
+ const turn = new AbortController();
236
+ turns.set(ctx, turn.signal);
237
+ void (async () => {
238
+ await cancelled(ctx);
239
+ turn.abort(new restate.CancelledError());
240
+ await cancelCalls(ctx);
241
+ })().catch(() => { });
242
+ // The attempt ends before the turn does: its work stops (a model's
243
+ // request, say), rather than run on for an attempt that can store nothing.
244
+ const attempt = ctx.request.attemptCompletedSignal;
245
+ const attemptEnded = () => turn.abort(new AttemptEnded());
246
+ attempt.addEventListener('abort', attemptEnded, { once: true });
247
+ let answered;
248
+ try {
249
+ answered = await answer(ctx, text);
250
+ // Cancelled once answered: the answer stands.
251
+ }
252
+ catch (error) {
253
+ if (error instanceof restate.TerminalError) {
254
+ await end();
255
+ throw error;
256
+ }
257
+ // Any other error fails the attempt, and Restate retries the turn.
258
+ const terminal = refusal(error);
259
+ if (!terminal)
260
+ throw error;
261
+ await end();
262
+ throw terminal;
263
+ }
264
+ finally {
265
+ // An attempt's signal aborts at every attempt's end, the turn's too.
266
+ attempt.removeEventListener('abort', attemptEnded);
267
+ }
268
+ await end();
269
+ return answered;
270
+ },
271
+ });
272
+ /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
273
+ export class ToolError extends Error {
274
+ tool;
275
+ constructor(tool, cause) {
276
+ super(`the tool ${tool} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
277
+ this.name = 'ToolError';
278
+ this.tool = tool;
279
+ }
280
+ }
281
+ /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
282
+ const toolErrors = new WeakSet();
283
+ /**
284
+ * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
285
+ * that failed, whose error is never taken for the model's provider refusing
286
+ * (a tool that calls a model API may fail as one does). `tool()`'s are
287
+ * {@link ToolError}s.
288
+ */
289
+ export function fromTool(error) {
290
+ if (typeof error === 'object' && error !== null)
291
+ toolErrors.add(error);
292
+ }
293
+ /** The Anthropic SDK's errors of a request that fails again however often it is made. */
294
+ const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFoundError', 'BadRequestError']);
295
+ /**
296
+ * Whether `error` is a model provider's refusal that a retry does not change:
297
+ * a missing or wrong API key, an unknown model, a bad request. Other errors
298
+ * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
299
+ */
300
+ function refused(error) {
301
+ if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
302
+ return false;
303
+ if (error instanceof Error && FOR_GOOD.has(error.constructor.name))
304
+ return true;
305
+ 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));
306
+ }
307
+ /**
308
+ * `error` as a terminal error ({@link REFUSED}), if a retry does not change
309
+ * it: a model the agent cannot take, or its provider's refusal.
310
+ */
311
+ export function refusal(error) {
312
+ if (error instanceof ModelError)
313
+ return error;
314
+ if (error instanceof restate.TerminalError || !refused(error))
315
+ return undefined;
316
+ return new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}. ${String(error)}`, {
317
+ errorCode: REFUSED,
318
+ });
319
+ }
320
+ /**
321
+ * A prompt's stored answer, as the prompt returns it: {@link UNANSWERED},
322
+ * stored as its provider refused it, fails as the prompt did then
323
+ * ({@link REFUSED}), also in a retry after a crash right after it was stored.
324
+ */
325
+ export function storedAnswer(answer) {
326
+ if (answer !== UNANSWERED)
327
+ return answer;
328
+ throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
329
+ }
330
+ /**
331
+ * A conversation as `messages` gives it, built from a framework's transcript:
332
+ * each message is started by `say`, a tool call goes to the assistant's
333
+ * message, and its result to its call. Messages without parts are left out.
334
+ *
335
+ * A message, once given out by `messages()`, is never changed: a change
336
+ * makes a new one in its place. So a framework can keep its transcript and
337
+ * add to it as its conversation grows, and the log stores only the messages
338
+ * that are not the ones it stored last (see log.ts).
339
+ */
340
+ export class Transcript {
341
+ #messages = [];
342
+ /** The message of each tool call, by the call's id: its index. */
343
+ #calls = new Map();
344
+ /** A new message of `role`, with `text` if there is any. */
345
+ say(role, text = '') {
346
+ this.#messages.push({ role, parts: text.trim() ? [{ type: 'text', text }] : [] });
347
+ }
348
+ /** Tool call `id` of the assistant's message. */
349
+ call(id, name, input) {
350
+ if (this.#messages.at(-1)?.role !== 'assistant')
351
+ this.say('assistant');
352
+ const at = this.#messages.length - 1;
353
+ this.#change(at, (parts) => [...parts, { type: 'tool', id, name, input }]);
354
+ this.#calls.set(id, at);
355
+ }
356
+ /** The output of tool call `id`; an error's if the framework says so, or it is a tool's `Error: <message>`. */
357
+ result(id, output, error = false) {
358
+ const at = this.#calls.get(id);
359
+ if (at === undefined)
360
+ return;
361
+ const failed = error || output.startsWith('Error: ');
362
+ this.#change(at, (parts) => parts.map((p) => (p.type === 'tool' && p.id === id ? { ...p, output, ...(failed ? { error: true } : {}) } : p)));
363
+ }
364
+ /**
365
+ * Whether tool call `id` has its output: not an error's, unless it is
366
+ * `failed`, the error the call answered with.
367
+ */
368
+ answered(id, failed) {
369
+ const at = this.#calls.get(id);
370
+ return (at !== undefined &&
371
+ this.#messages[at].parts.some((p) => p.type === 'tool' && p.id === id && p.output !== undefined && (!p.error || p.output === failed)));
372
+ }
373
+ /** Its messages, in order: those with parts. */
374
+ messages() {
375
+ return this.#messages.filter((m) => m.parts.length > 0);
376
+ }
377
+ /** Message `at` with its parts as `change` makes them: a new message, in its place. */
378
+ #change(at, change) {
379
+ const message = this.#messages[at];
380
+ this.#messages[at] = { ...message, parts: change(message.parts) };
381
+ }
382
+ }
383
+ /** The transcript of the turn of each context, while it answers. */
384
+ const reading = new WeakMap();
385
+ /** The log writes of each context, one after another: tool calls in parallel publish at once. */
386
+ const writing = new WeakMap();
387
+ /** The log of the conversation of `ctx` takes its transcript as `read` gives it. */
388
+ function logged(ctx, read) {
389
+ const write = async () => {
390
+ const transcript = await read();
391
+ await log.sync(ctx.db, transcript.messages());
392
+ // The calls whose results the framework stored are made: see calls.ts.
393
+ await settle(ctx, (id, failed) => transcript.answered(id, failed));
394
+ };
395
+ const done = (writing.get(ctx) ?? Promise.resolve()).then(write, write);
396
+ writing.set(ctx, done);
397
+ return done;
398
+ }
399
+ /**
400
+ * Run `work`, a framework's turn (or a compaction, a reset), with `read`
401
+ * giving the framework's transcript as it stands, from the framework as
402
+ * `work` holds it open: each publish meanwhile (a tool call's start and end)
403
+ * takes it into the conversation's log, and so does `work`'s end, before the
404
+ * framework closes. `messages` and `sync` read the log.
405
+ */
406
+ export async function transcribing(ctx, read, work) {
407
+ const outer = reading.get(ctx);
408
+ reading.set(ctx, read);
409
+ let failed = false;
410
+ try {
411
+ return await work();
412
+ }
413
+ catch (error) {
414
+ failed = !(error instanceof restate.TerminalError);
415
+ throw error;
416
+ }
417
+ finally {
418
+ try {
419
+ // A failed attempt stores nothing more: its retry runs again.
420
+ if (!failed)
421
+ await logged(ctx, read);
422
+ }
423
+ finally {
424
+ if (outer)
425
+ reading.set(ctx, outer);
426
+ else
427
+ reading.delete(ctx);
428
+ }
429
+ }
430
+ }
431
+ /**
432
+ * The handler of an agent's conversation as clients read it, from its log:
433
+ * a page of it (`{limit, before}`), or what is new or changed since a cursor
434
+ * (`{cursor}`). It is a view: it answers while a message is answered, with
435
+ * what was stored so far, and stores nothing.
436
+ */
437
+ export const messagesHandler = () => async (ctx, request) => log.page(ctx.db, request ?? {});
438
+ //# 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,gEAAgE;AAChE,gDAAgD;AAChD,OAAO,KAAK,O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Ae,GAC1B,GAAG,EAAE,CACL,KAAK,EAAE,GAAwB,EAAE,OAAyB,EAAqB,EAAE,CAC/E,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,EAAE,OAAO,IAAI,EAAE,CAAC,CAAC"}
@@ -0,0 +1,68 @@
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
+ notifications: (ctx: restate.ViewContext) => Promise<import("../signals.ts").Notifications>;
59
+ watch: (ctx: restate.ViewContext, watch: import("../signals.ts").Watch) => Promise<import("../signals.ts").Notifications>;
60
+ } & {
61
+ clear: (ctx: restate.ViewContext) => Promise<import("../object.ts").Stopped>;
62
+ sync: (ctx: restate.ViewContext, { cursor, revision, timeoutSeconds, limit }?: import("../object.ts").SyncRequest) => Promise<import("../object.ts").Synced>;
63
+ } & {
64
+ chat: (ctx: restate.SessionContext, text: string) => Promise<Answer<O>>;
65
+ } & {
66
+ messages: (ctx: restate.ViewContext, request?: import("../common.ts").MessagesRequest) => Promise<import("../common.ts").Messages>;
67
+ }>;
68
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.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