@restatedev/agents 0.11.1 → 0.12.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 (218) hide show
  1. package/README.md +189 -808
  2. package/dist/pi/factory.d.ts +73 -0
  3. package/dist/pi/factory.d.ts.map +1 -0
  4. package/dist/pi/factory.js +145 -0
  5. package/dist/pi/factory.js.map +1 -0
  6. package/dist/pi/index.d.ts +5 -129
  7. package/dist/pi/index.d.ts.map +1 -1
  8. package/dist/pi/index.js +31 -571
  9. package/dist/pi/index.js.map +1 -1
  10. package/dist/pi/keepalive.d.ts +3 -16
  11. package/dist/pi/keepalive.d.ts.map +1 -1
  12. package/dist/pi/keepalive.js +38 -41
  13. package/dist/pi/keepalive.js.map +1 -1
  14. package/dist/pi/left.d.ts +16 -0
  15. package/dist/pi/left.d.ts.map +1 -0
  16. package/dist/pi/left.js +23 -0
  17. package/dist/pi/left.js.map +1 -0
  18. package/dist/pi/storage.d.ts +19 -76
  19. package/dist/pi/storage.d.ts.map +1 -1
  20. package/dist/pi/storage.js +50 -368
  21. package/dist/pi/storage.js.map +1 -1
  22. package/dist/pi/tools.d.ts +12 -0
  23. package/dist/pi/tools.d.ts.map +1 -0
  24. package/dist/pi/tools.js +70 -0
  25. package/dist/pi/tools.js.map +1 -0
  26. package/package.json +11 -254
  27. package/src/pi/factory.ts +231 -0
  28. package/src/pi/index.ts +31 -759
  29. package/src/pi/keepalive.ts +46 -56
  30. package/src/pi/left.ts +52 -0
  31. package/src/pi/storage.ts +75 -409
  32. package/src/pi/tools.ts +78 -0
  33. package/dist/agentlib/agent.d.ts +0 -32
  34. package/dist/agentlib/agent.d.ts.map +0 -1
  35. package/dist/agentlib/agent.js +0 -174
  36. package/dist/agentlib/agent.js.map +0 -1
  37. package/dist/agentlib/index.d.ts +0 -5
  38. package/dist/agentlib/index.d.ts.map +0 -1
  39. package/dist/agentlib/index.js +0 -15
  40. package/dist/agentlib/index.js.map +0 -1
  41. package/dist/agentlib/messages.d.ts +0 -39
  42. package/dist/agentlib/messages.d.ts.map +0 -1
  43. package/dist/agentlib/messages.js +0 -177
  44. package/dist/agentlib/messages.js.map +0 -1
  45. package/dist/agentlib/model.d.ts +0 -31
  46. package/dist/agentlib/model.d.ts.map +0 -1
  47. package/dist/agentlib/model.js +0 -140
  48. package/dist/agentlib/model.js.map +0 -1
  49. package/dist/agentlib/options.d.ts +0 -58
  50. package/dist/agentlib/options.d.ts.map +0 -1
  51. package/dist/agentlib/options.js +0 -2
  52. package/dist/agentlib/options.js.map +0 -1
  53. package/dist/agentlib/runtime.d.ts +0 -37
  54. package/dist/agentlib/runtime.d.ts.map +0 -1
  55. package/dist/agentlib/runtime.js +0 -216
  56. package/dist/agentlib/runtime.js.map +0 -1
  57. package/dist/agentlib/state.d.ts +0 -114
  58. package/dist/agentlib/state.d.ts.map +0 -1
  59. package/dist/agentlib/state.js +0 -52
  60. package/dist/agentlib/state.js.map +0 -1
  61. package/dist/agentlib/steering.d.ts +0 -23
  62. package/dist/agentlib/steering.d.ts.map +0 -1
  63. package/dist/agentlib/steering.js +0 -48
  64. package/dist/agentlib/steering.js.map +0 -1
  65. package/dist/agentlib/tools.d.ts +0 -33
  66. package/dist/agentlib/tools.d.ts.map +0 -1
  67. package/dist/agentlib/tools.js +0 -245
  68. package/dist/agentlib/tools.js.map +0 -1
  69. package/dist/agentlib/turn.d.ts +0 -82
  70. package/dist/agentlib/turn.d.ts.map +0 -1
  71. package/dist/agentlib/turn.js +0 -253
  72. package/dist/agentlib/turn.js.map +0 -1
  73. package/dist/calls.d.ts +0 -90
  74. package/dist/calls.d.ts.map +0 -1
  75. package/dist/calls.js +0 -235
  76. package/dist/calls.js.map +0 -1
  77. package/dist/claude/index.d.ts +0 -106
  78. package/dist/claude/index.d.ts.map +0 -1
  79. package/dist/claude/index.js +0 -386
  80. package/dist/claude/index.js.map +0 -1
  81. package/dist/client.d.ts +0 -90
  82. package/dist/client.d.ts.map +0 -1
  83. package/dist/client.js +0 -88
  84. package/dist/client.js.map +0 -1
  85. package/dist/common.d.ts +0 -410
  86. package/dist/common.d.ts.map +0 -1
  87. package/dist/common.js +0 -563
  88. package/dist/common.js.map +0 -1
  89. package/dist/companion.d.ts +0 -286
  90. package/dist/companion.d.ts.map +0 -1
  91. package/dist/companion.js +0 -463
  92. package/dist/companion.js.map +0 -1
  93. package/dist/conversation.d.ts +0 -576
  94. package/dist/conversation.d.ts.map +0 -1
  95. package/dist/conversation.js +0 -1476
  96. package/dist/conversation.js.map +0 -1
  97. package/dist/deepseek/barriers.d.ts +0 -11
  98. package/dist/deepseek/barriers.d.ts.map +0 -1
  99. package/dist/deepseek/barriers.js +0 -36
  100. package/dist/deepseek/barriers.js.map +0 -1
  101. package/dist/deepseek/index.d.ts +0 -97
  102. package/dist/deepseek/index.d.ts.map +0 -1
  103. package/dist/deepseek/index.js +0 -603
  104. package/dist/deepseek/index.js.map +0 -1
  105. package/dist/deepseek/persistence.d.ts +0 -83
  106. package/dist/deepseek/persistence.d.ts.map +0 -1
  107. package/dist/deepseek/persistence.js +0 -262
  108. package/dist/deepseek/persistence.js.map +0 -1
  109. package/dist/index.d.ts +0 -14
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -17
  112. package/dist/index.js.map +0 -1
  113. package/dist/langgraph/checkpointer.d.ts +0 -52
  114. package/dist/langgraph/checkpointer.d.ts.map +0 -1
  115. package/dist/langgraph/checkpointer.js +0 -477
  116. package/dist/langgraph/checkpointer.js.map +0 -1
  117. package/dist/langgraph/context.d.ts +0 -10
  118. package/dist/langgraph/context.d.ts.map +0 -1
  119. package/dist/langgraph/context.js +0 -21
  120. package/dist/langgraph/context.js.map +0 -1
  121. package/dist/langgraph/errors.d.ts +0 -16
  122. package/dist/langgraph/errors.d.ts.map +0 -1
  123. package/dist/langgraph/errors.js +0 -30
  124. package/dist/langgraph/errors.js.map +0 -1
  125. package/dist/langgraph/graph.d.ts +0 -25
  126. package/dist/langgraph/graph.d.ts.map +0 -1
  127. package/dist/langgraph/graph.js +0 -378
  128. package/dist/langgraph/graph.js.map +0 -1
  129. package/dist/langgraph/index.d.ts +0 -119
  130. package/dist/langgraph/index.d.ts.map +0 -1
  131. package/dist/langgraph/index.js +0 -325
  132. package/dist/langgraph/index.js.map +0 -1
  133. package/dist/langgraph/keepalive.d.ts +0 -16
  134. package/dist/langgraph/keepalive.d.ts.map +0 -1
  135. package/dist/langgraph/keepalive.js +0 -51
  136. package/dist/langgraph/keepalive.js.map +0 -1
  137. package/dist/langgraph/nodes.d.ts +0 -71
  138. package/dist/langgraph/nodes.d.ts.map +0 -1
  139. package/dist/langgraph/nodes.js +0 -148
  140. package/dist/langgraph/nodes.js.map +0 -1
  141. package/dist/messages.d.ts +0 -18
  142. package/dist/messages.d.ts.map +0 -1
  143. package/dist/messages.js +0 -182
  144. package/dist/messages.js.map +0 -1
  145. package/dist/object.d.ts +0 -213
  146. package/dist/object.d.ts.map +0 -1
  147. package/dist/object.js +0 -309
  148. package/dist/object.js.map +0 -1
  149. package/dist/opencode/db.d.ts +0 -81
  150. package/dist/opencode/db.d.ts.map +0 -1
  151. package/dist/opencode/db.js +0 -249
  152. package/dist/opencode/db.js.map +0 -1
  153. package/dist/opencode/index.d.ts +0 -184
  154. package/dist/opencode/index.d.ts.map +0 -1
  155. package/dist/opencode/index.js +0 -1079
  156. package/dist/opencode/index.js.map +0 -1
  157. package/dist/output.d.ts +0 -25
  158. package/dist/output.d.ts.map +0 -1
  159. package/dist/output.js +0 -99
  160. package/dist/output.js.map +0 -1
  161. package/dist/pi/commits.d.ts +0 -6
  162. package/dist/pi/commits.d.ts.map +0 -1
  163. package/dist/pi/commits.js +0 -3
  164. package/dist/pi/commits.js.map +0 -1
  165. package/dist/steering.d.ts +0 -32
  166. package/dist/steering.d.ts.map +0 -1
  167. package/dist/steering.js +0 -45
  168. package/dist/steering.js.map +0 -1
  169. package/dist/tools.d.ts +0 -267
  170. package/dist/tools.d.ts.map +0 -1
  171. package/dist/tools.js +0 -305
  172. package/dist/tools.js.map +0 -1
  173. package/dist/webhook.d.ts +0 -71
  174. package/dist/webhook.d.ts.map +0 -1
  175. package/dist/webhook.js +0 -102
  176. package/dist/webhook.js.map +0 -1
  177. package/src/agentlib/README.md +0 -229
  178. package/src/agentlib/agent.ts +0 -216
  179. package/src/agentlib/index.ts +0 -16
  180. package/src/agentlib/messages.ts +0 -207
  181. package/src/agentlib/model.ts +0 -156
  182. package/src/agentlib/options.ts +0 -62
  183. package/src/agentlib/runtime.ts +0 -252
  184. package/src/agentlib/state.ts +0 -93
  185. package/src/agentlib/steering.ts +0 -53
  186. package/src/agentlib/tools.ts +0 -355
  187. package/src/agentlib/turn.ts +0 -302
  188. package/src/calls.ts +0 -330
  189. package/src/claude/README.md +0 -107
  190. package/src/claude/index.ts +0 -487
  191. package/src/client.ts +0 -187
  192. package/src/common.ts +0 -766
  193. package/src/companion.ts +0 -675
  194. package/src/conversation.ts +0 -1799
  195. package/src/deepseek/README.md +0 -202
  196. package/src/deepseek/barriers.ts +0 -63
  197. package/src/deepseek/index.ts +0 -740
  198. package/src/deepseek/persistence.ts +0 -337
  199. package/src/index.ts +0 -41
  200. package/src/langgraph/README.md +0 -199
  201. package/src/langgraph/checkpointer.ts +0 -614
  202. package/src/langgraph/context.ts +0 -27
  203. package/src/langgraph/errors.ts +0 -26
  204. package/src/langgraph/graph.ts +0 -422
  205. package/src/langgraph/index.ts +0 -500
  206. package/src/langgraph/keepalive.ts +0 -58
  207. package/src/langgraph/nodes.ts +0 -247
  208. package/src/messages.ts +0 -244
  209. package/src/object.ts +0 -454
  210. package/src/opencode/README.md +0 -249
  211. package/src/opencode/db.ts +0 -387
  212. package/src/opencode/index.ts +0 -1339
  213. package/src/output.ts +0 -116
  214. package/src/pi/README.md +0 -174
  215. package/src/pi/commits.ts +0 -7
  216. package/src/steering.ts +0 -68
  217. package/src/tools.ts +0 -515
  218. package/src/webhook.ts +0 -161
package/src/object.ts DELETED
@@ -1,454 +0,0 @@
1
- // Virtual objects set up for SQL and agents.
2
- import * as restate from '@restatedev/sessions';
3
- import { reset } from '@restatedev/sessions/internal';
4
- import {
5
- type AgentContext,
6
- type AgentViewContext,
7
- type Answering,
8
- BUDGET,
9
- type Chat,
10
- chatOf,
11
- type Steers,
12
- chatTurn,
13
- checkWindow,
14
- isAgent,
15
- ITEMS,
16
- messageSerde,
17
- type Messages,
18
- type MessagesRequest,
19
- publish,
20
- refusalOf,
21
- type Summarize,
22
- WINDOW,
23
- type Window,
24
- } from './common.ts';
25
- import { compact, type Items, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.ts';
26
- import {
27
- companionAt,
28
- type Notifications,
29
- type Resolved,
30
- type Signal,
31
- type Steer,
32
- type Steered,
33
- type Steering,
34
- withCompanion,
35
- type Waiting,
36
- type Watch,
37
- } from './companion.ts';
38
-
39
- /**
40
- * The options of every object here, beside a session object's: retries for
41
- * weeks, since each attempt resumes from the database: soon after a crash,
42
- * then twice as long each time, up to 10 seconds apart (a provider's rate
43
- * limit, say, is not asked again twice a second).
44
- */
45
- const OPTIONS = {
46
- retryPolicy: { initialInterval: 50, exponentiationFactor: 2, maxInterval: 10_000, maxAttempts: 100_000 },
47
- } satisfies restate.ObjectOptions;
48
-
49
- /** What an object is doing: the message it answers, if any, and what its tools wait for. */
50
- export interface Status {
51
- /** The message being answered (by a `chat` handler), or null. */
52
- answering: Answering | null;
53
- /** The waits of its tools, oldest first (see `pending`). */
54
- waiting: Waiting[];
55
- /** The messages steered to the message being answered that it has not taken yet, oldest first; absent if none. */
56
- steering?: Steering[];
57
- }
58
-
59
- /** What `stop` did: the invocation of the message it stopped, or null if none was answered. */
60
- export interface Stopped {
61
- stopped: string | null;
62
- }
63
-
64
- /**
65
- * A call of the companion of the object of `ctx` (its own, at its key); with
66
- * `step`, a change, keyed by the request and `step`: a restarted view joins
67
- * the same call. A read has no key: asked again, it answers again, and
68
- * Restate keeps nothing of it.
69
- */
70
- const companion = (ctx: AgentViewContext, step?: string) =>
71
- ctx.rpc(companionAt(ctx), ctx.key, step === undefined ? {} : { idempotencyKey: `${ctx.request.id}:${step}` });
72
-
73
- /**
74
- * Cancel the invocation of the message being answered, if any, and say
75
- * which. The companion's `status` says which, with a key of the request and
76
- * `step`: a restarted view gets the same answer, and cancels the same
77
- * invocation again (which does nothing), not the message that started once
78
- * it was cancelled.
79
- */
80
- async function stopped(ctx: AgentViewContext, step: string): Promise<Stopped> {
81
- const turn = (await companion(ctx, step).status()).answering;
82
- if (turn) ctx.cancel(turn.invocationId);
83
- return { stopped: turn?.invocationId ?? null };
84
- }
85
-
86
- /**
87
- * Views that wait on the companion (`watch`, `sync`, up to a minute) or on
88
- * the object (`clear`): Restate
89
- * suspends one that waits past its inactivity timeout, which restarts it,
90
- * so it is longer than the wait.
91
- */
92
- const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOptions;
93
-
94
- /**
95
- * The views every object here has, beside its own: `signal`, which resolves
96
- * a wait of the object's tools (see `signal` in tools.ts), `pending`, the
97
- * waits, `status`, what the object is doing, `stop`, which stops the message
98
- * it answers, and `notifications` and `watch`, the revision of its
99
- * conversation, and a wait for a newer one (an agent's
100
- * has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
101
- * companion (its own `<name>.prebuilt.restate`, at the same key), which
102
- * knows what the object does: they run while the object's handler works.
103
- * They are the only way a client reaches the companion, whose handlers
104
- * Restate's ingress refuses.
105
- */
106
- const BUILT_IN = {
107
- signal: async (ctx: AgentViewContext, signal: Signal): Promise<Resolved> => companion(ctx, 'signal').resolve(signal),
108
- pending: async (ctx: AgentViewContext): Promise<Waiting[]> => companion(ctx).pending(),
109
- status: async (ctx: AgentViewContext): Promise<Status> => companion(ctx).status(),
110
- /** Cancel the invocation of the message being answered (`status`'s), as Restate's admin API cancels one. */
111
- stop: async (ctx: AgentViewContext): Promise<Stopped> => stopped(ctx, 'stop'),
112
- /** The revision of the conversation: each change of what `messages` and `status` give increases it. */
113
- notifications: async (ctx: AgentViewContext): Promise<Notifications> => companion(ctx).notifications(),
114
- /**
115
- * The revision, once there is one newer than `revision`, or at the timeout (50 s by
116
- * default, at most 60 s), whichever comes first: a client then reads what
117
- * changed. It waits in Restate, holding no process; a client that retries
118
- * it with the same idempotency key joins the same wait.
119
- */
120
- watch: {
121
- ...WAITS,
122
- handler: async (ctx: AgentViewContext, watch: Watch): Promise<Notifications> =>
123
- companion(ctx, 'watch').watch(watch),
124
- },
125
- };
126
-
127
- /**
128
- * The views that agents (an object with a `messages` view) have beside
129
- * those of every object: `clear`, which forgets the conversation; `steer`,
130
- * which sends a message while a turn is answered (for an agent whose `chat`
131
- * a framework's `chat()` made: `chatHandler`'s, which answers it as a turn
132
- * of its own if no turn takes it); and `sync`, the conversation since
133
- * `cursor` (by default, all of it), what the agent is doing, and the
134
- * revision, in one request; with `revision`, once there is a newer one, or
135
- * at the timeout. A client follows the conversation by sending each
136
- * answer's `revision` and `cursor` back, at once while it has `more`.
137
- */
138
- const followed = (steerable: boolean) => ({
139
- /**
140
- * Forget the conversation: stop the message being answered (as `stop`),
141
- * then empty the key's database, and what its companion holds (waits and
142
- * kept signals). The conversation's ids and cursors go on (see
143
- * conversation.ts), so a follower reads on, and drops the messages before `first`.
144
- * A message sent before it is answered first, then forgotten too; one sent
145
- * after starts anew.
146
- */
147
- clear: {
148
- // `erase` waits for the messages sent before it.
149
- ...WAITS,
150
- handler: async (ctx: AgentViewContext): Promise<Stopped> => {
151
- const stop = await stopped(ctx, 'clear');
152
- await ctx.rpc({
153
- service: ctx.request.target.service,
154
- key: ctx.key,
155
- handler: 'erase',
156
- idempotencyKey: `${ctx.request.id}:erase`,
157
- });
158
- return stop;
159
- },
160
- },
161
- /**
162
- * Send a message to the agent while it answers another: the turn being
163
- * answered takes it at its next step (once the model's tool calls have
164
- * their results), if its framework takes steered messages and it reaches
165
- * one; otherwise the message is answered as a turn of its own, after the
166
- * messages before it, in the order it was sent. With no message being
167
- * answered, it starts a turn. Either way it is answered once: send it with
168
- * an idempotency key, so that a retried request is the same message. It
169
- * takes the message as plain text or as a JSON string, as `chat` does.
170
- */
171
- steer: {
172
- input: messageSerde,
173
- accept: '*/*',
174
- handler: async (ctx: AgentViewContext, text: string): Promise<Steered> => {
175
- if (!steerable) {
176
- throw new restate.TerminalError(
177
- `${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`,
178
- { errorCode: 400 },
179
- );
180
- }
181
- return companion(ctx, 'steer').steer({ id: ctx.request.id, text });
182
- },
183
- },
184
- sync: {
185
- ...WAITS,
186
- handler: async (
187
- ctx: AgentViewContext,
188
- { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view }: SyncRequest = {},
189
- ): Promise<Synced> => {
190
- if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
191
- // The revision first: a change after it shows in the next sync. Then
192
- // what the object does, and its conversation, in an invocation of its
193
- // own, which starts after the revision: a view reads the database as
194
- // committed when it started, and this one started before the revision
195
- // (by the whole wait, when it waited). So the page has every change the
196
- // revision counts.
197
- const now = await companion(ctx).notifications();
198
- const status = await companion(ctx).status();
199
- const request: MessagesRequest = { cursor, limit, ...(view ? { view } : {}) };
200
- const page = (await ctx.rpc({
201
- service: ctx.request.target.service,
202
- key: ctx.key,
203
- handler: 'messages',
204
- input: request,
205
- })) as Messages;
206
- return { revision: now.revision, status, ...page };
207
- },
208
- },
209
- });
210
-
211
- /** The views of every agent: {@link followed}'s. */
212
- const FOLLOWED = followed(false);
213
-
214
- /**
215
- * The agents' handlers that only their own views call (Restate's ingress
216
- * refuses them), and their types leave out: `erase`, `clear`'s work, once
217
- * the handlers before it are done. It empties the key's database and what its
218
- * companion holds, and the conversation's ids and cursors go on where they got to
219
- * (conversation.ts).
220
- */
221
- const internal = (items: Items<unknown> | undefined) => ({
222
- erase: {
223
- ingressPrivate: true,
224
- handler: async (ctx: AgentContext) => {
225
- // Read first, which also makes the reset apply the conversation's schema again.
226
- await SCHEMA.ensure(ctx.db);
227
- const start = await nextStart(ctx.db);
228
- // A framework's database of its own first: the conversation's rows say what is left.
229
- await items?.erase?.(ctx);
230
- await ctx.db.transaction(async (tx) => {
231
- await reset(tx);
232
- await restart(tx, start);
233
- });
234
- await ctx.rpc(companionAt(ctx), ctx.key, { idempotencyKey: `${ctx.request.id}:reset` }).reset();
235
- },
236
- },
237
- /**
238
- * Close the latest turn, unanswered, if invocation `invocationId` ran it
239
- * and is gone: the companion sends this once it finds the turn's
240
- * invocation ended without answering (killed, say), so that the
241
- * conversation shows the turn closed before the next message. Whether it
242
- * closed it.
243
- */
244
- settle: {
245
- ingressPrivate: true,
246
- handler: async (ctx: AgentContext, invocationId: string) => {
247
- if (!items || !(await settle(ctx, items, invocationId))) return false;
248
- // The companion published as it closed the turn, before this stored how it ended: publish that too.
249
- await publish(ctx);
250
- return true;
251
- },
252
- },
253
- /** Summarize the earliest turns, past the agent's budget. Whether it did. */
254
- compact: {
255
- ingressPrivate: true,
256
- handler: async (ctx: AgentContext) => (items ? compact(ctx, items) : false),
257
- },
258
- });
259
-
260
- /**
261
- * The private `steered` of an agent whose `chat` is `chat` (`chatHandler`'s):
262
- * it answers a message sent to `steer` as a turn of its own, with that
263
- * `chat`, unless the turn it was sent to took it. The companion sends it as
264
- * the message is sent, so that it keeps its place in the key's queue: it runs
265
- * once the messages before it are answered.
266
- */
267
- const steeredOf = ({ answer, steers }: { answer: Chat; steers: Steers }) => ({
268
- ingressPrivate: true,
269
- explicitCancellation: true,
270
- handler: async (ctx: AgentContext, { id, text }: Steer) => {
271
- if (await steerStored(ctx.db, id)) return;
272
- await chatTurn(ctx, text, answer, steers);
273
- },
274
- });
275
-
276
- /**
277
- * What `sync` reads: what is new or changed since `cursor` (default 0, all
278
- * of it), at most `limit` messages (default 100); once the revision is past
279
- * `revision`, if given, or at `timeoutSeconds` (default 50, at most 60).
280
- */
281
- export interface SyncRequest {
282
- /** The messages' view: `full` (the default), or `summary` (see `MessagesRequest`). */
283
- view?: MessagesRequest['view'];
284
- cursor?: number;
285
- revision?: number;
286
- timeoutSeconds?: number;
287
- limit?: number;
288
- }
289
-
290
- /** What `sync` answers: the messages since the cursor, as `messages` gives them, the status and the revision. */
291
- export interface Synced extends Messages {
292
- revision: number;
293
- status: Status;
294
- }
295
-
296
- /** An object's (or agent's) name, its description, and the tables of your own in its database, if any (see `sessionObject`). */
297
- export interface Definition<P extends string> {
298
- name: P;
299
- /** What it is: for the UI, and for the model of a parent that hands it tasks (`subagent`). */
300
- description?: string;
301
- schema?: readonly restate.Step[];
302
- /**
303
- * Whether it works unwatched, such as a subagent: its turn publishes to its
304
- * companion only at its end, not at each step, so a client that follows it
305
- * sees each turn once it ended. `messages` has every turn as before.
306
- */
307
- background?: boolean;
308
- /**
309
- * For an agent on the conversation of turns: how many of the latest
310
- * answered turns its model sees whole, with their tool calls and results
311
- * (default 1), or `'all'`.
312
- */
313
- window?: Window;
314
- /** For an agent on the conversation of turns: how many tokens of the turns before the window its model sees (default 32 000). */
315
- budget?: number;
316
- /**
317
- * For an agent on the conversation of turns: how it summarizes the turns
318
- * before the window once they outgrow `budget`, in an invocation of its
319
- * own (`compact`), after the answer. Without, they are only left out.
320
- */
321
- summarize?: Summarize;
322
- }
323
-
324
- /** Each entry's function, as clients see it; none for entries left out. */
325
- type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] extends { handler: infer F } ? F : H[K] };
326
-
327
- /** The names of the handlers and views every object (or agent) has, which its own cannot take. */
328
- type Reserved = {
329
- [
330
- name in keyof typeof BUILT_IN | keyof typeof FOLLOWED | keyof ReturnType<typeof internal> | 'steered'
331
- ]?: 'a handler every object has: name yours otherwise';
332
- };
333
-
334
- /** What an object with `handlers` and `views` has: those of every object, an agent's `clear` and `sync`, and its own. */
335
- type With<H, V> = Functions<typeof BUILT_IN> &
336
- (V extends { messages: unknown } ? Functions<typeof FOLLOWED> : unknown) &
337
- Functions<H> &
338
- Functions<V>;
339
-
340
- /**
341
- * A Restate virtual object with a SQL database per key, `ctx.db`: a
342
- * `restate.sessionObject` of @restatedev/sessions, set up for agents.
343
- *
344
- * const notes = sessionObject({
345
- * name: 'notes',
346
- * handlers: {
347
- * add: (ctx, note: string) => ctx.db.execute('INSERT INTO notes VALUES (?)', [note]),
348
- * },
349
- * });
350
- *
351
- * Besides its own handlers and views, it has the views `status`, what it is
352
- * doing (the message it answers, and what its tools wait for), `stop`,
353
- * which stops that message, `pending`, the waits
354
- * of its tools (`signal()`), `signal({ id, value })`, which resolves one,
355
- * and `notifications` and `watch({ revision })`, to follow its
356
- * conversation. An agent, an object with a `messages` view (such as
357
- * `claude.messages()`), has `clear` too, which forgets its conversation
358
- * (its database too), and `sync`, which `follow()` of @restatedev/agents/client
359
- * reads.
360
- *
361
- * `schema`, optional: tables of your own, beside the agent's (which are its
362
- * own business), made in each key's database as a session object makes
363
- * them. Any name is yours but those starting with `restate_`, the agent's
364
- * (`restate_pi_tasks`, `restate_agent_turns`, `restate_agent_items`...).
365
- *
366
- * `options` and `metadata` add to (or replace) the ones set here, such as
367
- * `options: { retryPolicy: ... }`.
368
- */
369
- export const sessionObject = <
370
- P extends string,
371
- H extends Record<string, restate.Entry<AgentContext>>,
372
- V extends Record<string, restate.Entry<AgentViewContext>>,
373
- >(
374
- definition: Definition<P> & {
375
- handlers?: H & Reserved;
376
- views?: V & Reserved;
377
- metadata?: Record<string, string>;
378
- options?: restate.ObjectOptions;
379
- },
380
- ): restate.VirtualObjectDefinition<P, With<H, V>> => {
381
- const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
382
- const { window = WINDOW, budget = BUDGET, summarize } = definition;
383
- checkWindow(window);
384
- if (!(Number.isInteger(budget) && budget >= 0)) {
385
- throw new Error(`${name}: budget must be a number of tokens (0 or more), not ${JSON.stringify(budget)}`);
386
- }
387
- const own = [...Object.keys(BUILT_IN), ...Object.keys(FOLLOWED), ...Object.keys(internal(undefined)), 'steered'];
388
- if ('messages' in handlers) {
389
- throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
390
- }
391
- for (const key of own) {
392
- if (key in handlers || key in views)
393
- throw new Error(`${name}: \`${key}\` is a handler of @restatedev/agents' own: name yours otherwise`);
394
- }
395
- // A model provider's refusal (a missing API key) ends a handler's invocation.
396
- const yours = Object.fromEntries(
397
- Object.entries(handlers as Record<string, restate.Entry<AgentContext>>).map(([key, entry]) => [
398
- key,
399
- answering(entry),
400
- ]),
401
- );
402
- const messages = (views as Record<string, restate.Entry<AgentViewContext>>).messages;
403
- const page = (typeof messages === 'function' ? messages : messages?.handler) as
404
- | ((ctx: AgentViewContext, request: MessagesRequest) => Promise<Messages>)
405
- | undefined;
406
- // A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
407
- const chatEntry = (handlers as Record<string, unknown>).chat;
408
- const chat = typeof chatEntry === 'object' || typeof chatEntry === 'function' ? chatOf(chatEntry!) : undefined;
409
- const agent = page === undefined ? {} : followed(chat !== undefined);
410
- // A framework on the conversation of turns: its view carries its items.
411
- const items = (page && ITEMS.of(page)) as Items<unknown> | undefined;
412
- // Its `compact` summarizes: without the conversation of turns, it has none, and nothing would.
413
- if (summarize && !items) {
414
- throw new Error(
415
- `${name}: \`summarize\` needs the conversation of turns: a framework's \`messages\` view (\`claude.messages()\`, say)`,
416
- );
417
- }
418
- const { erase, ...stored } = internal(items);
419
- const steering: Record<string, restate.Entry<AgentContext>> = chat ? { steered: steeredOf(chat) } : {};
420
- const privates: Record<string, restate.Entry<AgentContext>> = messages === undefined
421
- ? {}
422
- : items
423
- ? { erase, ...stored, ...steering }
424
- : { erase, ...steering };
425
- return withCompanion(
426
- isAgent(
427
- restate.sessionObject({
428
- name,
429
- description,
430
- schema,
431
- handlers: { ...privates, ...yours },
432
- views: { ...BUILT_IN, ...agent, ...views },
433
- metadata,
434
- options: { ...OPTIONS, ...options },
435
- }),
436
- { background, items, window, budget, summarize },
437
- ),
438
- );
439
- };
440
-
441
- /** `entry`, but a model provider's refusal it fails with ends its invocation, as `chat`'s does. */
442
- function answering(entry: restate.Entry<AgentContext>): restate.Entry<AgentContext> {
443
- const { handler, ...options } = typeof entry === 'function' ? { handler: entry } : entry;
444
- return {
445
- ...options,
446
- handler: async (ctx: AgentContext, input: unknown) => {
447
- try {
448
- return await handler(ctx, input);
449
- } catch (error) {
450
- throw refusalOf(ctx, error) ?? error;
451
- }
452
- },
453
- };
454
- }