@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/signals.ts CHANGED
@@ -1,30 +1,27 @@
1
1
  // Signals to agents: a virtual object per agent, keyed `<agent>:<key>` (such
2
2
  // as `assistant:alice`), whose `wait` returns once `resolve` gives the wait
3
- // its value; the messages steered to the message an agent answers; and the
4
- // revision of the agent's conversation, which its `watch` waits on.
3
+ // its value; the message the agent answers; and the revision of the agent's
4
+ // conversation, which its `watch` waits on.
5
5
  //
6
6
  // An agent's own handler cannot wait on an awakeable (it has no journal to
7
7
  // replay one from), so it calls `wait`, which can: a journaled handler of
8
8
  // this object, which waits without holding a process.
9
9
  import type { SessionContext } from '@restatedev/sessions';
10
- import { sdk as restate } from '@restatedev/sessions/internal';
10
+ import { Link, needing, sdk as restate } from '@restatedev/sessions/internal';
11
11
  import type { Turn } from './common.ts';
12
12
  import type { Status } from './object.ts';
13
13
 
14
14
  /** An agent's context, as far as its signals need it: any handler's or view's of its object. */
15
15
  type AgentContext = { readonly key: string; readonly request: { readonly target: { readonly service: string } } };
16
16
 
17
- /** The agent of `ctx`: its object's name, and key. */
18
- export const agentOf = (ctx: AgentContext): Agent => ({ service: ctx.request.target.service, key: ctx.key });
19
-
20
17
  /** The key of the signals of agent `service`'s key `key`: `<agent>:<key>`. */
21
18
  const keyOf = (service: string, key: string) => `${service}:${key}`;
22
19
 
23
20
  /** The key of the signals of the agent of `ctx`. */
24
21
  export const signalsOf = (ctx: AgentContext) => keyOf(ctx.request.target.service, ctx.key);
25
22
 
26
- /** Where an object of @restatedev/agents (`sessionObject()`, every `agent()`) points to its companion. */
27
- const COMPANION = Symbol('restate-agents.companion');
23
+ /** How an object of @restatedev/agents (`sessionObject()`, every `agent()`) reaches its companion, for one of its keys. */
24
+ const COMPANION = new Link<(key: string) => Companion>('restate-agents.companion');
28
25
 
29
26
  /**
30
27
  * An agent's companion, for one of its keys: its `signals` object, which
@@ -40,51 +37,63 @@ export interface Companion {
40
37
  agent: Agent;
41
38
  }
42
39
 
43
- /** `definition`, pointing to its companion: what `sessionObject()` returns. */
40
+ /**
41
+ * `definition`, pointing to its companion: what `sessionObject()` returns.
42
+ * `serve` serves its `signals` object beside it.
43
+ */
44
44
  export const withCompanion = <D extends { name: string }>(definition: D): D =>
45
- Object.defineProperty(definition, COMPANION, {
46
- value: (key: string): Companion => ({
45
+ needing(
46
+ COMPANION.on(definition, (key) => ({
47
47
  object: signals,
48
48
  key: keyOf(definition.name, key),
49
49
  agent: { service: definition.name, key },
50
- }),
51
- });
50
+ })),
51
+ () => [signals],
52
+ );
52
53
 
53
54
  /**
54
55
  * The companion of `agent`'s key `key`: for anyone holding an agent (an
55
56
  * `sessionObject()` or `agent()` of @restatedev/agents) to reach what it is doing.
56
57
  */
57
58
  export function companionOf(agent: { name: string }, key: string): Companion {
58
- const companion = (agent as { [COMPANION]?: (key: string) => Companion })[COMPANION];
59
+ const companion = COMPANION.of(agent);
59
60
  if (!companion)
60
61
  throw new Error(`${agent.name} is not an agent of @restatedev/agents (a sessionObject() or an agent())`);
61
62
  return companion(key);
62
63
  }
63
64
 
64
65
  /** Whether `agent` is an object of @restatedev/agents, with a companion. */
65
- export const hasCompanion = (agent: object) => COMPANION in agent;
66
+ export const hasCompanion = (agent: object) => COMPANION.of(agent) !== undefined;
66
67
 
67
68
  /**
68
- * Deliver `text` to `agent`'s key `key`, from any handler: to the message it
69
- * answers, if it answers one, which takes it at its next step (as `steer`);
70
- * else as a message of its own (as `chat`). A turn that ends, or is stopped,
71
- * before it takes it answers it after. It is sent, not awaited: `opts` may
72
- * give it an idempotency key, so that it is delivered once.
69
+ * Deliver `text` to `agent`'s key `key`, from any handler: a message of its
70
+ * own (as `chat`), which it answers after the messages before it. It is
71
+ * sent, not awaited: `opts` may give it an idempotency key, so that it is
72
+ * delivered once.
73
73
  *
74
74
  * deliver(ctx, triage, 'ENG-1', 'The issue was closed', { idempotencyKey: delivery });
75
75
  */
76
76
  export function deliver(
77
- ctx: Pick<restate.Context, 'objectSendClient'> | Pick<SessionContext, 'send'>,
77
+ ctx: Pick<restate.Context, 'genericSend'> | Pick<SessionContext, 'send'>,
78
78
  agent: { name: string },
79
79
  key: string,
80
80
  text: string,
81
- opts: { idempotencyKey?: string } = {},
81
+ { idempotencyKey }: { idempotencyKey?: string } = {},
82
82
  ) {
83
- const { object, key: companion, agent: target } = companionOf(agent, key);
84
- const delivery = { agent: target, text };
83
+ companionOf(agent, key); // an agent of @restatedev/agents, with a `chat` handler
84
+ const message = { service: agent.name, handler: 'chat', key, input: text, idempotencyKey };
85
85
  // A session object's handler, or one of the SDK's.
86
- if ('send' in ctx) ctx.send(object, companion, opts).deliver(delivery);
87
- else ctx.objectSendClient(object, companion).deliver(delivery, restate.rpc.sendOpts(opts));
86
+ if ('send' in ctx) ctx.send(message);
87
+ else {
88
+ ctx.genericSend({
89
+ service: agent.name,
90
+ method: 'chat',
91
+ key,
92
+ parameter: text,
93
+ inputSerde: restate.serde.json,
94
+ idempotencyKey,
95
+ });
96
+ }
88
97
  }
89
98
 
90
99
  /** A wait for a signal, as `pending` lists it. */
@@ -116,24 +125,6 @@ export interface Resolved {
116
125
  resolved: string | null;
117
126
  }
118
127
 
119
- /** A message steered to the message being answered (its turn): its id, `<turn>:steer:<n>`, and its text. */
120
- export interface Steer {
121
- id: string;
122
- text: string;
123
- /** A delivery (`deliver`): a cancelled turn answers it as a message of its own, rather than drop it. */
124
- keep?: boolean;
125
- }
126
-
127
- /**
128
- * What `steer` did: the invocation that answers it, and whether it steers
129
- * the message being answered (or, with none answered, was sent as a message
130
- * of its own).
131
- */
132
- export interface Steered {
133
- invocationId: string;
134
- steered: boolean;
135
- }
136
-
137
128
  /** The revision of an agent's conversation: each change of what a client reads increases it. */
138
129
  export interface Notifications {
139
130
  revision: number;
@@ -151,22 +142,16 @@ interface Agent {
151
142
  key: string;
152
143
  }
153
144
 
154
- /** The turns closed last, newest last: a message steered to one of them is a message of its own. */
155
- const CLOSED = 16;
156
-
157
145
  /**
158
- * The waits, in the order they started, each with its awakeable; the signals
159
- * kept for the next wait; the messages steered to the turn being answered,
160
- * and the turns closed last; and the conversation's revision, with the
161
- * `watch`es waiting for a newer one.
146
+ * The message the agent answers; the waits, in the order they started, each
147
+ * with its awakeable; the signals kept for the next wait; and the
148
+ * conversation's revision, with the `watch`es waiting for a newer one.
162
149
  */
163
150
  interface State {
164
151
  /** The message the agent answers, from its turn's start to its close. */
165
152
  turn: Turn;
166
153
  waiting: (Waiting & { awakeable: string })[];
167
154
  kept: Record<string, unknown[]>;
168
- steering: { turn: string; messages: Steer[] };
169
- closed: string[];
170
155
  revision: number;
171
156
  watching: { revision: number; awakeable: string }[];
172
157
  }
@@ -180,47 +165,28 @@ async function publish(ctx: restate.ObjectContext<State>): Promise<Notifications
180
165
  return { revision };
181
166
  }
182
167
 
183
- /** Send `text` to `agent`'s `chat`, as a message of its own: its invocation's id. */
184
- const send = (ctx: restate.ObjectContext<State>, { service, key }: Agent, text: string) =>
185
- ctx.genericSend({ service, method: 'chat', key, parameter: text, inputSerde: restate.serde.json }).invocationId;
168
+ /** How long one `awaitTurn` waits for its turn to end, before a new one takes over. */
169
+ const WATCH = { hours: 1 };
186
170
 
187
171
  /**
188
- * Steer `turn` (the message `agent` answers, if any) with `text`: queued for
189
- * it to take at its next step, or, if it is over, sent as a message of its own.
172
+ * `turn` (an invocation id) is over: forget it, if the agent answers it, and
173
+ * its tools' waits, which no one waits for any more, ending their `wait`s (a
174
+ * turn that ends as it should has none left, but a killed one leaves them).
175
+ * It publishes the change, for the clients that follow the conversation: a
176
+ * turn's own close (its last change), or the close of one that never closed
177
+ * itself. A close again changes nothing, and publishes nothing.
190
178
  */
191
- async function steered(ctx: restate.ObjectContext<State>, agent: Agent, text: string, keep = false): Promise<Steered> {
192
- const turn = (await ctx.get('turn'))?.invocationId ?? null;
193
- if (turn === null || ((await ctx.get('closed')) ?? []).includes(turn)) {
194
- return { invocationId: await send(ctx, agent, text), steered: false };
195
- }
196
- const steering = await ctx.get('steering');
197
- const messages = steering?.turn === turn ? steering.messages : [];
198
- const id = `${turn}:steer:${messages.length + 1}`;
199
- ctx.set('steering', { turn, messages: [...messages, { id, text, ...(keep ? { keep } : {}) }] });
200
- await publish(ctx);
201
- return { invocationId: turn, steered: true };
202
- }
203
-
204
- /** A turn's close: see `close`. */
205
- interface Close {
206
- agent: Agent;
207
- turn: string;
208
- taken: string[];
209
- cancelled: boolean;
210
- }
211
-
212
- /** Close `turn`, once: see `close`. */
213
- async function closed(ctx: restate.ObjectContext<State>, { agent, turn, taken, cancelled }: Close) {
214
- if ((await ctx.get('turn'))?.invocationId === turn) ctx.clear('turn');
215
- const done = (await ctx.get('closed')) ?? [];
216
- if (done.includes(turn)) return;
217
- ctx.set('closed', [...done, turn].slice(-CLOSED));
218
- const steering = await ctx.get('steering');
219
- if (steering?.turn !== turn) return;
220
- ctx.clear('steering');
221
- for (const { id, text, keep } of steering.messages) {
222
- if (!taken.includes(id) && (keep || !cancelled)) await send(ctx, agent, text);
223
- }
179
+ async function closed(ctx: restate.ObjectContext<State>, turn: string) {
180
+ const answering = (await ctx.get('turn'))?.invocationId === turn;
181
+ if (answering) ctx.clear('turn');
182
+ const waiting = (await ctx.get('waiting')) ?? [];
183
+ // A wait's id starts with the invocation id of the turn whose tool waits.
184
+ const ofTurn = (id: string) => id.startsWith(`${turn}:`);
185
+ const over = waiting.filter((w) => ofTurn(w.id));
186
+ const left = waiting.filter((w) => !ofTurn(w.id));
187
+ for (const w of over) ctx.rejectAwakeable(w.awakeable, 'its turn is over');
188
+ if (over.length > 0) ctx.set('waiting', left);
189
+ if (answering || over.length > 0) await publish(ctx);
224
190
  }
225
191
 
226
192
  /** A handler that the agents' own handlers call, which clients cannot (through Restate's ingress). */
@@ -288,28 +254,54 @@ export const signals = restate.object({
288
254
  await publish(ctx);
289
255
  }),
290
256
 
291
- /**
292
- * @internal Steer the message `agent` answers, if any, with `text`:
293
- * queued for it to take at its next step, or, if none is answered, sent
294
- * as a message of its own.
295
- */
296
- steer: internal(async (ctx: restate.ObjectContext<State>, { agent, text }: { agent: Agent; text: string }) =>
297
- steered(ctx, agent, text),
298
- ),
299
-
300
257
  /**
301
258
  * @internal The agent's `chat` started answering `turn`: the same
302
259
  * invocation again (a retry) keeps when it started. A turn before it that
303
- * never closed (its invocation was killed) closes now, as a cancelled one:
304
- * the deliveries steered to it are answered.
260
+ * never closed itself (its invocation was killed) closes now, if its
261
+ * `awaitTurn` did not close it yet. `awaitTurn` watches the new turn, so
262
+ * that it closes even if no turn comes after it.
305
263
  */
306
- start: internal(async (ctx: restate.ObjectContext<State>, { agent, turn }: { agent: Agent; turn: Turn }) => {
264
+ start: internal(async (ctx: restate.ObjectContext<State>, turn: Turn) => {
307
265
  const before = (await ctx.get('turn'))?.invocationId;
308
266
  if (before === turn.invocationId) return;
309
- if (before !== undefined) await closed(ctx, { agent, turn: before, taken: [], cancelled: true });
267
+ if (before !== undefined) await closed(ctx, before);
310
268
  ctx.set('turn', turn);
269
+ ctx.objectSendClient(signals, ctx.key).awaitTurn(turn.invocationId);
311
270
  }),
312
271
 
272
+ /**
273
+ * @internal Wait for `turn` to end, without holding a process, and close
274
+ * it if it failed: its waits end, and `status` no longer says the agent
275
+ * answers it. A turn that never closed itself failed: it was killed, ran
276
+ * out of retries, or was lost. A turn that ends as it should, or is
277
+ * cancelled, closed itself already: its `close` is a call it waits for
278
+ * before it ends, so this `close` comes second, and changes nothing.
279
+ *
280
+ * It waits {@link WATCH} at most: a turn still answered then gets a new
281
+ * watch, which runs on the deployment of the day, rather than this one
282
+ * waiting for weeks on the one it started on (a turn that waits for an
283
+ * approval, say). A cancelled watch (an operator's) rejects the race
284
+ * itself, before either side's `map`: it closes nothing.
285
+ */
286
+ awaitTurn: restate.handlers.object.shared(
287
+ // It leaves nothing behind once done: a turn has one at a time.
288
+ { ingressPrivate: true, journalRetention: 0, idempotencyRetention: 0 },
289
+ async (ctx: restate.ObjectSharedContext<State>, turn: string) => {
290
+ const ended = await restate.RestatePromise.race([
291
+ // `map` gets the turn's failure too: a killed turn's (a TerminalError).
292
+ ctx
293
+ .invocation(restate.InvocationIdParser.fromString(turn))
294
+ .attach()
295
+ .map((_answer, failure) => ({ failed: failure !== undefined })),
296
+ ctx.sleep(WATCH).map(() => null),
297
+ ]);
298
+ if (ended?.failed) ctx.objectSendClient(signals, ctx.key).close(turn);
299
+ else if (ended === null && (await ctx.get('turn'))?.invocationId === turn) {
300
+ ctx.objectSendClient(signals, ctx.key).awaitTurn(turn);
301
+ }
302
+ },
303
+ ),
304
+
313
305
  /** What the agent does: the message it answers, if any, and the waits of its tools. */
314
306
  status: restate.handlers.object.shared(async (ctx: restate.ObjectSharedContext<State>): Promise<Status> => ({
315
307
  answering: (await ctx.get('turn')) ?? null,
@@ -337,40 +329,16 @@ export const signals = restate.object({
337
329
  },
338
330
  ),
339
331
 
340
- /**
341
- * @internal Deliver `text` to `agent` (a webhook's delivery, say): steered
342
- * to the message it answers, if any, which takes it at its next step;
343
- * else, or once that turn is over, as a message of its own. Unlike a
344
- * steer, a cancelled turn does not drop it: it is answered after.
345
- */
346
- deliver: internal(async (ctx: restate.ObjectContext<State>, { agent, text }: { agent: Agent; text: string }) =>
347
- steered(ctx, agent, text, true),
348
- ),
349
-
350
- /** @internal The messages steered to `turn`, in order. */
351
- steering: restate.handlers.object.shared(
352
- { ingressPrivate: true },
353
- async (ctx: restate.ObjectSharedContext<State>, turn: string) => {
354
- const steering = await ctx.get('steering');
355
- return steering?.turn === turn ? steering.messages : [];
356
- },
357
- ),
358
-
359
- /**
360
- * @internal `turn` is over: each message steered to it that it did not
361
- * take (not in `taken`) is sent as a message of its own, unless the turn
362
- * was cancelled (but for a delivery); later ones are, too.
363
- */
332
+ /** @internal The message `turn` (an invocation id) is answered, or its turn ended otherwise: see {@link closed}. */
364
333
  close: internal(closed),
365
334
 
366
335
  /**
367
336
  * @internal The agent forgot its conversation (`clear`): forget its
368
- * waits, kept signals and steered messages, and publish the change.
337
+ * waits and kept signals, and publish the change.
369
338
  */
370
339
  reset: restate.handlers.object.exclusive({ ingressPrivate: true }, async (ctx: restate.ObjectContext<State>) => {
371
340
  ctx.clear('waiting');
372
341
  ctx.clear('kept');
373
- ctx.clear('steering');
374
342
  await publish(ctx);
375
343
  }),
376
344
 
@@ -387,16 +355,6 @@ export const signals = restate.object({
387
355
  /** @internal The conversation changed: increase its revision, and answer the `watch`es. */
388
356
  publish: restate.handlers.object.exclusive({ ingressPrivate: true }, publish),
389
357
 
390
- /**
391
- * @internal The turn `turn` made progress (a tool call ended): publish
392
- * it, and answer the messages steered to the turn.
393
- */
394
- progress: internal(async (ctx: restate.ObjectContext<State>, turn: string) => {
395
- await publish(ctx);
396
- const steering = await ctx.get('steering');
397
- return steering?.turn === turn ? steering.messages : [];
398
- }),
399
-
400
358
  /** The conversation's revision. */
401
359
  notifications: restate.handlers.object.shared(
402
360
  async (ctx: restate.ObjectSharedContext<State>): Promise<Notifications> => ({
package/src/webhook.ts CHANGED
@@ -103,10 +103,8 @@ const parsed = (body: Uint8Array): WebhookEvent => {
103
103
  /**
104
104
  * A webhook into agents: a service `name`, whose `webhook` handler checks a
105
105
  * delivery's signature, and delivers it to each agent of `route`, keyed by
106
- * `key`, as a {@link webhookMessage}, through the agent's `signals`: to the
107
- * message the agent answers, if any, which takes it at its next step (as
108
- * `steer`), or else as a message of its own (as `chat`). A turn that ends,
109
- * or is stopped, before it takes it answers it after. It answers once the
106
+ * `key`, as a {@link webhookMessage}: a message of its own (as `chat`),
107
+ * which the agent answers after the messages before it. It answers once the
110
108
  * deliveries are sent, not answered: a system that waits seconds for an
111
109
  * answer (Linear, GitHub) gets one at once. What it is (its routes, auth and
112
110
  * idempotency) is in the handler's metadata, which the admin API shows.