@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/object.ts CHANGED
@@ -1,23 +1,12 @@
1
1
  // Virtual objects set up for SQL and agents.
2
2
  import * as restate from '@restatedev/sessions';
3
3
  import { reset } from '@restatedev/sessions/internal';
4
- import {
5
- cleared,
6
- onClear,
7
- inBackground,
8
- type Messages,
9
- type MessagesRequest,
10
- messageSerde,
11
- refusal,
12
- type Turn,
13
- } from './common.ts';
4
+ import { cleared, isAgent, type Messages, type MessagesRequest, refusalOf, type Turn } from './common.ts';
14
5
  import * as log from './log.ts';
15
6
  import {
16
- agentOf,
17
7
  type Notifications,
18
8
  type Resolved,
19
9
  type Signal,
20
- type Steered,
21
10
  signals,
22
11
  signalsOf,
23
12
  withCompanion,
@@ -81,8 +70,8 @@ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOpt
81
70
  * The views every object here has, beside its own: `signal`, which resolves
82
71
  * a wait of the object's tools (see `signal` in tools.ts), `pending`, the
83
72
  * waits, `status`, what the object is doing, `stop`, which stops the message
84
- * it answers, `steer`, which adds to it, and `notifications` and `watch`,
85
- * the revision of its conversation, and a wait for a newer one (an agent's
73
+ * it answers, and `notifications` and `watch`, the revision of its
74
+ * conversation, and a wait for a newer one (an agent's
86
75
  * has `clear` and `sync` too: {@link followed}). Each asks the object's
87
76
  * `signals` companion, which knows what the object does: they run while the
88
77
  * object's handler works.
@@ -94,18 +83,6 @@ const BUILT_IN = {
94
83
  status: async (ctx: restate.ViewContext): Promise<Status> => companion(ctx).status(),
95
84
  /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
96
85
  stop: async (ctx: restate.ViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
97
- /**
98
- * Add `text` to the message being answered (`status`'s), such as "Only
99
- * Monday, please": the agent takes it at its next tool call, as its
100
- * framework steers a turn. A turn that ends first answers it as a message
101
- * of its own, as `chat` does when no message is answered.
102
- */
103
- steer: {
104
- input: messageSerde,
105
- accept: '*/*',
106
- handler: async (ctx: restate.ViewContext, text: string): Promise<Steered> =>
107
- companion(ctx, 'steer').steer({ agent: agentOf(ctx), text }),
108
- },
109
86
  /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
110
87
  notifications: async (ctx: restate.ViewContext): Promise<Notifications> => companion(ctx).notifications(),
111
88
  /**
@@ -133,8 +110,8 @@ const BUILT_IN = {
133
110
  const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>) => ({
134
111
  /**
135
112
  * Forget the conversation: stop the message being answered (as `stop`),
136
- * then empty the key's database, and what its `signals` hold (waits, kept
137
- * signals, steered messages). The log's ids and cursors go on (see
113
+ * then empty the key's database, and what its `signals` hold (waits and
114
+ * kept signals). The log's ids and cursors go on (see
138
115
  * log.ts), so a follower reads on, and drops the messages before `first`.
139
116
  * A message sent before it is answered first, then forgotten too; one sent
140
117
  * after starts anew.
@@ -223,8 +200,7 @@ export interface Definition<P extends string> {
223
200
  /**
224
201
  * Whether it works unwatched, such as a subagent: its turn calls its
225
202
  * `signals` only at its end, not at each step, so a client that follows it
226
- * sees each turn once it ended, and a steered message waits for the turn's
227
- * end. `messages` has every turn as before.
203
+ * sees each turn once it ended. `messages` has every turn as before.
228
204
  */
229
205
  background?: boolean;
230
206
  }
@@ -258,7 +234,7 @@ type With<H, V> = Functions<typeof BUILT_IN> &
258
234
  *
259
235
  * Besides its own handlers and views, it has the views `status`, what it is
260
236
  * doing (the message it answers, and what its tools wait for), `stop`,
261
- * which stops that message, `steer`, which adds to it, `pending`, the waits
237
+ * which stops that message, `pending`, the waits
262
238
  * of its tools (`signal()`), `signal({ id, value })`, which resolves one,
263
239
  * and `notifications` and `watch({ revision })`, to follow its
264
240
  * conversation. An agent, an object with a `messages` view (such as
@@ -288,7 +264,6 @@ export const sessionObject = <
288
264
  },
289
265
  ): restate.VirtualObjectDefinition<P, With<H, V>> => {
290
266
  const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
291
- if (background) inBackground(name);
292
267
  const own = [
293
268
  ...Object.keys(BUILT_IN),
294
269
  ...Object.keys(followed(async () => ({}) as Messages)),
@@ -309,21 +284,23 @@ export const sessionObject = <
309
284
  ]),
310
285
  );
311
286
  const messages = (views as Record<string, restate.Entry<restate.ViewContext>>).messages;
312
- onClear(name, messages);
313
287
  const page = (typeof messages === 'function' ? messages : messages?.handler) as
314
288
  | ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
315
289
  | undefined;
316
290
  const agent = page === undefined ? {} : followed(page);
317
291
  return withCompanion(
318
- restate.sessionObject({
319
- name,
320
- description,
321
- schema,
322
- handlers: { ...(messages === undefined ? {} : INTERNAL), ...yours },
323
- views: { ...BUILT_IN, ...agent, ...views },
324
- metadata,
325
- options: { ...OPTIONS, ...options },
326
- }),
292
+ isAgent(
293
+ restate.sessionObject({
294
+ name,
295
+ description,
296
+ schema,
297
+ handlers: { ...(messages === undefined ? {} : INTERNAL), ...yours },
298
+ views: { ...BUILT_IN, ...agent, ...views },
299
+ metadata,
300
+ options: { ...OPTIONS, ...options },
301
+ }),
302
+ { background, messages },
303
+ ),
327
304
  );
328
305
  };
329
306
 
@@ -336,7 +313,7 @@ function answering(entry: restate.Entry<restate.SessionContext>): restate.Entry<
336
313
  try {
337
314
  return await handler(ctx, input);
338
315
  } catch (error) {
339
- throw refusal(error) ?? error;
316
+ throw refusalOf(ctx, error) ?? error;
340
317
  }
341
318
  },
342
319
  };
@@ -42,7 +42,6 @@ import type { Plugin } from '@opencode/plugin';
42
42
  import type { StandardSchemaV1 } from '@standard-schema/spec';
43
43
  import {
44
44
  alsoClearing,
45
- AttemptEnded,
46
45
  chatHandler,
47
46
  CHECK_MODEL,
48
47
  checkModelName,
@@ -54,8 +53,6 @@ import {
54
53
  providerOf,
55
54
  refusal,
56
55
  REFUSED,
57
- settleSteering,
58
- type Steerable,
59
56
  stopSignalOf,
60
57
  toolCallEnded,
61
58
  toolCallStarted,
@@ -189,23 +186,17 @@ function toolsPlugin(tools: OpenCodeTool[], fail: (error: unknown) => Promise<ne
189
186
  }
190
187
 
191
188
  /**
192
- * An OpenCode plugin that publishes each tool call as it starts and ends
193
- * (for the clients that follow the conversation), and gives the session the
194
- * messages steered to the turn (`steerable`) at its end: OpenCode's
195
- * steering, which its next step takes.
189
+ * An OpenCode plugin that publishes each tool call as it starts and ends,
190
+ * for the clients that follow the conversation.
196
191
  */
197
- const steeringPlugin = (
198
- ctx: restate.SessionContext,
199
- steerable: Steerable,
200
- fail: (error: unknown) => Promise<never>,
201
- ): Plugin.Plugin => ({
202
- id: 'restate-agents.steering',
192
+ const followPlugin = (ctx: restate.SessionContext, fail: (error: unknown) => Promise<never>): Plugin.Plugin => ({
193
+ id: 'restate-agents.follow',
203
194
  async setup(plugin) {
204
195
  const before = await plugin.tool.hook('execute.before', async () => {
205
196
  await toolCallStarted(ctx).catch(fail);
206
197
  });
207
198
  const after = await plugin.tool.hook('execute.after', async () => {
208
- await toolCallEnded(ctx, steerable).catch(fail);
199
+ await toolCallEnded(ctx).catch(fail);
209
200
  });
210
201
  return async () => {
211
202
  await before.dispose();
@@ -214,12 +205,9 @@ const steeringPlugin = (
214
205
  },
215
206
  });
216
207
 
217
- /** OpenCode's message id of prompt (or steered message) `id`: letters, digits, `_` and `-`. */
208
+ /** OpenCode's message id of prompt `id`: letters, digits, `_` and `-`. */
218
209
  const messageIdOf = (id: string) => `msg_${id.replace(/[^\w-]/g, '_')}`;
219
210
 
220
- /** Whether message `id` is one steered to a turn (see `steer` in object.ts), not a prompt. */
221
- const steered = (id: string) => /_steer_\d+$/.test(id);
222
-
223
211
  /** A part of an assistant message: text, or a tool call (`id`, `name`, and its `state`). */
224
212
  interface Content {
225
213
  type: string;
@@ -294,14 +282,14 @@ async function messagesAfter(host: Host, messageId: string): Promise<Message[] |
294
282
 
295
283
  /**
296
284
  * How the turn of the messages `after` a prompt ended: at an idle marker, or
297
- * where the next prompt, queued while it ran, starts (a message steered to it
298
- * is not one). Running, if neither came yet.
285
+ * where the next prompt, queued while it ran, starts. Running, if neither
286
+ * came yet.
299
287
  */
300
288
  function turnOutcome(after: Message[]): Outcome {
301
289
  let last: Message | undefined;
302
290
  for (const m of after) {
303
291
  if (m.type === 'idle') return ended(last, m.outcome);
304
- if (m.type === 'user' && last !== undefined && !steered(m.id)) return ended(last, 'succeeded');
292
+ if (m.type === 'user' && last !== undefined) return ended(last, 'succeeded');
305
293
  if (m.type === 'assistant') last = m;
306
294
  }
307
295
  return { state: 'running' };
@@ -316,10 +304,10 @@ function ended(last: Message | undefined, how: string | undefined): Outcome {
316
304
 
317
305
  /** The id of the session's latest prompt, if any. */
318
306
  async function lastPrompt(host: Host): Promise<string | undefined> {
319
- const queued = (await inbox(host)).findLast((item) => !steered(item.id));
307
+ const queued = (await inbox(host)).at(-1);
320
308
  if (queued) return queued.id;
321
309
  for await (const page of messagePages(host, 'desc')) {
322
- const user = page.find((m) => m.type === 'user' && !steered(m.id));
310
+ const user = page.find((m) => m.type === 'user');
323
311
  if (user) return user.id;
324
312
  }
325
313
  return undefined;
@@ -331,12 +319,6 @@ const active = async (host: Host) => {
331
319
  return turns[SESSION] !== undefined;
332
320
  };
333
321
 
334
- /** Whether the session has message `messageId`: in its inbox, or in its transcript. */
335
- const inSession = async (host: Host, messageId: string) => {
336
- const given = (m: { id: string }) => m.id === messageId;
337
- return (await inbox(host)).some(given) || (await sessionMessages(host)).some(given);
338
- };
339
-
340
322
  /**
341
323
  * Start the session's queued prompts, if no turn runs them. OpenCode resumes
342
324
  * the turns it claimed when it boots, but a crash between a prompt's queueing
@@ -463,19 +445,10 @@ export const withOpenCode = async <T>(
463
445
  const turn = stopSignalOf(ctx);
464
446
  const onStop = () => void fail(turn!.reason);
465
447
  turn?.addEventListener('abort', onStop, { once: true });
466
- // Messages steered to the turn: OpenCode's steering input (by its message
467
- // id, once), which the session takes at its next step.
468
- const steerable: Steerable = {
469
- steer: async ({ id, text }) => {
470
- const steer = { sessionID: SESSION as never, id: messageIdOf(id) as never, text, delivery: 'steer' as const };
471
- await host.call(host.client.session.prompt(steer));
472
- },
473
- has: (id) => inSession(host, messageIdOf(id)),
474
- };
475
448
  const host = await openOpenCode(database(ctx.db, DATABASE), fence, {
476
449
  plugins: [
477
450
  ...plugins,
478
- steeringPlugin(ctx, steerable, fail),
451
+ followPlugin(ctx, fail),
479
452
  toolsPlugin(
480
453
  tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
481
454
  fail,
@@ -492,10 +465,7 @@ export const withOpenCode = async <T>(
492
465
  await openSession(host, model, workspace);
493
466
  await submit(host, messageId, text);
494
467
  const now = await settled(host, messageId);
495
- if (now.state === 'answered') {
496
- await settleSteering(ctx, steerable);
497
- return now.text;
498
- }
468
+ if (now.state === 'answered') return now.text;
499
469
  if (now.state !== 'failed') throw new Error(`prompt ${id} is not in the session`);
500
470
  // A prompt the cancellation's interrupt ended fails with the cancellation.
501
471
  if (cancelled) throw cancelled;
@@ -510,12 +480,6 @@ export const withOpenCode = async <T>(
510
480
  // The log reads the session through this host, while it is open.
511
481
  const read = () => transcribe(host);
512
482
  return await transcribing(ctx, read, () => Promise.race([interruptOn(host, failure), work({ host, prompt })]));
513
- } catch (error) {
514
- // A turn that ends unanswered (cancelled, refused) counts the messages
515
- // steered to it that the session has, given in an earlier attempt too:
516
- // its close answers only the others. An attempt that ended closes nothing.
517
- if (!(error instanceof AttemptEnded)) await settleSteering(ctx, steerable).catch(() => {});
518
- throw error;
519
483
  } finally {
520
484
  turn?.removeEventListener('abort', onStop);
521
485
  await host.close();
package/src/pi/index.ts CHANGED
@@ -32,7 +32,7 @@
32
32
  // and a coding tool cut off by a crash is not run again (the model is told
33
33
  // it was interrupted).
34
34
  import * as restate from '@restatedev/sessions';
35
- import type { Database } from '@restatedev/sessions';
35
+ import { ScopeKey } from '@restatedev/sessions/internal';
36
36
  import type { Context } from '@earendil-works/chord';
37
37
  import { awaitWithContext, BACKGROUND_CONTEXT, withCancel, withoutAbortSignal } from '@earendil-works/chord/context';
38
38
  import { mkdir } from 'node:fs/promises';
@@ -67,8 +67,6 @@ import {
67
67
  providerOf,
68
68
  refusal,
69
69
  REFUSED,
70
- settleSteering,
71
- type Steerable,
72
70
  stopSignalOf,
73
71
  toolCallEnded,
74
72
  toolCallStarted,
@@ -224,17 +222,6 @@ export const withPi = async <T>(
224
222
  turn?.addEventListener('abort', onStop, { once: true });
225
223
  // The root conversation, once the Harness is open (below).
226
224
  const conversation = () => rootOn(harness, context, model);
227
- // Messages steered to the turn: given as pi-durable's steering input (by
228
- // its id, once), which the run takes once the round's tools are done.
229
- const steerable: Steerable = {
230
- steer: async ({ id, text }) => {
231
- await (await conversation()).submit({ type: 'input', content: text, requestId: id, whenBusy: 'steer' }, context);
232
- },
233
- has: async (id) => {
234
- const root = await conversation();
235
- return (await root.commit((tx) => tx.submissionByRequest(root.id, id), context)) !== undefined;
236
- },
237
- };
238
225
  // A tool call's error: the attempt fails, and the call never returns.
239
226
  const stopped = (error: unknown, task: Context): Promise<never> => {
240
227
  // The turn was cancelled, and the abort ended the call: pi-durable records it.
@@ -253,7 +240,7 @@ export const withPi = async <T>(
253
240
  try {
254
241
  await toolCallStarted(ctx);
255
242
  const result = await t.execute(args, api, task);
256
- await toolCallEnded(ctx, steerable);
243
+ await toolCallEnded(ctx);
257
244
  return result;
258
245
  } catch (error) {
259
246
  return stopped(error, task);
@@ -285,7 +272,6 @@ export const withPi = async <T>(
285
272
  const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
286
273
  const reply = entry?.model?.at(-1);
287
274
  if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
288
- await settleSteering(ctx, steerable);
289
275
  return textOf(reply.content);
290
276
  };
291
277
  // `failure`, once it comes; a cancellation first aborts the conversation's work.
@@ -300,16 +286,10 @@ export const withPi = async <T>(
300
286
 
301
287
  try {
302
288
  // The log reads the root conversation through this Harness, while it is open.
303
- const read = async () => transcribe(ctx.db, await harness.root(context), context);
289
+ const read = async () => transcribe(ctx, await harness.root(context), context);
304
290
  return await transcribing(ctx, read, () =>
305
291
  Promise.race([abortOn(), work({ harness, context, conversation, prompt })]),
306
292
  );
307
- } catch (error) {
308
- // A turn that ends unanswered (cancelled, refused) counts the messages
309
- // steered to it that the conversation has, given in an earlier attempt
310
- // too: its close answers only the others. An attempt that ended closes nothing.
311
- if (!(error instanceof AttemptEnded)) await settleSteering(ctx, steerable).catch(() => {});
312
- throw error;
313
293
  } finally {
314
294
  turn?.removeEventListener('abort', onStop);
315
295
  await harness.close(withoutAbortSignal(context));
@@ -356,12 +336,11 @@ export const messages = () => messagesHandler();
356
336
  * never change, and a new one takes a greater id than any before it (they
357
337
  * are committed one at a time), so each read adds the entries after it.
358
338
  */
359
- const transcripts = new WeakMap<Database, { last?: EntryId; transcript: Transcript }>();
339
+ const TRANSCRIPT = new ScopeKey<{ last?: EntryId; transcript: Transcript }>('the transcript');
360
340
 
361
- /** The root conversation in `db`, `root` of a Harness on it, from pi-durable's entries, as `messages` gives it. */
362
- const transcribe = async (db: Database, root: Conversation, context: Context) => {
363
- const read = transcripts.get(db) ?? { transcript: new Transcript() };
364
- transcripts.set(db, read);
341
+ /** The root conversation in the database of `ctx`, `root` of a Harness on it, from pi-durable's entries, as `messages` gives it. */
342
+ const transcribe = async (ctx: restate.SessionContext, root: Conversation, context: Context) => {
343
+ const read = TRANSCRIPT.of(ctx, () => ({ transcript: new Transcript() }));
365
344
  const { transcript } = read;
366
345
  // From the last entry read (the bound is inclusive), or the first.
367
346
  const query = { order: 'ascending' as const, ...(read.last === undefined ? {} : { minEntryId: read.last }) };