@restatedev/agents 0.3.0 → 0.5.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 +107 -53
  2. package/dist/calls.d.ts +29 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  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 +232 -151
  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 +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +478 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1256 -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 +322 -106
  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 +227 -171
  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 -35
  64. package/dist/object.js.map +1 -1
  65. package/dist/opencode/db.d.ts +51 -10
  66. package/dist/opencode/db.d.ts.map +1 -1
  67. package/dist/opencode/db.js +122 -34
  68. package/dist/opencode/db.js.map +1 -1
  69. package/dist/opencode/index.d.ts +105 -21
  70. package/dist/opencode/index.d.ts.map +1 -1
  71. package/dist/opencode/index.js +827 -279
  72. package/dist/opencode/index.js.map +1 -1
  73. package/dist/output.d.ts +15 -7
  74. package/dist/output.d.ts.map +1 -1
  75. package/dist/output.js +44 -26
  76. package/dist/output.js.map +1 -1
  77. package/dist/pi/index.d.ts +39 -11
  78. package/dist/pi/index.d.ts.map +1 -1
  79. package/dist/pi/index.js +281 -77
  80. package/dist/pi/index.js.map +1 -1
  81. package/dist/pi/storage.d.ts +29 -4
  82. package/dist/pi/storage.d.ts.map +1 -1
  83. package/dist/pi/storage.js +18 -6
  84. package/dist/pi/storage.js.map +1 -1
  85. package/dist/signals.d.ts +74 -4
  86. package/dist/signals.d.ts.map +1 -1
  87. package/dist/signals.js +144 -15
  88. package/dist/signals.js.map +1 -1
  89. package/dist/steering.d.ts +31 -0
  90. package/dist/steering.d.ts.map +1 -0
  91. package/dist/steering.js +45 -0
  92. package/dist/steering.js.map +1 -0
  93. package/dist/tools.d.ts +28 -0
  94. package/dist/tools.d.ts.map +1 -1
  95. package/dist/tools.js +34 -5
  96. package/dist/tools.js.map +1 -1
  97. package/package.json +42 -13
  98. package/src/calls.ts +107 -15
  99. package/src/claude/README.md +41 -20
  100. package/src/claude/index.ts +266 -178
  101. package/src/client.ts +14 -3
  102. package/src/common.ts +317 -232
  103. package/src/conversation.ts +1547 -0
  104. package/src/deepseek/README.md +78 -11
  105. package/src/deepseek/index.ts +384 -137
  106. package/src/deepseek/persistence.ts +11 -8
  107. package/src/index.ts +13 -4
  108. package/src/langgraph/README.md +115 -25
  109. package/src/langgraph/checkpointer.ts +168 -28
  110. package/src/langgraph/context.ts +27 -0
  111. package/src/langgraph/errors.ts +26 -0
  112. package/src/langgraph/graph.ts +396 -0
  113. package/src/langgraph/index.ts +326 -181
  114. package/src/langgraph/nodes.ts +243 -0
  115. package/src/messages.ts +244 -0
  116. package/src/object.ts +169 -38
  117. package/src/opencode/README.md +172 -66
  118. package/src/opencode/db.ts +204 -40
  119. package/src/opencode/index.ts +1010 -325
  120. package/src/output.ts +52 -31
  121. package/src/pi/README.md +18 -3
  122. package/src/pi/index.ts +346 -78
  123. package/src/pi/storage.ts +20 -7
  124. package/src/signals.ts +225 -19
  125. package/src/steering.ts +67 -0
  126. package/src/tools.ts +61 -8
  127. package/dist/claude/conversation.d.ts +0 -33
  128. package/dist/claude/conversation.d.ts.map +0 -1
  129. package/dist/claude/conversation.js +0 -95
  130. package/dist/claude/conversation.js.map +0 -1
  131. package/dist/log.d.ts +0 -29
  132. package/dist/log.d.ts.map +0 -1
  133. package/dist/log.js +0 -146
  134. package/dist/log.js.map +0 -1
  135. package/src/claude/conversation.ts +0 -114
  136. package/src/log.ts +0 -194
package/src/pi/index.ts CHANGED
@@ -16,7 +16,13 @@
16
16
  //
17
17
  // It runs `work` over `ctx.db`: pi-durable's storage is the object's
18
18
  // database (storage.ts), and each pi-durable commit is an SQL transaction
19
- // in it, stored in order with everything else the handler does. The Harness
19
+ // in it, stored in order with everything else the handler does. pi keeps its
20
+ // own history (and compacts it); each commit of a prompt's run copies its
21
+ // new entries (the model's replies, the tools' results) into the
22
+ // conversation of turns (../conversation.ts) in the same transaction: what
23
+ // clients read, and how turns end. A run another invocation left (killed)
24
+ // is aborted, never finished, and the next prompt tells the model how the
25
+ // turn before it ended. The Harness
20
26
  // is opened with `tools` (made with pi-durable's `defineTool`) and closed at
21
27
  // the end. A retried attempt (a crash, a lost connection) opens it again and
22
28
  // carries on: a prompt is submitted once, by its id (pi-durable's requestId),
@@ -32,7 +38,6 @@
32
38
  // and a coding tool cut off by a crash is not run again (the model is told
33
39
  // it was interrupted).
34
40
  import * as restate from '@restatedev/sessions';
35
- import { ScopeKey } from '@restatedev/sessions/internal';
36
41
  import type { Context } from '@earendil-works/chord';
37
42
  import { awaitWithContext, BACKGROUND_CONTEXT, withCancel, withoutAbortSignal } from '@earendil-works/chord/context';
38
43
  import { mkdir } from 'node:fs/promises';
@@ -44,47 +49,60 @@ import {
44
49
  createRegistry,
45
50
  defineExtension,
46
51
  defineTool,
52
+ GenerationTask,
47
53
  Harness,
54
+ hook,
48
55
  section,
49
56
  type Conversation,
57
+ type ConversationId,
58
+ type ConversationRetryPolicy,
50
59
  type ConversationStreamOptions,
51
- type EntryId,
52
60
  type ToolRegistration,
53
61
  } from '@earendil-works/pi-durable';
54
62
  import { NodeExecutionEnv } from '@earendil-works/pi-durable/env/node';
55
63
  import { CodingTools } from '@earendil-works/pi-durable/tools';
64
+ import type { Transaction } from '@restatedev/sessions';
56
65
  import {
57
66
  AttemptEnded,
58
67
  chatHandler,
59
68
  CHECK_MODEL,
69
+ type Check,
60
70
  checkModelName,
61
71
  type Configure,
62
72
  configured,
63
- messagesHandler,
73
+ fromTool,
74
+ inboxOf,
64
75
  ModelError,
65
76
  modelOf,
66
- nextPromptId,
67
77
  providerOf,
68
78
  refusal,
69
79
  REFUSED,
80
+ RETURNED_UNRECORDED,
70
81
  stopSignalOf,
71
82
  toolCallEnded,
72
83
  toolCallStarted,
73
- transcribing,
74
- Transcript,
75
84
  } from '../common.ts';
76
- import { type Answer, withOutput } from '../output.ts';
85
+ import { answerOnce, invocationOf, type Items, type Parsed, type Turn } from '../conversation.ts';
86
+ import { tookSteers } from '../steering.ts';
87
+ import { conversationView } from '../messages.ts';
88
+ import { type Answer, withChecked } from '../output.ts';
77
89
  import { type Definition, sessionObject } from '../object.ts';
78
90
  import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
79
91
  import type { z } from 'zod';
80
- import { openSqlKvStorage } from './storage.ts';
92
+ import { openSqlKvStorage, SqlKvDatabase } from './storage.ts';
81
93
 
82
94
  /** What `work` gets: `prompt(text)`, the `conversation()`, and the `harness` and chord `context` for anything else. */
83
95
  export interface Pi {
84
96
  harness: Harness;
85
97
  context: Context;
86
- /** Answer `text`, once per prompt `id`, with the answer's text. By default, each prompt of an invocation has an id of its own, the same on every attempt. */
87
- prompt: (text: string, id?: string) => Promise<string>;
98
+ /**
99
+ * Answer `text`, once, with the answer's text: a turn of the object's
100
+ * conversation (each prompt of an invocation has an id of its own, the
101
+ * same on every attempt). With `check`, a reply it returns a message for
102
+ * is asked again within the turn, once. With `reminder`, the model is told
103
+ * it after the prompt, which the conversation keeps as it was asked.
104
+ */
105
+ prompt: (text: string, check?: Check, reminder?: string) => Promise<string>;
88
106
  /** The object's conversation, on the model: for `reset`, `compact`, `entries` and the like. */
89
107
  conversation: () => Promise<Conversation>;
90
108
  }
@@ -93,6 +111,144 @@ export interface Pi {
93
111
  const textOf = (content: Message['content']): string =>
94
112
  typeof content === 'string' ? content : content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
95
113
 
114
+ /** A pi message as the conversation of turns keeps it: with the id of the pi entry it was copied from. */
115
+ export interface Item {
116
+ entry?: number;
117
+ message: Message;
118
+ }
119
+
120
+ /** No usage: a message the conversation makes, which no model gave. */
121
+ const NO_USAGE = {
122
+ input: 0,
123
+ output: 0,
124
+ cacheRead: 0,
125
+ cacheWrite: 0,
126
+ totalTokens: 0,
127
+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
128
+ };
129
+
130
+ /**
131
+ * pi's items: pi-ai's messages. A user's message is said by the user; an
132
+ * assistant's (but one aborted, failed or deferred) says its text, with its
133
+ * tool calls; a tool's result is a result; a system message says nothing.
134
+ */
135
+ export const items: Items<Item> = {
136
+ dump: (item) => JSON.stringify(item),
137
+ load: (stored) => {
138
+ // Only a pi message, with the entry it was copied from: another framework's row is not one.
139
+ const item = JSON.parse(stored) as Item;
140
+ const { message, entry, ...rest } = item;
141
+ if (typeof message !== 'object' || message === null || typeof message.role !== 'string')
142
+ throw new Error("not a pi item (a pi-ai message, with its entry's id)");
143
+ if (Object.keys(rest).length > 0 || (entry !== undefined && typeof entry !== 'number'))
144
+ throw new Error(`not a pi item: ${Object.keys(item).join(', ')}`);
145
+ return item;
146
+ },
147
+ prompt: (text) => ({ message: { role: 'user', content: text, timestamp: 0 } }),
148
+ reply: (text) => ({
149
+ message: {
150
+ role: 'assistant',
151
+ content: [{ type: 'text', text }],
152
+ api: 'restate',
153
+ provider: 'restate',
154
+ model: 'note',
155
+ usage: NO_USAGE,
156
+ stopReason: 'stop',
157
+ timestamp: 0,
158
+ },
159
+ }),
160
+ results: (results) =>
161
+ results.map(([call, output]) => ({
162
+ message: {
163
+ role: 'toolResult',
164
+ toolCallId: call.id,
165
+ toolName: call.name,
166
+ content: [{ type: 'text', text: output }],
167
+ isError: output !== RETURNED_UNRECORDED,
168
+ timestamp: 0,
169
+ },
170
+ })),
171
+ read: ({ message: m }): Parsed => {
172
+ if (m.role === 'user') return { said: ['user', textOf(m.content)] };
173
+ if (m.role === 'assistant') {
174
+ if (m.stopReason === 'aborted' || m.stopReason === 'error' || m.stopReason === 'deferred') return {};
175
+ const calls = m.content.flatMap((c) =>
176
+ c.type === 'toolCall' ? [{ id: c.id, name: c.name, input: c.arguments }] : [],
177
+ );
178
+ // Each reply is a message of its own, its tool calls' too.
179
+ return { said: ['assistant', textOf(m.content)], calls };
180
+ }
181
+ if (m.role === 'toolResult')
182
+ return { results: [{ id: m.toolCallId, output: textOf(m.content), error: m.isError }] };
183
+ return {};
184
+ },
185
+ };
186
+
187
+ /** The kind of the entry of a message steered to a turn, as pi places it: its data is the message's id. */
188
+ const STEER_ENTRY = 'restate.steer';
189
+
190
+ /**
191
+ * What each pi commit copies into `turn`, in its transaction: the entries of
192
+ * the run of the turn's request `requestId` after its user entry (pi's
193
+ * submission names it),
194
+ * its replies, its tools' results, and the messages steered to the turn that
195
+ * pi placed at a step (whose companion is told they are taken, in the
196
+ * commit); nothing once `stopped()`, or once the turn is closed. Each entry
197
+ * once: after the last one copied. `resulted` gets the calls whose results
198
+ * it copied.
199
+ */
200
+ function copying(
201
+ ctx: restate.SessionContext,
202
+ turn: Turn<Item>,
203
+ requestId: string,
204
+ stopped: () => boolean,
205
+ resulted: (calls: string[]) => void,
206
+ ) {
207
+ let from: { conversation: number; last: number } | undefined;
208
+ return async (tx: Transaction) => {
209
+ if (stopped() || !turn.writable) return;
210
+ if (!from) {
211
+ const submitted = await tx.get<{ entry: number | null; conversation: number }>(
212
+ "SELECT json_extract(record, '$.entry') AS entry, conversation_id AS conversation FROM restate_pi_submissions WHERE request_id = ?",
213
+ [JSON.stringify(requestId)],
214
+ );
215
+ if (submitted?.entry === null || submitted?.entry === undefined) return;
216
+ const copied = turn.items.flatMap((e) => (e.item.entry === undefined ? [] : [e.item.entry]));
217
+ from = { conversation: submitted.conversation, last: Math.max(submitted.entry, ...copied) };
218
+ }
219
+ const rows = await tx.values(
220
+ 'SELECT id, record FROM restate_pi_entries WHERE conversation_id = ? AND id > ? ORDER BY id',
221
+ [from.conversation, from.last],
222
+ );
223
+ const copied: { item: Item; reply?: boolean; steer?: string }[] = [];
224
+ const held = new Set(turn.steered().map((e) => e.steer));
225
+ for (const [id, record] of rows) {
226
+ const entry = JSON.parse(String(record)) as { kind: string; model?: Message[]; data?: { id?: unknown } };
227
+ from.last = Number(id);
228
+ if (entry.kind === STEER_ENTRY) {
229
+ const steer = typeof entry.data?.id === 'string' ? entry.data.id : undefined;
230
+ const [message] = entry.model ?? [];
231
+ if (steer !== undefined && message && !held.has(steer)) {
232
+ copied.push({ item: { entry: Number(id), message }, steer });
233
+ }
234
+ continue;
235
+ }
236
+ if (entry.kind !== 'pi.assistant' && entry.kind !== 'pi.tool-result') continue;
237
+ for (const message of entry.model ?? []) {
238
+ copied.push({ item: { entry: Number(id), message }, reply: message.role === 'assistant' });
239
+ }
240
+ }
241
+ if (copied.length === 0) return;
242
+ await turn.copyIn(tx, copied);
243
+ tookSteers(
244
+ ctx,
245
+ tx,
246
+ copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
247
+ );
248
+ resulted(copied.flatMap(({ item: { message } }) => (message.role === 'toolResult' ? [message.toolCallId] : [])));
249
+ };
250
+ }
251
+
96
252
  /** An agent's options: `chat`, `prompt` and `withPi` take them. */
97
253
  export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
98
254
  /** The model, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
@@ -107,6 +263,15 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
107
263
  workspace?: string;
108
264
  /** OpenAI's service tier for each request: `fast` for its fast mode (priced higher), `flex`, and so on. */
109
265
  serviceTier?: ServiceTier;
266
+ /**
267
+ * How pi asks the model again after a request failed for a reason that
268
+ * passes (an overloaded or unreachable provider, a rate limit): by
269
+ * default without limit, 2 s after the first failure, then twice as long
270
+ * each time, a minute apart at most. With `maxRetries`, a failure after
271
+ * that many retries ends the turn. A request refused for good (a wrong API
272
+ * key, an unknown model) is never asked again.
273
+ */
274
+ retry?: Partial<ConversationRetryPolicy>;
110
275
  /**
111
276
  * The answer as data: a zod object, whose JSON the agent replies with
112
277
  * (checked), and `chat` and `prompt` answer with (see output.ts).
@@ -145,9 +310,21 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolRegistration =>
145
310
  * `workspace`, pi's coding tools working there, with the environment they
146
311
  * run in.
147
312
  */
148
- async function extensions(tools: ToolRegistration[], system: string | undefined, workspace: string | undefined) {
313
+ async function extensions(
314
+ tools: ToolRegistration[],
315
+ system: string | undefined,
316
+ workspace: string | undefined,
317
+ afterTools: (conversation: ConversationId) => Promise<void>,
318
+ ) {
149
319
  const registry = createRegistry();
150
320
  registry.install(defineExtension({ name: 'tools', tools }));
321
+ // Once a round's tools are done, before pi places what waits at its end: the messages steered to the turn.
322
+ registry.install(
323
+ defineExtension({
324
+ name: 'steering',
325
+ hooks: [hook(GenerationTask, { afterTools: (_assistant, _results, api) => afterTools(api.conversationId) })],
326
+ }),
327
+ );
151
328
  if (system) registry.install(defineExtension({ name: 'system', sections: [section('system', () => system)] }));
152
329
  if (!workspace) return { registry, env: undefined };
153
330
  await mkdir(workspace, { recursive: true });
@@ -196,7 +373,7 @@ function unanswered(id: string, why: string | null | undefined, detail: unknown,
196
373
  */
197
374
  export const withPi = async <T>(
198
375
  ctx: restate.SessionContext,
199
- { model: named, models, system, tools = [], workspace, serviceTier }: Options,
376
+ { model: named, models, system, tools = [], workspace, serviceTier, retry }: Options,
200
377
  work: (pi: Pi) => Promise<T>,
201
378
  ): Promise<T> => {
202
379
  const model = modelOf(named);
@@ -222,6 +399,19 @@ export const withPi = async <T>(
222
399
  turn?.addEventListener('abort', onStop, { once: true });
223
400
  // The root conversation, once the Harness is open (below).
224
401
  const conversation = () => rootOn(harness, context, model);
402
+ /**
403
+ * Abort the run of a live input of the root conversation that `kept` does
404
+ * not keep: a run a prompt left, whose turn is closed (or the next prompt
405
+ * closes it), is aborted, never finished. pi's own writes (a compaction's)
406
+ * are not runs, and an input without a request id is not a prompt's.
407
+ */
408
+ const abortLeft = async (kept: (requestId: string) => boolean) => {
409
+ const { submissions } = await harness.inspect(context);
410
+ const left = submissions.filter((s) => s.type === 'input' && s.requestId !== undefined && !kept(s.requestId));
411
+ if (left.length === 0) return;
412
+ const root = await conversation();
413
+ if (left.some((s) => s.conversationId === root.id)) await root.abort(context);
414
+ };
225
415
  // A tool call's error: the attempt fails, and the call never returns.
226
416
  const stopped = (error: unknown, task: Context): Promise<never> => {
227
417
  // The turn was cancelled, and the abort ended the call: pi-durable records it.
@@ -234,15 +424,25 @@ export const withPi = async <T>(
234
424
  cancel(error);
235
425
  return awaitWithContext(new Promise<never>(() => {}), context);
236
426
  };
427
+ // The tool calls that returned, whose ends are published once pi stored their results (`prompt`).
428
+ const returned = new Set<string>();
429
+ // The messages steered to the turn of a prompt's run, submitted to pi as a publish lists them (`prompt`).
430
+ let steering: ((of: ConversationId) => Promise<void>) | undefined;
431
+ // Whether a tool of the round asks to end the run (`terminate`, a handoff): pi then ends the round at its final
432
+ // boundary, which would start a run of its own for a message submitted there, outside the turn.
433
+ let ending = false;
237
434
  const tracked = (t: ToolRegistration): ToolRegistration => ({
238
435
  ...t,
239
436
  execute: async (args, api, task) => {
240
437
  try {
241
438
  await toolCallStarted(ctx);
242
439
  const result = await t.execute(args, api, task);
243
- await toolCallEnded(ctx);
440
+ if (result.control?.terminate === true || result.control?.handoff !== undefined) ending = true;
441
+ returned.add(api.callId);
244
442
  return result;
245
443
  } catch (error) {
444
+ // The tool's error: never taken for the model's provider refusing (a tool may call a model API).
445
+ fromTool(ctx, error);
246
446
  return stopped(error, task);
247
447
  }
248
448
  },
@@ -251,55 +451,149 @@ export const withPi = async <T>(
251
451
  tools.map((t) => tracked(isTool(t) ? native(t, ctx) : t)),
252
452
  system,
253
453
  workspace,
454
+ async (of) => {
455
+ // A round that may end the run takes no steered message: each waits for the turn's end, then is a turn of its own.
456
+ const ends = ending;
457
+ ending = false;
458
+ if (!ends) await steering?.(of);
459
+ },
254
460
  );
255
461
  const settings = {
256
462
  // A task that crashes is run again however often Restate retries the attempt (its retry policy decides):
257
463
  // pi-durable would park it after 5 crashes in a row, and the prompt would never be answered.
258
464
  restartLimit: Infinity,
465
+ // A provider's outage never ends the turn: pi asks again until it answers (pi-durable would give up after 3
466
+ // retries, ending the turn unanswered for good). Each retry is committed: a retried attempt waits as it would.
467
+ retry: { maxRetries: Infinity, ...retry },
468
+ // Every message steered to a turn that waits at a step is placed there, not one a step.
469
+ steeringMode: 'all' as const,
259
470
  // pi-durable hands its stream settings to pi-ai's requests as they are: serviceTier is pi-ai's.
260
471
  ...(serviceTier ? { stream: { serviceTier } as ConversationStreamOptions } : {}),
261
472
  };
262
- const harness = await Harness.open(await openSqlKvStorage(ctx.db), { models, registry, env, settings }, context);
473
+ const database = new SqlKvDatabase(ctx.db);
474
+ const harness = await Harness.open(
475
+ await openSqlKvStorage(ctx.db, database),
476
+ { models, registry, env, settings },
477
+ context,
478
+ );
263
479
 
264
- const prompt = async (text: string, id = nextPromptId(ctx)) => {
265
- const root = await conversation();
266
- const submission = await root.submit({ type: 'input', content: text, requestId: id }, context);
267
- const settled = await submission.wait(context);
268
- // A prompt the cancellation's abort ended fails with the cancellation.
269
- if (settled.status !== 'done' || settled.answer === undefined)
270
- throw cancelled ?? unanswered(id, settled.reason, settled.detail, model);
271
- const { answer } = settled;
272
- const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
273
- const reply = entry?.model?.at(-1);
274
- if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
275
- return textOf(reply.content);
480
+ const prompt = (text: string, check?: Check, reminder?: string) => {
481
+ // 0.3.0's `prompt(text, id)` took a prompt's id: from JavaScript, it would
482
+ // fail as the check is called, again at every retry.
483
+ if (check !== undefined && typeof check !== 'function') {
484
+ throw new restate.TerminalError(
485
+ `pi's prompt(text, check) takes a check of the answer, not ${JSON.stringify(check)}: a prompt has an id of its own`,
486
+ );
487
+ }
488
+ return answerOnce(
489
+ ctx,
490
+ text,
491
+ items,
492
+ async (store) => {
493
+ const current = store.turn;
494
+ const id = current.id;
495
+ const root = await conversation();
496
+ // The turn's own request: its prompt, or the message that asked again within it.
497
+ const again = current.latestAsk() !== current.prompt;
498
+ const requestId = again ? `${id}:again` : id;
499
+ // A run an earlier prompt of this invocation left (its turn failed, say). A steered message is its run's.
500
+ await abortLeft((r) => r === id || r === `${id}:again` || r.startsWith('steer:'));
501
+ // Once stopped, the turn's close says how it ended: not pi's abort of its tools.
502
+ // A tool call's end is published once its result is stored, for followers to read it there.
503
+ let ended = false;
504
+ database.onCommit = copying(
505
+ ctx,
506
+ current,
507
+ requestId,
508
+ () => cancelled !== undefined || stopSignalOf(ctx)?.aborted === true,
509
+ (calls) => {
510
+ for (const call of calls) if (returned.delete(call)) ended = true;
511
+ },
512
+ );
513
+ database.afterCommit = async () => {
514
+ if (!ended) return;
515
+ ended = false;
516
+ // Failing, it fails the attempt, as a tool's error does: never pi's commit, which is done.
517
+ await toolCallEnded(ctx).catch((error: unknown) => {
518
+ failed(error);
519
+ cancel(error);
520
+ });
521
+ };
522
+ // Each message steered to the turn, submitted to pi once (keyed by its id, also by a retried attempt)
523
+ // as a round of tool calls is done (`afterTools`): pi places it at the round's end, after its results,
524
+ // as an entry of its own kind, which `copying` stores.
525
+ const given = new Set<string>();
526
+ steering = async (of) => {
527
+ const inbox = inboxOf(ctx);
528
+ // The root conversation's rounds only: it is the turn's.
529
+ if (!inbox || of !== root.id || cancelled !== undefined) return;
530
+ if (stopSignalOf(ctx)?.aborted || !current.writable) return;
531
+ const held = new Set(current.steered().map((e) => e.steer));
532
+ for (const { id: steerId, text: said } of inbox.messages) {
533
+ if (given.has(steerId) || held.has(steerId)) continue;
534
+ given.add(steerId);
535
+ await root.submit(
536
+ {
537
+ type: 'input',
538
+ content: said,
539
+ whenBusy: 'steer',
540
+ requestId: `steer:${steerId}`,
541
+ entry: { kind: STEER_ENTRY, data: { id: steerId } },
542
+ },
543
+ context,
544
+ );
545
+ }
546
+ };
547
+ // The model is told how the turn before this one ended, if its run did not answer it.
548
+ const before = store.transcript.at(-2);
549
+ const note = !again && before && before.status !== 'answered' && before.answer ? `(${before.answer})\n\n` : '';
550
+ // pi keeps the prompt as it is given, the turn's reminder too; the conversation as it was asked.
551
+ const asked = textOf(current.latestAsk().item.message.content) + (again ? '' : (current.reminder ?? ''));
552
+ const submission = await root.submit({ type: 'input', content: note + asked, requestId }, context);
553
+ const settled = await submission.wait(context);
554
+ // A prompt the cancellation's abort ended fails with the cancellation.
555
+ if (settled.status !== 'done' || settled.answer === undefined)
556
+ throw cancelled ?? unanswered(id, settled.reason, settled.detail, model);
557
+ const { answer } = settled;
558
+ const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);
559
+ const reply = entry?.model?.at(-1);
560
+ if (!reply) throw new restate.TerminalError(`prompt ${id}: no answer entry`);
561
+ return textOf(reply.content);
562
+ },
563
+ // pi keeps the model's history: the conversation reads only its latest turns.
564
+ { check, reminder, ownHistory: true },
565
+ );
276
566
  };
277
- // `failure`, once it comes; a cancellation first aborts the conversation's work.
567
+ // `failure`, once it comes. A cancellation aborts the conversation's work
568
+ // instead: the work ends with it (a prompt closes its turn, cancelled).
278
569
  const abortOn = async (): Promise<never> => {
279
570
  try {
280
571
  return await failure;
281
572
  } catch (error) {
282
- if (error instanceof restate.CancelledError) await (await conversation()).abort(context);
283
- throw error;
573
+ if (!(error instanceof restate.CancelledError)) throw error;
574
+ await (await conversation()).abort(context);
575
+ return new Promise<never>(() => {});
284
576
  }
285
577
  };
286
578
 
579
+ // Whatever `work` does (a prompt, a compaction, a wait) has pi schedule
580
+ // what it has: a run another invocation left is aborted first. This
581
+ // invocation's own (a retried attempt's) goes on.
582
+ const working = async () => {
583
+ await abortLeft((r) => invocationOf(r) === ctx.request.id || r.startsWith('steer:'));
584
+ return work({ harness, context, conversation, prompt });
585
+ };
287
586
  try {
288
- // The log reads the root conversation through this Harness, while it is open.
289
- const read = async () => transcribe(ctx, await harness.root(context), context);
290
- return await transcribing(ctx, read, () =>
291
- Promise.race([abortOn(), work({ harness, context, conversation, prompt })]),
292
- );
587
+ const done = await Promise.race([abortOn(), working()]);
588
+ // Work the cancellation's abort ended (a wait for pi, say) fails with it, as a prompt does.
589
+ if (cancelled) throw cancelled;
590
+ return done;
293
591
  } finally {
294
592
  turn?.removeEventListener('abort', onStop);
295
593
  await harness.close(withoutAbortSignal(context));
296
594
  }
297
595
  };
298
596
 
299
- /** {@link prompt}, answering with the agent's text. */
300
- const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
301
- withPi(ctx, options, (session) => session.prompt(text));
302
-
303
597
  /**
304
598
  * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
305
599
  * of an invocation is a prompt of its own.
@@ -310,7 +604,10 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
310
604
  ctx: restate.SessionContext,
311
605
  text: string,
312
606
  options: Options<O> = {},
313
- ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
607
+ ): Promise<Answer<O>> =>
608
+ withChecked(text, options, (t, o, check, reminder) =>
609
+ withPi(ctx, o, (session) => session.prompt(t, check, reminder)),
610
+ ) as Promise<Answer<O>>;
314
611
 
315
612
  /**
316
613
  * A chat handler: each message an invocation, the conversation in the
@@ -320,48 +617,15 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
320
617
  */
321
618
  export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
322
619
  if (typeof options === 'object') checkModelName('pi', options.model);
323
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
620
+ return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)), { steers: true });
324
621
  };
325
622
 
326
623
  /**
327
- * A handler of the conversation as clients read it: a page at a time, or
328
- * what is new or changed since a cursor, from the log each change writes
329
- * (log.ts). It answers while a message is answered.
330
- */
331
- export const messages = () => messagesHandler();
332
-
333
- /**
334
- * The transcript of each session's root conversation (`ctx.db`, one per
335
- * attempt), as far as it was read, to its last entry. pi-durable's entries
336
- * never change, and a new one takes a greater id than any before it (they
337
- * are committed one at a time), so each read adds the entries after it.
624
+ * A view of the conversation as clients read it: a page at a time, or what
625
+ * is new or changed since a cursor; `view: 'summary'` for each turn's
626
+ * message and answer. It answers while a message is answered.
338
627
  */
339
- const TRANSCRIPT = new ScopeKey<{ last?: EntryId; transcript: Transcript }>('the transcript');
340
-
341
- /** The root conversation in the database of `ctx`, `root` of a Harness on it, from pi-durable's entries, as `messages` gives it. */
342
- const transcribe = async (ctx: restate.SessionContext, root: Conversation, context: Context) => {
343
- const read = TRANSCRIPT.of(ctx, () => ({ transcript: new Transcript() }));
344
- const { transcript } = read;
345
- // From the last entry read (the bound is inclusive), or the first.
346
- const query = { order: 'ascending' as const, ...(read.last === undefined ? {} : { minEntryId: read.last }) };
347
- for (let cursor: Parameters<typeof root.entries>[2]; ;) {
348
- const page = await root.entries(query, 100, cursor, context);
349
- for (const entry of page.items) {
350
- if (entry.id === read.last) continue;
351
- read.last = entry.id;
352
- for (const m of entry.model ?? []) {
353
- if (m.role === 'user') transcript.say('user', textOf(m.content));
354
- if (m.role === 'assistant') {
355
- transcript.say('assistant', textOf(m.content));
356
- for (const c of m.content) if (c.type === 'toolCall') transcript.call(c.id, c.name, c.arguments);
357
- }
358
- if (m.role === 'toolResult') transcript.result(m.toolCallId, textOf(m.content), m.isError);
359
- }
360
- }
361
- cursor = page.next;
362
- if (cursor === undefined) return transcript;
363
- }
364
- };
628
+ export const messages = () => conversationView(items);
365
629
 
366
630
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
367
631
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -369,6 +633,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
369
633
  description,
370
634
  schema,
371
635
  background,
636
+ window,
637
+ budget,
372
638
  ...options
373
639
  }: Options<O> & Definition<P>) =>
374
640
  sessionObject({
@@ -376,6 +642,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
376
642
  description,
377
643
  schema,
378
644
  background,
645
+ window,
646
+ budget,
379
647
  handlers: { chat: chat(options) },
380
648
  views: { messages: messages() },
381
649
  });
package/src/pi/storage.ts CHANGED
@@ -10,7 +10,7 @@
10
10
  //
11
11
  // pi-durable's tables and indexes are named `restate_pi_<name>` (its
12
12
  // storage's `prefix`), apart from the tables of yours in the same database.
13
- import type { DatabaseWriter, Database } from '@restatedev/sessions';
13
+ import type { DatabaseWriter, Database, Transaction } from '@restatedev/sessions';
14
14
  import {
15
15
  SqliteStorage,
16
16
  type SqliteDatabase,
@@ -41,9 +41,16 @@ class Executor implements SqliteExecutor {
41
41
  }
42
42
  }
43
43
 
44
+ /** What runs at the end of each pi commit, in its transaction: the copy of its entries (index.ts). */
45
+ export type OnCommit = (tx: Transaction) => Promise<void>;
46
+
44
47
  /** The `SqliteDatabase` facade over the session `db`. */
45
- class SqlKvDatabase extends Executor implements SqliteDatabase {
48
+ export class SqlKvDatabase extends Executor implements SqliteDatabase {
46
49
  readonly #session: Database;
50
+ /** Runs at the end of each commit, in its transaction, so that what it writes commits with it. */
51
+ onCommit: OnCommit | undefined;
52
+ /** Runs once each commit is done, outside its transaction: to tell others what it stored, say. */
53
+ afterCommit: (() => Promise<void>) | undefined;
47
54
 
48
55
  constructor(db: Database) {
49
56
  super(db);
@@ -51,15 +58,21 @@ class SqlKvDatabase extends Executor implements SqliteDatabase {
51
58
  }
52
59
 
53
60
  /** Commits when the callback resolves; rolls back, and rejects with its error, when it rejects. */
54
- transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
55
- return this.#session.transaction((tx) => callback(new Executor(tx)));
61
+ async transaction<T>(callback: (transaction: SqliteExecutor) => Promise<T>): Promise<T> {
62
+ const result = await this.#session.transaction(async (tx) => {
63
+ const done = await callback(new Executor(tx));
64
+ if (this.onCommit) await this.onCommit(tx);
65
+ return done;
66
+ });
67
+ if (this.afterCommit) await this.afterCommit();
68
+ return result;
56
69
  }
57
70
 
58
71
  /** The session is the caller's to end, after the calls made before. */
59
72
  async close() {}
60
73
  }
61
74
 
62
- /** Open pi-durable storage on the session `db`. */
63
- export function openSqlKvStorage(db: Database): Promise<SqliteStorage> {
64
- return SqliteStorage.open(new SqlKvDatabase(db), { prefix: PREFIX });
75
+ /** Open pi-durable storage on the session `db`, through `database`, its facade, if given (to set its `onCommit`). */
76
+ export function openSqlKvStorage(db: Database, database = new SqlKvDatabase(db)): Promise<SqliteStorage> {
77
+ return SqliteStorage.open(database, { prefix: PREFIX });
65
78
  }