@restatedev/agents 0.2.0 → 0.4.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 (136) hide show
  1. package/README.md +89 -49
  2. package/dist/calls.d.ts +29 -8
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +79 -18
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +238 -156
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +161 -71
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +277 -226
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +323 -107
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +234 -180
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +123 -40
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +75 -7
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +154 -27
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +110 -24
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +271 -183
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +354 -247
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +385 -138
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +337 -193
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +178 -48
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -79
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +235 -31
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -145
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -193
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
package/src/object.ts CHANGED
@@ -1,14 +1,35 @@
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 { cleared, onClear, inBackground, type Messages, type MessagesRequest, refusal, type Turn } from './common.ts';
5
- import * as log from './log.ts';
4
+ import {
5
+ type Answering,
6
+ BUDGET,
7
+ type Chat,
8
+ chatOf,
9
+ type Steers,
10
+ chatTurn,
11
+ checkWindow,
12
+ isAgent,
13
+ ITEMS,
14
+ messageSerde,
15
+ type Messages,
16
+ type MessagesRequest,
17
+ publish,
18
+ refusalOf,
19
+ type Summarize,
20
+ WINDOW,
21
+ type Window,
22
+ } from './common.ts';
23
+ import { compact, type Items, nextStart, restart, SCHEMA, settle, steerStored } from './conversation.ts';
6
24
  import {
7
25
  type Notifications,
8
26
  type Resolved,
9
27
  type Signal,
10
28
  signals,
11
29
  signalsOf,
30
+ type Steer,
31
+ type Steered,
32
+ type Steering,
12
33
  withCompanion,
13
34
  type Waiting,
14
35
  type Watch,
@@ -27,9 +48,11 @@ const OPTIONS = {
27
48
  /** What an object is doing: the message it answers, if any, and what its tools wait for. */
28
49
  export interface Status {
29
50
  /** The message being answered (by a `chat` handler), or null. */
30
- answering: Turn | null;
51
+ answering: Answering | null;
31
52
  /** The waits of its tools, oldest first (see `pending`). */
32
53
  waiting: Waiting[];
54
+ /** The messages steered to the message being answered that it has not taken yet, oldest first; absent if none. */
55
+ steering?: Steering[];
33
56
  }
34
57
 
35
58
  /** What `stop` did: the invocation of the message it stopped, or null if none was answered. */
@@ -72,7 +95,7 @@ const WAITS = { inactivityTimeout: { minutes: 5 } } satisfies restate.HandlerOpt
72
95
  * waits, `status`, what the object is doing, `stop`, which stops the message
73
96
  * it answers, and `notifications` and `watch`, the revision of its
74
97
  * conversation, and a wait for a newer one (an agent's
75
- * has `clear` and `sync` too: {@link followed}). Each asks the object's
98
+ * has `clear` and `sync` too: {@link FOLLOWED}). Each asks the object's
76
99
  * `signals` companion, which knows what the object does: they run while the
77
100
  * object's handler works.
78
101
  */
@@ -100,19 +123,21 @@ const BUILT_IN = {
100
123
 
101
124
  /**
102
125
  * The views that agents (an object with a `messages` view) have beside
103
- * those of every object: `clear`, which forgets the conversation; and
104
- * `sync`, the conversation since `cursor` (by default, all of it), what the
105
- * agent is doing, and the revision, in one request; with `revision`, once
106
- * there is a newer one, or at the timeout. A client follows the
107
- * conversation by sending each answer's `revision` and `cursor` back, at
108
- * once while it has `more`.
126
+ * those of every object: `clear`, which forgets the conversation; `steer`,
127
+ * which sends a message while a turn is answered (for an agent whose `chat`
128
+ * a framework's `chat()` made: `chatHandler`'s, which answers it as a turn
129
+ * of its own if no turn takes it); and `sync`, the conversation since
130
+ * `cursor` (by default, all of it), what the agent is doing, and the
131
+ * revision, in one request; with `revision`, once there is a newer one, or
132
+ * at the timeout. A client follows the conversation by sending each
133
+ * answer's `revision` and `cursor` back, at once while it has `more`.
109
134
  */
110
- const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>) => ({
135
+ const followed = (steerable: boolean) => ({
111
136
  /**
112
137
  * Forget the conversation: stop the message being answered (as `stop`),
113
138
  * 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
115
- * log.ts), so a follower reads on, and drops the messages before `first`.
139
+ * kept signals). The conversation's ids and cursors go on (see
140
+ * conversation.ts), so a follower reads on, and drops the messages before `first`.
116
141
  * A message sent before it is answered first, then forgotten too; one sent
117
142
  * after starts anew.
118
143
  */
@@ -130,47 +155,117 @@ const followed = (messages: (ctx: restate.ViewContext, request: MessagesRequest)
130
155
  return stop;
131
156
  },
132
157
  },
158
+ /**
159
+ * Send a message to the agent while it answers another: the turn being
160
+ * answered takes it at its next step (once the model's tool calls have
161
+ * their results), if its framework takes steered messages and it reaches
162
+ * one; otherwise the message is answered as a turn of its own, after the
163
+ * messages before it, in the order it was sent. With no message being
164
+ * answered, it starts a turn. Either way it is answered once: send it with
165
+ * an idempotency key, so that a retried request is the same message. It
166
+ * takes the message as plain text or as a JSON string, as `chat` does.
167
+ */
168
+ steer: {
169
+ input: messageSerde,
170
+ accept: '*/*',
171
+ handler: async (ctx: restate.ViewContext, text: string): Promise<Steered> => {
172
+ if (!steerable) {
173
+ throw new restate.TerminalError(
174
+ `${ctx.request.target.service} takes no steered messages: its \`chat\` handler is no framework's \`chat()\` (chatHandler)`,
175
+ { errorCode: 400 },
176
+ );
177
+ }
178
+ return companion(ctx, 'steer').steer({ id: ctx.request.id, text });
179
+ },
180
+ },
133
181
  sync: {
134
182
  ...WAITS,
135
183
  handler: async (
136
184
  ctx: restate.ViewContext,
137
- { cursor = 0, revision, timeoutSeconds = 50, limit = 100 }: SyncRequest = {},
185
+ { cursor = 0, revision, timeoutSeconds = 50, limit = 100, view }: SyncRequest = {},
138
186
  ): Promise<Synced> => {
139
187
  if (revision !== undefined) await companion(ctx, 'watch').watch({ revision, timeoutSeconds });
140
188
  // The revision first: a change after it shows in the next sync. Then
141
- // what the object does, and its conversation, as they are now.
189
+ // what the object does, and its conversation, in an invocation of its
190
+ // own, which starts after the revision: a view reads the database as
191
+ // committed when it started, and this one started before the revision
192
+ // (by the whole wait, when it waited). So the page has every change the
193
+ // revision counts.
142
194
  const now = await companion(ctx).notifications();
143
195
  const status = await companion(ctx).status();
144
- return { revision: now.revision, status, ...(await messages(ctx, { cursor, limit })) };
196
+ const request: MessagesRequest = { cursor, limit, ...(view ? { view } : {}) };
197
+ const page = (await ctx.rpc({
198
+ service: ctx.request.target.service,
199
+ key: ctx.key,
200
+ handler: 'messages',
201
+ input: request,
202
+ })) as Messages;
203
+ return { revision: now.revision, status, ...page };
145
204
  },
146
205
  },
147
206
  });
148
207
 
208
+ /** The views of every agent: {@link followed}'s. */
209
+ const FOLLOWED = followed(false);
210
+
149
211
  /**
150
212
  * The agents' handlers that only their own views call (Restate's ingress
151
213
  * refuses them), and their types leave out: `erase`, `clear`'s work, once
152
214
  * the handlers before it are done. It empties the key's database and its
153
- * signals', and the log goes on where it got to (see log.ts).
215
+ * signals', and the conversation's ids and cursors go on where they got to
216
+ * (conversation.ts).
154
217
  */
155
- const INTERNAL = {
218
+ const internal = (items: Items<unknown> | undefined) => ({
156
219
  erase: {
157
220
  ingressPrivate: true,
158
221
  handler: async (ctx: restate.SessionContext) => {
159
- const start = startAfter(await log.page(ctx.db, { limit: 1 }));
222
+ // Read first, which also makes the reset apply the conversation's schema again.
223
+ await SCHEMA.ensure(ctx.db);
224
+ const start = await nextStart(ctx.db);
160
225
  await ctx.db.transaction(async (tx) => {
161
226
  await reset(tx);
162
- await log.restart(tx, start);
227
+ await restart(tx, start);
163
228
  });
164
- await cleared(ctx);
165
229
  await ctx.rpc(signals, signalsOf(ctx), { idempotencyKey: `${ctx.request.id}:reset` }).reset();
166
230
  },
167
231
  },
168
- };
232
+ /**
233
+ * Close the latest turn, unanswered, if invocation `invocationId` ran it
234
+ * and is gone: the companion sends this once it finds the turn's
235
+ * invocation ended without answering (killed, say), so that the
236
+ * conversation shows the turn closed before the next message. Whether it
237
+ * closed it.
238
+ */
239
+ settle: {
240
+ ingressPrivate: true,
241
+ handler: async (ctx: restate.SessionContext, invocationId: string) => {
242
+ if (!items || !(await settle(ctx, items, invocationId))) return false;
243
+ // The companion published as it closed the turn, before this stored how it ended: publish that too.
244
+ await publish(ctx);
245
+ return true;
246
+ },
247
+ },
248
+ /** Summarize the earliest turns, past the agent's budget. Whether it did. */
249
+ compact: {
250
+ ingressPrivate: true,
251
+ handler: async (ctx: restate.SessionContext) => (items ? compact(ctx, items) : false),
252
+ },
253
+ });
169
254
 
170
- /** Where the log starts after `latest`, its latest message: past its ids and cursor. */
171
- const startAfter = ({ messages: [latest], cursor, first = 0 }: Messages): log.Start => ({
172
- seq: cursor,
173
- id: latest ? latest.id + 1 : first,
255
+ /**
256
+ * The private `steered` of an agent whose `chat` is `chat` (`chatHandler`'s):
257
+ * it answers a message sent to `steer` as a turn of its own, with that
258
+ * `chat`, unless the turn it was sent to took it. The companion sends it as
259
+ * the message is sent, so that it keeps its place in the key's queue: it runs
260
+ * once the messages before it are answered.
261
+ */
262
+ const steeredOf = ({ answer, steers }: { answer: Chat; steers: Steers }) => ({
263
+ ingressPrivate: true,
264
+ explicitCancellation: true,
265
+ handler: async (ctx: restate.SessionContext, { id, text }: Steer) => {
266
+ if (await steerStored(ctx.db, id)) return;
267
+ await chatTurn(ctx, text, answer, steers);
268
+ },
174
269
  });
175
270
 
176
271
  /**
@@ -179,6 +274,8 @@ const startAfter = ({ messages: [latest], cursor, first = 0 }: Messages): log.St
179
274
  * `revision`, if given, or at `timeoutSeconds` (default 50, at most 60).
180
275
  */
181
276
  export interface SyncRequest {
277
+ /** The messages' view: `full` (the default), or `summary` (see `MessagesRequest`). */
278
+ view?: MessagesRequest['view'];
182
279
  cursor?: number;
183
280
  revision?: number;
184
281
  timeoutSeconds?: number;
@@ -203,6 +300,20 @@ export interface Definition<P extends string> {
203
300
  * sees each turn once it ended. `messages` has every turn as before.
204
301
  */
205
302
  background?: boolean;
303
+ /**
304
+ * For an agent on the conversation of turns: how many of the latest
305
+ * answered turns its model sees whole, with their tool calls and results
306
+ * (default 1), or `'all'`.
307
+ */
308
+ window?: Window;
309
+ /** For an agent on the conversation of turns: how many tokens of the turns before the window its model sees (default 32 000). */
310
+ budget?: number;
311
+ /**
312
+ * For an agent on the conversation of turns: how it summarizes the turns
313
+ * before the window once they outgrow `budget`, in an invocation of its
314
+ * own (`compact`), after the answer. Without, they are only left out.
315
+ */
316
+ summarize?: Summarize;
206
317
  }
207
318
 
208
319
  /** Each entry's function, as clients see it; none for entries left out. */
@@ -211,13 +322,13 @@ type Functions<H> = string extends keyof H ? unknown : { [K in keyof H]: H[K] ex
211
322
  /** The names of the handlers and views every object (or agent) has, which its own cannot take. */
212
323
  type Reserved = {
213
324
  [
214
- name in keyof typeof BUILT_IN | keyof ReturnType<typeof followed> | keyof typeof INTERNAL
325
+ name in keyof typeof BUILT_IN | keyof typeof FOLLOWED | keyof ReturnType<typeof internal> | 'steered'
215
326
  ]?: 'a handler every object has: name yours otherwise';
216
327
  };
217
328
 
218
329
  /** What an object with `handlers` and `views` has: those of every object, an agent's `clear` and `sync`, and its own. */
219
330
  type With<H, V> = Functions<typeof BUILT_IN> &
220
- (V extends { messages: unknown } ? Functions<ReturnType<typeof followed>> : unknown) &
331
+ (V extends { messages: unknown } ? Functions<typeof FOLLOWED> : unknown) &
221
332
  Functions<H> &
222
333
  Functions<V>;
223
334
 
@@ -245,8 +356,7 @@ type With<H, V> = Functions<typeof BUILT_IN> &
245
356
  * `schema`, optional: tables of your own, beside the agent's (which are its
246
357
  * own business), made in each key's database as a session object makes
247
358
  * them. Any name is yours but those starting with `restate_`, the agent's
248
- * (`restate_pi_tasks`, `restate_claude_messages`, `restate_agent_log`...);
249
- * OpenCode's tables are in a database of their own.
359
+ * (`restate_pi_tasks`, `restate_agent_turns`, `restate_agent_items`...).
250
360
  *
251
361
  * `options` and `metadata` add to (or replace) the ones set here, such as
252
362
  * `options: { retryPolicy: ... }`.
@@ -264,12 +374,12 @@ export const sessionObject = <
264
374
  },
265
375
  ): restate.VirtualObjectDefinition<P, With<H, V>> => {
266
376
  const { name, description, schema, background, handlers = {}, views = {}, metadata, options } = definition;
267
- if (background) inBackground(name);
268
- const own = [
269
- ...Object.keys(BUILT_IN),
270
- ...Object.keys(followed(async () => ({}) as Messages)),
271
- ...Object.keys(INTERNAL),
272
- ];
377
+ const { window = WINDOW, budget = BUDGET, summarize } = definition;
378
+ checkWindow(window);
379
+ if (!(Number.isInteger(budget) && budget >= 0)) {
380
+ throw new Error(`${name}: budget must be a number of tokens (0 or more), not ${JSON.stringify(budget)}`);
381
+ }
382
+ const own = [...Object.keys(BUILT_IN), ...Object.keys(FOLLOWED), ...Object.keys(internal(undefined)), 'steered'];
273
383
  if ('messages' in handlers) {
274
384
  throw new Error(`${name}: \`messages\` is a view: put it in \`views\`, so that the object is an agent`);
275
385
  }
@@ -285,21 +395,41 @@ export const sessionObject = <
285
395
  ]),
286
396
  );
287
397
  const messages = (views as Record<string, restate.Entry<restate.ViewContext>>).messages;
288
- onClear(name, messages);
289
398
  const page = (typeof messages === 'function' ? messages : messages?.handler) as
290
399
  | ((ctx: restate.ViewContext, request: MessagesRequest) => Promise<Messages>)
291
400
  | undefined;
292
- const agent = page === undefined ? {} : followed(page);
401
+ // A `chat` that `chatHandler` made: its answer answers the steered messages no turn took (`steered`).
402
+ const chatEntry = (handlers as Record<string, unknown>).chat;
403
+ const chat = typeof chatEntry === 'object' || typeof chatEntry === 'function' ? chatOf(chatEntry!) : undefined;
404
+ const agent = page === undefined ? {} : followed(chat !== undefined);
405
+ // A framework on the conversation of turns: its view carries its items.
406
+ const items = (page && ITEMS.of(page)) as Items<unknown> | undefined;
407
+ // Its `compact` summarizes: without the conversation of turns, it has none, and nothing would.
408
+ if (summarize && !items) {
409
+ throw new Error(
410
+ `${name}: \`summarize\` needs the conversation of turns: a framework's \`messages\` view (\`claude.messages()\`, say)`,
411
+ );
412
+ }
413
+ const { erase, ...stored } = internal(items);
414
+ const steering: Record<string, restate.Entry<restate.SessionContext>> = chat ? { steered: steeredOf(chat) } : {};
415
+ const privates: Record<string, restate.Entry<restate.SessionContext>> = messages === undefined
416
+ ? {}
417
+ : items
418
+ ? { erase, ...stored, ...steering }
419
+ : { erase, ...steering };
293
420
  return withCompanion(
294
- restate.sessionObject({
295
- name,
296
- description,
297
- schema,
298
- handlers: { ...(messages === undefined ? {} : INTERNAL), ...yours },
299
- views: { ...BUILT_IN, ...agent, ...views },
300
- metadata,
301
- options: { ...OPTIONS, ...options },
302
- }),
421
+ isAgent(
422
+ restate.sessionObject({
423
+ name,
424
+ description,
425
+ schema,
426
+ handlers: { ...privates, ...yours },
427
+ views: { ...BUILT_IN, ...agent, ...views },
428
+ metadata,
429
+ options: { ...OPTIONS, ...options },
430
+ }),
431
+ { background, items, window, budget, summarize },
432
+ ),
303
433
  );
304
434
  };
305
435
 
@@ -312,7 +442,7 @@ function answering(entry: restate.Entry<restate.SessionContext>): restate.Entry<
312
442
  try {
313
443
  return await handler(ctx, input);
314
444
  } catch (error) {
315
- throw refusal(error) ?? error;
445
+ throw refusalOf(ctx, error) ?? error;
316
446
  }
317
447
  },
318
448
  };
package/src/output.ts CHANGED
@@ -1,16 +1,19 @@
1
1
  // An agent's answer as data, with `output` (every framework's option): a zod
2
- // object schema. The agent's reply is its answer, as JSON: the system prompt
3
- // asks for it, with the schema, and each prompt again, at its end; the reply
4
- // is checked against it. The
5
- // prompt (and so `chat`) then answers with the value, as an RPC answers.
2
+ // object schema. The agent's reply is its answer, as JSON: a framework that
3
+ // can ask the model for it natively does so (Claude's structured outputs, the
4
+ // API's `output_config.format`); else the system prompt asks for it, with the
5
+ // schema, and each prompt again, at its end. Either way, the reply is checked
6
+ // against it. The prompt (and so `chat`) then answers with the value, as an
7
+ // RPC answers.
6
8
  //
7
9
  // const planner = claude.agent({ name: 'planner', output: Plan }); // chat answers with a Plan
8
10
  //
9
11
  // The JSON may be in a code fence, or after a sentence. A reply that is not
10
12
  // such JSON is answered with what is wrong with it, once, for the agent to
11
13
  // answer again; then the prompt fails (a terminal error), saying how the
12
- // reply starts. A retried attempt resumes the conversation, so it reads the
13
- // same reply.
14
+ // reply starts. The ask again is a step of the turn (`answerOnce`'s
15
+ // `check`), and a retried attempt resumes the turn, so it reads the same
16
+ // reply.
14
17
  import * as restate from '@restatedev/sessions';
15
18
  import { z } from 'zod';
16
19
 
@@ -23,9 +26,11 @@ const format = (output: z.ZodObject) =>
23
26
  JSON.stringify(z.toJSONSchema(output));
24
27
 
25
28
  /**
26
- * What each prompt ends with, with `output`: the system prompt's ask, again,
27
- * where an agent reads it last (after a long run of tool calls, it may have
28
- * drifted from its system prompt to a summary in prose).
29
+ * What the model is told after each prompt, with `output` asked in the
30
+ * prompt: the system prompt's ask, again, where an agent reads it last
31
+ * (after a long run of tool calls, it may have drifted from its system
32
+ * prompt to a summary in prose). It is not stored: clients read the prompt
33
+ * as it was asked.
29
34
  */
30
35
  const reminder =
31
36
  '\n\nWhen you are done, reply with your answer as JSON only, of the schema you were given: no other text.';
@@ -60,36 +65,52 @@ function parsed<O extends z.ZodObject>(output: O, reply: string): { value: z.inf
60
65
  return result.success ? { value: result.data } : { wrong: z.prettifyError(result.error) };
61
66
  }
62
67
 
68
+ /** The error of a prompt whose answer is not a value of its `output`, `wrong` saying why. */
69
+ const notAsked = (wrong: string) =>
70
+ new restate.TerminalError(`The agent's reply is not the answer asked for: ${wrong}`);
71
+
63
72
  /**
64
- * Answer `text` with a value of `output`: the agent's reply to it, parsed;
65
- * one that is not is answered with what is wrong, once, for another reply.
73
+ * The check of an answer that must be a value of `output`: what asks again
74
+ * for one, if it is not (`answerOnce`'s `check`, which asks within the
75
+ * turn), or, once it asked (`last`), the error that fails the turn.
66
76
  */
67
- export async function answerWith<O extends z.ZodObject>(
68
- text: string,
69
- output: O,
70
- prompt: (text: string) => Promise<string>,
71
- ): Promise<z.infer<O>> {
72
- let answer = parsed(output, await prompt(text));
73
- if ('wrong' in answer) {
74
- const again = `Your reply is not the answer asked for: ${answer.wrong}\nReply again, with the JSON only.`;
75
- answer = parsed(output, await prompt(again));
76
- }
77
- if ('wrong' in answer)
78
- throw new restate.TerminalError(`The agent's reply is not the answer asked for: ${answer.wrong}`);
79
- return answer.value;
80
- }
77
+ export const recheck =
78
+ (output: z.ZodObject) =>
79
+ (reply: string, last?: boolean): string | undefined => {
80
+ const answer = parsed(output, reply);
81
+ if (!('wrong' in answer)) return undefined;
82
+ if (last) throw notAsked(answer.wrong);
83
+ return `Your reply is not the answer asked for: ${answer.wrong}\nReply again, with the JSON only.`;
84
+ };
81
85
 
82
86
  /**
83
- * `prompt` (a framework's, of `options`), answering with a value of
84
- * `options.output` if it has one, or else with the agent's text.
87
+ * `prompt` (a framework's on the conversation of turns, of `options`),
88
+ * answering with a value of `options.output` if it has one, or else with the
89
+ * agent's text. A reply that is not the value is asked again within its
90
+ * turn, once (`check`), and the reply to that must be one, or the prompt
91
+ * fails, terminal, and its turn is closed failed. The model is told
92
+ * `reminder` after the prompt, which the conversation keeps as it was asked
93
+ * (`answerOnce`'s `reminder`). With `native`, the framework asks the model
94
+ * for the value itself (a JSON schema mode): neither the system prompt nor
95
+ * a reminder asks for it, and the reply is checked all the same.
85
96
  */
86
- export const withOutput = <T extends { system?: string; output?: z.ZodObject }>(
97
+ export const withChecked = async <T extends { system?: string; output?: z.ZodObject }>(
87
98
  text: string,
88
99
  options: T,
89
- prompt: (text: string, options: T) => Promise<string>,
100
+ prompt: (
101
+ text: string,
102
+ options: T,
103
+ check?: (answer: string) => string | undefined,
104
+ reminder?: string,
105
+ ) => Promise<string>,
106
+ native = false,
90
107
  ): Promise<Answer<T['output']>> => {
91
108
  const { output } = options;
92
109
  if (!output) return prompt(text, options) as Promise<Answer<T['output']>>;
93
- const asked = { ...options, system: [options.system, format(output)].filter(Boolean).join('\n\n') };
94
- return answerWith(text + reminder, output, (t) => prompt(t, asked)) as Promise<Answer<T['output']>>;
110
+ const asked = native
111
+ ? options
112
+ : { ...options, system: [options.system, format(output)].filter(Boolean).join('\n\n') };
113
+ const answer = parsed(output, await prompt(text, asked, recheck(output), native ? undefined : reminder));
114
+ if ('wrong' in answer) throw notAsked(answer.wrong);
115
+ return answer.value as Answer<T['output']>;
95
116
  };
package/src/pi/README.md CHANGED
@@ -26,6 +26,7 @@ await serve(assistant);
26
26
  | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
27
27
  | `workspace` | A directory for pi-durable's coding tools (`read`, `write`, `edit`, `bash`), on the local file system; use a sandbox |
28
28
  | `serviceTier` | OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on |
29
+ | `retry` | How pi asks the model again after a request failed for a reason that passes (an outage, a rate limit): by default without limit, 2 s to a minute apart |
29
30
 
30
31
  For a session object of your own, `pi.chat(options)` is the handler and
31
32
  `pi.messages()` the view; `options` may be a function of the invocation's context, such as
@@ -68,7 +69,21 @@ handler does. A retried attempt opens the Harness again and carries on:
68
69
  `Infinity`: Restate's retry policy decides);
69
70
  - a tool's error fails the attempt, and Restate retries it (pi-durable would
70
71
  hand it to the model); a `restate.TerminalError` of a `@restatedev/agents`
71
- tool is its answer to the model.
72
+ tool is its answer to the model;
73
+ - a provider's outage never ends the turn: pi asks the model again until it
74
+ answers (pi-durable gives up after 3 retries; `retry` sets how often), and
75
+ each retry is committed, so a retried attempt waits as the attempt before
76
+ it would have; a request the provider refuses for good (a wrong API key)
77
+ ends the turn, with a terminal error that says what to check;
78
+ - a run a killed invocation left is aborted, never finished: its turn is
79
+ closed (`ended`) in the agent's conversation of turns, and the next
80
+ prompt tells the model how it ended.
81
+
82
+ pi keeps its own history (and compacts it); each pi commit of a prompt's run
83
+ copies its new entries (the model's replies, the tools' results) into the
84
+ agent's conversation of turns, in the same transaction: what `messages`
85
+ shows ([docs/conversation.md](../../docs/conversation.md)). The views show
86
+ each turn as it was asked and answered, not pi's summaries and handoffs.
72
87
 
73
88
  The files of a `workspace` are not in the database: they last as long as the
74
89
  disk does, and a coding tool a crash cut off is not run again (the model is
@@ -83,8 +98,8 @@ cd packages/examples && OPENAI_API_KEY=… node basic/chat.ts
83
98
  With a Restate server, and the agent registered with it: see
84
99
  [Run an example](../../../examples/README.md#run-an-example).
85
100
  [`examples/basic/chat.ts`](../../../examples/basic/chat.ts) is a chat agent with a
86
- tool, and [`examples/intermediate/coding.ts`](../../../examples/intermediate/coding.ts) a pi
87
- coordinator that hands coding tasks to OpenCode coders.
101
+ tool, and [`examples/intermediate/team.ts`](../../../examples/intermediate/team.ts) a pi
102
+ editor that hands tasks to agents of other frameworks.
88
103
 
89
104
  ## Tests
90
105