@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
@@ -1,5 +1,8 @@
1
1
  // DeepSeek Harness agents in Restate virtual objects: the session (the
2
- // harness's event log) is in the object's database (persistence.ts).
2
+ // harness's event log) is in the object's database (persistence.ts), and
3
+ // each of its flushes copies the turn's new messages into the conversation of
4
+ // turns (../conversation.ts) in the same transaction: the harness keeps its
5
+ // own history, and the conversation is what clients read, and how turns end.
3
6
  //
4
7
  // const assistant = deepseek.agent({ name: 'assistant', tools: [weather] });
5
8
  //
@@ -27,18 +30,26 @@
27
30
  // - A message is answered once per invocation: its message carries the
28
31
  // invocation id, and a retried attempt returns the answer of the turn that
29
32
  // finished it.
33
+ // - A tool call that needs a person's approval (`approval`) waits for the
34
+ // signal `approval` before it runs: the harness asks its approval service
35
+ // (@deepseek-ai/dsh-user-approval), which this answers with a wait
36
+ // (`waitFor` of ../tools.ts). The wait is opened once: a crash, or a
37
+ // suspension, has the model make the call again, which joins it.
30
38
  import * as restate from '@restatedev/sessions';
31
- import type { Database } from '@restatedev/sessions';
32
39
  import { Context } from '@deepseek-ai/cordis';
33
40
  import { AgentRegistry } from '@deepseek-ai/dsh-agent';
34
41
  import { AgentLoop } from '@deepseek-ai/dsh-agent-loop';
35
42
  import * as deepseek from '@deepseek-ai/dsh-llm-deepseek-api-key';
36
43
  import * as piAi from '@deepseek-ai/dsh-llm-pi-ai';
37
- import { LlmRuntime, MessageId, freezeMessage, type Message, type UserMessage } from '@deepseek-ai/dsh-llm';
44
+ import { LlmRuntime, MessageId, ToolCallId, freezeMessage, type Message, type UserMessage } from '@deepseek-ai/dsh-llm';
38
45
  import { SessionId, SessionStore, type SessionEvent } from '@deepseek-ai/dsh-session';
39
46
  import * as checkpoints from '@deepseek-ai/dsh-session-checkpoint-policy';
40
47
  import { SessionProjectionRegistry } from '@deepseek-ai/dsh-session-projection';
41
48
  import { SystemPrompt } from '@deepseek-ai/dsh-system-prompt';
49
+ import { TokenMeter } from '@deepseek-ai/dsh-token-meter';
50
+ import { ToolResultPruner } from '@deepseek-ai/dsh-compaction-tool-result-pruner';
51
+ import { BasicCompactionEngine, type BasicCompactionConfig } from '@deepseek-ai/dsh-compaction-basic';
52
+ import { ApprovalService, type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval';
42
53
  import { builtinProviders } from '@earendil-works/pi-ai/providers/all';
43
54
  import {
44
55
  defineTool,
@@ -51,31 +62,28 @@ import {
51
62
  } from '@deepseek-ai/dsh-tools';
52
63
  import {
53
64
  aborted,
54
- CANCELLED,
55
65
  chatHandler,
56
66
  checkModelName,
57
67
  type Configure,
58
68
  configured,
59
69
  fromTool,
60
- messagesHandler,
70
+ inboxOf,
61
71
  ModelError,
62
72
  modelOf,
63
- nextPromptId,
64
73
  providerOf,
65
- refusal,
74
+ RETURNED_UNRECORDED,
66
75
  stopSignalOf,
67
- storedAnswer,
68
76
  toolCallEnded,
69
77
  toolCallStarted,
70
- transcribing,
71
- Transcript,
72
- UNANSWERED,
73
78
  } from '../common.ts';
74
- import { type Answer, withOutput } from '../output.ts';
79
+ import { answerOnce, type Items, type Parsed, type Run, type Turn } from '../conversation.ts';
80
+ import { tookSteers } from '../steering.ts';
81
+ import { conversationView } from '../messages.ts';
82
+ import { type Answer, withChecked } from '../output.ts';
75
83
  import { type Definition, sessionObject } from '../object.ts';
76
- import { isTool, jsonSchemaOf, type Tool as AnyTool } from '../tools.ts';
84
+ import { isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
77
85
  import type { z } from 'zod';
78
- import { SqlSessionPersistence, storedEvents } from './persistence.ts';
86
+ import { SqlSessionPersistence } from './persistence.ts';
79
87
 
80
88
  export { SqlSessionPersistence };
81
89
 
@@ -123,19 +131,37 @@ function routeOf(model: string): Route {
123
131
 
124
132
  /**
125
133
  * The harness, its session in `db`: the services
126
- * an agent loop needs, the persistence and its checkpoints, and the provider
127
- * of `route`.
134
+ * an agent loop needs, the persistence and its checkpoints, compaction (with
135
+ * `compaction`'s settings), the provider of `route`, and with `approvals`
136
+ * the approval service, which asks before a tool call that needs a person's
137
+ * approval runs (see {@link approving}).
128
138
  */
129
- async function boot(db: restate.Database, route: Route, system?: string): Promise<Context> {
139
+ async function boot(
140
+ db: restate.Database,
141
+ route: Route,
142
+ system?: string,
143
+ compaction: BasicCompactionConfig = {},
144
+ approvals = false,
145
+ ): Promise<Context> {
130
146
  const harness = new Context();
131
147
  await harness.plugin(LlmRuntime);
132
148
  await harness.plugin(SessionStore);
133
149
  await harness.plugin(SystemPrompt, system ? { personaPrefix: system } : {});
134
150
  await harness.plugin(ToolRuntime, {});
151
+ // Without it, the harness denies a call that asks for an approval. With it,
152
+ // the model is also told that some calls may ask for one.
153
+ if (approvals) await harness.plugin(ApprovalService, {});
135
154
  await harness.plugin(AgentRegistry);
136
155
  await harness.plugin(SessionProjectionRegistry);
137
156
  await harness.plugin(SqlSessionPersistence, { db });
138
157
  await harness.plugin(checkpoints);
158
+ // The model's input stays within its context window: as it nears the
159
+ // window (or overflows it), the oldest history is condensed into a summary,
160
+ // one more model request, after oversized tool results are trimmed. The
161
+ // log keeps every event, and the conversation of turns every message.
162
+ await harness.plugin(TokenMeter);
163
+ await harness.plugin(ToolResultPruner);
164
+ await harness.plugin(BasicCompactionEngine, compaction);
139
165
  // DeepSeek's with DEEPSEEK_API_KEY; another's with the key pi-ai finds for it (OPENAI_API_KEY...).
140
166
  if (route.provider === 'deepseek-official') await harness.plugin(deepseek, {});
141
167
  else await harness.plugin(piAi, { providers: { [route.provider]: {} } });
@@ -150,37 +176,34 @@ const promptId = (id: string) => MessageId(`prompt:${id}`);
150
176
  const textOf = (message: Message) => message.content.flatMap((c) => (c.type === 'text' ? [c.text] : [])).join('');
151
177
 
152
178
  /**
153
- * The answer to prompt `id` in the session log: the last reply of the first
154
- * turn completed after it, {@link CANCELLED} if a cancellation aborted its
155
- * turn, or {@link UNANSWERED} if the model's provider refused it for good;
156
- * undefined while it is absent or unfinished (a crash's interrupted turn, or
157
- * one that failed otherwise, is continued).
179
+ * How the harness's turn of prompt `id` ended in the session log: the last
180
+ * reply of its first harness turn that completed (`answer`), or a failure
181
+ * (`error`); none while it is absent (`asked: false`) or was interrupted (a
182
+ * crash), when it is continued.
158
183
  */
159
- function answerOf(events: readonly SessionEvent[], id: MessageId): string | undefined {
184
+ function endOf(events: readonly SessionEvent[], id: MessageId) {
160
185
  const at = events.findIndex((e) => e.type === 'user/message' && e.data.id === id);
161
- if (at < 0) return undefined;
186
+ if (at < 0) return { asked: false as const };
162
187
  let answer: string | undefined;
188
+ let error: unknown;
163
189
  for (const e of events.slice(at)) {
164
190
  if (e.type === 'assistant/message') answer = textOf(e.data.message);
165
191
  if (e.type !== 'turn/end') continue;
166
192
  const { reason } = e.data;
167
- if (reason.kind === 'completed') return answer ?? '';
168
- if (reason.kind === 'aborted' && reason.reason.kind === 'user') return CANCELLED;
169
- if (reason.kind === 'error' && refusal(turnError(reason.error))) return UNANSWERED;
193
+ if (reason.kind === 'completed') return { asked: true as const, answer: answer ?? '' };
194
+ // A failed harness turn, continued after (by a retry), or the last.
195
+ error = reason.kind === 'error' ? reason.error : undefined;
170
196
  }
171
- return undefined;
197
+ return { asked: true as const, error };
172
198
  }
173
199
 
174
- /** The error a turn failed with, as the attempt fails with it (see {@link throwIfTurnFailed}). */
175
- const turnError = (error: unknown) => new Error(`the agent's turn failed: ${JSON.stringify(error)}`);
176
-
177
- /** The last prompt in the session log, by id. */
178
- function lastPrompt(events: readonly SessionEvent[]): MessageId | undefined {
179
- const prompt = events.findLast(
180
- (e): e is SessionEvent<'user/message'> => e.type === 'user/message' && e.data.id.startsWith('prompt:'),
181
- );
182
- return prompt?.data.id;
183
- }
200
+ /** The error a harness turn failed with: terminal for an overflow of the model's context, which a retry meets again. */
201
+ const turnError = (error: unknown) => {
202
+ const message = `the agent's turn failed: ${JSON.stringify(error)}`;
203
+ return /context.?length|context_length_exceeded|context window|maximum context/i.test(message)
204
+ ? new restate.TerminalError(message)
205
+ : new Error(message);
206
+ };
184
207
 
185
208
  const message = (id: string, text: string): UserMessage =>
186
209
  freezeMessage({ id: MessageId(id), role: 'user', content: [{ type: 'text', text }], source: { kind: 'user' } });
@@ -255,6 +278,72 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolDefinition =>
255
278
  },
256
279
  });
257
280
 
281
+ /** The signal that a tool call waits for, to the agent, when it needs a person's approval (`approval`). */
282
+ export const APPROVAL = 'approval';
283
+
284
+ /** Which tool calls wait for a person's approval: the names of their tools, or a function of a call that says whether it does. */
285
+ export type Approval = readonly string[] | ((call: { name: string; args: unknown }) => boolean);
286
+
287
+ /** The texts that approve a tool call, whatever their case. */
288
+ const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
289
+
290
+ /**
291
+ * What the value of an {@link APPROVAL} signal decides about its tool call:
292
+ * `true`, `{ "approved": true }`, or a text such as "approved" or "yes"
293
+ * approves it once; anything else rejects it, so a value that does not say
294
+ * "approved" never runs the tool.
295
+ */
296
+ const decided = (value: unknown): ApprovalOutcome =>
297
+ value === true ||
298
+ (typeof value === 'string' && APPROVED.has(value.trim().toLowerCase())) ||
299
+ (typeof value === 'object' && value !== null && (value as { approved?: unknown }).approved === true)
300
+ ? 'allowed-once'
301
+ : 'rejected';
302
+
303
+ /**
304
+ * Have the harness of the agent of `agentCtx` ask for an approval before
305
+ * each tool call that `approval` names (`tools/pre-execute`, once the call
306
+ * is allowed otherwise), and answer each ask (`approval/request`) with a
307
+ * person's decision: a wait for the signal {@link APPROVAL} (`waitFor`),
308
+ * which `pending` shows with the call's tool and arguments, without holding
309
+ * a process.
310
+ *
311
+ * A crash, or a suspension, ends the attempt before the harness stored the
312
+ * call: the retry asks the model again, which makes the call again under a
313
+ * new id. Made with the same arguments, it joins the wait (`rejoin`): the
314
+ * person is asked once. The wait is an approval (`approval`): a stopped
315
+ * turn does not report its call as done because it was approved. An error
316
+ * of the wait fails the attempt (`fail`), and its ask never ends: the
317
+ * harness does not go on without a decision.
318
+ */
319
+ function approving(agentCtx: Context, ctx: restate.SessionContext, approval: Approval, fail: (error: unknown) => void) {
320
+ const needs = typeof approval === 'function' ? approval : ({ name }: { name: string }) => approval.includes(name);
321
+ // The calls asked about, by id: what `pending` shows of each.
322
+ const asked = new Map<string, { tool: string; args: unknown }>();
323
+ agentCtx.on('tools/pre-execute', async (exec, next) => {
324
+ const decision = await next();
325
+ if (decision.kind !== 'allow' || !needs({ name: exec.name, args: exec.arguments })) return decision;
326
+ asked.set(exec.callId, { tool: exec.name, args: exec.arguments });
327
+ return { kind: 'ask' };
328
+ });
329
+ agentCtx.on('approval/request', async ({ callId }, next) => {
330
+ const call = callId === undefined ? undefined : asked.get(callId);
331
+ // Asked by another (none is mounted): no one answers, and the harness denies it.
332
+ if (callId === undefined || call === undefined) return next();
333
+ asked.delete(callId);
334
+ try {
335
+ // The calls whose results are stored are forgotten first: an earlier
336
+ // attempt's call with the same arguments, approved and done, is not this one.
337
+ await toolCallStarted(ctx);
338
+ return decided(await waitFor(ctx, callId, APPROVAL, call, { approval: true, rejoin: true }));
339
+ } catch (error) {
340
+ fromTool(ctx, error);
341
+ fail(error);
342
+ return new Promise<never>(() => {});
343
+ }
344
+ });
345
+ }
346
+
258
347
  /** An agent's options: `chat` and `prompt` take them. */
259
348
  export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
260
349
  /**
@@ -266,6 +355,22 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
266
355
  system?: string;
267
356
  /** The agent's tools: `tool()`s, Restate's (`call`, `signal`...), or the harness's (`defineTool`). */
268
357
  tools?: (AnyTool | ToolDefinition)[];
358
+ /**
359
+ * The tool calls that wait for a person's approval before they run: the
360
+ * names of their tools, or a function of a call (its tool's name, and its
361
+ * arguments) that says whether it does. Each waits for the signal
362
+ * {@link APPROVAL} to the agent, which `pending` shows with the call's
363
+ * tool and arguments; `true`, or a text such as "approved" or "yes",
364
+ * approves it, anything else denies it.
365
+ */
366
+ approval?: Approval;
367
+ /**
368
+ * When the model's input is condensed: the settings of the harness's
369
+ * compaction (@deepseek-ai/dsh-compaction-basic), such as `thresholdRatio`
370
+ * (by default 0.8 of the model's context window) and `retainRatio` (the
371
+ * newest 0.16 kept as it is).
372
+ */
373
+ compaction?: BasicCompactionConfig;
269
374
  /**
270
375
  * The answer as data: a zod object, whose JSON the agent replies with
271
376
  * (checked), and `chat` and `prompt` answer with (see output.ts).
@@ -273,91 +378,235 @@ export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undef
273
378
  output?: O;
274
379
  }
275
380
 
276
- /** {@link prompt}, answering with the agent's text. */
277
- const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
278
- transcribing(
279
- ctx,
280
- () => transcribe(ctx.db, ctx.key),
281
- () => answerOnce(ctx, text, options),
282
- );
381
+ /**
382
+ * DeepSeek's items, as the conversation of turns keeps them: the harness's
383
+ * messages. A user's text is said by the user; an assistant's by the
384
+ * assistant, with its tool calls; a tool message is a result.
385
+ */
386
+ export const items: Items<Message> = {
387
+ dump: (m) => JSON.stringify(m),
388
+ load: (stored) => {
389
+ // Only a harness's message (an id, a role, a list of content parts): another framework's row is not one.
390
+ const m = JSON.parse(stored) as Message;
391
+ if (typeof m.id !== 'string' || typeof m.role !== 'string' || !Array.isArray(m.content))
392
+ throw new Error("not a DeepSeek harness's message (an id, a role and a list of content parts)");
393
+ return freezeMessage(m);
394
+ },
395
+ prompt: (text) => message('prompt', text),
396
+ reply: (text) =>
397
+ freezeMessage({
398
+ id: MessageId('reply'),
399
+ role: 'assistant',
400
+ content: [{ type: 'text', text }],
401
+ source: { kind: 'model', provider: 'restate', model: 'note' },
402
+ }),
403
+ results: (results) =>
404
+ results.map(([call, output]) =>
405
+ freezeMessage({
406
+ id: MessageId(`result:${call.id}`),
407
+ role: 'tool',
408
+ toolCallId: ToolCallId(call.id),
409
+ content: [{ type: 'text', text: output }],
410
+ source: { kind: 'tool', callId: ToolCallId(call.id) },
411
+ isError: output !== RETURNED_UNRECORDED,
412
+ }),
413
+ ),
414
+ read: (m): Parsed => {
415
+ if (m.role === 'user') return { said: ['user', textOf(m)] };
416
+ if (m.role === 'assistant') {
417
+ const calls = m.content.flatMap((c) =>
418
+ c.type === 'tool-call' ? [{ id: c.id, name: c.name, input: parsedJson(c.arguments) }] : [],
419
+ );
420
+ // Each reply is a message of its own, its tool calls' too.
421
+ return { said: ['assistant', textOf(m)], calls };
422
+ }
423
+ if (m.role === 'tool') return { results: [{ id: m.toolCallId, output: textOf(m), error: m.isError === true }] };
424
+ return {};
425
+ },
426
+ };
283
427
 
284
428
  /** An agent of the harness, on a session. */
285
429
  type Agent = Awaited<ReturnType<Context['agents']['create']>>['agent'];
286
430
 
287
- const answerOnce = async (
288
- ctx: restate.SessionContext,
289
- text: string,
290
- { model: named, system, tools = [] }: Options,
291
- ): Promise<string> => {
292
- const id = nextPromptId(ctx);
293
- const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
294
- const harness = await boot(ctx.db, route, system);
295
- // A tool's error fails the attempt, which Restate retries: the harness
296
- // stores nothing more, so the retry finds the tool's call without a result.
297
- // The turn's stop fails it too: a cancellation (below), or an attempt that
298
- // ended first.
299
- const { promise: failed, reject: fail } = Promise.withResolvers<never>();
300
- failed.catch(() => {});
301
- const turn = stopSignalOf(ctx);
302
- const onStop = () => fail(turn!.reason);
303
- turn?.addEventListener('abort', onStop, { once: true });
304
- let agent: Agent | undefined;
305
- try {
306
- const sessionId = SessionId(ctx.key);
307
- const options = {
308
- agentOptions: route,
309
- setup: (agentCtx: Context) => {
310
- for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail));
311
- },
312
- };
313
- // Resuming closes a turn a crash left open.
314
- const started = (await harness.sessionPersistence.stat(sessionId))
315
- ? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
316
- : await harness.agents.create({ sessionId, ...options });
317
- agent = started.agent;
318
- const answer = await answered(harness, agent, id, text, failed);
319
- return answer;
320
- } catch (e) {
321
- // A cancelled invocation cancels the agent's turn, which the log keeps.
322
- if (e instanceof restate.CancelledError && agent) await cancelTurn(harness, agent);
323
- else (harness.sessionPersistence as SqlSessionPersistence).abandon();
324
- throw e;
325
- } finally {
326
- turn?.removeEventListener('abort', onStop);
327
- await harness.fiber.dispose();
328
- }
329
- };
330
-
331
431
  /**
332
- * The answer of prompt `id`, `text`, asked once: a prompt left unfinished
333
- * (this one's, after a crash) is finished first, then this one starts.
432
+ * The harness's message of `turn`'s prompt: its text, after how the turn
433
+ * before it ended if its run did not answer it (stopped, refused, failed,
434
+ * or ended once its invocation was gone), which the harness's log does not
435
+ * say.
334
436
  */
335
- async function answered(harness: Context, agent: Agent, id: string, text: string, failed: Promise<never>) {
336
- // The log as this attempt found it: a turn that failed before is continued like an interrupted one.
337
- const found = agent.session.snapshotEvents().length;
338
- for (;;) {
339
- const events = agent.session.snapshotEvents();
340
- // First: a prompt refused in this attempt fails it, rather than answer.
341
- throwIfTurnFailed(events.slice(found));
342
- const answer = answerOf(events, promptId(id));
343
- if (answer !== undefined) return storedAnswer(answer);
344
- const last = lastPrompt(events);
345
- const unfinished = last !== undefined && answerOf(events, last) === undefined;
346
- agent.followup(unfinished ? message(`continue:${events.length}`, CONTINUE) : message(promptId(id), text));
347
- await Promise.race([agent.whenIdle(), failed]);
348
- await harness.sessions.flush(agent.session);
349
- }
437
+ function promptOf(turn: Turn<Message>, before: { status?: string; answer?: string } | undefined) {
438
+ const text = textOf(turn.prompt.item);
439
+ const note = before && before.status !== 'answered' && before.answer ? `(${before.answer})\n\n` : '';
440
+ // The harness keeps the prompt as it is given, the turn's reminder too; the conversation as it was asked.
441
+ return message(promptId(turn.id), note + text + (turn.reminder ?? ''));
350
442
  }
351
443
 
444
+ /** The id of the harness's message of the message `id` steered to a turn. */
445
+ const steerMessageId = (id: string) => `steer:${id}`;
446
+
447
+ /** The id of the steered message whose harness message has the id `messageId`, if it is one. */
448
+ const steeredId = (messageId: string) => (messageId.startsWith('steer:') ? messageId.slice(6) : undefined);
449
+
352
450
  /**
353
- * Fail the attempt if a turn of `events` (this attempt's) failed: its model
354
- * request, or a checkpoint. Its end may be stored already, so only this
355
- * attempt's turns count: the retry asks the model again.
451
+ * Copy the events of `batch` that are `turn`'s (after its latest ask, at seq
452
+ * `from()` of the log) into it, in `tx`: the model's replies, the tools'
453
+ * results, and the messages steered to the turn that the harness placed at
454
+ * a step (whose companion is told they are taken, in `tx`). Not the requests
455
+ * to continue (a step of the run's own), nor anything once the run stopped
456
+ * or `failed()` (the harness's result of a tool that failed the attempt, or
457
+ * was cancelled, is not the call's): the turn's close, or the retry, says
458
+ * how it ended. `resulted` gets the calls whose results it copied.
356
459
  */
357
- function throwIfTurnFailed(events: readonly SessionEvent[]) {
358
- const end = events.findLast((e): e is SessionEvent<'turn/end'> => e.type === 'turn/end')?.data.reason;
359
- if (end?.kind === 'error') throw turnError(end.error);
360
- }
460
+ const copying =
461
+ (
462
+ ctx: restate.SessionContext,
463
+ turn: Turn<Message>,
464
+ from: () => number | undefined,
465
+ failed: () => boolean,
466
+ resulted: (calls: string[]) => void,
467
+ ) =>
468
+ async (tx: Parameters<NonNullable<SqlSessionPersistence['copy']>>[0], batch: readonly SessionEvent[]) => {
469
+ const start = from();
470
+ if (start === undefined || failed() || stopSignalOf(ctx)?.aborted || !turn.writable) return;
471
+ const held = new Set(turn.steered().map((e) => e.steer));
472
+ const copied = batch.flatMap((e): { item: Message; reply?: boolean; steer?: string }[] => {
473
+ if (e.seq <= start) return [];
474
+ if (e.type === 'assistant/message') return [{ item: e.data.message, reply: true }];
475
+ if (e.type === 'tool/result') return [{ item: e.data.message }];
476
+ if (e.type !== 'user/message') return [];
477
+ const steer = steeredId(e.data.id);
478
+ return steer === undefined || held.has(steer) ? [] : [{ item: e.data, steer }];
479
+ });
480
+ if (copied.length === 0) return;
481
+ await turn.copyIn(tx, copied);
482
+ tookSteers(
483
+ ctx,
484
+ tx,
485
+ copied.flatMap(({ steer }) => (steer === undefined ? [] : [steer])),
486
+ );
487
+ resulted(batch.flatMap((e) => (e.seq > start && e.type === 'tool/result' ? [e.data.message.toolCallId] : [])));
488
+ };
489
+
490
+ /**
491
+ * The run of the harness of `options`, on the conversation: its turn's
492
+ * latest ask (its prompt, or the message that asked again) asked once, and
493
+ * continued after a crash.
494
+ */
495
+ const runOf =
496
+ (ctx: restate.SessionContext, { model: named, system, tools = [], compaction, approval }: Options): Run<Message> =>
497
+ async (conversation) => {
498
+ const turn = conversation.turn;
499
+ const route = routeOf(modelOf(named, DEEPSEEK_MODEL));
500
+ const harness = await boot(ctx.db, route, system, compaction, approval !== undefined);
501
+ const persistence = harness.sessionPersistence as SqlSessionPersistence;
502
+ // A tool's error fails the attempt, which Restate retries: the harness
503
+ // stores nothing more, so the retry finds the tool's call without a result.
504
+ // The turn's stop fails it too: a cancellation, or an attempt that ended first.
505
+ const { promise: failed, reject } = Promise.withResolvers<never>();
506
+ failed.catch(() => {});
507
+ let broken = false;
508
+ const fail = (error: unknown) => {
509
+ broken = true;
510
+ reject(error);
511
+ };
512
+ const stop = stopSignalOf(ctx);
513
+ const onStop = () => fail(stop!.reason);
514
+ stop?.addEventListener('abort', onStop, { once: true });
515
+ let agent: Agent | undefined;
516
+ let unlisten: (() => void) | undefined;
517
+ // The turn asked again (its output's check, say): the harness is asked that, and answers it.
518
+ const asked = turn.latestAsk();
519
+ const again = asked !== turn.prompt;
520
+ const id = again ? MessageId(`prompt:${turn.id}:again`) : promptId(turn.id);
521
+ // Where the turn's latest ask is in the log, once it is.
522
+ let from: number | undefined;
523
+ // The tool calls that returned, whose ends are published once a flush stored their results.
524
+ const returned = new Set<string>();
525
+ try {
526
+ const sessionId = SessionId(ctx.key);
527
+ const options = {
528
+ agentOptions: route,
529
+ setup: (agentCtx: Context) => {
530
+ for (const t of tools) agentCtx.tools.register(tracked(isTool(t) ? native(t, ctx) : t, ctx, fail, returned));
531
+ if (approval !== undefined) approving(agentCtx, ctx, approval, fail);
532
+ },
533
+ };
534
+ // Resuming closes a harness turn a crash, or a killed invocation, left open.
535
+ const started = (await persistence.stat(sessionId))
536
+ ? await harness.agents.resume({ resumeSessionId: sessionId, ...options })
537
+ : await harness.agents.create({ sessionId, ...options });
538
+ agent = started.agent;
539
+ const found = agent.session.snapshotEvents().length;
540
+ from = agent.session.snapshotEvents().find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
541
+ // A tool call's end is published once a flush stored its result, for followers to read it there.
542
+ let ended = false;
543
+ // The harness messages of the steered messages in the log: those before this attempt, and each flush's.
544
+ const placed = new Set(
545
+ agent.session
546
+ .snapshotEvents()
547
+ .flatMap((e) => (e.type === 'user/message' && steeredId(e.data.id) !== undefined ? [String(e.data.id)] : [])),
548
+ );
549
+ persistence.copy = async (tx, batch) => {
550
+ for (const e of batch)
551
+ if (e.type === 'user/message' && steeredId(e.data.id) !== undefined) placed.add(e.data.id);
552
+ from ??= batch.find((e) => e.type === 'user/message' && e.data.id === id)?.seq;
553
+ await copying(
554
+ ctx,
555
+ turn,
556
+ () => from,
557
+ () => broken,
558
+ (calls) => {
559
+ for (const call of calls) if (returned.delete(call)) ended = true;
560
+ },
561
+ )(tx, batch);
562
+ };
563
+ persistence.flushed = async () => {
564
+ if (!ended) return;
565
+ ended = false;
566
+ // Failing, it fails the attempt, as a tool's error does: never the flush, which is done.
567
+ await toolCallEnded(ctx).catch(fail);
568
+ };
569
+ // The messages steered to the turn, handed to the harness's step inbox as a publish lists them: only
570
+ // while a tool call runs or its result is stored, so that a step after them places them, in this turn.
571
+ const harnessAgent = agent;
572
+ const given = new Set<string>();
573
+ unlisten = inboxOf(ctx)?.listen(() => {
574
+ if (stop?.aborted || broken) return;
575
+ const pending = new Set(harnessAgent.inbox.nextStep.map((m) => String(m.id)));
576
+ for (const { id: steerId, text } of inboxOf(ctx)!.messages) {
577
+ const messageId = steerMessageId(steerId);
578
+ if (given.has(steerId) || pending.has(messageId) || placed.has(messageId)) continue;
579
+ given.add(steerId);
580
+ harnessAgent.steer(message(messageId, text));
581
+ }
582
+ });
583
+ // The turn before this one, as the conversation has it.
584
+ const before = conversation.transcript.at(-2);
585
+ for (;;) {
586
+ const events = agent.session.snapshotEvents();
587
+ const end = endOf(events, id);
588
+ // A turn of this attempt's that failed fails it (a refusal ends the turn); the retry asks the model again.
589
+ if ('error' in end && end.error !== undefined) {
590
+ const failedHere = events.slice(found).some((e) => e.type === 'turn/end' && e.data.reason.kind === 'error');
591
+ if (failedHere) throw turnError(end.error);
592
+ }
593
+ if ('answer' in end && end.answer !== undefined) return end.answer;
594
+ const ask = again ? message(id, textOf(asked.item)) : promptOf(turn, before);
595
+ agent.followup(end.asked ? message(`continue:${events.length}`, CONTINUE) : ask);
596
+ await Promise.race([agent.whenIdle(), failed]);
597
+ await harness.sessions.flush(agent.session);
598
+ }
599
+ } catch (e) {
600
+ // A cancelled invocation cancels the agent's turn, which the log keeps.
601
+ if (e instanceof restate.CancelledError && agent) await cancelTurn(harness, agent);
602
+ else persistence.abandon();
603
+ throw e;
604
+ } finally {
605
+ unlisten?.();
606
+ stop?.removeEventListener('abort', onStop);
607
+ await harness.fiber.dispose();
608
+ }
609
+ };
361
610
 
362
611
  /** Cancel `agent`'s turn, and store it cancelled. */
363
612
  async function cancelTurn(harness: Context, agent: Agent) {
@@ -367,20 +616,24 @@ async function cancelTurn(harness: Context, agent: Agent) {
367
616
  }
368
617
 
369
618
  /**
370
- * `definition`, its calls published as they start and end (for the clients
371
- * that follow the conversation), and its error failing the attempt.
619
+ * `definition`, its calls published as they start, and as they end once
620
+ * their results are stored (each call that returned is put in `returned`),
621
+ * for the clients that follow the conversation; its error failing the
622
+ * attempt.
372
623
  */
373
624
  const tracked = (
374
625
  definition: ToolDefinition,
375
626
  ctx: restate.SessionContext,
376
627
  fail: (error: unknown) => void,
628
+ returned: Set<string>,
377
629
  ): ToolDefinition => ({
378
630
  ...definition,
379
631
  execute: async (args, exec) => {
380
632
  try {
381
633
  await toolCallStarted(ctx);
382
634
  const result = await definition.execute(args, exec);
383
- await toolCallEnded(ctx);
635
+ // Its end is published once the harness stored its result (`runOf`).
636
+ returned.add(exec.callId);
384
637
  return result;
385
638
  } catch (error) {
386
639
  fromTool(ctx, error);
@@ -400,7 +653,11 @@ export const prompt = <O extends z.ZodObject | undefined = undefined>(
400
653
  ctx: restate.SessionContext,
401
654
  text: string,
402
655
  options: Options<O> = {},
403
- ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
656
+ ): Promise<Answer<O>> =>
657
+ withChecked(text, options, (t, o, check, reminder) =>
658
+ // The harness keeps the model's history: the conversation reads only its latest turns.
659
+ answerOnce(ctx, t, items, runOf(ctx, o), { check, reminder, ownHistory: true }),
660
+ ) as Promise<Answer<O>>;
404
661
 
405
662
  /**
406
663
  * A chat handler: each message an invocation, the session in the object's
@@ -413,11 +670,11 @@ export const chat = <O extends z.ZodObject | undefined = undefined>(options: Con
413
670
  checkModelName('deepseek', options.model);
414
671
  routeOf(modelOf(options.model, DEEPSEEK_MODEL));
415
672
  }
416
- return chatHandler(async (ctx, text) => prompt(ctx, text, await configured(options, ctx)));
673
+ return chatHandler(async (ctx, text) => prompt(ctx, text, await configured(options, ctx)), { steers: true });
417
674
  };
418
675
 
419
676
  /** `json` parsed, or as it is if it is not JSON. */
420
- const parsed = (json: string): unknown => {
677
+ const parsedJson = (json: string): unknown => {
421
678
  try {
422
679
  return JSON.parse(json);
423
680
  } catch {
@@ -426,25 +683,11 @@ const parsed = (json: string): unknown => {
426
683
  };
427
684
 
428
685
  /**
429
- * A handler of the conversation as clients read it: a page at a time, or
430
- * what is new or changed since a cursor, from the log each change writes
431
- * (log.ts). It answers while a message is answered.
686
+ * A view of the conversation as clients read it: a page at a time, or what
687
+ * is new or changed since a cursor; `view: 'summary'` for each turn's
688
+ * message and answer. It answers while a message is answered.
432
689
  */
433
- export const messages = () => messagesHandler();
434
-
435
- /** The session `key` in `db`, from its log, as `messages` gives it. */
436
- const transcribe = async (db: Database, key: string) => {
437
- const transcript = new Transcript();
438
- for (const e of await storedEvents(db, SessionId(key))) {
439
- // The prompts, not the requests to continue an interrupted turn.
440
- if (e.type === 'user/message' && e.data.id.startsWith('prompt:')) transcript.say('user', textOf(e.data));
441
- if (e.type === 'assistant/message') transcript.say('assistant', textOf(e.data.message));
442
- if (e.type === 'tool/call') transcript.call(e.data.callId, e.data.name, parsed(e.data.arguments));
443
- if (e.type === 'tool/result')
444
- transcript.result(e.data.message.toolCallId, textOf(e.data.message), e.data.message.isError);
445
- }
446
- return transcript;
447
- };
690
+ export const messages = () => conversationView(items);
448
691
 
449
692
  /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
450
693
  export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
@@ -452,6 +695,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
452
695
  description,
453
696
  schema,
454
697
  background,
698
+ window,
699
+ budget,
455
700
  ...options
456
701
  }: Options<O> & Definition<P>) =>
457
702
  sessionObject({
@@ -459,6 +704,8 @@ export const agent = <P extends string, O extends z.ZodObject | undefined = unde
459
704
  description,
460
705
  schema,
461
706
  background,
707
+ window,
708
+ budget,
462
709
  handlers: { chat: chat(options) },
463
710
  views: { messages: messages() },
464
711
  });