@restatedev/agents 0.2.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 -8
- package/dist/calls.d.ts.map +1 -1
- package/dist/calls.js +79 -18
- 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 +238 -156
- 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 +161 -71
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +277 -226
- 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 +323 -107
- 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 +234 -180
- 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 +123 -40
- 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 +75 -7
- package/dist/signals.d.ts.map +1 -1
- package/dist/signals.js +154 -27
- 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 +110 -24
- package/src/claude/README.md +41 -20
- package/src/claude/index.ts +271 -183
- package/src/client.ts +14 -3
- package/src/common.ts +354 -247
- package/src/conversation.ts +1527 -0
- package/src/deepseek/README.md +78 -11
- package/src/deepseek/index.ts +385 -138
- 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 +337 -193
- package/src/langgraph/nodes.ts +243 -0
- package/src/messages.ts +244 -0
- package/src/object.ts +178 -48
- package/src/output.ts +52 -31
- package/src/pi/README.md +18 -3
- package/src/pi/index.ts +346 -79
- package/src/pi/storage.ts +20 -7
- package/src/signals.ts +235 -31
- 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 -145
- 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 -193
- package/src/opencode/README.md +0 -125
- package/src/opencode/db.ts +0 -223
- package/src/opencode/index.ts +0 -559
package/dist/common.js
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
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
|
-
import { cancelCalls, cancelled } from '@restatedev/sessions/internal';
|
|
7
|
-
import {
|
|
8
|
-
import * as log from './log.js';
|
|
7
|
+
import { cancelCalls, cancelled, definitionOf, Link, ScopeKey } from '@restatedev/sessions/internal';
|
|
8
|
+
import { settleCalls } from './calls.js';
|
|
9
9
|
import { signals, signalsOf } from './signals.js';
|
|
10
10
|
/** `value` for the invocation of `ctx`. */
|
|
11
11
|
export const configured = async (value, ctx) => typeof value === 'function' ? value(ctx) : value;
|
|
12
12
|
/** The prompts each invocation made so far, by its context. */
|
|
13
|
-
const
|
|
13
|
+
const PROMPTS = new ScopeKey('nextPromptId');
|
|
14
14
|
/**
|
|
15
15
|
* The id of the next prompt of the invocation of `ctx`: the invocation's id,
|
|
16
16
|
* then `<id>:2`, `<id>:3`... A retried attempt makes its prompts in the same
|
|
17
17
|
* order, so each gets the same id again, and its answer.
|
|
18
18
|
*/
|
|
19
19
|
export const nextPromptId = (ctx) => {
|
|
20
|
-
const n = (
|
|
21
|
-
|
|
20
|
+
const n = (PROMPTS.get(ctx) ?? 0) + 1;
|
|
21
|
+
PROMPTS.set(ctx, n);
|
|
22
22
|
return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
|
|
23
23
|
};
|
|
24
|
-
/** The default model of pi
|
|
24
|
+
/** The default model of pi and LangGraph, with OPENAI_API_KEY. */
|
|
25
25
|
export const DEFAULT_MODEL = 'openai/gpt-6-sol';
|
|
26
26
|
/** The default model of Claude agents, with ANTHROPIC_API_KEY. */
|
|
27
27
|
export const CLAUDE_MODEL = 'anthropic/claude-sonnet-5-5';
|
|
@@ -87,6 +87,11 @@ export const messageSerde = {
|
|
|
87
87
|
}
|
|
88
88
|
},
|
|
89
89
|
};
|
|
90
|
+
/**
|
|
91
|
+
* What an empty answer says, as the model sees it later in the conversation:
|
|
92
|
+
* a provider's API may refuse an empty text (Anthropic's does).
|
|
93
|
+
*/
|
|
94
|
+
export const NO_ANSWER = '(no answer)';
|
|
90
95
|
/**
|
|
91
96
|
* What a cancelled turn answers, and each tool call it cut off: the model
|
|
92
97
|
* sees it in the conversation that goes on.
|
|
@@ -98,8 +103,40 @@ export const CANCELLED = 'Cancelled: the turn was stopped before it finished.';
|
|
|
98
103
|
* conversation that goes on, rather than answer it with the next message.
|
|
99
104
|
*/
|
|
100
105
|
export const UNANSWERED = "Unanswered: the model's provider refused the request.";
|
|
106
|
+
/**
|
|
107
|
+
* What a turn whose invocation ended without answering it (killed, say)
|
|
108
|
+
* answers, and each tool call it cut off: the next message, or the companion
|
|
109
|
+
* once it finds the invocation gone (`settle`), closes it with this.
|
|
110
|
+
*/
|
|
111
|
+
export const ENDED = 'Ended: the turn ended before it finished, and was not answered.';
|
|
112
|
+
/** The result of a tool call a stopped turn cut off once its Restate call had answered: it happened. */
|
|
113
|
+
export const RETURNED_UNRECORDED = "Done, but the turn was stopped before this call's result was recorded: it did happen, so check its effect before doing it again.";
|
|
114
|
+
/**
|
|
115
|
+
* What a stopped turn records as the result of its tool call `callId`, which
|
|
116
|
+
* has none: `text` (cancelled, say), unless the call's Restate call answered
|
|
117
|
+
* (`outcomes` of calls.ts), which the model would take for undone, and do
|
|
118
|
+
* again: then the error it answered with, or {@link RETURNED_UNRECORDED}.
|
|
119
|
+
*/
|
|
120
|
+
export function cutOffResult(outcomes, callId, text) {
|
|
121
|
+
if (!outcomes.has(callId))
|
|
122
|
+
return text;
|
|
123
|
+
return outcomes.get(callId) ?? RETURNED_UNRECORDED;
|
|
124
|
+
}
|
|
125
|
+
/** The window by default: the previous turn's tool calls and results stay in view, for a follow-up. */
|
|
126
|
+
export const WINDOW = 1;
|
|
127
|
+
/** How many tokens of the turns before the window the model sees, by default, counted as 4 characters each. */
|
|
128
|
+
export const BUDGET = 32_000;
|
|
129
|
+
/** What a request to summarize earlier turns starts with, before the turns themselves. */
|
|
130
|
+
export const SUMMARIZE = "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";
|
|
131
|
+
/** `window`, if it is one: a whole number of turns (0 or more), or `'all'`. */
|
|
132
|
+
export function checkWindow(window) {
|
|
133
|
+
if (window !== 'all' && !(Number.isInteger(window) && window >= 0)) {
|
|
134
|
+
throw new Error(`window must be a number of turns (0 or more) or 'all', not ${JSON.stringify(window)}`);
|
|
135
|
+
}
|
|
136
|
+
return window;
|
|
137
|
+
}
|
|
101
138
|
/** What stops each turn, by its context: see {@link stopSignalOf}. */
|
|
102
|
-
const
|
|
139
|
+
const TURN = new ScopeKey('stopSignalOf');
|
|
103
140
|
/**
|
|
104
141
|
* Why a turn stopped when its attempt ended before it did: Restate suspended
|
|
105
142
|
* the attempt, gave up on it, or lost its connection. Nothing the attempt
|
|
@@ -120,52 +157,87 @@ export class AttemptEnded extends Error {
|
|
|
120
157
|
* {@link AttemptEnded} once the attempt ends first (the work stops, and
|
|
121
158
|
* answers nothing).
|
|
122
159
|
*/
|
|
123
|
-
export const stopSignalOf = (ctx) =>
|
|
124
|
-
/**
|
|
125
|
-
const
|
|
126
|
-
/**
|
|
127
|
-
export const
|
|
128
|
-
/**
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
export const alsoClearing = (view, clear) => {
|
|
138
|
-
viewsClearing.set(view, clear);
|
|
139
|
-
return view;
|
|
160
|
+
export const stopSignalOf = (ctx) => TURN.get(ctx);
|
|
161
|
+
/** An agent's settings, on its definition. */
|
|
162
|
+
const AGENT = new Link('an agent');
|
|
163
|
+
/** The items of a framework's `messages` view on the conversation of turns. */
|
|
164
|
+
export const ITEMS = new Link('restate-agents.items');
|
|
165
|
+
/** `definition` is an agent's, with these settings: its framework's items, if it is on the conversation of turns. */
|
|
166
|
+
export const isAgent = (definition, { background = false, items = undefined, window = WINDOW, budget = BUDGET, summarize = undefined, }) => {
|
|
167
|
+
return AGENT.on(definition, {
|
|
168
|
+
background,
|
|
169
|
+
items,
|
|
170
|
+
window,
|
|
171
|
+
budget,
|
|
172
|
+
summarize,
|
|
173
|
+
});
|
|
140
174
|
};
|
|
141
|
-
/**
|
|
142
|
-
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
clearing.delete(name);
|
|
146
|
-
else
|
|
147
|
-
clearing.set(name, clear);
|
|
175
|
+
/** The settings of the agent of `ctx`, if it is one. */
|
|
176
|
+
const agentOf = (ctx) => {
|
|
177
|
+
const definition = definitionOf(ctx);
|
|
178
|
+
return definition && AGENT.of(definition);
|
|
148
179
|
};
|
|
149
|
-
/**
|
|
150
|
-
export const
|
|
180
|
+
/** The settings of the agent of `ctx`: the defaults, for an object that is no agent. */
|
|
181
|
+
export const settingsOf = (ctx) => agentOf(ctx) ?? { background: false, window: WINDOW, budget: BUDGET };
|
|
151
182
|
/** Whether the agent of `ctx` runs in the background. */
|
|
152
|
-
const unfollowed = (ctx) =>
|
|
183
|
+
const unfollowed = (ctx) => agentOf(ctx)?.background === true;
|
|
153
184
|
/** The `signals` object of the agent of `ctx`. */
|
|
154
185
|
const signalsOfAgent = (ctx) => ctx.rpc(signals, signalsOf(ctx));
|
|
155
186
|
/**
|
|
156
|
-
* The
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
187
|
+
* The messages steered to a `chat` turn that it has not taken yet, as the
|
|
188
|
+
* companion last published them. The companion answers them to every
|
|
189
|
+
* `publish`, which a turn makes at each tool call's start and end: so the
|
|
190
|
+
* turn knows of them without a call of its own, and finds them at its next
|
|
191
|
+
* step (`takeSteers`). The newest revision wins, as tool calls that run at
|
|
192
|
+
* once publish at once.
|
|
160
193
|
*/
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
194
|
+
export class Inbox {
|
|
195
|
+
revision = -1;
|
|
196
|
+
messages = [];
|
|
197
|
+
#listeners = new Set();
|
|
198
|
+
/** Keep what `publish` answered, if it is newer than what is kept, and tell the listeners if it lists messages. */
|
|
199
|
+
saw(published) {
|
|
200
|
+
if (typeof published !== 'object' || published === null)
|
|
201
|
+
return;
|
|
202
|
+
const revision = published.revision ?? -1;
|
|
203
|
+
if (revision <= this.revision)
|
|
204
|
+
return;
|
|
205
|
+
this.revision = revision;
|
|
206
|
+
this.messages = [...(published.steering ?? [])];
|
|
207
|
+
if (this.messages.length > 0)
|
|
208
|
+
for (const listener of this.#listeners)
|
|
209
|
+
listener();
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Call `listener` after each publish that lists messages, until the
|
|
213
|
+
* returned function is called: for a framework that takes steered
|
|
214
|
+
* messages through an inbox of its own (pi's, DeepSeek's), handed to it as
|
|
215
|
+
* they come.
|
|
216
|
+
*/
|
|
217
|
+
listen(listener) {
|
|
218
|
+
this.#listeners.add(listener);
|
|
219
|
+
return () => this.#listeners.delete(listener);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const INBOX = new ScopeKey('inbox');
|
|
223
|
+
/** The inbox of the `chat` turn running on `ctx`, if it takes steered messages: none outside one. */
|
|
224
|
+
export const inboxOf = (ctx) => INBOX.get(ctx);
|
|
225
|
+
/**
|
|
226
|
+
* The conversation of `ctx` changed (see `watch` in object.ts): its revision
|
|
227
|
+
* increases, and the clients that follow it read it again; while a framework
|
|
228
|
+
* answers ({@link answering}), the calls whose results it stored are
|
|
229
|
+
* forgotten first. It is a call to Restate, so it also sends what the
|
|
230
|
+
* handler wrote before, for them to read.
|
|
231
|
+
*/
|
|
232
|
+
export const publish = async (ctx) => {
|
|
233
|
+
const stored = ANSWERING.get(ctx);
|
|
234
|
+
if (stored)
|
|
235
|
+
await settled(ctx, stored);
|
|
236
|
+
const published = await signalsOfAgent(ctx).publish();
|
|
237
|
+
INBOX.get(ctx)?.saw(published);
|
|
166
238
|
};
|
|
167
239
|
/** 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) => {
|
|
240
|
+
export const stepped = async (ctx) => {
|
|
169
241
|
if (!unfollowed(ctx))
|
|
170
242
|
await publish(ctx);
|
|
171
243
|
};
|
|
@@ -178,16 +250,56 @@ const stepped = async (ctx) => {
|
|
|
178
250
|
export async function toolCallStarted(ctx) {
|
|
179
251
|
if (!unfollowed(ctx))
|
|
180
252
|
return publish(ctx);
|
|
181
|
-
const
|
|
182
|
-
if (
|
|
183
|
-
|
|
184
|
-
await settle(ctx, (id, failed) => transcript.answered(id, failed));
|
|
185
|
-
}
|
|
253
|
+
const stored = ANSWERING.get(ctx);
|
|
254
|
+
if (stored)
|
|
255
|
+
await settled(ctx, stored);
|
|
186
256
|
}
|
|
187
257
|
/** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
|
|
188
258
|
export async function toolCallEnded(ctx) {
|
|
189
259
|
await stepped(ctx);
|
|
190
260
|
}
|
|
261
|
+
/** What the attempt's turn has stored, while it answers (see {@link answering}). */
|
|
262
|
+
const ANSWERING = new ScopeKey('answering');
|
|
263
|
+
/** The attempt's latest settling of calls: one after another, as parallel tool calls publish at once. */
|
|
264
|
+
const SETTLING = new ScopeKey('settling');
|
|
265
|
+
/** Forget the calls whose results the conversation stored (calls.ts), after any settling before. */
|
|
266
|
+
function settled(ctx, stored) {
|
|
267
|
+
const settle = () => settleCalls(ctx, stored);
|
|
268
|
+
const done = (SETTLING.get(ctx) ?? Promise.resolve()).then(settle, settle);
|
|
269
|
+
SETTLING.set(ctx, done);
|
|
270
|
+
return done;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Run `work`, a framework's turn on the conversation of turns, forgetting
|
|
274
|
+
* the calls whose results it stores as it goes: each publish while it runs
|
|
275
|
+
* (a tool call's start and end), and its end, forget the Restate calls of
|
|
276
|
+
* the tool calls whose results `stored` says are stored (calls.ts).
|
|
277
|
+
*/
|
|
278
|
+
export async function answering(ctx, stored, work) {
|
|
279
|
+
const outer = ANSWERING.get(ctx);
|
|
280
|
+
ANSWERING.set(ctx, stored);
|
|
281
|
+
let failed = false;
|
|
282
|
+
try {
|
|
283
|
+
return await work();
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
failed = !(error instanceof restate.TerminalError);
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
finally {
|
|
290
|
+
try {
|
|
291
|
+
// A failed attempt stores nothing more: its retry runs again.
|
|
292
|
+
if (!failed)
|
|
293
|
+
await settled(ctx, stored);
|
|
294
|
+
}
|
|
295
|
+
finally {
|
|
296
|
+
if (outer)
|
|
297
|
+
ANSWERING.set(ctx, outer);
|
|
298
|
+
else
|
|
299
|
+
ANSWERING.delete(ctx);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
191
303
|
/** A promise that rejects with `signal`'s reason once it aborts. */
|
|
192
304
|
export const aborted = (signal) => new Promise((_, reject) => {
|
|
193
305
|
if (signal.aborted)
|
|
@@ -195,6 +307,10 @@ export const aborted = (signal) => new Promise((_, reject) => {
|
|
|
195
307
|
else
|
|
196
308
|
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
|
197
309
|
});
|
|
310
|
+
/** What makes a `chat` handler (`chatHandler`): its answer, and whether it takes steered messages. */
|
|
311
|
+
const CHAT = new Link('restate-agents.chat');
|
|
312
|
+
/** The answer of `entry`, a handler that `chatHandler` made, and whether it takes steered messages. */
|
|
313
|
+
export const chatOf = (entry) => CHAT.of(entry);
|
|
198
314
|
/**
|
|
199
315
|
* `answer` as a chat handler, which takes its message as plain text or as a
|
|
200
316
|
* JSON string, so that both of these work:
|
|
@@ -202,7 +318,7 @@ export const aborted = (signal) => new Promise((_, reject) => {
|
|
|
202
318
|
* curl localhost:8080/assistant/alice/chat -d 'Hi'
|
|
203
319
|
* curl localhost:8080/assistant/alice/chat --json '"Hi"'
|
|
204
320
|
*
|
|
205
|
-
* While it answers, the object's `status` says so (its {@link
|
|
321
|
+
* While it answers, the object's `status` says so (its {@link Answering}). Its
|
|
206
322
|
* invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
|
|
207
323
|
* @restatedev/sessions/internal) aborts {@link stopSignalOf} its
|
|
208
324
|
* context, whenever it comes, and cancels the calls its tools made
|
|
@@ -213,62 +329,86 @@ export const aborted = (signal) => new Promise((_, reject) => {
|
|
|
213
329
|
*
|
|
214
330
|
* It publishes when it starts and ends ({@link publish}), for the clients
|
|
215
331
|
* that follow the conversation.
|
|
332
|
+
*
|
|
333
|
+
* As the `chat` handler of an agent, it also answers each message sent to
|
|
334
|
+
* the agent's `steer` view that no turn took, as a turn of its own (the
|
|
335
|
+
* private `steered` handler). With `steers` (a framework's integration says
|
|
336
|
+
* so), its turns take steered messages at their steps (`takeSteers`).
|
|
216
337
|
*/
|
|
217
|
-
export const chatHandler = (answer) => ({
|
|
338
|
+
export const chatHandler = (answer, { steers = false } = {}) => CHAT.on({
|
|
218
339
|
input: messageSerde,
|
|
219
340
|
accept: '*/*',
|
|
220
341
|
explicitCancellation: true,
|
|
221
|
-
handler:
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
342
|
+
handler: (ctx, text) => chatTurn(ctx, text, answer, steers),
|
|
343
|
+
}, { answer, steers });
|
|
344
|
+
/**
|
|
345
|
+
* Answer `text` as a turn of the agent of `ctx`, with `answer`: the body of a
|
|
346
|
+
* `chat` handler ({@link chatHandler}), and of `steered`. With `steers`, the
|
|
347
|
+
* turn takes the messages steered to it at its steps (unless the agent runs
|
|
348
|
+
* in the background).
|
|
349
|
+
*/
|
|
350
|
+
export async function chatTurn(ctx, text, answer, steers = false) {
|
|
351
|
+
const invocationId = ctx.request.id;
|
|
352
|
+
// The companion knows the turn from here to its close: `status` and `stop` ask it.
|
|
353
|
+
// An agent on the conversation of turns has `settle`: the companion sends it
|
|
354
|
+
// this turn, should its invocation be gone without closing it.
|
|
355
|
+
const settles = agentOf(ctx)?.items !== undefined;
|
|
356
|
+
const steering = !unfollowed(ctx) && (typeof steers === 'function' ? await steers(ctx) : steers);
|
|
357
|
+
// Before the first publish, which may answer messages steered to the turn already (a retried attempt's).
|
|
358
|
+
if (steering)
|
|
359
|
+
INBOX.set(ctx, new Inbox());
|
|
360
|
+
await ctx.rpc(signals, signalsOf(ctx)).start({
|
|
361
|
+
invocationId,
|
|
362
|
+
since: new Date().toISOString(),
|
|
363
|
+
...(settles ? { settles } : {}),
|
|
364
|
+
...(steering ? { steers: steering } : {}),
|
|
365
|
+
});
|
|
366
|
+
await stepped(ctx);
|
|
367
|
+
// The log takes the turn's last change, then the companion closes the
|
|
368
|
+
// turn, which publishes it: one revision. The close is a call the turn
|
|
369
|
+
// waits for, so that it is done before the turn ends (see `awaitTurn`).
|
|
370
|
+
const end = async () => {
|
|
371
|
+
const stored = ANSWERING.get(ctx);
|
|
372
|
+
if (stored)
|
|
373
|
+
await settled(ctx, stored);
|
|
374
|
+
await signalsOfAgent(ctx).close(invocationId);
|
|
375
|
+
};
|
|
376
|
+
const turn = new AbortController();
|
|
377
|
+
TURN.set(ctx, turn.signal);
|
|
378
|
+
void (async () => {
|
|
379
|
+
await cancelled(ctx);
|
|
380
|
+
turn.abort(new restate.CancelledError());
|
|
381
|
+
await cancelCalls(ctx);
|
|
382
|
+
})().catch(() => { });
|
|
383
|
+
// The attempt ends before the turn does: its work stops (a model's
|
|
384
|
+
// request, say), rather than run on for an attempt that can store nothing.
|
|
385
|
+
const attempt = ctx.request.attemptCompletedSignal;
|
|
386
|
+
const attemptEnded = () => turn.abort(new AttemptEnded());
|
|
387
|
+
attempt.addEventListener('abort', attemptEnded, { once: true });
|
|
388
|
+
let answered;
|
|
389
|
+
try {
|
|
390
|
+
answered = await answer(ctx, text);
|
|
391
|
+
// Cancelled once answered: the answer stands.
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
if (error instanceof restate.TerminalError) {
|
|
261
395
|
await end();
|
|
262
|
-
throw
|
|
263
|
-
}
|
|
264
|
-
finally {
|
|
265
|
-
// An attempt's signal aborts at every attempt's end, the turn's too.
|
|
266
|
-
attempt.removeEventListener('abort', attemptEnded);
|
|
396
|
+
throw error;
|
|
267
397
|
}
|
|
398
|
+
// Any other error fails the attempt, and Restate retries the turn.
|
|
399
|
+
const terminal = refusalOf(ctx, error);
|
|
400
|
+
if (!terminal)
|
|
401
|
+
throw error;
|
|
268
402
|
await end();
|
|
269
|
-
|
|
270
|
-
}
|
|
271
|
-
|
|
403
|
+
throw terminal;
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
// An attempt's signal aborts at every attempt's end, the turn's too.
|
|
407
|
+
attempt.removeEventListener('abort', attemptEnded);
|
|
408
|
+
}
|
|
409
|
+
await end();
|
|
410
|
+
return answered;
|
|
411
|
+
}
|
|
272
412
|
/** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
|
|
273
413
|
export class ToolError extends Error {
|
|
274
414
|
tool;
|
|
@@ -278,32 +418,42 @@ export class ToolError extends Error {
|
|
|
278
418
|
this.tool = tool;
|
|
279
419
|
}
|
|
280
420
|
}
|
|
281
|
-
/** The errors
|
|
282
|
-
const
|
|
421
|
+
/** The errors the attempt's framework tools (not `tool()`'s) failed with: see {@link fromTool}. */
|
|
422
|
+
const TOOL_ERRORS = new ScopeKey('fromTool');
|
|
283
423
|
/**
|
|
284
|
-
* `error` is a tool's
|
|
285
|
-
* that failed, whose error is never taken for
|
|
286
|
-
* (a tool that calls a model API may fail as
|
|
287
|
-
* {@link ToolError}s.
|
|
424
|
+
* `error` is a tool's, in the attempt of `ctx`: a framework's own tool
|
|
425
|
+
* (Claude's, LangChain's...) that failed, whose error is never taken for
|
|
426
|
+
* the model's provider refusing (a tool that calls a model API may fail as
|
|
427
|
+
* one does). `tool()`'s are {@link ToolError}s.
|
|
288
428
|
*/
|
|
289
|
-
export function fromTool(error) {
|
|
429
|
+
export function fromTool(ctx, error) {
|
|
290
430
|
if (typeof error === 'object' && error !== null)
|
|
291
|
-
|
|
431
|
+
TOOL_ERRORS.of(ctx, () => new WeakSet()).add(error);
|
|
292
432
|
}
|
|
293
433
|
/** The Anthropic SDK's errors of a request that fails again however often it is made. */
|
|
294
|
-
const FOR_GOOD = new Set([
|
|
434
|
+
const FOR_GOOD = new Set([
|
|
435
|
+
'AuthenticationError',
|
|
436
|
+
'PermissionDeniedError',
|
|
437
|
+
'NotFoundError',
|
|
438
|
+
'BadRequestError',
|
|
439
|
+
]);
|
|
295
440
|
/**
|
|
296
441
|
* Whether `error` is a model provider's refusal that a retry does not change:
|
|
297
442
|
* a missing or wrong API key, an unknown model, a bad request. Other errors
|
|
298
443
|
* (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
|
|
299
444
|
*/
|
|
300
445
|
function refused(error) {
|
|
301
|
-
if (error instanceof ToolError
|
|
446
|
+
if (error instanceof ToolError)
|
|
302
447
|
return false;
|
|
303
448
|
if (error instanceof Error && FOR_GOOD.has(error.constructor.name))
|
|
304
449
|
return true;
|
|
305
450
|
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
451
|
}
|
|
452
|
+
/** {@link refusal}, but not of an error a framework's tool failed with in the attempt of `ctx` ({@link fromTool}). */
|
|
453
|
+
export function refusalOf(ctx, error) {
|
|
454
|
+
const failedTool = typeof error === 'object' && error !== null && TOOL_ERRORS.get(ctx)?.has(error);
|
|
455
|
+
return failedTool ? undefined : refusal(error);
|
|
456
|
+
}
|
|
307
457
|
/**
|
|
308
458
|
* `error` as a terminal error ({@link REFUSED}), if a retry does not change
|
|
309
459
|
* it: a model the agent cannot take, or its provider's refusal.
|
|
@@ -318,121 +468,22 @@ export function refusal(error) {
|
|
|
318
468
|
});
|
|
319
469
|
}
|
|
320
470
|
/**
|
|
321
|
-
* A prompt's stored answer, as the prompt returns it
|
|
322
|
-
*
|
|
323
|
-
*
|
|
324
|
-
|
|
325
|
-
|
|
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.
|
|
471
|
+
* A prompt's stored answer, as the prompt returns it, by how its turn ended
|
|
472
|
+
* (`status`): a turn refused ({@link UNANSWERED}) fails with
|
|
473
|
+
* {@link REFUSED}, one failed for good with its error, one cancelled with
|
|
474
|
+
* the cancellation, one another invocation ended with its note; so that a
|
|
475
|
+
* retry after a crash right after the close fails as the prompt did.
|
|
405
476
|
*/
|
|
406
|
-
export
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
}
|
|
477
|
+
export function storedAnswer(answer, status = 'answered') {
|
|
478
|
+
if (status === 'refused') {
|
|
479
|
+
throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
|
|
429
480
|
}
|
|
481
|
+
if (status === 'cancelled')
|
|
482
|
+
throw new restate.CancelledError();
|
|
483
|
+
if (status === 'failed')
|
|
484
|
+
throw new restate.TerminalError(answer.replace(/^Error: /, ''));
|
|
485
|
+
if (status === 'ended')
|
|
486
|
+
throw new restate.TerminalError(answer);
|
|
487
|
+
return answer;
|
|
430
488
|
}
|
|
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
489
|
//# sourceMappingURL=common.js.map
|