@restatedev/agents 0.1.0 → 0.3.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 (66) hide show
  1. package/README.md +25 -41
  2. package/dist/calls.d.ts +2 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +3 -9
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +0 -1
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +15 -14
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +2 -4
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +25 -39
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +77 -105
  16. package/dist/common.js.map +1 -1
  17. package/dist/deepseek/index.d.ts +0 -1
  18. package/dist/deepseek/index.d.ts.map +1 -1
  19. package/dist/deepseek/index.js +8 -26
  20. package/dist/deepseek/index.js.map +1 -1
  21. package/dist/index.d.ts +3 -10
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +3 -28
  24. package/dist/index.js.map +1 -1
  25. package/dist/langgraph/index.d.ts +0 -1
  26. package/dist/langgraph/index.d.ts.map +1 -1
  27. package/dist/langgraph/index.js +11 -13
  28. package/dist/langgraph/index.js.map +1 -1
  29. package/dist/log.d.ts +2 -2
  30. package/dist/log.d.ts.map +1 -1
  31. package/dist/log.js +13 -12
  32. package/dist/log.js.map +1 -1
  33. package/dist/object.d.ts +7 -19
  34. package/dist/object.d.ts.map +1 -1
  35. package/dist/object.js +10 -24
  36. package/dist/object.js.map +1 -1
  37. package/dist/opencode/index.d.ts +0 -1
  38. package/dist/opencode/index.d.ts.map +1 -1
  39. package/dist/opencode/index.js +14 -42
  40. package/dist/opencode/index.js.map +1 -1
  41. package/dist/pi/index.d.ts +0 -1
  42. package/dist/pi/index.d.ts.map +1 -1
  43. package/dist/pi/index.js +8 -28
  44. package/dist/pi/index.js.map +1 -1
  45. package/dist/signals.d.ts +17 -60
  46. package/dist/signals.d.ts.map +1 -1
  47. package/dist/signals.js +93 -97
  48. package/dist/signals.js.map +1 -1
  49. package/dist/webhook.d.ts +2 -4
  50. package/dist/webhook.d.ts.map +1 -1
  51. package/dist/webhook.js +2 -4
  52. package/dist/webhook.js.map +1 -1
  53. package/package.json +3 -3
  54. package/src/calls.ts +6 -12
  55. package/src/claude/index.ts +15 -15
  56. package/src/client.ts +1 -4
  57. package/src/common.ts +88 -109
  58. package/src/deepseek/index.ts +6 -29
  59. package/src/index.ts +3 -39
  60. package/src/langgraph/index.ts +15 -16
  61. package/src/log.ts +14 -13
  62. package/src/object.ts +20 -43
  63. package/src/opencode/index.ts +13 -49
  64. package/src/pi/index.ts +7 -28
  65. package/src/signals.ts +98 -140
  66. package/src/webhook.ts +2 -4
package/src/common.ts CHANGED
@@ -1,13 +1,13 @@
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, steering, publishing for the clients that follow it), and
3
+ // cancellation, publishing for the clients that follow it), and
4
4
  // the `messages` handler with its `Transcript`.
5
5
  import * as restate from '@restatedev/sessions';
6
- import { cancelCalls, cancelled } from '@restatedev/sessions/internal';
6
+ import { cancelCalls, cancelled, definitionOf, Link, ScopeKey } from '@restatedev/sessions/internal';
7
7
  import { settle } from './calls.ts';
8
8
  import * as log from './log.ts';
9
9
  import type { Said } from './log.ts';
10
- import { agentOf, type Steer, signals, signalsOf } from './signals.ts';
10
+ import { signals, signalsOf } from './signals.ts';
11
11
 
12
12
  /**
13
13
  * A value, or a function of the invocation's context that gives it: the
@@ -23,7 +23,7 @@ export const configured = async <T>(value: Configure<T>, ctx: restate.SessionCon
23
23
  typeof value === 'function' ? (value as (ctx: restate.SessionContext) => T | Promise<T>)(ctx) : value;
24
24
 
25
25
  /** The prompts each invocation made so far, by its context. */
26
- const prompts = new WeakMap<object, number>();
26
+ const PROMPTS = new ScopeKey<number>('nextPromptId');
27
27
 
28
28
  /**
29
29
  * The id of the next prompt of the invocation of `ctx`: the invocation's id,
@@ -31,8 +31,8 @@ const prompts = new WeakMap<object, number>();
31
31
  * order, so each gets the same id again, and its answer.
32
32
  */
33
33
  export const nextPromptId = (ctx: restate.SessionContext) => {
34
- const n = (prompts.get(ctx) ?? 0) + 1;
35
- prompts.set(ctx, n);
34
+ const n = (PROMPTS.get(ctx) ?? 0) + 1;
35
+ PROMPTS.set(ctx, n);
36
36
  return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
37
37
  };
38
38
 
@@ -133,7 +133,7 @@ export interface Turn {
133
133
  }
134
134
 
135
135
  /** What stops each turn, by its context: see {@link stopSignalOf}. */
136
- const turns = new WeakMap<object, AbortSignal>();
136
+ const TURN = new ScopeKey<AbortSignal>('stopSignalOf');
137
137
 
138
138
  /**
139
139
  * Why a turn stopped when its attempt ended before it did: Restate suspended
@@ -156,53 +156,54 @@ export class AttemptEnded extends Error {
156
156
  * {@link AttemptEnded} once the attempt ends first (the work stops, and
157
157
  * answers nothing).
158
158
  */
159
- export const stopSignalOf = (ctx: object): AbortSignal | undefined => turns.get(ctx);
159
+ export const stopSignalOf = (ctx: restate.SessionContext): AbortSignal | undefined => TURN.get(ctx);
160
160
 
161
- /** The ids of the messages steered to each turn that its conversation has, by its context. */
162
- const steerings = new WeakMap<object, Set<string>>();
161
+ /** What `clear` also empties, beside the agent's database. */
162
+ type Clear = (ctx: restate.SessionContext) => Promise<void>;
163
163
 
164
- /** A framework's conversation, while it answers a message: what steering needs of it. */
165
- export interface Steerable {
166
- /** Give it `message`, for its next step: once, by the message's id, however often it is given. */
167
- steer(message: Steer): Promise<void>;
168
- /** Whether it has message `id`: given in this attempt, or an earlier one. */
169
- has(id: string): Promise<boolean>;
164
+ /** An agent's own: whether it runs in the background (`background: true`: no one follows it as it works), and what its `clear` also empties. */
165
+ interface Agent {
166
+ background: boolean;
167
+ clear?: Clear;
170
168
  }
171
169
 
172
- /** The agents that run in the background (`background: true`): no one follows them as they work. */
173
- const background = new Set<string>();
174
-
175
- /** Agent `name` runs in the background: see `background` in object.ts. */
176
- export const inBackground = (name: string) => void background.add(name);
177
-
178
- /** What each agent clears beside its database, by its object's name: see {@link onClear}. */
179
- const clearing = new Map<string, (ctx: restate.SessionContext) => Promise<void>>();
170
+ /** An agent's own, on its definition. */
171
+ const AGENT = new Link<Agent>('an agent');
180
172
 
181
173
  /** What a framework's `messages` view clears beside the agent's database: see {@link alsoClearing}. */
182
- const viewsClearing = new WeakMap<object, (ctx: restate.SessionContext) => Promise<void>>();
174
+ const CLEARS = new Link<Clear>('alsoClearing');
183
175
 
184
176
  /**
185
177
  * The `messages` view `view` of a framework that keeps a conversation apart
186
178
  * (OpenCode, in a database of its own): `clear` empties it too, as an agent
187
179
  * with this view is cleared.
188
180
  */
189
- export const alsoClearing = <V extends object>(view: V, clear: (ctx: restate.SessionContext) => Promise<void>) => {
190
- viewsClearing.set(view, clear);
191
- return view;
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
+ */
189
+ export const isAgent = <D extends object>(
190
+ definition: D,
191
+ { background = false, messages = undefined as object | undefined },
192
+ ) => {
193
+ return AGENT.on(definition, { background, clear: messages && CLEARS.of(messages) });
192
194
  };
193
195
 
194
- /** When the agent `name`, whose `messages` view is `view`, is cleared, clear what that view keeps apart too. */
195
- export const onClear = (name: string, view: object | undefined) => {
196
- const clear = view === undefined ? undefined : viewsClearing.get(view);
197
- if (clear === undefined) clearing.delete(name);
198
- else clearing.set(name, clear);
196
+ /** The agent of `ctx`'s own (see {@link isAgent}). */
197
+ const agentOf = (ctx: restate.SessionContext) => {
198
+ const definition = definitionOf(ctx);
199
+ return definition && AGENT.of(definition);
199
200
  };
200
201
 
201
- /** Clear what the agent of `ctx` keeps beside its database ({@link onClear}). */
202
- export const cleared = async (ctx: restate.SessionContext) => clearing.get(ctx.request.target.service)?.(ctx);
202
+ /** Clear what the agent of `ctx` keeps beside its database. */
203
+ export const cleared = async (ctx: restate.SessionContext) => agentOf(ctx)?.clear?.(ctx);
203
204
 
204
205
  /** Whether the agent of `ctx` runs in the background. */
205
- const unfollowed = (ctx: restate.SessionContext) => background.has(ctx.request.target.service);
206
+ const unfollowed = (ctx: restate.SessionContext) => agentOf(ctx)?.background === true;
206
207
 
207
208
  /** The `signals` object of the agent of `ctx`. */
208
209
  const signalsOfAgent = (ctx: restate.SessionContext) => ctx.rpc(signals, signalsOf(ctx));
@@ -214,7 +215,7 @@ const signalsOfAgent = (ctx: restate.SessionContext) => ctx.rpc(signals, signals
214
215
  * Restate, so it also sends what the handler wrote before, for them to read.
215
216
  */
216
217
  const publish = async (ctx: restate.SessionContext) => {
217
- const read = reading.get(ctx);
218
+ const read = READING.get(ctx);
218
219
  if (read) await logged(ctx, read);
219
220
  await signalsOfAgent(ctx).publish();
220
221
  };
@@ -232,43 +233,16 @@ const stepped = async (ctx: restate.SessionContext) => {
232
233
  */
233
234
  export async function toolCallStarted(ctx: restate.SessionContext) {
234
235
  if (!unfollowed(ctx)) return publish(ctx);
235
- const read = reading.get(ctx);
236
+ const read = READING.get(ctx);
236
237
  if (read) {
237
238
  const transcript = await read();
238
239
  await settle(ctx, (id, failed) => transcript.answered(id, failed));
239
240
  }
240
241
  }
241
242
 
242
- /**
243
- * A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish}
244
- * it, and give `conversation` the messages steered to the turn since, which it
245
- * does not have yet: its next step takes them. Without a conversation (a
246
- * framework that takes no steering), they wait for the turn's end.
247
- */
248
- export async function toolCallEnded(ctx: restate.SessionContext, conversation?: Steerable) {
249
- // In the background, no one steers: a message steered anyway is answered after the turn.
250
- if (unfollowed(ctx)) return;
251
- const messages = await signalsOfAgent(ctx).progress(ctx.request.id);
252
- const taken = steerings.get(ctx);
253
- if (!taken || !conversation) return;
254
- for (const message of messages.filter((m) => !taken.has(m.id))) {
255
- if (!(await conversation.has(message.id))) await conversation.steer(message);
256
- taken.add(message.id);
257
- }
258
- }
259
-
260
- /**
261
- * Count the messages steered to the turn of `ctx` that `conversation` has,
262
- * such as those an earlier attempt gave it. A framework calls it once a
263
- * prompt is answered; the turn's other messages are answered as messages of
264
- * their own, when it ends.
265
- */
266
- export async function settleSteering(ctx: restate.SessionContext, conversation: Pick<Steerable, 'has'>) {
267
- const taken = steerings.get(ctx);
268
- if (!taken) return;
269
- for (const message of await signalsOfAgent(ctx).steering(ctx.request.id)) {
270
- if (!taken.has(message.id) && (await conversation.has(message.id))) taken.add(message.id);
271
- }
243
+ /** A tool call of the turn of `ctx` (a `chat` handler's) ended: {@link publish} it, unless the agent runs in the background. */
244
+ export async function toolCallEnded(ctx: restate.SessionContext) {
245
+ await stepped(ctx);
272
246
  }
273
247
 
274
248
  /** A promise that rejects with `signal`'s reason once it aborts. */
@@ -294,11 +268,8 @@ export const aborted = (signal: AbortSignal) =>
294
268
  * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
295
269
  * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
296
270
  *
297
- * Messages steered to it (`steer`) go to the agent's conversation at its next
298
- * tool call ({@link toolCallEnded}); when it ends, those it did not take are
299
- * answered as messages of their own, unless it was cancelled. It publishes
300
- * when it starts and ends ({@link publish}), for the clients that follow the
301
- * conversation.
271
+ * It publishes when it starts and ends ({@link publish}), for the clients
272
+ * that follow the conversation.
302
273
  */
303
274
  export const chatHandler = <A = string>(answer: (ctx: restate.SessionContext, message: string) => Promise<A>) => ({
304
275
  input: messageSerde,
@@ -306,21 +277,19 @@ export const chatHandler = <A = string>(answer: (ctx: restate.SessionContext, me
306
277
  explicitCancellation: true,
307
278
  handler: async (ctx: restate.SessionContext, text: string): Promise<A> => {
308
279
  const invocationId = ctx.request.id;
309
- // The companion knows the turn from here to its close: `status`, `stop` and `steer` ask it.
310
- await ctx
311
- .rpc(signals, signalsOf(ctx))
312
- .start({ agent: agentOf(ctx), turn: { invocationId, since: new Date().toISOString() } });
313
- const taken = new Set<string>();
314
- steerings.set(ctx, taken);
280
+ // The companion knows the turn from here to its close: `status` and `stop` ask it.
281
+ await ctx.rpc(signals, signalsOf(ctx)).start({ invocationId, since: new Date().toISOString() });
315
282
  await stepped(ctx);
316
- const end = async (dropped = false) => {
317
- ctx
318
- .send(signals, signalsOf(ctx))
319
- .close({ agent: agentOf(ctx), turn: invocationId, taken: [...taken], cancelled: dropped });
320
- await publish(ctx);
283
+ // The log takes the turn's last change, then the companion closes the
284
+ // turn, which publishes it: one revision. The close is a call the turn
285
+ // waits for, so that it is done before the turn ends (see `awaitTurn`).
286
+ const end = async () => {
287
+ const read = READING.get(ctx);
288
+ if (read) await logged(ctx, read);
289
+ await signalsOfAgent(ctx).close(invocationId);
321
290
  };
322
291
  const turn = new AbortController();
323
- turns.set(ctx, turn.signal);
292
+ TURN.set(ctx, turn.signal);
324
293
  void (async () => {
325
294
  await cancelled(ctx);
326
295
  turn.abort(new restate.CancelledError());
@@ -337,11 +306,11 @@ export const chatHandler = <A = string>(answer: (ctx: restate.SessionContext, me
337
306
  // Cancelled once answered: the answer stands.
338
307
  } catch (error) {
339
308
  if (error instanceof restate.TerminalError) {
340
- await end(error instanceof restate.CancelledError);
309
+ await end();
341
310
  throw error;
342
311
  }
343
312
  // Any other error fails the attempt, and Restate retries the turn.
344
- const terminal = refusal(error);
313
+ const terminal = refusalOf(ctx, error);
345
314
  if (!terminal) throw error;
346
315
  await end();
347
316
  throw terminal;
@@ -364,21 +333,26 @@ export class ToolError extends Error {
364
333
  }
365
334
  }
366
335
 
367
- /** The errors a framework's own tools (not `tool()`'s) failed with: see {@link fromTool}. */
368
- const toolErrors = new WeakSet<object>();
336
+ /** The errors the attempt's framework tools (not `tool()`'s) failed with: see {@link fromTool}. */
337
+ const TOOL_ERRORS = new ScopeKey<WeakSet<object>>('fromTool');
369
338
 
370
339
  /**
371
- * `error` is a tool's: a framework's own tool (Claude's, LangChain's...)
372
- * that failed, whose error is never taken for the model's provider refusing
373
- * (a tool that calls a model API may fail as one does). `tool()`'s are
374
- * {@link ToolError}s.
340
+ * `error` is a tool's, in the attempt of `ctx`: a framework's own tool
341
+ * (Claude's, LangChain's...) that failed, whose error is never taken for
342
+ * the model's provider refusing (a tool that calls a model API may fail as
343
+ * one does). `tool()`'s are {@link ToolError}s.
375
344
  */
376
- export function fromTool(error: unknown) {
377
- if (typeof error === 'object' && error !== null) toolErrors.add(error);
345
+ export function fromTool(ctx: restate.SessionContext, error: unknown) {
346
+ if (typeof error === 'object' && error !== null) TOOL_ERRORS.of(ctx, () => new WeakSet()).add(error);
378
347
  }
379
348
 
380
349
  /** The Anthropic SDK's errors of a request that fails again however often it is made. */
381
- const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFoundError', 'BadRequestError']);
350
+ const FOR_GOOD: ReadonlySet<string> = new Set([
351
+ 'AuthenticationError',
352
+ 'PermissionDeniedError',
353
+ 'NotFoundError',
354
+ 'BadRequestError',
355
+ ]);
382
356
 
383
357
  /**
384
358
  * Whether `error` is a model provider's refusal that a retry does not change:
@@ -386,14 +360,19 @@ const FOR_GOOD = new Set(['AuthenticationError', 'PermissionDeniedError', 'NotFo
386
360
  * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
387
361
  */
388
362
  function refused(error: unknown) {
389
- if (error instanceof ToolError || (typeof error === 'object' && error !== null && toolErrors.has(error)))
390
- return false;
363
+ if (error instanceof ToolError) return false;
391
364
  if (error instanceof Error && FOR_GOOD.has(error.constructor.name)) return true;
392
365
  return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(
393
366
  String(error),
394
367
  );
395
368
  }
396
369
 
370
+ /** {@link refusal}, but not of an error a framework's tool failed with in the attempt of `ctx` ({@link fromTool}). */
371
+ export function refusalOf(ctx: restate.SessionContext, error: unknown): restate.TerminalError | undefined {
372
+ const failedTool = typeof error === 'object' && error !== null && TOOL_ERRORS.get(ctx)?.has(error);
373
+ return failedTool ? undefined : refusal(error);
374
+ }
375
+
397
376
  /**
398
377
  * `error` as a terminal error ({@link REFUSED}), if a retry does not change
399
378
  * it: a model the agent cannot take, or its provider's refusal.
@@ -535,22 +514,22 @@ export class Transcript {
535
514
  */
536
515
  export type Read = () => Promise<Transcript>;
537
516
 
538
- /** The transcript of the turn of each context, while it answers. */
539
- const reading = new WeakMap<object, Read>();
517
+ /** The transcript of the attempt's turn, while it answers. */
518
+ const READING = new ScopeKey<Read>('transcribing');
540
519
 
541
- /** The log writes of each context, one after another: tool calls in parallel publish at once. */
542
- const writing = new WeakMap<object, Promise<void>>();
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');
543
522
 
544
523
  /** The log of the conversation of `ctx` takes its transcript as `read` gives it. */
545
524
  function logged(ctx: restate.SessionContext, read: Read): Promise<void> {
546
525
  const write = async () => {
547
526
  const transcript = await read();
548
- await log.sync(ctx.db, transcript.messages());
527
+ await log.sync(ctx, transcript.messages());
549
528
  // The calls whose results the framework stored are made: see calls.ts.
550
529
  await settle(ctx, (id, failed) => transcript.answered(id, failed));
551
530
  };
552
- const done = (writing.get(ctx) ?? Promise.resolve()).then(write, write);
553
- writing.set(ctx, done);
531
+ const done = (WRITING.get(ctx) ?? Promise.resolve()).then(write, write);
532
+ WRITING.set(ctx, done);
554
533
  return done;
555
534
  }
556
535
 
@@ -562,8 +541,8 @@ function logged(ctx: restate.SessionContext, read: Read): Promise<void> {
562
541
  * framework closes. `messages` and `sync` read the log.
563
542
  */
564
543
  export async function transcribing<T>(ctx: restate.SessionContext, read: Read, work: () => Promise<T>): Promise<T> {
565
- const outer = reading.get(ctx);
566
- reading.set(ctx, read);
544
+ const outer = READING.get(ctx);
545
+ READING.set(ctx, read);
567
546
  let failed = false;
568
547
  try {
569
548
  return await work();
@@ -575,8 +554,8 @@ export async function transcribing<T>(ctx: restate.SessionContext, read: Read, w
575
554
  // A failed attempt stores nothing more: its retry runs again.
576
555
  if (!failed) await logged(ctx, read);
577
556
  } finally {
578
- if (outer) reading.set(ctx, outer);
579
- else reading.delete(ctx);
557
+ if (outer) READING.set(ctx, outer);
558
+ else READING.delete(ctx);
580
559
  }
581
560
  }
582
561
  }
@@ -51,7 +51,6 @@ import {
51
51
  } from '@deepseek-ai/dsh-tools';
52
52
  import {
53
53
  aborted,
54
- AttemptEnded,
55
54
  CANCELLED,
56
55
  chatHandler,
57
56
  checkModelName,
@@ -64,8 +63,6 @@ import {
64
63
  nextPromptId,
65
64
  providerOf,
66
65
  refusal,
67
- settleSteering,
68
- type Steerable,
69
66
  stopSignalOf,
70
67
  storedAnswer,
71
68
  toolCallEnded,
@@ -150,7 +147,6 @@ async function boot(db: restate.Database, route: Route, system?: string): Promis
150
147
  const CONTINUE = 'Continue: your last turn was interrupted. Finish the request.';
151
148
 
152
149
  const promptId = (id: string) => MessageId(`prompt:${id}`);
153
- const steerId = (id: string) => MessageId(`steer:${id}`);
154
150
  const textOf = (message: Message) => message.content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
155
151
 
156
152
  /**
@@ -308,11 +304,10 @@ const answerOnce = async (
308
304
  let agent: Agent | undefined;
309
305
  try {
310
306
  const sessionId = SessionId(ctx.key);
311
- const steerable = () => steeringOf(agent!);
312
307
  const options = {
313
308
  agentOptions: route,
314
309
  setup: (agentCtx: Context) => {
315
- for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, steerable, fail));
310
+ for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
316
311
  },
317
312
  };
318
313
  // Resuming closes a turn a crash left open.
@@ -321,13 +316,8 @@ const answerOnce = async (
321
316
  : await harness.agents.create({ sessionId, ...options });
322
317
  agent = started.agent;
323
318
  const answer = await answered(harness, agent, id, text, failed);
324
- await settleSteering(ctx, steerable());
325
319
  return answer;
326
320
  } catch (e) {
327
- // A turn that ends unanswered (cancelled, refused) counts the messages
328
- // steered to it that the session has, given in an earlier attempt too:
329
- // its close answers only the others. An attempt that ended closes nothing.
330
- if (agent && !(e instanceof AttemptEnded)) await settleSteering(ctx, steeringOf(agent)).catch(() => {});
331
321
  // A cancelled invocation cancels the agent's turn, which the log keeps.
332
322
  if (e instanceof restate.CancelledError && agent) await cancelTurn(harness, agent);
333
323
  else (harness.sessionPersistence as SqlSessionPersistence).abandon();
@@ -376,25 +366,13 @@ async function cancelTurn(harness: Context, agent: Agent) {
376
366
  await harness.sessions.flush(agent.session);
377
367
  }
378
368
 
379
- /**
380
- * Messages steered to the turn: the agent's steering, which its next step
381
- * takes (after the tool calls), and the log keeps, by id.
382
- */
383
- const steeringOf = (agent: Agent): Steerable => ({
384
- steer: async (steered) => agent.steer(message(steerId(steered.id), steered.text)),
385
- has: async (steered) =>
386
- agent.session.snapshotEvents().some((e) => e.type === 'user/message' && e.data.id === steerId(steered)),
387
- });
388
-
389
369
  /**
390
370
  * `definition`, its calls published as they start and end (for the clients
391
- * that follow the conversation, and the steering), and its error failing the
392
- * attempt.
371
+ * that follow the conversation), and its error failing the attempt.
393
372
  */
394
373
  const tracked = (
395
374
  definition: ToolDefinition,
396
375
  ctx: restate.SessionContext,
397
- steerable: () => Steerable,
398
376
  fail: (error: unknown) => void,
399
377
  ): ToolDefinition => ({
400
378
  ...definition,
@@ -402,10 +380,10 @@ const tracked = (
402
380
  try {
403
381
  await toolCallStarted(ctx);
404
382
  const result = await definition.execute(args, exec);
405
- await toolCallEnded(ctx, steerable());
383
+ await toolCallEnded(ctx);
406
384
  return result;
407
385
  } catch (error) {
408
- fromTool(error);
386
+ fromTool(ctx, error);
409
387
  fail(error);
410
388
  throw error;
411
389
  }
@@ -458,9 +436,8 @@ export const messages = () => messagesHandler();
458
436
  const transcribe = async (db: Database, key: string) => {
459
437
  const transcript = new Transcript();
460
438
  for (const e of await storedEvents(db, SessionId(key))) {
461
- // The prompts and the messages steered to them, not the requests to
462
- // continue an interrupted turn.
463
- if (e.type === 'user/message' && /^(prompt|steer):/.test(e.data.id)) transcript.say('user', textOf(e.data));
439
+ // The prompts, not the requests to continue an interrupted turn.
440
+ if (e.type === 'user/message' && e.data.id.startsWith('prompt:')) transcript.say('user', textOf(e.data));
464
441
  if (e.type === 'assistant/message') transcript.say('assistant', textOf(e.data.message));
465
442
  if (e.type === 'tool/call') transcript.call(e.data.callId, e.data.name, parsed(e.data.arguments));
466
443
  if (e.type === 'tool/result')
package/src/index.ts CHANGED
@@ -2,8 +2,6 @@
2
2
  // is a subpath (@restatedev/agents/pi, /opencode, /langgraph, /claude,
3
3
  // /deepseek); this is what they share: session objects, tools for
4
4
  // any of them, and the tools that are Restate itself.
5
- import { sdk as restate } from '@restatedev/sessions/internal';
6
- import { signals } from './signals.ts';
7
5
 
8
6
  export {
9
7
  CANCELLED,
@@ -18,43 +16,9 @@ export {
18
16
  type Configure,
19
17
  } from './common.ts';
20
18
  export { sessionObject, type Status, type Stopped } from './object.ts';
21
- export {
22
- companionOf,
23
- deliver,
24
- signals,
25
- type Companion,
26
- type Resolved,
27
- type Signal,
28
- type Steer,
29
- type Steered,
30
- type Waiting,
31
- } from './signals.ts';
19
+ export { companionOf, deliver, signals, type Companion, type Resolved, type Signal, type Waiting } from './signals.ts';
32
20
  export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall, type ToolContext } from './tools.ts';
33
21
  export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
34
22
 
35
- /**
36
- * Serve `services` on PORT (default 9080), with what the agents need beside
37
- * them (the `signals` object). RESTATE_SERVE_ONLY, names separated by commas
38
- * (`triage,planner,signals`), serves only those of them: one image, deployed
39
- * in parts. The agents reach `signals` through Restate, so one part serves it
40
- * for them all.
41
- */
42
- export const serve = (...services: restate.ServeOptions['services']) =>
43
- restate.serve({
44
- services: only([...services.filter((s) => s !== signals), signals], process.env.RESTATE_SERVE_ONLY),
45
- port: Number(process.env.PORT ?? 9080),
46
- });
47
-
48
- /** The `services` that `names` (comma separated) names, or all of them without names; a name of none is an error. */
49
- function only(services: restate.ServeOptions['services'], names: string | undefined) {
50
- const wanted = (names ?? '')
51
- .split(',')
52
- .map((name) => name.trim())
53
- .filter(Boolean);
54
- if (wanted.length === 0) return services;
55
- const known = services.map((s) => s.name);
56
- const unknown = wanted.filter((name) => !known.includes(name));
57
- if (unknown.length > 0)
58
- throw new Error(`RESTATE_SERVE_ONLY names ${unknown.join(', ')}: the services are ${known.join(', ')}`);
59
- return services.filter((s) => wanted.includes(s.name));
60
- }
23
+ /** @restatedev/sessions' `serve`: the services on PORT, with what they need beside them (an agent's `signals`). */
24
+ export { serve } from '@restatedev/sessions';
@@ -28,8 +28,6 @@
28
28
  import * as restate from '@restatedev/sessions';
29
29
  import type { Database } from '@restatedev/sessions';
30
30
  import type { RunnableConfig } from '@langchain/core/runnables';
31
- import type { ChatAnthropic } from '@langchain/anthropic';
32
- import type { ChatOpenAI } from '@langchain/openai';
33
31
  import type { BaseChatModel } from '@langchain/core/language_models/chat_models';
34
32
  import { AIMessage, type BaseMessage, HumanMessage, SystemMessage, ToolMessage } from '@langchain/core/messages';
35
33
  import { type StructuredToolInterface, tool, ToolInputParsingException } from '@langchain/core/tools';
@@ -47,7 +45,7 @@ import {
47
45
  modelOf,
48
46
  nextPromptId,
49
47
  providerOf,
50
- refusal,
48
+ refusalOf,
51
49
  stopSignalOf,
52
50
  storedAnswer,
53
51
  toolCallEnded,
@@ -89,7 +87,7 @@ function toolsNode(ctx: restate.SessionContext, tools: StructuredToolInterface[]
89
87
  const { promise: failure, reject: failed } = Promise.withResolvers<never>();
90
88
  failure.catch(() => {});
91
89
  const node = new ToolNode(
92
- tools.map((t) => failing(t, failed)),
90
+ tools.map((t) => failing(ctx, t, failed)),
93
91
  { handleToolErrors: true },
94
92
  );
95
93
  const ran: { messages: BaseMessage[] } = await Promise.race([node.invoke(state, config), failure]);
@@ -99,7 +97,11 @@ function toolsNode(ctx: restate.SessionContext, tools: StructuredToolInterface[]
99
97
  }
100
98
 
101
99
  /** `t`, its errors given to `failed`, but for its input's (arguments that do not fit) and LangGraph's interrupts. */
102
- const failing = (t: StructuredToolInterface, failed: (error: unknown) => void): StructuredToolInterface =>
100
+ const failing = (
101
+ ctx: restate.SessionContext,
102
+ t: StructuredToolInterface,
103
+ failed: (error: unknown) => void,
104
+ ): StructuredToolInterface =>
103
105
  Object.create(t, {
104
106
  invoke: {
105
107
  value: async (...args: Parameters<StructuredToolInterface['invoke']>) => {
@@ -107,7 +109,7 @@ const failing = (t: StructuredToolInterface, failed: (error: unknown) => void):
107
109
  return await t.invoke(...args);
108
110
  } catch (error) {
109
111
  if (!(error instanceof ToolInputParsingException) && !isGraphInterrupt(error)) {
110
- fromTool(error);
112
+ fromTool(ctx, error);
111
113
  failed(error);
112
114
  }
113
115
  throw error;
@@ -128,22 +130,19 @@ const providerOfModel = (named: string) => {
128
130
 
129
131
  /**
130
132
  * The chat model `provider/model-id` names: OpenAI's or Anthropic's, through
131
- * LangChain's integration of the provider, loaded once, when a model of it is
132
- * first used: only that one need be installed.
133
+ * LangChain's integration of the provider, loaded when a model of it is
134
+ * used (Node loads a module once): only that one need be installed.
133
135
  */
134
136
  const chatModel = async (named: string): Promise<BaseChatModel> => {
135
137
  const [provider, id] = providerOfModel(named);
136
138
  if (provider === 'openai') {
137
- openai ??= integration('@langchain/openai', () => import('@langchain/openai'));
138
- return new (await openai).ChatOpenAI({ model: id });
139
+ const { ChatOpenAI } = await integration('@langchain/openai', () => import('@langchain/openai'));
140
+ return new ChatOpenAI({ model: id });
139
141
  }
140
- anthropic ??= integration('@langchain/anthropic', () => import('@langchain/anthropic'));
141
- return new (await anthropic).ChatAnthropic({ model: id });
142
+ const { ChatAnthropic } = await integration('@langchain/anthropic', () => import('@langchain/anthropic'));
143
+ return new ChatAnthropic({ model: id });
142
144
  };
143
145
 
144
- let openai: Promise<{ ChatOpenAI: typeof ChatOpenAI }> | undefined;
145
- let anthropic: Promise<{ ChatAnthropic: typeof ChatAnthropic }> | undefined;
146
-
147
146
  /** The integration `name`, which its user installs beside @restatedev/agents. */
148
147
  async function integration<T>(name: string, load: () => Promise<T>): Promise<T> {
149
148
  try {
@@ -249,7 +248,7 @@ const answerOnce = async (
249
248
  }
250
249
  // Refused for good (a wrong API key): the run ends unanswered, and
251
250
  // fails as terminal. An earlier prompt's, this one goes on.
252
- const refused = refusal(error);
251
+ const refused = refusalOf(ctx, error);
253
252
  if (!refused) throw error;
254
253
  await close(app, config, UNANSWERED);
255
254
  if (!interrupted || last === id) throw refused;
package/src/log.ts CHANGED
@@ -14,8 +14,8 @@
14
14
  // got to: the next conversation's ids and cursors go on from there (its
15
15
  // start, a row of `restate_agent_log_start`), so a client following it reads
16
16
  // on, and drops the messages before `first`.
17
- import type { Database, DatabaseReader, DatabaseWriter } from '@restatedev/sessions';
18
- import { Schema } from '@restatedev/sessions/internal';
17
+ import type { DatabaseReader, DatabaseWriter, SessionContext } from '@restatedev/sessions';
18
+ import { Schema, ScopeKey } from '@restatedev/sessions/internal';
19
19
  import type { ChatMessage, Messages, MessagesRequest } from './common.ts';
20
20
 
21
21
  const TABLE = 'restate_agent_log';
@@ -73,16 +73,16 @@ interface Head {
73
73
  }
74
74
 
75
75
  /**
76
- * The head of each session (`ctx.db`, one per attempt), as its last `sync`
77
- * stored it: the next compares the transcript with it, rather than read the
78
- * whole log again at each step.
76
+ * The log's head, as the attempt's last `sync` stored it: the next compares
77
+ * the transcript with it, rather than read the whole log again at each step.
79
78
  */
80
- const heads = new WeakMap<Database, Head>();
79
+ const HEAD = new ScopeKey<Head>('the log');
81
80
 
82
- /** The log's head in `db`: as this session stored it last, or else as the log has it. */
83
- async function headOf(db: Database): Promise<Head> {
84
- const cached = heads.get(db);
81
+ /** The log's head in the attempt of `ctx`: as it stored it last, or else as the log has it. */
82
+ async function headOf(ctx: SessionContext): Promise<Head> {
83
+ const cached = HEAD.get(ctx);
85
84
  if (cached) return cached;
85
+ const { db } = ctx;
86
86
  const rows = (await db.values(`SELECT id, message FROM ${TABLE} WHERE position IS NOT NULL ORDER BY position`)).map(
87
87
  ([id, json]) => ({ id: Number(id), message: JSON.parse(String(json)) as Said, json: String(json) }),
88
88
  );
@@ -98,9 +98,10 @@ async function headOf(db: Database): Promise<Head> {
98
98
  * Store the transcript's `messages`, in order, in the log: those that
99
99
  * changed since the last time, in one transaction.
100
100
  */
101
- export async function sync(db: Database, messages: Said[]) {
101
+ export async function sync(ctx: SessionContext, messages: Said[]) {
102
+ const { db } = ctx;
102
103
  await SCHEMA.ensure(db);
103
- const head = await headOf(db);
104
+ const head = await headOf(ctx);
104
105
  // A message the transcript did not change is the one stored (see Transcript in common.ts):
105
106
  // only the others are compared, as JSON.
106
107
  const jsons: string[] = [];
@@ -134,10 +135,10 @@ export async function sync(db: Database, messages: Said[]) {
134
135
  });
135
136
  } catch (error) {
136
137
  // Rolled back: the log is as it was, which the next sync reads again.
137
- heads.delete(db);
138
+ HEAD.delete(ctx);
138
139
  throw error;
139
140
  }
140
- heads.set(db, { rows, seq, next: id });
141
+ HEAD.set(ctx, { rows, seq, next: id });
141
142
  }
142
143
 
143
144
  /**