@restatedev/agents 0.5.0 → 0.6.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 (96) hide show
  1. package/README.md +69 -17
  2. package/dist/calls.d.ts +20 -1
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +46 -7
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +11 -11
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +9 -6
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +1 -1
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/common.d.ts +62 -23
  13. package/dist/common.d.ts.map +1 -1
  14. package/dist/common.js +67 -38
  15. package/dist/common.js.map +1 -1
  16. package/dist/{signals.d.ts → companion.d.ts} +106 -43
  17. package/dist/companion.d.ts.map +1 -0
  18. package/dist/companion.js +463 -0
  19. package/dist/companion.js.map +1 -0
  20. package/dist/conversation.d.ts +103 -5
  21. package/dist/conversation.d.ts.map +1 -1
  22. package/dist/conversation.js +295 -75
  23. package/dist/conversation.js.map +1 -1
  24. package/dist/deepseek/index.d.ts +11 -11
  25. package/dist/deepseek/index.d.ts.map +1 -1
  26. package/dist/deepseek/index.js +23 -26
  27. package/dist/deepseek/index.js.map +1 -1
  28. package/dist/index.d.ts +8 -4
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +7 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/langgraph/checkpointer.d.ts +2 -0
  33. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  34. package/dist/langgraph/checkpointer.js +1 -1
  35. package/dist/langgraph/checkpointer.js.map +1 -1
  36. package/dist/langgraph/graph.d.ts.map +1 -1
  37. package/dist/langgraph/graph.js +32 -13
  38. package/dist/langgraph/graph.js.map +1 -1
  39. package/dist/langgraph/index.d.ts +11 -11
  40. package/dist/langgraph/index.d.ts.map +1 -1
  41. package/dist/langgraph/index.js +19 -13
  42. package/dist/langgraph/index.js.map +1 -1
  43. package/dist/langgraph/nodes.d.ts +2 -1
  44. package/dist/langgraph/nodes.d.ts.map +1 -1
  45. package/dist/langgraph/nodes.js +23 -20
  46. package/dist/langgraph/nodes.js.map +1 -1
  47. package/dist/object.d.ts +24 -22
  48. package/dist/object.d.ts.map +1 -1
  49. package/dist/object.js +14 -11
  50. package/dist/object.js.map +1 -1
  51. package/dist/opencode/index.d.ts +11 -11
  52. package/dist/opencode/index.d.ts.map +1 -1
  53. package/dist/opencode/index.js +25 -27
  54. package/dist/opencode/index.js.map +1 -1
  55. package/dist/pi/index.d.ts +11 -11
  56. package/dist/pi/index.d.ts.map +1 -1
  57. package/dist/pi/index.js +16 -17
  58. package/dist/pi/index.js.map +1 -1
  59. package/dist/steering.d.ts +2 -1
  60. package/dist/steering.d.ts.map +1 -1
  61. package/dist/steering.js +2 -2
  62. package/dist/steering.js.map +1 -1
  63. package/dist/tools.d.ts +21 -0
  64. package/dist/tools.d.ts.map +1 -1
  65. package/dist/tools.js +54 -14
  66. package/dist/tools.js.map +1 -1
  67. package/dist/webhook.js +1 -1
  68. package/dist/webhook.js.map +1 -1
  69. package/package.json +3 -3
  70. package/src/calls.ts +52 -11
  71. package/src/claude/README.md +4 -2
  72. package/src/claude/index.ts +9 -7
  73. package/src/client.ts +1 -1
  74. package/src/common.ts +99 -40
  75. package/src/companion.ts +674 -0
  76. package/src/conversation.ts +353 -101
  77. package/src/deepseek/README.md +7 -1
  78. package/src/deepseek/index.ts +22 -24
  79. package/src/index.ts +10 -4
  80. package/src/langgraph/README.md +8 -5
  81. package/src/langgraph/checkpointer.ts +1 -1
  82. package/src/langgraph/graph.ts +30 -16
  83. package/src/langgraph/index.ts +24 -17
  84. package/src/langgraph/nodes.ts +24 -20
  85. package/src/object.ts +43 -40
  86. package/src/opencode/README.md +5 -2
  87. package/src/opencode/index.ts +26 -27
  88. package/src/pi/README.md +6 -1
  89. package/src/pi/index.ts +16 -15
  90. package/src/steering.ts +8 -7
  91. package/src/tools.ts +60 -18
  92. package/src/webhook.ts +1 -1
  93. package/dist/signals.d.ts.map +0 -1
  94. package/dist/signals.js +0 -383
  95. package/dist/signals.js.map +0 -1
  96. package/src/signals.ts +0 -590
package/src/signals.ts DELETED
@@ -1,590 +0,0 @@
1
- // Signals to agents: a virtual object per agent, keyed `<agent>:<key>` (such
2
- // as `assistant:alice`), whose `wait` returns once `resolve` gives the wait
3
- // its value; the message the agent answers; the messages steered to it that
4
- // it has not taken yet (`steer`); and the revision of the agent's
5
- // conversation, which its `watch` waits on.
6
- //
7
- // An agent's own handler cannot wait on an awakeable (it has no journal to
8
- // replay one from), so it calls `wait`, which can: a journaled handler of
9
- // this object, which waits without holding a process.
10
- import type { SessionContext } from '@restatedev/sessions';
11
- import { Link, needing, sdk as restate } from '@restatedev/sessions/internal';
12
- import type { Answering } from './common.ts';
13
- import type { Status } from './object.ts';
14
-
15
- /** An agent's context, as far as its signals need it: any handler's or view's of its object. */
16
- type AgentContext = { readonly key: string; readonly request: { readonly target: { readonly service: string } } };
17
-
18
- /** The key of the signals of agent `service`'s key `key`: `<agent>:<key>`. */
19
- const keyOf = (service: string, key: string) => `${service}:${key}`;
20
-
21
- /** The key of the signals of the agent of `ctx`. */
22
- export const signalsOf = (ctx: AgentContext) => keyOf(ctx.request.target.service, ctx.key);
23
-
24
- /** How an object of @restatedev/agents (`sessionObject()`, every `agent()`) reaches its companion, for one of its keys. */
25
- const COMPANION = new Link<(key: string) => Companion>('restate-agents.companion');
26
-
27
- /**
28
- * An agent's companion, for one of its keys: its `signals` object, which
29
- * knows what the agent is doing (the message it answers, what its tools wait
30
- * for), and how to reach it.
31
- */
32
- export interface Companion {
33
- /** The `signals` object, as a client takes it. */
34
- object: typeof signals;
35
- /** The key of the agent's key there: `<agent>:<key>`. */
36
- key: string;
37
- /** The agent, and its key. */
38
- agent: Agent;
39
- }
40
-
41
- /**
42
- * `definition`, pointing to its companion: what `sessionObject()` returns.
43
- * `serve` serves its `signals` object beside it.
44
- */
45
- export const withCompanion = <D extends { name: string }>(definition: D): D =>
46
- needing(
47
- COMPANION.on(definition, (key) => ({
48
- object: signals,
49
- key: keyOf(definition.name, key),
50
- agent: { service: definition.name, key },
51
- })),
52
- () => [signals],
53
- );
54
-
55
- /**
56
- * The companion of `agent`'s key `key`: for anyone holding an agent (an
57
- * `sessionObject()` or `agent()` of @restatedev/agents) to reach what it is doing.
58
- */
59
- export function companionOf(agent: { name: string }, key: string): Companion {
60
- const companion = COMPANION.of(agent);
61
- if (!companion)
62
- throw new Error(`${agent.name} is not an agent of @restatedev/agents (a sessionObject() or an agent())`);
63
- return companion(key);
64
- }
65
-
66
- /** Whether `agent` is an object of @restatedev/agents, with a companion. */
67
- export const hasCompanion = (agent: object) => COMPANION.of(agent) !== undefined;
68
-
69
- /**
70
- * Deliver `text` to `agent`'s key `key`, from any handler: a message of its
71
- * own (as `chat`), which it answers after the messages before it. It is
72
- * sent, not awaited: `opts` may give it an idempotency key, so that it is
73
- * delivered once.
74
- *
75
- * deliver(ctx, triage, 'ENG-1', 'The issue was closed', { idempotencyKey: delivery });
76
- */
77
- export function deliver(
78
- ctx: Pick<restate.Context, 'genericSend'> | Pick<SessionContext, 'send'>,
79
- agent: { name: string },
80
- key: string,
81
- text: string,
82
- { idempotencyKey }: { idempotencyKey?: string } = {},
83
- ) {
84
- companionOf(agent, key); // an agent of @restatedev/agents, with a `chat` handler
85
- const message = { service: agent.name, handler: 'chat', key, input: text, idempotencyKey };
86
- // A session object's handler, or one of the SDK's.
87
- if ('send' in ctx) ctx.send(message);
88
- else {
89
- ctx.genericSend({
90
- service: agent.name,
91
- method: 'chat',
92
- key,
93
- parameter: text,
94
- inputSerde: restate.serde.json,
95
- idempotencyKey,
96
- });
97
- }
98
- }
99
-
100
- /** A wait for a signal, as `pending` lists it. */
101
- export interface Waiting {
102
- /** The wait's id, which `signal` takes to resolve this wait and no other. */
103
- id: string;
104
- /** The signal it waits for, such as `approval`. */
105
- name: string;
106
- /** What it waits for, as the model said it (such as the refund to approve), if the tool takes an input. */
107
- input?: unknown;
108
- /** When it started, as an ISO date. */
109
- since: string;
110
- }
111
-
112
- /** Which wait a signal resolves, and with what. */
113
- export interface Signal {
114
- /** The wait of this id (from `pending`). */
115
- id?: string;
116
- /** Else the oldest wait for the signal of this name. */
117
- name?: string;
118
- /** Its value: what the wait answers the model with. */
119
- value?: unknown;
120
- /** With a `name` and no one waiting for it, keep the signal for the next wait for it (by default it is dropped). */
121
- keep?: boolean;
122
- }
123
-
124
- /** What `signal` did: the id of the wait it resolved, or null if none waited (and it was dropped, or kept). */
125
- export interface Resolved {
126
- resolved: string | null;
127
- }
128
-
129
- /** The revision of an agent's conversation: each change of what a client reads increases it. */
130
- export interface Notifications {
131
- revision: number;
132
- }
133
-
134
- /** A message steered to the turn being answered (`steer`): its id (the `steer` request's) and its text. */
135
- export interface Steer {
136
- id: string;
137
- text: string;
138
- }
139
-
140
- /**
141
- * What `publish` answers the turn that published: the new revision, and the
142
- * messages steered to the turn being answered that it has not taken yet, if
143
- * any, oldest first.
144
- */
145
- export interface Published extends Notifications {
146
- steering?: Steer[];
147
- }
148
-
149
- /** A message steered to the turn being answered that it has not taken yet, as `status` shows it. */
150
- export interface Steering {
151
- id: string;
152
- /** When it was sent, as an ISO date. */
153
- since: string;
154
- }
155
-
156
- /**
157
- * What the `steer` view answers: the message's id (the request's), and the
158
- * invocation of the turn being answered, which takes the message at its next
159
- * step if it reaches one; null if no turn takes it. Either way the message is
160
- * answered once: in that turn, or else as a turn of its own, in the order it
161
- * was sent.
162
- */
163
- export interface Steered {
164
- id: string;
165
- turn: string | null;
166
- }
167
-
168
- /**
169
- * How many messages a turn takes by `steer`, at most: past them, each is
170
- * answered as a turn of its own. The companion counts each message it holds
171
- * for the turn, taken or not, until the turn ends: so a turn that someone
172
- * steers on and on stays within bounds, and so does what the companion holds
173
- * for it.
174
- */
175
- export const STEERS = 16;
176
-
177
- /** What `watch` waits for: a revision newer than `revision`, for at most `timeoutSeconds` (default 50, at most 60). */
178
- export interface Watch {
179
- revision: number;
180
- timeoutSeconds?: number;
181
- }
182
-
183
- /**
184
- * A turn as its agent starts it, and whether the agent closes it itself once
185
- * its invocation is gone: whether it has the private `settle` handler, which
186
- * the companion sends such a turn. An agent of another SDK (the companion's
187
- * handlers are shared) that does not say so is sent nothing: its next
188
- * message closes such a turn.
189
- */
190
- export interface Started extends Answering {
191
- settles?: boolean;
192
- /**
193
- * Whether the turn takes steered messages at its steps (`steer`). A turn
194
- * that does not say so (of another SDK, or of an agent whose framework
195
- * cannot take them) gets none: each is answered as a turn of its own.
196
- */
197
- steers?: boolean;
198
- }
199
-
200
- /**
201
- * A message steered to the turn `turn` (an invocation id), as the companion
202
- * holds it until the turn ends: with its text until the turn takes it
203
- * (`taken`), and then only as one of the turn's {@link STEERS}.
204
- */
205
- interface Inboxed {
206
- id: string;
207
- since: string;
208
- turn: string;
209
- text?: string;
210
- }
211
-
212
- /** The messages of `inbox` steered to the turn being answered (`answering`) that it has not taken yet, oldest first. */
213
- const waitingIn = (inbox: readonly Inboxed[], answering: Started | null | undefined) =>
214
- answering ? inbox.filter((m) => m.turn === answering.invocationId && m.text !== undefined) : [];
215
-
216
- /** `turn` as `status` shows it: without what only the companion reads. */
217
- const shown = (turn: Started | null | undefined): Answering | null =>
218
- turn ? { invocationId: turn.invocationId, since: turn.since } : null;
219
-
220
- /** An agent: its object's name, and key. */
221
- interface Agent {
222
- service: string;
223
- key: string;
224
- }
225
-
226
- /**
227
- * The message the agent answers; the waits, in the order they started, each
228
- * with its awakeable; the signals kept for the next wait; and the
229
- * conversation's revision, with the `watch`es waiting for a newer one.
230
- */
231
- interface State {
232
- /** The message the agent answers, from its turn's start to its close. */
233
- turn: Started;
234
- waiting: (Waiting & { awakeable: string })[];
235
- kept: Record<string, unknown[]>;
236
- /** The messages steered to the turns not closed yet (the one being answered), taken or not, oldest first. */
237
- inbox: Inboxed[];
238
- revision: number;
239
- watching: { revision: number; awakeable: string }[];
240
- }
241
-
242
- /** Increase the revision, and answer each `watch` waiting for it: the new revision. */
243
- async function publish(ctx: restate.ObjectContext<State>): Promise<Notifications> {
244
- const revision = ((await ctx.get('revision')) ?? 0) + 1;
245
- ctx.set('revision', revision);
246
- for (const { awakeable } of (await ctx.get('watching')) ?? []) ctx.resolveAwakeable(awakeable, { revision });
247
- ctx.clear('watching');
248
- return { revision };
249
- }
250
-
251
- /** Keep `inbox`, or forget it once it is empty. */
252
- const setInbox = (ctx: restate.ObjectContext<State>, inbox: Inboxed[]) =>
253
- inbox.length > 0 ? ctx.set('inbox', inbox) : ctx.clear('inbox');
254
-
255
- /** How long one `awaitTurn` waits for its turn to end, before a new one takes over. */
256
- const WATCH = { hours: 1 };
257
-
258
- /**
259
- * `turn` (an invocation id) is over: forget it, if the agent answers it, and
260
- * its tools' waits, which no one waits for any more, ending their `wait`s (a
261
- * turn that ends as it should has none left, but a killed one leaves them).
262
- * It publishes the change, for the clients that follow the conversation: a
263
- * turn's own close (its last change), or the close of one that never closed
264
- * itself. A close again changes nothing, and publishes nothing.
265
- *
266
- * If the turn's invocation is `gone` and the turn did not close itself, its
267
- * agent is sent `settle`, which closes the turn in its conversation too, if
268
- * it said, as it started the turn, that it `settles`.
269
- *
270
- * The messages steered to the turn are forgotten here: each that it did not
271
- * take was queued as a turn of its own as it was sent (`steer`), and is
272
- * answered as one.
273
- */
274
- async function closed(ctx: restate.ObjectContext<State>, turn: string, gone = false) {
275
- const started = await ctx.get('turn');
276
- const answering = started?.invocationId === turn;
277
- if (answering) {
278
- ctx.clear('turn');
279
- if (gone && started?.settles) {
280
- const at = ctx.key.indexOf(':');
281
- ctx.genericSend({
282
- service: ctx.key.slice(0, at),
283
- method: 'settle',
284
- key: ctx.key.slice(at + 1),
285
- parameter: turn,
286
- inputSerde: restate.serde.json,
287
- });
288
- }
289
- }
290
- const inbox = (await ctx.get('inbox')) ?? [];
291
- const dropped = inbox.some((m) => m.turn === turn);
292
- if (dropped)
293
- setInbox(
294
- ctx,
295
- inbox.filter((m) => m.turn !== turn),
296
- );
297
- const waiting = (await ctx.get('waiting')) ?? [];
298
- // A wait's id starts with the invocation id of the turn whose tool waits.
299
- const ofTurn = (id: string) => id.startsWith(`${turn}:`);
300
- const over = waiting.filter((w) => ofTurn(w.id));
301
- const left = waiting.filter((w) => !ofTurn(w.id));
302
- for (const w of over) ctx.rejectAwakeable(w.awakeable, 'its turn is over');
303
- if (over.length > 0) ctx.set('waiting', left);
304
- if (answering || over.length > 0 || dropped) await publish(ctx);
305
- }
306
-
307
- /** A handler that the agents' own handlers call, which clients cannot (through Restate's ingress). */
308
- const internal = <I, O>(fn: (ctx: restate.ObjectContext<State>, input: I) => Promise<O>) =>
309
- restate.handlers.object.exclusive({ ingressPrivate: true }, fn);
310
-
311
- /**
312
- * The signals of every agent, keyed `<agent>:<key>` ({@link signalsOf}).
313
- * `serve` serves it beside the agents; the handlers marked `@internal` are
314
- * called by the agents' own handlers, and Restate's ingress refuses them.
315
- */
316
- export const signals = restate.object({
317
- name: 'signals',
318
- handlers: {
319
- /** Wait for the signal `name`, as wait `id` (for `input`), and return its value. */
320
- wait: restate.handlers.object.shared(
321
- async (ctx: restate.ObjectSharedContext<State>, wait: { id: string; name: string; input?: unknown }) => {
322
- const { id, promise } = ctx.awakeable<unknown>();
323
- const since = new Date(await ctx.date.now()).toISOString();
324
- ctx.objectSendClient(signals, ctx.key).listen({ ...wait, since, awakeable: id });
325
- try {
326
- return await promise;
327
- } catch (error) {
328
- // The agent's invocation was cancelled: no one waits any more.
329
- if (error instanceof restate.CancelledError) ctx.objectSendClient(signals, ctx.key).forget(wait.id);
330
- throw error;
331
- }
332
- },
333
- ),
334
-
335
- /** Resolve the wait `id`, or else the oldest wait for `name`, with `value`. */
336
- resolve: async (ctx: restate.ObjectContext<State>, { id, name, value = null, keep = false }: Signal) => {
337
- if (id === undefined && name === undefined) throw new restate.TerminalError('a signal needs an id or a name');
338
- const waiting = (await ctx.get('waiting')) ?? [];
339
- const at = waiting.findIndex((w) => (id === undefined ? w.name === name : w.id === id));
340
- if (at < 0) {
341
- if (keep && name !== undefined && id === undefined) {
342
- const kept = (await ctx.get('kept')) ?? {};
343
- ctx.set('kept', { ...kept, [name]: [...(kept[name] ?? []), value] });
344
- }
345
- return { resolved: null } satisfies Resolved;
346
- }
347
- const [wait] = waiting.splice(at, 1);
348
- ctx.resolveAwakeable(wait!.awakeable, value);
349
- ctx.set('waiting', waiting);
350
- await publish(ctx);
351
- return { resolved: wait!.id } satisfies Resolved;
352
- },
353
-
354
- /** The waits, oldest first. */
355
- pending: restate.handlers.object.shared(async (ctx: restate.ObjectSharedContext<State>): Promise<Waiting[]> =>
356
- ((await ctx.get('waiting')) ?? []).map(({ id, name, input, since }) => ({ id, name, input, since })),
357
- ),
358
-
359
- /** @internal A wait: resolved now with a signal kept for it, or else when one comes. */
360
- listen: internal(async (ctx: restate.ObjectContext<State>, wait: Waiting & { awakeable: string }) => {
361
- const kept = (await ctx.get('kept')) ?? {};
362
- const [value, ...rest] = kept[wait.name] ?? [];
363
- if (kept[wait.name]?.length) {
364
- ctx.resolveAwakeable(wait.awakeable, value);
365
- ctx.set('kept', { ...kept, [wait.name]: rest });
366
- return;
367
- }
368
- ctx.set('waiting', [...((await ctx.get('waiting')) ?? []), wait]);
369
- await publish(ctx);
370
- }),
371
-
372
- /**
373
- * @internal The agent's `chat` started answering `turn`: the same
374
- * invocation again (a retry) keeps when it started. A turn before it that
375
- * never closed itself (its invocation was killed) closes now, if its
376
- * `awaitTurn` did not close it yet. `awaitTurn` watches the new turn, so
377
- * that it closes even if no turn comes after it.
378
- */
379
- start: internal(async (ctx: restate.ObjectContext<State>, turn: Started) => {
380
- const before = (await ctx.get('turn'))?.invocationId;
381
- if (before === turn.invocationId) return;
382
- if (before !== undefined) await closed(ctx, before, true);
383
- ctx.set('turn', turn);
384
- ctx.objectSendClient(signals, ctx.key).awaitTurn(turn.invocationId);
385
- }),
386
-
387
- /**
388
- * @internal Wait for `turn` to end, without holding a process, and close
389
- * it if it failed: its waits end, and `status` no longer says the agent
390
- * answers it. A turn that never closed itself failed: it was killed, ran
391
- * out of retries, or was lost. A turn that ends as it should, or is
392
- * cancelled, closed itself already: its `close` is a call it waits for
393
- * before it ends, so this `close` comes second, and changes nothing.
394
- *
395
- * It waits {@link WATCH} at most: a turn still answered then gets a new
396
- * watch, which runs on the deployment of the day, rather than this one
397
- * waiting for weeks on the one it started on (a turn that waits for an
398
- * approval, say). A cancelled watch (an operator's) rejects the race
399
- * itself, before either side's `map`: it closes nothing.
400
- */
401
- awaitTurn: restate.handlers.object.shared(
402
- // It leaves nothing behind once done: a turn has one at a time.
403
- { ingressPrivate: true, journalRetention: 0, idempotencyRetention: 0 },
404
- async (ctx: restate.ObjectSharedContext<State>, turn: string) => {
405
- const ended = await restate.RestatePromise.race([
406
- // `map` gets the turn's failure too: a killed turn's (a TerminalError).
407
- ctx
408
- .invocation(restate.InvocationIdParser.fromString(turn))
409
- .attach()
410
- .map((_answer, failure) => ({ failed: failure !== undefined })),
411
- ctx.sleep(WATCH).map(() => null),
412
- ]);
413
- if (ended?.failed) ctx.objectSendClient(signals, ctx.key).ended(turn);
414
- else if (ended === null && (await ctx.get('turn'))?.invocationId === turn) {
415
- ctx.objectSendClient(signals, ctx.key).awaitTurn(turn);
416
- }
417
- },
418
- ),
419
-
420
- /**
421
- * What the agent does: the message it answers, if any, the waits of its
422
- * tools, and the messages steered to it that it has not taken yet.
423
- */
424
- status: restate.handlers.object.shared(async (ctx: restate.ObjectSharedContext<State>): Promise<Status> => {
425
- const answering = await ctx.get('turn');
426
- const status: Status = {
427
- answering: shown(answering),
428
- waiting: ((await ctx.get('waiting')) ?? []).map(({ id, name, input, since }) => ({ id, name, input, since })),
429
- };
430
- const steering = waitingIn((await ctx.get('inbox')) ?? [], answering).map(({ id, since }) => ({ id, since }));
431
- return steering.length > 0 ? { ...status, steering } : status;
432
- }),
433
-
434
- /**
435
- * The revision, once there is one newer than `revision`, or at the
436
- * timeout (50 s by default, at most 60 s), whichever comes first. It
437
- * waits in Restate, holding no process; a caller that retries it with the
438
- * same idempotency key joins the same wait.
439
- */
440
- watch: restate.handlers.object.shared(
441
- async (
442
- ctx: restate.ObjectSharedContext<State>,
443
- { revision, timeoutSeconds = 50 }: Watch,
444
- ): Promise<Notifications> => {
445
- const { id, promise } = ctx.awakeable<Notifications>();
446
- ctx.objectSendClient(signals, ctx.key).subscribe({ revision, awakeable: id });
447
- const timeout = ctx.sleep({ seconds: Math.min(Math.max(timeoutSeconds, 0), 60) }).map(() => null);
448
- const changed = await restate.RestatePromise.race([promise, timeout]);
449
- if (changed) return changed;
450
- ctx.objectSendClient(signals, ctx.key).unsubscribe(id);
451
- return { revision: (await ctx.get('revision')) ?? 0 };
452
- },
453
- ),
454
-
455
- /** @internal The message `turn` (an invocation id) is answered, or its turn ended otherwise: see {@link closed}. */
456
- close: internal(async (ctx: restate.ObjectContext<State>, turn: string) => closed(ctx, turn)),
457
-
458
- /**
459
- * @internal The invocation of `turn` failed (killed, out of retries): if
460
- * the turn did not close itself, its agent closes it too (see {@link closed}).
461
- */
462
- ended: internal(async (ctx: restate.ObjectContext<State>, turn: string) => closed(ctx, turn, true)),
463
-
464
- /**
465
- * @internal The agent forgot its conversation (`clear`): forget its
466
- * waits, kept signals and steered messages, and publish the change. Each
467
- * steered message was queued as a turn of its own as it was sent, before
468
- * the `clear`.
469
- */
470
- reset: restate.handlers.object.exclusive({ ingressPrivate: true }, async (ctx: restate.ObjectContext<State>) => {
471
- ctx.clear('waiting');
472
- ctx.clear('kept');
473
- ctx.clear('inbox');
474
- await publish(ctx);
475
- }),
476
-
477
- /** @internal Forget wait `id`, whose agent no longer waits. */
478
- forget: internal(async (ctx: restate.ObjectContext<State>, id: string) => {
479
- const waiting = (await ctx.get('waiting')) ?? [];
480
- ctx.set(
481
- 'waiting',
482
- waiting.filter((w) => w.id !== id),
483
- );
484
- await publish(ctx);
485
- }),
486
-
487
- /**
488
- * @internal The conversation changed: increase its revision, and answer
489
- * the `watch`es. It answers the new revision, and the messages steered
490
- * to the turn being answered that it has not taken yet, if any: a turn
491
- * publishes at each tool call's start and end, so it learns of them at
492
- * no cost of its own.
493
- */
494
- publish: restate.handlers.object.exclusive(
495
- { ingressPrivate: true },
496
- async (ctx: restate.ObjectContext<State>): Promise<Published> => {
497
- const published: Published = await publish(ctx);
498
- const inbox = (await ctx.get('inbox')) ?? [];
499
- // Only then is the turn read: a turn that nobody steers costs one read more, of the empty inbox.
500
- if (inbox.some((m) => m.text !== undefined)) {
501
- const steering = waitingIn(inbox, await ctx.get('turn')).map(({ id, text }) => ({ id, text: text! }));
502
- if (steering.length > 0) published.steering = steering;
503
- }
504
- return published;
505
- },
506
- ),
507
-
508
- /**
509
- * @internal Take a message steered to the agent (its `steer` view): for
510
- * the turn being answered, or as a turn of its own.
511
- *
512
- * The message is always sent to the agent's private `steered` handler at
513
- * once, which keeps its place in the key's queue, in order with the
514
- * messages sent after it: once the turn being answered ends, `steered`
515
- * answers the message as a turn of its own, unless that turn took it. A
516
- * turn that takes steered messages (`Started.steers`) also finds it
517
- * here, at its next step, through `publish`, until it takes it (`taken`)
518
- * or ends.
519
- */
520
- steer: internal(async (ctx: restate.ObjectContext<State>, { id, text }: Steer): Promise<Steered> => {
521
- const at = ctx.key.indexOf(':');
522
- ctx.genericSend({
523
- service: ctx.key.slice(0, at),
524
- method: 'steered',
525
- key: ctx.key.slice(at + 1),
526
- parameter: { id, text },
527
- inputSerde: restate.serde.json,
528
- idempotencyKey: `steer:${id}`,
529
- });
530
- const answering = await ctx.get('turn');
531
- if (!answering?.steers) return { id, turn: null };
532
- const turn = answering.invocationId;
533
- const inbox = (await ctx.get('inbox')) ?? [];
534
- if (inbox.some((m) => m.id === id)) return { id, turn };
535
- // Taken or not: the turn has room for so many in all.
536
- if (inbox.filter((m) => m.turn === turn).length >= STEERS) return { id, turn: null };
537
- const since = new Date(await ctx.date.now()).toISOString();
538
- ctx.set('inbox', [...inbox, { id, since, turn, text }]);
539
- await publish(ctx);
540
- return { id, turn };
541
- }),
542
-
543
- /**
544
- * @internal Mark the steered messages `ids` taken, which their turn has
545
- * stored, and publish the change, if any. The turn sends it with the
546
- * transaction that stores them, so it comes once they are stored, and
547
- * once only. Each is kept without its text until the turn ends, as one
548
- * of its {@link STEERS}; one already forgotten (its turn closed first)
549
- * is left so.
550
- */
551
- taken: internal(async (ctx: restate.ObjectContext<State>, ids: string[]) => {
552
- const inbox = (await ctx.get('inbox')) ?? [];
553
- let changed = false;
554
- const marked = inbox.map((m) => {
555
- if (m.text === undefined || !ids.includes(m.id)) return m;
556
- changed = true;
557
- return { id: m.id, since: m.since, turn: m.turn };
558
- });
559
- if (!changed) return;
560
- setInbox(ctx, marked);
561
- await publish(ctx);
562
- }),
563
-
564
- /** The conversation's revision. */
565
- notifications: restate.handlers.object.shared(
566
- async (ctx: restate.ObjectSharedContext<State>): Promise<Notifications> => ({
567
- revision: (await ctx.get('revision')) ?? 0,
568
- }),
569
- ),
570
-
571
- /** @internal Answer `awakeable` once there is a revision newer than `revision`: at once, if there is. */
572
- subscribe: internal(async (ctx: restate.ObjectContext<State>, watch: { revision: number; awakeable: string }) => {
573
- const revision = (await ctx.get('revision')) ?? 0;
574
- if (revision > watch.revision) {
575
- ctx.resolveAwakeable(watch.awakeable, { revision });
576
- return;
577
- }
578
- ctx.set('watching', [...((await ctx.get('watching')) ?? []), watch]);
579
- }),
580
-
581
- /** @internal Forget the `watch` of `awakeable`, which no longer waits. */
582
- unsubscribe: internal(async (ctx: restate.ObjectContext<State>, awakeable: string) => {
583
- const watching = (await ctx.get('watching')) ?? [];
584
- ctx.set(
585
- 'watching',
586
- watching.filter((w) => w.awakeable !== awakeable),
587
- );
588
- }),
589
- },
590
- });