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