@restatedev/agents 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +189 -808
  2. package/dist/pi/factory.d.ts +73 -0
  3. package/dist/pi/factory.d.ts.map +1 -0
  4. package/dist/pi/factory.js +145 -0
  5. package/dist/pi/factory.js.map +1 -0
  6. package/dist/pi/index.d.ts +5 -129
  7. package/dist/pi/index.d.ts.map +1 -1
  8. package/dist/pi/index.js +31 -571
  9. package/dist/pi/index.js.map +1 -1
  10. package/dist/pi/keepalive.d.ts +3 -16
  11. package/dist/pi/keepalive.d.ts.map +1 -1
  12. package/dist/pi/keepalive.js +38 -41
  13. package/dist/pi/keepalive.js.map +1 -1
  14. package/dist/pi/left.d.ts +16 -0
  15. package/dist/pi/left.d.ts.map +1 -0
  16. package/dist/pi/left.js +23 -0
  17. package/dist/pi/left.js.map +1 -0
  18. package/dist/pi/storage.d.ts +19 -76
  19. package/dist/pi/storage.d.ts.map +1 -1
  20. package/dist/pi/storage.js +50 -368
  21. package/dist/pi/storage.js.map +1 -1
  22. package/dist/pi/tools.d.ts +12 -0
  23. package/dist/pi/tools.d.ts.map +1 -0
  24. package/dist/pi/tools.js +70 -0
  25. package/dist/pi/tools.js.map +1 -0
  26. package/package.json +11 -254
  27. package/src/pi/factory.ts +231 -0
  28. package/src/pi/index.ts +31 -759
  29. package/src/pi/keepalive.ts +46 -56
  30. package/src/pi/left.ts +52 -0
  31. package/src/pi/storage.ts +75 -409
  32. package/src/pi/tools.ts +78 -0
  33. package/dist/agentlib/agent.d.ts +0 -32
  34. package/dist/agentlib/agent.d.ts.map +0 -1
  35. package/dist/agentlib/agent.js +0 -174
  36. package/dist/agentlib/agent.js.map +0 -1
  37. package/dist/agentlib/index.d.ts +0 -5
  38. package/dist/agentlib/index.d.ts.map +0 -1
  39. package/dist/agentlib/index.js +0 -15
  40. package/dist/agentlib/index.js.map +0 -1
  41. package/dist/agentlib/messages.d.ts +0 -39
  42. package/dist/agentlib/messages.d.ts.map +0 -1
  43. package/dist/agentlib/messages.js +0 -177
  44. package/dist/agentlib/messages.js.map +0 -1
  45. package/dist/agentlib/model.d.ts +0 -31
  46. package/dist/agentlib/model.d.ts.map +0 -1
  47. package/dist/agentlib/model.js +0 -140
  48. package/dist/agentlib/model.js.map +0 -1
  49. package/dist/agentlib/options.d.ts +0 -58
  50. package/dist/agentlib/options.d.ts.map +0 -1
  51. package/dist/agentlib/options.js +0 -2
  52. package/dist/agentlib/options.js.map +0 -1
  53. package/dist/agentlib/runtime.d.ts +0 -37
  54. package/dist/agentlib/runtime.d.ts.map +0 -1
  55. package/dist/agentlib/runtime.js +0 -216
  56. package/dist/agentlib/runtime.js.map +0 -1
  57. package/dist/agentlib/state.d.ts +0 -114
  58. package/dist/agentlib/state.d.ts.map +0 -1
  59. package/dist/agentlib/state.js +0 -52
  60. package/dist/agentlib/state.js.map +0 -1
  61. package/dist/agentlib/steering.d.ts +0 -23
  62. package/dist/agentlib/steering.d.ts.map +0 -1
  63. package/dist/agentlib/steering.js +0 -48
  64. package/dist/agentlib/steering.js.map +0 -1
  65. package/dist/agentlib/tools.d.ts +0 -33
  66. package/dist/agentlib/tools.d.ts.map +0 -1
  67. package/dist/agentlib/tools.js +0 -245
  68. package/dist/agentlib/tools.js.map +0 -1
  69. package/dist/agentlib/turn.d.ts +0 -82
  70. package/dist/agentlib/turn.d.ts.map +0 -1
  71. package/dist/agentlib/turn.js +0 -253
  72. package/dist/agentlib/turn.js.map +0 -1
  73. package/dist/calls.d.ts +0 -90
  74. package/dist/calls.d.ts.map +0 -1
  75. package/dist/calls.js +0 -235
  76. package/dist/calls.js.map +0 -1
  77. package/dist/claude/index.d.ts +0 -106
  78. package/dist/claude/index.d.ts.map +0 -1
  79. package/dist/claude/index.js +0 -386
  80. package/dist/claude/index.js.map +0 -1
  81. package/dist/client.d.ts +0 -90
  82. package/dist/client.d.ts.map +0 -1
  83. package/dist/client.js +0 -88
  84. package/dist/client.js.map +0 -1
  85. package/dist/common.d.ts +0 -410
  86. package/dist/common.d.ts.map +0 -1
  87. package/dist/common.js +0 -563
  88. package/dist/common.js.map +0 -1
  89. package/dist/companion.d.ts +0 -286
  90. package/dist/companion.d.ts.map +0 -1
  91. package/dist/companion.js +0 -463
  92. package/dist/companion.js.map +0 -1
  93. package/dist/conversation.d.ts +0 -576
  94. package/dist/conversation.d.ts.map +0 -1
  95. package/dist/conversation.js +0 -1476
  96. package/dist/conversation.js.map +0 -1
  97. package/dist/deepseek/barriers.d.ts +0 -11
  98. package/dist/deepseek/barriers.d.ts.map +0 -1
  99. package/dist/deepseek/barriers.js +0 -36
  100. package/dist/deepseek/barriers.js.map +0 -1
  101. package/dist/deepseek/index.d.ts +0 -97
  102. package/dist/deepseek/index.d.ts.map +0 -1
  103. package/dist/deepseek/index.js +0 -603
  104. package/dist/deepseek/index.js.map +0 -1
  105. package/dist/deepseek/persistence.d.ts +0 -83
  106. package/dist/deepseek/persistence.d.ts.map +0 -1
  107. package/dist/deepseek/persistence.js +0 -262
  108. package/dist/deepseek/persistence.js.map +0 -1
  109. package/dist/index.d.ts +0 -14
  110. package/dist/index.d.ts.map +0 -1
  111. package/dist/index.js +0 -17
  112. package/dist/index.js.map +0 -1
  113. package/dist/langgraph/checkpointer.d.ts +0 -52
  114. package/dist/langgraph/checkpointer.d.ts.map +0 -1
  115. package/dist/langgraph/checkpointer.js +0 -477
  116. package/dist/langgraph/checkpointer.js.map +0 -1
  117. package/dist/langgraph/context.d.ts +0 -10
  118. package/dist/langgraph/context.d.ts.map +0 -1
  119. package/dist/langgraph/context.js +0 -21
  120. package/dist/langgraph/context.js.map +0 -1
  121. package/dist/langgraph/errors.d.ts +0 -16
  122. package/dist/langgraph/errors.d.ts.map +0 -1
  123. package/dist/langgraph/errors.js +0 -30
  124. package/dist/langgraph/errors.js.map +0 -1
  125. package/dist/langgraph/graph.d.ts +0 -25
  126. package/dist/langgraph/graph.d.ts.map +0 -1
  127. package/dist/langgraph/graph.js +0 -378
  128. package/dist/langgraph/graph.js.map +0 -1
  129. package/dist/langgraph/index.d.ts +0 -119
  130. package/dist/langgraph/index.d.ts.map +0 -1
  131. package/dist/langgraph/index.js +0 -325
  132. package/dist/langgraph/index.js.map +0 -1
  133. package/dist/langgraph/keepalive.d.ts +0 -16
  134. package/dist/langgraph/keepalive.d.ts.map +0 -1
  135. package/dist/langgraph/keepalive.js +0 -51
  136. package/dist/langgraph/keepalive.js.map +0 -1
  137. package/dist/langgraph/nodes.d.ts +0 -71
  138. package/dist/langgraph/nodes.d.ts.map +0 -1
  139. package/dist/langgraph/nodes.js +0 -148
  140. package/dist/langgraph/nodes.js.map +0 -1
  141. package/dist/messages.d.ts +0 -18
  142. package/dist/messages.d.ts.map +0 -1
  143. package/dist/messages.js +0 -182
  144. package/dist/messages.js.map +0 -1
  145. package/dist/object.d.ts +0 -213
  146. package/dist/object.d.ts.map +0 -1
  147. package/dist/object.js +0 -309
  148. package/dist/object.js.map +0 -1
  149. package/dist/opencode/db.d.ts +0 -81
  150. package/dist/opencode/db.d.ts.map +0 -1
  151. package/dist/opencode/db.js +0 -249
  152. package/dist/opencode/db.js.map +0 -1
  153. package/dist/opencode/index.d.ts +0 -184
  154. package/dist/opencode/index.d.ts.map +0 -1
  155. package/dist/opencode/index.js +0 -1079
  156. package/dist/opencode/index.js.map +0 -1
  157. package/dist/output.d.ts +0 -25
  158. package/dist/output.d.ts.map +0 -1
  159. package/dist/output.js +0 -99
  160. package/dist/output.js.map +0 -1
  161. package/dist/pi/commits.d.ts +0 -6
  162. package/dist/pi/commits.d.ts.map +0 -1
  163. package/dist/pi/commits.js +0 -3
  164. package/dist/pi/commits.js.map +0 -1
  165. package/dist/steering.d.ts +0 -32
  166. package/dist/steering.d.ts.map +0 -1
  167. package/dist/steering.js +0 -45
  168. package/dist/steering.js.map +0 -1
  169. package/dist/tools.d.ts +0 -267
  170. package/dist/tools.d.ts.map +0 -1
  171. package/dist/tools.js +0 -305
  172. package/dist/tools.js.map +0 -1
  173. package/dist/webhook.d.ts +0 -71
  174. package/dist/webhook.d.ts.map +0 -1
  175. package/dist/webhook.js +0 -102
  176. package/dist/webhook.js.map +0 -1
  177. package/src/agentlib/README.md +0 -229
  178. package/src/agentlib/agent.ts +0 -216
  179. package/src/agentlib/index.ts +0 -16
  180. package/src/agentlib/messages.ts +0 -207
  181. package/src/agentlib/model.ts +0 -156
  182. package/src/agentlib/options.ts +0 -62
  183. package/src/agentlib/runtime.ts +0 -252
  184. package/src/agentlib/state.ts +0 -93
  185. package/src/agentlib/steering.ts +0 -53
  186. package/src/agentlib/tools.ts +0 -355
  187. package/src/agentlib/turn.ts +0 -302
  188. package/src/calls.ts +0 -330
  189. package/src/claude/README.md +0 -107
  190. package/src/claude/index.ts +0 -487
  191. package/src/client.ts +0 -187
  192. package/src/common.ts +0 -766
  193. package/src/companion.ts +0 -675
  194. package/src/conversation.ts +0 -1799
  195. package/src/deepseek/README.md +0 -202
  196. package/src/deepseek/barriers.ts +0 -63
  197. package/src/deepseek/index.ts +0 -740
  198. package/src/deepseek/persistence.ts +0 -337
  199. package/src/index.ts +0 -41
  200. package/src/langgraph/README.md +0 -199
  201. package/src/langgraph/checkpointer.ts +0 -614
  202. package/src/langgraph/context.ts +0 -27
  203. package/src/langgraph/errors.ts +0 -26
  204. package/src/langgraph/graph.ts +0 -422
  205. package/src/langgraph/index.ts +0 -500
  206. package/src/langgraph/keepalive.ts +0 -58
  207. package/src/langgraph/nodes.ts +0 -247
  208. package/src/messages.ts +0 -244
  209. package/src/object.ts +0 -454
  210. package/src/opencode/README.md +0 -249
  211. package/src/opencode/db.ts +0 -387
  212. package/src/opencode/index.ts +0 -1339
  213. package/src/output.ts +0 -116
  214. package/src/pi/README.md +0 -174
  215. package/src/pi/commits.ts +0 -7
  216. package/src/steering.ts +0 -68
  217. package/src/tools.ts +0 -515
  218. package/src/webhook.ts +0 -161
package/src/common.ts DELETED
@@ -1,766 +0,0 @@
1
- // What the frameworks share: their options (`Configure`, the model), the
2
- // ids of an invocation's prompts, the `chat` handler with its turn (status,
3
- // cancellation, publishing for the clients that follow it), and what the
4
- // conversation of turns (conversation.ts) takes: its notes, window and
5
- // budget.
6
- import * as restate from '@restatedev/sessions';
7
- import { cancelCalls, cancelled, definitionOf, Link, ScopeKey } from '@restatedev/sessions/internal';
8
- import { flushCalls, flushHeld, settleCalls } from './calls.ts';
9
- import { companionHere, type Published, type Steer } from './companion.ts';
10
-
11
- /**
12
- * The context of an agent's handler: a session context, from an object that
13
- * has a companion.
14
- *
15
- * The agent's own surface takes it: the handlers and views of
16
- * `sessionObject()` and of a framework's `agent()`, a `chat` handler's
17
- * answer, and what only an agent does with a context ({@link chatTurn},
18
- * {@link publish}). The layer a handler belongs to is then in its
19
- * signature, where the person writing it reads it, rather than found out in
20
- * the middle of a turn, after a model round-trip, looking like a tool
21
- * failure.
22
- *
23
- * It is a signpost, not a fence: it adds nothing to a session context, so
24
- * the two are the same type to the compiler, and `NoCompanion` stays the
25
- * guard that stops a wait from an object without a companion.
26
- */
27
- export interface AgentContext extends restate.SessionContext {}
28
-
29
- /**
30
- * The context of an agent's view: a view context, from an object that has a
31
- * companion. What {@link AgentContext} is to a handler, for the views that
32
- * read what the agent is doing, or tell its companion to (`status`,
33
- * `pending`, `signal`, `steer`, `watch`).
34
- */
35
- export interface AgentViewContext extends restate.ViewContext {}
36
-
37
- /**
38
- * A value, or a function of the invocation's context that gives it: the
39
- * same for every message, or each user's (from the object's database, say).
40
- *
41
- * pi.chat({ model: 'openai/gpt-6-sol' })
42
- * pi.chat(async (ctx) => ({ model: await userModel(ctx) }))
43
- */
44
- export type Configure<T> = T | ((ctx: restate.SessionContext) => T | Promise<T>);
45
-
46
- /** `value` for the invocation of `ctx`. */
47
- export const configured = async <T>(value: Configure<T>, ctx: restate.SessionContext): Promise<T> =>
48
- typeof value === 'function' ? (value as (ctx: restate.SessionContext) => T | Promise<T>)(ctx) : value;
49
-
50
- /** The prompts each invocation made so far, by its context. */
51
- const PROMPTS = new ScopeKey<number>('nextPromptId');
52
-
53
- /**
54
- * The id of the next prompt of the invocation of `ctx`: the invocation's id,
55
- * then `<id>:2`, `<id>:3`... A retried attempt makes its prompts in the same
56
- * order, so each gets the same id again, and its answer.
57
- */
58
- export const nextPromptId = (ctx: restate.SessionContext) => {
59
- const n = (PROMPTS.get(ctx) ?? 0) + 1;
60
- PROMPTS.set(ctx, n);
61
- return n === 1 ? ctx.request.id : `${ctx.request.id}:${n}`;
62
- };
63
-
64
- /** The default model of pi and LangGraph, with OPENAI_API_KEY. */
65
- export const DEFAULT_MODEL = 'openai/gpt-6-sol';
66
-
67
- /** The default model of Claude agents, with ANTHROPIC_API_KEY. */
68
- export const CLAUDE_MODEL = 'anthropic/claude-sonnet-5-5';
69
-
70
- /**
71
- * The model, as `provider/model-id` (such as `openai/gpt-6-sol`):
72
- * `model`, or else MODEL, or else the framework's default.
73
- */
74
- export const modelOf = (model: string | undefined, fallback = DEFAULT_MODEL) => model || process.env.MODEL || fallback;
75
-
76
- /** `provider/model-id` as its provider and model id, split at the first `/` (`openrouter/meta-llama/llama-4`). */
77
- export const providerOf = (model: string): [provider: string, id: string] => {
78
- const slash = model.indexOf('/');
79
- return slash < 0 ? ['', model] : [model.slice(0, slash), model.slice(slash + 1)];
80
- };
81
-
82
- /**
83
- * The error code of a message the model's provider refused (a missing or
84
- * wrong API key, an unknown model): 424, Failed Dependency, as its HTTP
85
- * status.
86
- */
87
- export const REFUSED = 424;
88
-
89
- /** The texts that approve a tool call that waits for a person's approval, whatever their case. */
90
- const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
91
-
92
- /**
93
- * Whether `value`, a signal's that a tool call waits for to run (an
94
- * approval), approves it: `true`, `{ "approved": true }`, or a text such as
95
- * "approved" or "yes", whatever its case. Anything else denies it, so a
96
- * value that does not say "approved" never runs the tool. Every framework's
97
- * approvals take it (DeepSeek's, OpenCode's, agentlib's).
98
- */
99
- export const approves = (value: unknown): boolean =>
100
- value === true ||
101
- (typeof value === 'string' && APPROVED.has(value.trim().toLowerCase())) ||
102
- (typeof value === 'object' && value !== null && (value as { approved?: unknown }).approved === true);
103
-
104
- /** What to check when a model's provider refuses a request. */
105
- export const CHECK_MODEL = "check the agent's model (its `model` option, or MODEL) and its provider's API key";
106
-
107
- /**
108
- * An agent's model that it cannot take: not `provider/model-id`, another
109
- * provider's, or one its framework does not know. Terminal ({@link REFUSED}),
110
- * wherever it is thrown: a retry takes the same model.
111
- */
112
- export class ModelError extends restate.TerminalError {
113
- constructor(message: string) {
114
- super(message, { errorCode: REFUSED });
115
- this.name = 'ModelError';
116
- }
117
- }
118
-
119
- /** `model`, the explicit `model` option of `framework`'s agent, if it is not `provider/model-id`. */
120
- export const checkModelName = (framework: string, model: string | undefined) => {
121
- if (model !== undefined && !/^[^/\s]+\/\S+$/.test(model)) {
122
- throw new ModelError(`${framework}: the model "${model}" is not provider/model-id, such as openai/gpt-6-sol`);
123
- }
124
- };
125
-
126
- /**
127
- * The model id of `model`, for a framework with only `provider`'s models:
128
- * `provider/model-id`, or the id alone.
129
- */
130
- export const modelIdOf = (model: string, provider: string) => {
131
- const [named, id] = model.includes('/') ? providerOf(model) : [provider, model];
132
- if (named !== provider || !id) {
133
- const from = process.env.MODEL === model ? ' (from MODEL)' : '';
134
- throw new ModelError(`the model "${model}"${from} is not ${provider}'s: this agent takes ${provider}/<model-id>`);
135
- }
136
- return id;
137
- };
138
-
139
- /** A chat message: the request's body as text, or the string it is as JSON (`"Hi"`). */
140
- export const messageSerde: restate.Serde<string> = {
141
- contentType: 'text/plain',
142
- serialize: (text) => new TextEncoder().encode(text),
143
- deserialize: (bytes) => {
144
- const text = new TextDecoder().decode(bytes);
145
- try {
146
- const value: unknown = JSON.parse(text);
147
- return typeof value === 'string' ? value : text;
148
- } catch {
149
- return text;
150
- }
151
- },
152
- };
153
-
154
- /**
155
- * What an empty answer says, as the model sees it later in the conversation:
156
- * a provider's API may refuse an empty text (Anthropic's does).
157
- */
158
- export const NO_ANSWER = '(no answer)';
159
-
160
- /**
161
- * What a cancelled turn answers, and each tool call it cut off: the model
162
- * sees it in the conversation that goes on.
163
- */
164
- export const CANCELLED = 'Cancelled: the turn was stopped before it finished.';
165
-
166
- /**
167
- * What a prompt answers that the model's provider refused for good (see
168
- * {@link refusal}): the prompt is over, and the model sees it in the
169
- * conversation that goes on, rather than answer it with the next message.
170
- */
171
- export const UNANSWERED = "Unanswered: the model's provider refused the request.";
172
-
173
- /**
174
- * What a turn whose invocation ended without answering it (killed, say)
175
- * answers, and each tool call it cut off: the next message, or the companion
176
- * once it finds the invocation gone (`settle`), closes it with this.
177
- */
178
- export const ENDED = 'Ended: the turn ended before it finished, and was not answered.';
179
-
180
- /** The result of a tool call a stopped turn cut off once its Restate call had answered: it happened. */
181
- export const RETURNED_UNRECORDED =
182
- "Done, but the turn was stopped before this call's result was recorded: it did happen, so check its effect before doing it again.";
183
-
184
- /**
185
- * What a stopped turn records as the result of its tool call `callId`, which
186
- * has none: `text` (cancelled, say), unless the call's Restate call answered
187
- * (`outcomes` of calls.ts), which the model would take for undone, and do
188
- * again: then the error it answered with, or {@link RETURNED_UNRECORDED}.
189
- */
190
- export function cutOffResult(outcomes: ReadonlyMap<string, string | undefined>, callId: string, text: string) {
191
- if (!outcomes.has(callId)) return text;
192
- return outcomes.get(callId) ?? RETURNED_UNRECORDED;
193
- }
194
-
195
- /** How many of the latest answered turns the model sees whole (with their tool calls and results), or `'all'`. */
196
- export type Window = number | 'all';
197
-
198
- /** The window by default: the previous turn's tool calls and results stay in view, for a follow-up. */
199
- export const WINDOW: Window = 1;
200
-
201
- /** How many tokens of the turns before the window the model sees, by default, counted as 4 characters each. */
202
- export const BUDGET = 32_000;
203
-
204
- /** How an agent summarizes earlier turns: from the request ({@link SUMMARIZE} and the turns, as text) to the summary. */
205
- export type Summarize = (ctx: restate.SessionContext, request: string) => Promise<string>;
206
-
207
- /** What a request to summarize earlier turns starts with, before the turns themselves. */
208
- export const SUMMARIZE =
209
- "Summarize the conversation below, for the assistant who carries it on: keep the facts, names, numbers, decisions, the user's preferences, and what is still open. Answer with the summary only.\n\n";
210
-
211
- /**
212
- * What a turn checks its answer with: nothing if the answer is what was
213
- * asked for, else the message that asks the model again, once, within the
214
- * turn (`answerOnce`'s `check`). With `last`, the model was asked again
215
- * already: a check that throws a terminal error then fails the turn, which
216
- * is closed with it.
217
- */
218
- export type Check = (answer: string, last?: boolean) => string | undefined;
219
-
220
- /** `window`, if it is one: a whole number of turns (0 or more), or `'all'`. */
221
- export function checkWindow(window: Window): Window {
222
- if (window !== 'all' && !(Number.isInteger(window) && window >= 0)) {
223
- throw new Error(`window must be a number of turns (0 or more) or 'all', not ${JSON.stringify(window)}`);
224
- }
225
- return window;
226
- }
227
-
228
- /** The message a `chat` handler is answering: its invocation, and when it started. */
229
- export interface Answering {
230
- /** The invocation's id: `/restate/invocation/<id>/attach` waits for its answer. */
231
- invocationId: string;
232
- /** When it started, as an ISO date. */
233
- since: string;
234
- }
235
-
236
- /** What stops each turn, by its context: see {@link stopSignalOf}. */
237
- const TURN = new ScopeKey<AbortSignal>('stopSignalOf');
238
-
239
- /**
240
- * Why a turn stopped when its attempt ended before it did: Restate suspended
241
- * the attempt, gave up on it, or lost its connection. Nothing the attempt
242
- * does after is stored, and the next attempt goes on with the turn, so it
243
- * stops without answering: unlike a cancellation, nothing is cancelled.
244
- */
245
- export class AttemptEnded extends Error {
246
- constructor() {
247
- super('the attempt ended before its turn did');
248
- this.name = 'AttemptEnded';
249
- }
250
- }
251
-
252
- /**
253
- * The signal that stops the turn of `ctx` (of a `chat` handler,
254
- * `chatHandler`), and an agent's `prompt` stops its framework's work with it.
255
- * It aborts with a `restate.CancelledError` once Restate cancels the
256
- * invocation (the turn ends, answered as cancelled), or with an
257
- * {@link AttemptEnded} once the attempt ends first (the work stops, and
258
- * answers nothing).
259
- */
260
- export const stopSignalOf = (ctx: restate.SessionContext): AbortSignal | undefined => TURN.get(ctx);
261
-
262
- // --- Keeping an attempt alive
263
- //
264
- // A model's request runs in `ctx.working`, so that Restate does not shut its
265
- // attempt down while it streams: the request would be made again, from the
266
- // start of the turn. Nothing else of a turn does, unless a tool says so
267
- // (`keepalive`): a wait on Restate (a call, a signal) suspends.
268
-
269
- /**
270
- * Open a `ctx.working` scope until the function it returns is called (once
271
- * or more): for a framework's hooks that bracket a model's request without
272
- * wrapping it. A scope never released keeps the attempt alive to its end.
273
- */
274
- export function keepAlive(ctx: restate.SessionContext): () => void {
275
- const released = Promise.withResolvers<void>();
276
- void ctx.working(() => released.promise);
277
- return () => released.resolve();
278
- }
279
-
280
- /**
281
- * `source`, kept alive while it is iterated: from the first pull to its end,
282
- * however it ends (done, thrown, or returned early, as a `break` does). A
283
- * model's streamed response, say.
284
- */
285
- export async function* keptAlive<T>(ctx: restate.SessionContext, source: AsyncIterable<T>): AsyncGenerator<T> {
286
- const release = keepAlive(ctx);
287
- try {
288
- yield* source;
289
- } finally {
290
- release();
291
- }
292
- }
293
-
294
- /**
295
- * An agent's settings: whether it runs in the background (`background:
296
- * true`: no one follows it as it works), and, for an agent on the
297
- * conversation of turns (conversation.ts), its framework's items, how much
298
- * of the conversation its model sees (`window` and `budget`), and how it
299
- * summarizes the earliest turns (`summarize`).
300
- */
301
- export interface Settings {
302
- background: boolean;
303
- /** The items of its framework, if it keeps the conversation of turns (its `messages` view is `conversationView`'s). */
304
- items?: object;
305
- window: Window;
306
- budget: number;
307
- summarize?: Summarize;
308
- }
309
-
310
- /** An agent's settings, on its definition. */
311
- const AGENT = new Link<Settings>('an agent');
312
-
313
- /** The items of a framework's `messages` view on the conversation of turns. */
314
- export const ITEMS = new Link<object>('restate-agents.items');
315
-
316
- /** `definition` is an agent's, with these settings: its framework's items, if it is on the conversation of turns. */
317
- export const isAgent = <D extends object>(
318
- definition: D,
319
- {
320
- background = false,
321
- items = undefined as object | undefined,
322
- window = WINDOW as Window,
323
- budget = BUDGET,
324
- summarize = undefined as Summarize | undefined,
325
- },
326
- ) => {
327
- return AGENT.on(definition, {
328
- background,
329
- items,
330
- window,
331
- budget,
332
- summarize,
333
- });
334
- };
335
-
336
- /** The settings of the agent of `ctx`, if it is one. */
337
- const agentOf = (ctx: restate.SessionContext) => {
338
- const definition = definitionOf(ctx);
339
- return definition && AGENT.of(definition);
340
- };
341
-
342
- /** The settings of the agent of `ctx`: the defaults, for an object that is no agent. */
343
- export const settingsOf = (ctx: restate.SessionContext): Settings =>
344
- agentOf(ctx) ?? { background: false, window: WINDOW, budget: BUDGET };
345
-
346
- /** Whether the agent of `ctx` runs in the background. */
347
- const unfollowed = (ctx: restate.SessionContext) => agentOf(ctx)?.background === true;
348
-
349
- /**
350
- * The companion of the agent of `ctx`, for `needs`: its own, at its key. An
351
- * object without one fails with a terminal error (`NoCompanion`).
352
- */
353
- const companionOfAgent = (ctx: restate.SessionContext, needs: string) => ctx.rpc(companionHere(ctx, needs), ctx.key);
354
-
355
- /**
356
- * The messages steered to a `chat` turn that it has not taken yet, as the
357
- * companion last published them. The companion answers them to every
358
- * `publish` (and `start`), which a turn makes as it starts and after each
359
- * write of its steps that commits: so the turn knows of them without a call
360
- * of its own, and finds them at its next step (`takeSteers`). The newest
361
- * revision wins, as writes that run at once publish at once.
362
- */
363
- export class Inbox {
364
- revision = -1;
365
- messages: Steer[] = [];
366
- readonly #listeners = new Set<() => void>();
367
-
368
- /** Keep what `publish` answered, if it is newer than what is kept, and tell the listeners if it lists messages. */
369
- saw(published: Published | undefined) {
370
- if (typeof published !== 'object' || published === null) return;
371
- const revision = published.revision ?? -1;
372
- if (revision <= this.revision) return;
373
- this.revision = revision;
374
- this.messages = [...(published.steering ?? [])];
375
- if (this.messages.length > 0) for (const listener of this.#listeners) listener();
376
- }
377
-
378
- /**
379
- * Call `listener` after each publish that lists messages, until the
380
- * returned function is called: for a framework that takes steered
381
- * messages through an inbox of its own (pi's, DeepSeek's), handed to it as
382
- * they come.
383
- */
384
- listen(listener: () => void): () => void {
385
- this.#listeners.add(listener);
386
- return () => this.#listeners.delete(listener);
387
- }
388
- }
389
-
390
- const INBOX = new ScopeKey<Inbox>('inbox');
391
-
392
- /** The inbox of the `chat` turn running on `ctx`, if it takes steered messages: none outside one. */
393
- export const inboxOf = (ctx: restate.SessionContext) => INBOX.get(ctx);
394
-
395
- /**
396
- * The conversation of `ctx` changed (see `watch` in object.ts): its revision
397
- * increases, and the clients that follow it read it again; while a framework
398
- * answers ({@link answering}), the calls whose results it stored are
399
- * forgotten first. It is a call to Restate, so it also sends what the
400
- * handler wrote before, for them to read: the rows the conversation holds
401
- * back are written first (`flushHeld`), as the clients read them once told.
402
- *
403
- * Only a `chat` turn ({@link chatTurn}: after each commit of its steps) and
404
- * `settle` publish, on an object with a companion: one without fails with a
405
- * terminal error (`NoCompanion`), rather than call a companion nobody serves.
406
- */
407
- export const publish = async (ctx: AgentContext) => {
408
- const companion = companionOfAgent(ctx, 'a publish');
409
- await flushHeld(ctx);
410
- const published = await companion.publish();
411
- INBOX.get(ctx)?.saw(published);
412
- };
413
-
414
- /**
415
- * What the turn running on `ctx` makes after each commit of its steps (a
416
- * reply with tool calls, the tools' results), if anything: set by
417
- * {@link chatTurn}, for a followed turn, to publish. The conversation takes
418
- * it as it is, without knowing what it does (`answerOnce` hands it to
419
- * `Conversation.hold`); a turn run outside a `chat` turn (a handler of your
420
- * own that calls a framework's `prompt()`) has none: it stores its steps,
421
- * and publishes nothing.
422
- */
423
- const AFTER_STEPS = new ScopeKey<() => Promise<void>>('afterSteps');
424
-
425
- /** What the turn running on `ctx` makes after each commit of its steps, if anything: see {@link AFTER_STEPS}. */
426
- export const afterStepsOf = (ctx: restate.SessionContext): (() => Promise<void>) | undefined => AFTER_STEPS.get(ctx);
427
-
428
- /**
429
- * A tool call of the turn of `ctx` starts: forget the calls whose results are
430
- * stored (calls.ts) before the tool makes its own. It publishes nothing: a
431
- * followed `chat` turn publishes once the call is stored (with its reply),
432
- * and once its result is ({@link afterStepsOf}).
433
- */
434
- export async function toolCallStarted(ctx: restate.SessionContext) {
435
- await settleAnswered(ctx);
436
- }
437
-
438
- /**
439
- * Forget the call records (calls.ts) whose results the turn answering on
440
- * `ctx` has stored ({@link answering}), if one does: after each commit of its
441
- * steps (`answerOnce` does, before what the turn asked for then, such as a
442
- * `chat` turn's publish, for every turn, in a `chat` turn or not), as a tool
443
- * call starts, and as the turn ends.
444
- */
445
- export async function settleAnswered(ctx: restate.SessionContext) {
446
- const stored = ANSWERING.get(ctx);
447
- if (stored) await settled(ctx, stored);
448
- }
449
-
450
- /** Whether a tool call's result is stored: `stored(callId, failed)`, `failed` the error the call answered with. */
451
- export type Stored = (callId: string, failed?: string) => boolean;
452
-
453
- /** What the attempt's turn has stored, while it answers (see {@link answering}). */
454
- const ANSWERING = new ScopeKey<Stored>('answering');
455
-
456
- /** The attempt's latest settling of calls: one after another, as parallel tool calls publish at once. */
457
- const SETTLING = new ScopeKey<Promise<void>>('settling');
458
-
459
- /** Forget the calls whose results the conversation stored (calls.ts), after any settling before. */
460
- function settled(ctx: restate.SessionContext, stored: Stored): Promise<void> {
461
- const settle = () => settleCalls(ctx, stored);
462
- const done = (SETTLING.get(ctx) ?? Promise.resolve()).then(settle, settle);
463
- SETTLING.set(ctx, done);
464
- return done;
465
- }
466
-
467
- /**
468
- * Run `work`, a framework's turn on the conversation of turns, forgetting
469
- * the calls whose results it stores as it goes: each write of its steps
470
- * that commits ({@link settleAnswered}), each tool call's start, and its
471
- * end, forget the Restate calls of
472
- * the tool calls whose results `stored` says are stored (calls.ts).
473
- */
474
- export async function answering<T>(ctx: restate.SessionContext, stored: Stored, work: () => Promise<T>): Promise<T> {
475
- const outer = ANSWERING.get(ctx);
476
- ANSWERING.set(ctx, stored);
477
- let failed = false;
478
- try {
479
- return await work();
480
- } catch (error) {
481
- failed = !(error instanceof restate.TerminalError);
482
- throw error;
483
- } finally {
484
- try {
485
- // A failed attempt stores nothing more: its retry runs again.
486
- if (!failed) await settled(ctx, stored);
487
- } finally {
488
- if (outer) ANSWERING.set(ctx, outer);
489
- else ANSWERING.delete(ctx);
490
- // What rides the next commit is written if none is to come: after a turn that answered, the commit that
491
- // stored its answer wrote it, and this does nothing. A failed attempt's own error is not this write's.
492
- await (failed ? flushCalls(ctx).catch(() => {}) : flushCalls(ctx));
493
- }
494
- }
495
- }
496
-
497
- /** A promise that rejects with `signal`'s reason once it aborts. */
498
- export const aborted = (signal: AbortSignal) =>
499
- new Promise<never>((_, reject) => {
500
- if (signal.aborted) reject(signal.reason);
501
- else signal.addEventListener('abort', () => reject(signal.reason), { once: true });
502
- });
503
-
504
- /** A `chat` handler's answer to a message: a framework's prompt, say. */
505
- export type Chat<A = unknown> = (ctx: AgentContext, message: string) => Promise<A>;
506
-
507
- /**
508
- * Whether a `chat` handler's turns take steered messages: for every message,
509
- * or for each, as the invocation's context says (a framework's options that
510
- * a function gives, say).
511
- */
512
- export type Steers = boolean | ((ctx: AgentContext) => boolean | Promise<boolean>);
513
-
514
- /** What makes a `chat` handler (`chatHandler`): its answer, and whether it takes steered messages. */
515
- const CHAT = new Link<{ answer: Chat; steers: Steers }>('restate-agents.chat');
516
-
517
- /** The answer of `entry`, a handler that `chatHandler` made, and whether it takes steered messages. */
518
- export const chatOf = (entry: object) => CHAT.of(entry);
519
-
520
- /**
521
- * `answer` as a chat handler, which takes its message as plain text or as a
522
- * JSON string, so that both of these work:
523
- *
524
- * curl localhost:8080/assistant/alice/chat -d 'Hi'
525
- * curl localhost:8080/assistant/alice/chat --json '"Hi"'
526
- *
527
- * While it answers, the object's `status` says so (its {@link Answering}). Its
528
- * invocation's cancellation (Restate's, explicit: `cancelled(ctx)` of
529
- * @restatedev/sessions/internal) aborts {@link stopSignalOf} its
530
- * context, whenever it comes, and cancels the calls its tools made
531
- * (`cancelCalls(ctx)`): the agent's `prompt`
532
- * ends the turn, and the handler fails with a `restate.CancelledError`. An
533
- * attempt that ends first (`attemptCompletedSignal`) aborts it too, with an
534
- * {@link AttemptEnded}: the work stops, and the next attempt goes on with it.
535
- *
536
- * It publishes when it starts (its companion's `start` does) and ends
537
- * ({@link publish}), for the clients that follow the conversation, unless
538
- * the agent runs in the background, which publishes the end only.
539
- *
540
- * As the `chat` handler of an agent, it also answers each message sent to
541
- * the agent's `steer` view that no turn took, as a turn of its own (the
542
- * private `steered` handler). With `steers` (a framework's integration says
543
- * so), its turns take steered messages at their steps (`takeSteers`).
544
- */
545
- export const chatHandler = <A = string>(answer: Chat<A>, { steers = false }: { steers?: Steers } = {}) =>
546
- CHAT.on(
547
- {
548
- input: messageSerde,
549
- accept: '*/*',
550
- explicitCancellation: true,
551
- handler: (ctx: AgentContext, text: string): Promise<A> => chatTurn(ctx, text, answer, steers),
552
- },
553
- { answer, steers },
554
- );
555
-
556
- /**
557
- * Answer `text` as a turn of the agent of `ctx`, with `answer`: the body of a
558
- * `chat` handler ({@link chatHandler}), and of `steered`. With `steers`, the
559
- * turn takes the messages steered to it at its steps (unless the agent runs
560
- * in the background).
561
- */
562
- export async function chatTurn<A>(
563
- ctx: AgentContext,
564
- text: string,
565
- answer: Chat<A>,
566
- steers: Steers = false,
567
- ): Promise<A> {
568
- const invocationId = ctx.request.id;
569
- // The companion knows the turn from here to its close: `status` and `stop` ask it.
570
- // An agent on the conversation of turns has `settle`: the companion sends it
571
- // this turn, should its invocation be gone without closing it.
572
- const settles = agentOf(ctx)?.items !== undefined;
573
- const steering = !unfollowed(ctx) && (typeof steers === 'function' ? await steers(ctx) : steers);
574
- // Before the first publish, which may answer messages steered to the turn already (a retried attempt's).
575
- if (steering) INBOX.set(ctx, new Inbox());
576
- // A followed turn's start is its first publish: the companion makes it, and returns what `publish` returns.
577
- const followed = !unfollowed(ctx);
578
- const companion = companionOfAgent(ctx, 'a chat turn');
579
- const started = await companion.start({
580
- invocationId,
581
- since: new Date().toISOString(),
582
- ...(settles ? { settles } : {}),
583
- ...(steering ? { steers: steering } : {}),
584
- ...(followed ? { publishes: true } : {}),
585
- });
586
- INBOX.get(ctx)?.saw(started);
587
- // A followed turn publishes after each commit of its steps, for its
588
- // followers to read them there: the conversation makes what the turn sets
589
- // here (`afterStepsOf`), without knowing it publishes. A background turn
590
- // publishes its end only.
591
- if (followed) AFTER_STEPS.set(ctx, () => publish(ctx));
592
- // The log takes the turn's last change, then the companion closes the
593
- // turn, which publishes it: one revision. The close is a call the turn
594
- // waits for, so that it is done before the turn ends (see `awaitTurn`).
595
- const end = async () => {
596
- await settleAnswered(ctx);
597
- await companion.close(invocationId);
598
- };
599
- const turn = new AbortController();
600
- TURN.set(ctx, turn.signal);
601
- void (async () => {
602
- await cancelled(ctx);
603
- turn.abort(new restate.CancelledError());
604
- await cancelCalls(ctx);
605
- })().catch(() => {});
606
- // The attempt ends before the turn does: its work stops (a model's
607
- // request, say), rather than run on for an attempt that can store nothing.
608
- const attempt = ctx.request.attemptCompletedSignal;
609
- const attemptEnded = () => turn.abort(new AttemptEnded());
610
- attempt.addEventListener('abort', attemptEnded, { once: true });
611
- let answered: A;
612
- try {
613
- answered = await answer(ctx, text);
614
- // Cancelled once answered: the answer stands.
615
- } catch (error) {
616
- if (error instanceof restate.TerminalError) {
617
- await end();
618
- throw error;
619
- }
620
- // Any other error fails the attempt, and Restate retries the turn.
621
- const terminal = refusalOf(ctx, error);
622
- if (!terminal) throw error;
623
- await end();
624
- throw terminal;
625
- } finally {
626
- // An attempt's signal aborts at every attempt's end, the turn's too.
627
- attempt.removeEventListener('abort', attemptEnded);
628
- AFTER_STEPS.delete(ctx);
629
- }
630
- await end();
631
- return answered;
632
- }
633
-
634
- /** A tool's error, which fails the attempt (Restate retries it): the error `cause` of tool `tool`. */
635
- export class ToolError extends Error {
636
- readonly tool: string;
637
- constructor(tool: string, cause: unknown) {
638
- super(`the tool ${tool} failed: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
639
- this.name = 'ToolError';
640
- this.tool = tool;
641
- }
642
- }
643
-
644
- /** The errors the attempt's framework tools (not `tool()`'s) failed with: see {@link fromTool}. */
645
- const TOOL_ERRORS = new ScopeKey<WeakSet<object>>('fromTool');
646
-
647
- /**
648
- * `error` is a tool's, in the attempt of `ctx`: a framework's own tool
649
- * (Claude's, LangChain's...) that failed, whose error is never taken for
650
- * the model's provider refusing (a tool that calls a model API may fail as
651
- * one does). `tool()`'s are {@link ToolError}s.
652
- */
653
- export function fromTool(ctx: restate.SessionContext, error: unknown) {
654
- if (typeof error === 'object' && error !== null) TOOL_ERRORS.of(ctx, () => new WeakSet()).add(error);
655
- }
656
-
657
- /** The Anthropic SDK's errors of a request that fails again however often it is made. */
658
- const FOR_GOOD: ReadonlySet<string> = new Set([
659
- 'AuthenticationError',
660
- 'PermissionDeniedError',
661
- 'NotFoundError',
662
- 'BadRequestError',
663
- ]);
664
-
665
- /**
666
- * Whether `error` is a model provider's refusal that a retry does not change:
667
- * a missing or wrong API key, an unknown model, a bad request. Other errors
668
- * (a tool's, an overloaded provider's) fail the attempt, and Restate retries.
669
- */
670
- function refused(error: unknown) {
671
- if (error instanceof ToolError) return false;
672
- if (error instanceof Error && FOR_GOOD.has(error.constructor.name)) return true;
673
- return /API key not found|no API key|Could not resolve authentication method|Provider is not configured|"code":"(AUTH|MISSING_CREDENTIAL)"/i.test(
674
- String(error),
675
- );
676
- }
677
-
678
- /** {@link refusal}, but not of an error a framework's tool failed with in the attempt of `ctx` ({@link fromTool}). */
679
- export function refusalOf(ctx: restate.SessionContext, error: unknown): restate.TerminalError | undefined {
680
- const failedTool = typeof error === 'object' && error !== null && TOOL_ERRORS.get(ctx)?.has(error);
681
- return failedTool ? undefined : refusal(error);
682
- }
683
-
684
- /**
685
- * `error` as a terminal error ({@link REFUSED}), if a retry does not change
686
- * it: a model the agent cannot take, or its provider's refusal.
687
- */
688
- export function refusal(error: unknown): restate.TerminalError | undefined {
689
- if (error instanceof ModelError) return error;
690
- if (error instanceof restate.TerminalError || !refused(error)) return undefined;
691
- return new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}. ${String(error)}`, {
692
- errorCode: REFUSED,
693
- });
694
- }
695
-
696
- /**
697
- * A prompt's stored answer, as the prompt returns it, by how its turn ended
698
- * (`status`): a turn refused ({@link UNANSWERED}) fails with
699
- * {@link REFUSED}, one failed for good with its error, one cancelled with
700
- * the cancellation, one another invocation ended with its note; so that a
701
- * retry after a crash right after the close fails as the prompt did.
702
- */
703
- export function storedAnswer(answer: string, status = 'answered'): string {
704
- if (status === 'refused') {
705
- throw new restate.TerminalError(`the model's provider refused the request: ${CHECK_MODEL}`, { errorCode: REFUSED });
706
- }
707
- if (status === 'cancelled') throw new restate.CancelledError();
708
- if (status === 'failed') throw new restate.TerminalError(answer.replace(/^Error: /, ''));
709
- if (status === 'ended') throw new restate.TerminalError(answer);
710
- return answer;
711
- }
712
-
713
- /** A message of a conversation, as an agent's `messages` handler returns it. */
714
- export interface ChatMessage {
715
- /** Its id, from 0, in the order of the conversation; the same however it changes. `before` takes it. */
716
- id: number;
717
- role: 'user' | 'assistant';
718
- parts: Part[];
719
- }
720
-
721
- /**
722
- * What a message says: text, or a tool call with its output once it ran,
723
- * and `error: true` if the output is the tool's error (`Error: <message>` of
724
- * a `restate.TerminalError`, say).
725
- */
726
- export type Part =
727
- | { type: 'text'; text: string }
728
- | { type: 'tool'; id: string; name: string; input: unknown; output?: string; error?: true };
729
-
730
- /**
731
- * Which messages to read: the latest `limit`, or those before a message, for
732
- * a page of the conversation; or those new or changed since a `cursor`, to
733
- * follow it.
734
- */
735
- export interface MessagesRequest {
736
- /**
737
- * `full` (the default): every message, with its tool calls; `summary`:
738
- * each turn's message of the user and its answer, under the ids they have
739
- * in the full view.
740
- */
741
- view?: 'full' | 'summary';
742
- /** At most this many messages (default 50). */
743
- limit?: number;
744
- /** The messages before this one (its `id`): older ones, such as for scrolling back. */
745
- before?: number;
746
- /** The messages new or changed since this cursor (a page's `cursor`), by when they changed. */
747
- cursor?: number;
748
- }
749
-
750
- /**
751
- * A page of messages: oldest first; or, with a `cursor`, those new or
752
- * changed since it, by when they changed. Keep them by `id`: a message comes
753
- * again once it changed (its tool call's output came, say).
754
- */
755
- export interface Messages {
756
- messages: ChatMessage[];
757
- /** Whether there are more: older ones, or with a `cursor`, newer ones. */
758
- more: boolean;
759
- /** The cursor to read on from: what changes after this page. */
760
- cursor: number;
761
- /**
762
- * The id of the conversation's first message, once it was cleared
763
- * (`clear`): a client drops the messages it kept from before.
764
- */
765
- first?: number;
766
- }