@restatedev/agents 0.11.2 → 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 -241
  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 -333
  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
@@ -1,355 +0,0 @@
1
- // The tools of @restatedev/agents in an agentlib agent. Each becomes an
2
- // agentlib tool whose calls are the generator SDK's, on the classic context
3
- // of the agent's invocation, so Restate journals them:
4
- //
5
- // - `call`, `subagent` and `workflow` are calls: a crash replays their answer,
6
- // and stopping the turn cancels them. No call records or idempotency keys
7
- // are needed, as in a session object.
8
- // - `send` is a send, made once.
9
- // - `signal` waits at the agent's companion.
10
- // - A `tool()` runs as a journaled step, as agentlib's `asyncTool` does. Its
11
- // `ctx` has `key` and `request`, but no database or calls: a classic
12
- // object has no session.
13
- import {
14
- RunFailedError,
15
- tool as libTool,
16
- type JsonValue,
17
- type Tool as LibTool,
18
- type ToolContext as LibToolContext,
19
- } from '@restatedev/agentlib';
20
- import type { SessionContext } from '@restatedev/sessions';
21
- import { call, run, send, serde, type Operation } from '@restatedev/restate-sdk-gen';
22
- import { sdk as restate } from '@restatedev/sessions/internal';
23
- import type { z } from 'zod';
24
- import type { Configure } from '../common.ts';
25
- import {
26
- type Approval,
27
- isTool,
28
- keyed,
29
- sentTo,
30
- specOf,
31
- type Target,
32
- type TargetOptions,
33
- text,
34
- type Tool,
35
- type ToolSpec,
36
- } from '../tools.ts';
37
- import { waitForSignal } from './state.ts';
38
-
39
- /**
40
- * The context of an agentlib agent's run (agentlib's `RunContext.context`,
41
- * and a tool's `context.context`): the invocation's context of the classic
42
- * SDK. An operation awaits its calls with `internal.adopt` of
43
- * @restatedev/restate-sdk-gen.
44
- */
45
- export interface AgentlibContext {
46
- readonly ctx: restate.ObjectContext;
47
- }
48
-
49
- /** A tool of agentlib (`tool`, `asyncTool`, `serviceTool`, `agentTool`, MCP's...). */
50
- // A tool of any context (the agent's is AgentlibContext).
51
- // oxlint-disable-next-line typescript/no-explicit-any
52
- export type AgentlibTool = LibTool<any>;
53
-
54
- /**
55
- * An agentlib agent's tools: the tools of `@restatedev/agents` (named by
56
- * their `name`), and agentlib's own (named by their key), in a list or in
57
- * one record.
58
- */
59
- export type Tools =
60
- | ReadonlyArray<Tool | Record<string, AgentlibTool>>
61
- | Record<string, AgentlibTool | Tool>;
62
-
63
- export type { Approval };
64
-
65
- /**
66
- * Gives each tool its name, turning the tools of `@restatedev/agents` into
67
- * agentlib's. Those that `approval` names wait for a person's approval.
68
- */
69
- export function toolsOf(
70
- agent: string,
71
- tools: Tools,
72
- approval?: Approval,
73
- ): Record<string, AgentlibTool> {
74
- const named: Record<string, AgentlibTool> = {};
75
- const ours = new Set<string>();
76
- const add = (name: string, tool: AgentlibTool | Tool) => {
77
- if (name in named) throw new Error(`${agent}: two tools are named ${name}`);
78
- if (isTool(tool)) {
79
- named[name] = fromTool(tool, name, approval);
80
- ours.add(name);
81
- } else {
82
- named[name] = tool;
83
- }
84
- };
85
- const addRecord = (record: Record<string, AgentlibTool | Tool>) => {
86
- for (const [name, tool] of Object.entries(record)) add(name, tool);
87
- };
88
-
89
- if (Array.isArray(tools)) {
90
- for (const tool of tools as ReadonlyArray<Tool | Record<string, AgentlibTool>>) {
91
- if (isTool(tool)) add(tool.name, tool);
92
- else addRecord(tool);
93
- }
94
- } else {
95
- addRecord(tools as Record<string, AgentlibTool | Tool>);
96
- }
97
-
98
- for (const name of Array.isArray(approval) ? approval : []) {
99
- if (ours.has(name)) continue;
100
- throw new Error(
101
- `${agent}: approval names ${name}, which is none of its tools of @restatedev/agents ` +
102
- "(agentlib's own tools take needsApproval)",
103
- );
104
- }
105
- return named;
106
- }
107
-
108
- /**
109
- * Turns `tool`, one of `@restatedev/agents`, into agentlib's, named `name`.
110
- * As in every agent, arguments that do not fit its input are the model's to
111
- * fix, and a terminal error is the tool's answer, which the model sees.
112
- */
113
- export function fromTool(tool: Tool, name = tool.name, approval?: Approval): AgentlibTool {
114
- const spec = specOf(tool);
115
- if (!spec) {
116
- throw new Error(`${tool.name} is no tool of @restatedev/agents (tool(), call, send...)`);
117
- }
118
-
119
- function* execute(
120
- input: Record<string, unknown>,
121
- { context, callId }: LibToolContext<AgentlibContext>,
122
- ): Operation<JsonValue> {
123
- try {
124
- return yield* perform(tool, spec, input, context.ctx, callId);
125
- } catch (error) {
126
- // A tool() that reached for what an agentlib agent lacks is a programming
127
- // error: it fails the turn, rather than reach the model as an answer.
128
- if (error instanceof restate.TerminalError && error.message.startsWith(MISSING)) {
129
- throw new RunFailedError(`the tool ${tool.name}: ${error.message}`);
130
- }
131
- throw error;
132
- }
133
- }
134
-
135
- // agentlib's own tool(): it checks the input, and asks for the approval.
136
- return libTool<z.ZodObject, AgentlibContext>({
137
- description: tool.description,
138
- input: tool.input,
139
- needsApproval: needsApprovalOf(name, approval),
140
- execute,
141
- });
142
- }
143
-
144
- /** Whether the tool `name` needs approval, as agentlib's `needsApproval` takes it. */
145
- function needsApprovalOf(name: string, approval: Approval | undefined) {
146
- if (approval === undefined) return false;
147
- if (typeof approval !== 'function') return approval.includes(name);
148
- const asks = approval;
149
- // oxlint-disable-next-line require-yield -- deciding needs no wait
150
- return function* (args: unknown): Operation<boolean> {
151
- return asks({ name, args });
152
- };
153
- }
154
-
155
- /** Does what `tool` does, with its checked `input`, as tool call `callId`. */
156
- function* perform(
157
- tool: Tool,
158
- spec: ToolSpec,
159
- input: Record<string, unknown>,
160
- ctx: restate.ObjectContext,
161
- callId: string,
162
- ): Operation<JsonValue> {
163
- switch (spec.kind) {
164
- case 'run':
165
- return yield* runTool(tool.name, spec.run, input, ctx, callId);
166
- case 'call':
167
- return yield* callTool(tool.name, spec, input, ctx);
168
- case 'send':
169
- return yield* sendTool(tool.name, spec, input, ctx);
170
- case 'workflow':
171
- return yield* workflowTool(tool.name, spec, input, ctx, callId);
172
- case 'signal': {
173
- const shown = spec.shown ? input : undefined;
174
- return text(yield* waitForSignal(ctx, callId, spec.name, shown));
175
- }
176
- case 'subagent': {
177
- const { name, task } = input as { name: string; task: string };
178
- return text(yield* callJson(spec.agent, spec.handler, `${ctx.key}.${name}`, task));
179
- }
180
- default:
181
- throw new Error(`the tool ${tool.name} does what no agentlib agent knows`);
182
- }
183
- }
184
-
185
- // One function per kind of tool.
186
-
187
- type Spec<K extends ToolSpec['kind']> = Extract<ToolSpec, { kind: K }>;
188
-
189
- /**
190
- * A `tool()`: its `run` as a journaled step. It has no retry limit of its
191
- * own: a failure fails the attempt, which Restate retries.
192
- */
193
- function* runTool(
194
- name: string,
195
- runOf: Spec<'run'>['run'],
196
- input: unknown,
197
- ctx: restate.ObjectContext,
198
- callId: string,
199
- ): Operation<JsonValue> {
200
- const context = { ctx: sessionOf(ctx), callId, idempotencyKey: `${ctx.request().id}:${callId}` };
201
- const action = runOf as (input: unknown, context: unknown) => unknown;
202
- return yield* run(async () => text(await action(input, context)), { name, retry: {} });
203
- }
204
-
205
- /** A `call`: a call of the handler, or the run of a workflow, which it waits for. */
206
- function* callTool(
207
- name: string,
208
- spec: Spec<'call'>,
209
- input: Record<string, unknown>,
210
- ctx: restate.ObjectContext,
211
- ) {
212
- const { target, handler, options } = spec;
213
- const { key, parameter } = yield* split(name, target, options, input, ctx);
214
- if ('workflow' in target && handler === 'run') {
215
- return text(yield* runWorkflow(target.name, key!, parameter));
216
- }
217
- return text(yield* callJson(target.name, handler, key, parameter));
218
- }
219
-
220
- /** A `send`: a one-way call, after the tool's `delay` if it has one. */
221
- function* sendTool(
222
- name: string,
223
- spec: Spec<'send'>,
224
- input: Record<string, unknown>,
225
- ctx: restate.ObjectContext,
226
- ) {
227
- const { target, handler, options } = spec;
228
- const { key, parameter } = yield* split(name, target, options, input, ctx);
229
- const message = { service: target.name, method: handler, key, parameter, inputSerde: serde.json };
230
- send(options.delay === undefined ? message : { ...message, delay: options.delay });
231
- return sentTo(target.name, key, handler);
232
- }
233
-
234
- /** A `workflow`: a run of its own per tool call, unless the tool's `key` gives its id. */
235
- function* workflowTool(
236
- name: string,
237
- spec: Spec<'workflow'>,
238
- input: Record<string, unknown>,
239
- ctx: restate.ObjectContext,
240
- callId: string,
241
- ) {
242
- const { target, options } = spec;
243
- const key =
244
- options.key === undefined ? `${ctx.key}-${callId}` : yield* configured(name, options.key, ctx);
245
- return text(yield* runWorkflow(target.name, key, options.input ? input : undefined));
246
- }
247
-
248
- // The calls.
249
-
250
- /** Calls `method` of `service` (at `key`), with JSON in and out. */
251
- function callJson(service: string, method: string, key: string | undefined, parameter: unknown) {
252
- return call<unknown, unknown>({
253
- service,
254
- method,
255
- key,
256
- parameter,
257
- inputSerde: serde.json,
258
- outputSerde: serde.json,
259
- });
260
- }
261
-
262
- /**
263
- * Runs workflow `service` with id `key` to its end, and returns its result.
264
- * A workflow's `run` runs once per id: Restate refuses a second call of it,
265
- * but that call's invocation id is the run's. So the tool calls `run`, takes
266
- * the call's invocation id, and waits for that invocation; a fixed id that
267
- * ran before gets its run's result. It is a call, not a send, so that
268
- * stopping the turn cancels the run.
269
- */
270
- function* runWorkflow(service: string, key: string, parameter: unknown): Operation<unknown> {
271
- const started = call<unknown>({
272
- service,
273
- method: 'run',
274
- key,
275
- parameter,
276
- inputSerde: serde.json,
277
- outputSerde: serde.binary,
278
- });
279
- const invocation = yield* started.invocation;
280
- return yield* invocation.attach(serde.json);
281
- }
282
-
283
- /** The key, and the handler's input, of a tool call's input (as `split` in ../tools.ts). */
284
- function* split(
285
- name: string,
286
- target: Target,
287
- options: TargetOptions<z.ZodObject | undefined>,
288
- input: Record<string, unknown>,
289
- ctx: restate.ObjectContext,
290
- ): Operation<{ key: string | undefined; parameter: unknown }> {
291
- if (!keyed(target)) {
292
- return { key: undefined, parameter: options.input ? input : undefined };
293
- }
294
- if (options.key !== undefined) {
295
- const key = yield* configured(name, options.key, ctx);
296
- return { key, parameter: options.input ? input : undefined };
297
- }
298
- // The model chose the key, as a field of the tool's input.
299
- const { key, ...rest } = input as { key: string };
300
- return { key, parameter: options.input ? rest : undefined };
301
- }
302
-
303
- /** `value`, or, for a function of a session's context, what it returns, as a journaled step. */
304
- function* configured<T>(
305
- name: string,
306
- value: Configure<T>,
307
- ctx: restate.ObjectContext,
308
- ): Operation<T> {
309
- if (typeof value !== 'function') return value;
310
- const session = sessionOf(ctx);
311
- const of = value as (ctx: SessionContext) => T | Promise<T>;
312
- return yield* run(async () => of(session), { name: `${name}: key` });
313
- }
314
-
315
- // What a tool() gets as its ctx.
316
-
317
- /** How the error of a `tool()` that reached for a missing `ctx` field starts. */
318
- const MISSING = 'not in an agentlib agent:';
319
-
320
- const NO_DATABASE = 'an agentlib agent keeps its conversation in its state, with no SQL database';
321
-
322
- const CALLS_INSTEAD =
323
- "give the agent Restate's tools (call, send, workflow, subagent) or agentlib's own";
324
-
325
- /** Throws the error for a `tool()` that reached for `what`, saying what to use `instead`. */
326
- function missing(what: string, instead: string): never {
327
- throw new restate.TerminalError(`${MISSING} ${what}: ${instead}`);
328
- }
329
-
330
- /**
331
- * A session object's context, as a `tool()` in an agentlib agent gets it:
332
- * `key` and `request`. Its database and calls fail the turn, saying what to
333
- * use instead.
334
- */
335
- function sessionOf(ctx: restate.ObjectContext): SessionContext {
336
- const request = ctx.request();
337
- return Object.freeze({
338
- key: ctx.key,
339
- request,
340
- get db(): never {
341
- return missing('ctx.db', NO_DATABASE);
342
- },
343
- get rpc(): never {
344
- return missing('ctx.rpc', CALLS_INSTEAD);
345
- },
346
- get send(): never {
347
- return missing('ctx.send', CALLS_INSTEAD);
348
- },
349
- get cancel(): never {
350
- return missing('ctx.cancel', CALLS_INSTEAD);
351
- },
352
- // An agentlib agent runs on the SDK's journaled context, which has no `working`: the work just runs.
353
- working: <T>(fn: () => T | Promise<T>) => (async () => fn())(),
354
- });
355
- }
@@ -1,302 +0,0 @@
1
- // A turn of the agentlib agent: its messages as clients read them, written as
2
- // the run goes, and the model's conversation, which the run loads and saves.
3
- import {
4
- LazyStateConversation,
5
- type CompactionPolicy,
6
- type Conversation,
7
- type ConversationCompactionStatus,
8
- type ConversationSnapshot,
9
- type JsonValue,
10
- type Message,
11
- type Model,
12
- type ProgressEvent,
13
- } from '@restatedev/agentlib';
14
- import { execute, type Operation } from '@restatedev/restate-sdk-gen';
15
- import type { sdk as restate } from '@restatedev/sessions/internal';
16
- import { ENDED, type Part } from '../common.ts';
17
- import { type Entry, outputOf, render, type Rendered, steeringNote } from './messages.ts';
18
- import {
19
- CONVERSATION,
20
- CONVERSATION_META,
21
- emptyMeta,
22
- entryKey,
23
- type LiveTurn,
24
- META,
25
- type Meta,
26
- read,
27
- } from './state.ts';
28
-
29
- type ToolPart = Extract<Part, { type: 'tool' }>;
30
-
31
- /** How the model's conversation is summarized at a turn's start (see the agent's `history`). */
32
- export interface Compaction {
33
- model: Model;
34
- policy?: CompactionPolicy;
35
- }
36
-
37
- /**
38
- * The model's conversation, in the state of the object of `ctx`: agentlib's
39
- * `LazyStateConversation` over that state, its reads journaled. With
40
- * `compaction`, it summarizes its earliest messages when they grow too many.
41
- */
42
- export function conversationOf(
43
- ctx: restate.ObjectContext,
44
- compaction?: Compaction,
45
- ): LazyStateConversation {
46
- const store = {
47
- *get<T>(key: string) {
48
- const value = yield* read<T>(ctx, key);
49
- return value ?? undefined;
50
- },
51
- // A state write takes effect at once (and is journaled): nothing to wait for.
52
- // oxlint-disable-next-line require-yield
53
- *set(key: string, value: unknown) {
54
- ctx.set(key, value);
55
- },
56
- };
57
- return new LazyStateConversation({
58
- stateKey: CONVERSATION,
59
- metaKey: CONVERSATION_META,
60
- store,
61
- ...(compaction && { compaction }),
62
- });
63
- }
64
-
65
- /** The text of a rendered message's text parts. */
66
- function textOf(entry: Rendered): string {
67
- const texts = entry.parts.map((part) => (part.type === 'text' ? part.text : ''));
68
- return texts.join('');
69
- }
70
-
71
- /**
72
- * A turn being answered. It keeps the turn's messages as clients read them
73
- * (one state key each), and is the run's `Conversation`: agentlib loads the
74
- * model's conversation through it, and saves the turn through it when the
75
- * run ends. Its messages are then rewritten from what the run saved, under
76
- * the same ids.
77
- */
78
- export class Turn implements Conversation {
79
- readonly live: LiveTurn;
80
- /** Summarizes the model's conversation at the run's start, if the agent's `history` says to. */
81
- compactor?: LazyStateConversation;
82
-
83
- private readonly ctx: restate.ObjectContext;
84
- private readonly meta: Meta;
85
- private readonly conversation: LazyStateConversation;
86
- /** The turn's messages, as clients read them. Message `i` has id `live.from + i`. */
87
- private entries: Rendered[] = [];
88
- /** The index in {@link entries} of each step's reply, by step. */
89
- private readonly replies = new Map<number, number>();
90
- private step = 0;
91
- /** The conversation's version, once loaded or appended to. */
92
- private version?: number;
93
- /** The turn's messages of agentlib, once the run saved them. */
94
- private saved: Message[] = [];
95
-
96
- private constructor(ctx: restate.ObjectContext, meta: Meta, live: LiveTurn) {
97
- this.ctx = ctx;
98
- this.meta = meta;
99
- this.live = live;
100
- this.conversation = conversationOf(ctx);
101
- }
102
-
103
- /**
104
- * Starts the turn that answers `prompt`. A turn before it that never ended
105
- * (its invocation was killed) ends first.
106
- */
107
- static async start(ctx: restate.ObjectContext, prompt: string): Promise<Turn> {
108
- const meta = (await ctx.get<Meta>(META)) ?? emptyMeta();
109
- if (meta.live) await Turn.endKilled(ctx, meta, meta.live);
110
-
111
- const turn = new Turn(ctx, meta, { turn: ctx.request().id, prompt, from: meta.chats, n: 0 });
112
- meta.live = turn.live;
113
- turn.entries.push({ role: 'user', parts: [{ type: 'text', text: prompt }], prompt: true });
114
- turn.write(0);
115
- return turn;
116
- }
117
-
118
- /** Ends the turn `live`, whose invocation was killed, with the note {@link ENDED}. */
119
- private static async endKilled(ctx: restate.ObjectContext, meta: Meta, live: LiveTurn) {
120
- const turn = new Turn(ctx, meta, live);
121
- for (let i = 0; i < live.n; i++) {
122
- const entry = await ctx.get<Entry>(entryKey(live.from + i));
123
- if (!entry) continue;
124
- const rendered: Rendered = { role: entry.role, parts: entry.parts };
125
- if (entry.prompt) rendered.prompt = true;
126
- turn.entries.push(rendered);
127
- }
128
- await turn.close(ENDED);
129
- }
130
-
131
- // The run's progress, as clients see it.
132
-
133
- /** Records what a progress event of the run changes. Returns whether clients see a change. */
134
- progress(event: ProgressEvent): boolean {
135
- switch (event.type) {
136
- case 'step':
137
- this.step = event.step;
138
- return false;
139
- case 'tool-start':
140
- this.toolPart(event.callId, event.name, event.input);
141
- return true;
142
- case 'tool-end': {
143
- const [index, part] = this.toolPart(event.callId, event.name);
144
- Object.assign(part, outputOf(event.result));
145
- this.write(index);
146
- return true;
147
- }
148
- case 'steering':
149
- this.entries.push({ role: 'user', parts: [{ type: 'text', text: event.message }] });
150
- this.write(this.entries.length - 1);
151
- return true;
152
- default:
153
- return false;
154
- }
155
- }
156
-
157
- /**
158
- * Returns the tool part of call `callId` and the index of its reply. A call
159
- * that started earlier (a background call can end steps later) is found
160
- * where it is; a new one is added to the current step's reply.
161
- */
162
- private toolPart(callId: string, name: string, input?: JsonValue): [number, ToolPart] {
163
- for (const [index, entry] of this.entries.entries()) {
164
- if (entry.role !== 'assistant') continue;
165
- const part = entry.parts.find((p): p is ToolPart => p.type === 'tool' && p.id === callId);
166
- if (part) return [index, part];
167
- }
168
-
169
- let index = this.replies.get(this.step);
170
- if (index === undefined) {
171
- index = this.entries.push({ role: 'assistant', parts: [] }) - 1;
172
- this.replies.set(this.step, index);
173
- }
174
- const part: ToolPart = { type: 'tool', id: callId, name, input: input ?? null };
175
- this.entries[index]!.parts.push(part);
176
- this.write(index);
177
- return [index, part];
178
- }
179
-
180
- // agentlib's Conversation: what the run loads, compacts and saves.
181
-
182
- *load(): Operation<ConversationSnapshot> {
183
- const snapshot = yield* this.conversation.load();
184
- this.version = snapshot.version;
185
- return snapshot;
186
- }
187
-
188
- *compact(): Operation<ConversationCompactionStatus> {
189
- if (!this.compactor) return 'skipped';
190
- return yield* this.compactor.compact();
191
- }
192
-
193
- /**
194
- * Saves the turn's messages. Clients then read the turn as it was saved,
195
- * with its replies' texts.
196
- */
197
- *append(messages: readonly Message[], expectedVersion: number): Operation<number> {
198
- this.version = yield* this.conversation.append(messages, expectedVersion);
199
- this.saved.push(...messages);
200
- this.rewrite(render(this.saved));
201
- return this.version;
202
- }
203
-
204
- // How the turn ends.
205
-
206
- /** Ends the turn with its answer. A run that saved nothing leaves the prompt and the answer. */
207
- async answered(answer: unknown) {
208
- if (this.saved.length === 0) {
209
- const text = typeof answer === 'string' ? answer : JSON.stringify(answer);
210
- await this.endUnsaved(text);
211
- }
212
- this.finish();
213
- }
214
-
215
- /** Ends the turn without an answer: `note` says how (stopped, refused, failed, killed). */
216
- async close(note: string) {
217
- if (this.saved.length === 0) {
218
- await this.endUnsaved(note);
219
- } else {
220
- this.rewrite([...this.entries, answerEntry(note)]);
221
- }
222
- this.finish();
223
- }
224
-
225
- /**
226
- * Ends a turn that the run did not save, with `text`. The model's
227
- * conversation gets the prompt, the messages steered to the turn, and
228
- * `text`, but not the turn's tool calls, whose results may be missing.
229
- * Clients see each open tool call closed with `text`.
230
- */
231
- private async endUnsaved(text: string) {
232
- const steered = this.entries.slice(1).filter((entry) => entry.role === 'user');
233
- const messages: Message[] = [
234
- { role: 'user', content: this.live.prompt },
235
- ...steered.map((entry): Message => ({ role: 'user', content: steeringNote(textOf(entry)) })),
236
- { role: 'assistant', content: text },
237
- ];
238
- await this.appendOutsideRun(messages);
239
-
240
- const closed = this.entries.map((entry) => closeOpenCalls(entry, text));
241
- this.rewrite([...closed, answerEntry(text)]);
242
- }
243
-
244
- /** Appends `messages` to the model's conversation outside the run, in an operation of its own. */
245
- private async appendOutsideRun(messages: Message[]) {
246
- const conversation = this.conversation;
247
- const known = this.version;
248
- function* append(): Operation<number> {
249
- const version = known ?? (yield* conversation.load()).version;
250
- return yield* conversation.append(messages, version);
251
- }
252
- this.version = await execute(this.ctx, append());
253
- }
254
-
255
- /** Marks the turn ended: the next turn's messages start after its own. */
256
- private finish() {
257
- this.meta.chats = this.live.from + this.entries.length;
258
- delete this.meta.live;
259
- this.ctx.set(META, this.meta);
260
- }
261
-
262
- // Storing the turn's messages.
263
-
264
- /** Stores message `i` of the turn with the next cursor, and the turn's bookkeeping. */
265
- private write(i: number) {
266
- this.meta.cursor += 1;
267
- const entry: Entry = { ...this.entries[i]!, at: this.meta.cursor };
268
- this.ctx.set(entryKey(this.live.from + i), entry);
269
- this.live.n = Math.max(this.live.n, this.entries.length);
270
- this.ctx.set(META, this.meta);
271
- }
272
-
273
- /** Replaces the turn's messages with `entries`, each with a new cursor, in order. */
274
- private rewrite(entries: Rendered[]) {
275
- for (let i = entries.length; i < this.live.n; i++) {
276
- this.ctx.clear(entryKey(this.live.from + i));
277
- }
278
- this.entries = entries;
279
- this.live.n = entries.length;
280
- for (let i = 0; i < entries.length; i++) this.write(i);
281
- }
282
- }
283
-
284
- /** A reply that answers a turn with `text`. */
285
- function answerEntry(text: string): Rendered {
286
- return { role: 'assistant', parts: [{ type: 'text', text }], answer: true };
287
- }
288
-
289
- /** Whether `part` is a tool call without an output yet. */
290
- function isOpenCall(part: Part): part is ToolPart {
291
- return part.type === 'tool' && part.output === undefined;
292
- }
293
-
294
- /** Gives each tool call of `entry` that has no output yet `text` as its output, as an error. */
295
- function closeOpenCalls(entry: Rendered, text: string): Rendered {
296
- if (entry.role !== 'assistant' || !entry.parts.some(isOpenCall)) return entry;
297
- const parts = entry.parts.map((part): Part => {
298
- if (!isOpenCall(part)) return part;
299
- return { ...part, output: text, error: true };
300
- });
301
- return { ...entry, parts };
302
- }