@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/tools.ts DELETED
@@ -1,515 +0,0 @@
1
- // Tools for any of the frameworks: defined once with `tool()`, given to any
2
- // agent's `tools`, which turns them into the framework's own. And the tools
3
- // that are Restate itself: calling a handler, sending to one, running a
4
- // workflow, and waiting for a signal.
5
- //
6
- // A tool runs with the agent's context, and with the id of the model's tool
7
- // call: Restate calls carry an idempotency key made of the invocation id and
8
- // that id, so a tool call run again after a crash makes the same call, once.
9
- // A workflow's `run` is the exception: it runs once per workflow id, and
10
- // Restate refuses a second call of it whatever its idempotency key, so the
11
- // tool waits for the run by its invocation id ({@link runWorkflow}).
12
- import * as restate from '@restatedev/sessions';
13
- import { attach, start } from '@restatedev/sessions/internal';
14
- import { z } from 'zod';
15
- import { stopSignalOf, type Configure, configured, ToolError } from './common.ts';
16
- import { callOf } from './calls.ts';
17
- import { companionHere, NoCompanion } from './companion.ts';
18
-
19
- const TOOL = Symbol.for('restate-agents.tool');
20
- const SPEC = Symbol.for('restate-agents.tool-spec');
21
-
22
- /** A tool call: the agent's context, and the id of the model's call. */
23
- export interface ToolCall {
24
- /** The agent's context: Restate calls, `ctx.key`, `ctx.db`... */
25
- ctx: restate.SessionContext;
26
- /** The id of the model's tool call: the same when a crash runs the call again. */
27
- callId: string;
28
- }
29
-
30
- /** What a tool's `run` gets besides its input. */
31
- export interface ToolContext extends ToolCall {
32
- /**
33
- * The tool call's idempotency key, `<invocation id>:<call id>`: for a call
34
- * the tool makes once, however often it runs (a Restate call's
35
- * `idempotencyKey`, or a payment API's).
36
- */
37
- idempotencyKey: string;
38
- }
39
-
40
- /** A tool of any framework: see {@link tool}. */
41
- export interface Tool {
42
- readonly [TOOL]: true;
43
- readonly name: string;
44
- readonly description: string;
45
- /** The input: a zod object. A framework offers it to the model as its JSON schema ({@link jsonSchemaOf}). */
46
- readonly input: z.ZodObject;
47
- /**
48
- * Its result, as text for the model, of the model's arguments as they came:
49
- * `run` checks them against `input`, and answers arguments that do not fit
50
- * with what is wrong, for the model to call it again.
51
- */
52
- run(args: unknown, call: ToolCall): Promise<string>;
53
- }
54
-
55
- /**
56
- * What a tool does, beside its `run` (which takes a session object's
57
- * context): for a framework whose agent is no session object (agentlib's,
58
- * on the classic SDK), which makes the same calls its own way. Restate's
59
- * tools say which call; a `tool()`, its `run`.
60
- */
61
- export type ToolSpec =
62
- | { kind: 'run'; run: (input: never, context: ToolContext) => unknown }
63
- | { kind: 'call'; target: Target; handler: string; options: TargetOptions<z.ZodObject | undefined> }
64
- | {
65
- kind: 'send';
66
- target: Target;
67
- handler: string;
68
- options: TargetOptions<z.ZodObject | undefined> & { delay?: restate.Duration };
69
- }
70
- | { kind: 'workflow'; target: Target; options: TargetOptions<z.ZodObject | undefined> }
71
- | { kind: 'signal'; name: string; shown: boolean }
72
- | { kind: 'subagent'; agent: string; handler: string };
73
-
74
- /** `t`, saying what it does: see {@link ToolSpec}. */
75
- const withSpec = (t: Tool, spec: ToolSpec): Tool => Object.defineProperty(t, SPEC, { value: spec });
76
-
77
- /** What tool `t` does: see {@link ToolSpec}. */
78
- export const specOf = (t: Tool): ToolSpec => (t as Tool & { [SPEC]: ToolSpec })[SPEC];
79
-
80
- /**
81
- * Which tool calls wait for a person's approval before they run: the names
82
- * of their tools, or a function of a call that says whether it does. The
83
- * DeepSeek and agentlib agents take it as their `approval`.
84
- */
85
- export type Approval = readonly string[] | ((call: { name: string; args: unknown }) => boolean);
86
-
87
- /** The JSON schema of `t`'s input, which a framework offers the model. */
88
- export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<string, unknown>;
89
-
90
- /** Whether `value` is a {@link Tool}, rather than a framework's own. */
91
- export const isTool = (value: unknown): value is Tool => typeof value === 'object' && value !== null && TOOL in value;
92
-
93
- /** A result as text: a string as it is, nothing as "done", anything else as JSON. */
94
- export const text = (value: unknown) =>
95
- typeof value === 'string' ? value : value === null || value === undefined ? 'done' : JSON.stringify(value);
96
-
97
- /**
98
- * A tool, for any framework's agent:
99
- *
100
- * const weather = tool({
101
- * name: 'get_weather',
102
- * description: 'The current weather in a city.',
103
- * input: z.object({ city: z.string() }),
104
- * run: async ({ city }) => `Sunny in ${city}`,
105
- * });
106
- *
107
- * `run` returns the result (or a promise of it), text or anything JSON; it
108
- * gets the agent's `ctx`, the tool call's `callId`, and an `idempotencyKey`
109
- * made of both, for what the tool must do once. A `restate.TerminalError` it throws (or
110
- * a Restate call it makes fails with) is its answer, `Error: <message>`, for
111
- * the model to act on; and so are arguments that do not fit `input`, which
112
- * `run` never sees.
113
- *
114
- * A tool does not keep its attempt alive: one that works for longer than
115
- * Restate's inactivity timeout (a minute, by default) is cut off, and done
116
- * again from the start of the turn, by every attempt. One that must work
117
- * that long sets `keepalive`, and runs in `ctx.working`; it keeps long waits
118
- * on Restate (a call, a signal) out of its `run`, or holds its process for
119
- * as long as they take.
120
- */
121
- export const tool = <S extends z.ZodObject>(options: {
122
- name: string;
123
- description: string;
124
- input: S;
125
- run: (input: z.infer<S>, context: ToolContext) => unknown;
126
- /** Keep the attempt alive while `run` runs: see {@link tool}. */
127
- keepalive?: boolean;
128
- }): Tool => withSpec(ownTool(options), { kind: 'run', run: options.run });
129
-
130
- /** {@link tool}, without its spec: Restate's tools give their own. */
131
- const ownTool = <S extends z.ZodObject>(options: {
132
- name: string;
133
- description: string;
134
- input: S;
135
- run: (input: z.infer<S>, context: ToolContext) => unknown;
136
- keepalive?: boolean;
137
- }): Tool => ({
138
- [TOOL]: true,
139
- name: options.name,
140
- description: options.description,
141
- input: options.input,
142
- run: async (args, { ctx, callId }) => {
143
- // Arguments that do not fit: the model's to fix. Failing the attempt
144
- // instead, a retry would meet the same stored call again, and fail again.
145
- const parsed = options.input.safeParse(args);
146
- if (!parsed.success) return `Error: the arguments do not fit the tool's input: ${z.prettifyError(parsed.error)}`;
147
- const input = parsed.data;
148
- try {
149
- const run = () => options.run(input, { ctx, callId, idempotencyKey: `${ctx.request.id}:${callId}` });
150
- return text(await (options.keepalive ? ctx.working(run) : run()));
151
- } catch (error) {
152
- // The turn stopped (its invocation was cancelled, or its attempt
153
- // ended): it ends, rather than the model going on with the tool's error
154
- // as its answer (such as the failure of a call that the cancellation
155
- // cancelled).
156
- const turn = stopSignalOf(ctx);
157
- if (turn?.aborted) throw turn.reason;
158
- if (error instanceof restate.CancelledError) throw error;
159
- // An object without a companion, waiting for a signal: a programming error, which fails the turn once,
160
- // rather than an answer for the model to act on.
161
- if (error instanceof NoCompanion) throw error;
162
- // A terminal error is the tool's answer, which the model can act on; any
163
- // other error fails the attempt, which Restate retries.
164
- if (error instanceof restate.TerminalError) return `Error: ${error.message}`;
165
- throw new ToolError(options.name, error);
166
- }
167
- },
168
- });
169
-
170
- /**
171
- * `body`, a Restate call of tool `name` with `input`, made once however often
172
- * the tool call runs (see calls.ts): it gets the id of the call, which an
173
- * earlier attempt may have made, and so its idempotency key.
174
- */
175
- async function once<T>(
176
- name: string,
177
- input: unknown,
178
- context: ToolCall,
179
- body: (call: ToolContext) => Promise<T>,
180
- options?: { rejoin?: boolean; approval?: boolean },
181
- ) {
182
- const { ctx } = context;
183
- const call = await callOf(ctx, name, input, context.callId, options);
184
- try {
185
- const result = await body({ ctx, callId: call.id, idempotencyKey: `${ctx.request.id}:${call.id}` });
186
- await call.answered();
187
- return result;
188
- } catch (error) {
189
- // A terminal error answers the call; any other fails the attempt, and the
190
- // retry makes the call again.
191
- if (error instanceof restate.TerminalError) await call.answered(`Error: ${error.message}`);
192
- throw error;
193
- }
194
- }
195
-
196
- /** A service, virtual object or workflow, as its definition (`restate.service(...)` and so on), of handlers `M`. */
197
- export type Target<M = unknown> =
198
- | restate.ServiceDefinition<string, M>
199
- | restate.VirtualObjectDefinition<string, M>
200
- | restate.WorkflowDefinition<string, M>;
201
- /** Whether a target is keyed: a virtual object (key) or a workflow (id). */
202
- export const keyed = (target: Target) => 'object' in target || 'workflow' in target;
203
-
204
- /**
205
- * Call `method` of `service`, with JSON in and out, once per tool call (see
206
- * {@link ToolContext}): the call's idempotency key makes the call a new
207
- * attempt makes again (after a crash, or a suspension) the one the first
208
- * made, whose result it gets. A workflow's `run` runs instead ({@link runWorkflow}).
209
- */
210
- const invoke = (
211
- { ctx, idempotencyKey }: ToolContext,
212
- target: { service: string; method: string; key?: string; parameter: unknown; workflow?: boolean },
213
- ) =>
214
- target.workflow && target.method === 'run'
215
- ? runWorkflow(ctx, { service: target.service, key: target.key!, input: target.parameter })
216
- : ctx.rpc({
217
- service: target.service,
218
- handler: target.method,
219
- key: target.key,
220
- input: target.parameter,
221
- idempotencyKey,
222
- });
223
-
224
- /**
225
- * Run workflow `service` (its `run` handler) with id `key` and `input` to its
226
- * end, and resolve to its result: a call of it, whose result it does not wait
227
- * for, then a wait for the run by the call's invocation id. A workflow's
228
- * `run` runs once per id: Restate refuses a second call of it, whatever the
229
- * call's idempotency key, but that call's invocation id is the run's. So a
230
- * new attempt (after a crash, or a suspension while the run went on) that
231
- * makes the call again waits for the run an earlier attempt started, and
232
- * only the first starts one; and a fixed id that ran before gets its run's
233
- * result. It is a call, not a send: stopping the turn cancels the run, as it
234
- * cancels the turn's other calls (`cancelCalls`). The Python SDK's
235
- * `run_workflow` sends instead, and so leaves the run going.
236
- */
237
- export const runWorkflow = async (
238
- ctx: restate.SessionContext,
239
- { service, key, input }: { service: string; key: string; input: unknown },
240
- ): Promise<unknown> => attach(ctx, await start(ctx, { service, handler: 'run', key, input }));
241
-
242
- export interface TargetOptions<S extends z.ZodObject | undefined> {
243
- /** The tool's name, for the model; by default the handler's, such as `orders_status`. */
244
- name?: string;
245
- /** What it does, for the model. */
246
- description: string;
247
- /** The handler's input: a zod object, which the model fills in. Without one, the handler takes none. */
248
- input?: S;
249
- /**
250
- * For a virtual object, its key (or the workflow's id): fixed, or for an
251
- * invocation. Without one, the model chooses it.
252
- */
253
- key?: Configure<string>;
254
- }
255
-
256
- /** The tool's input: the handler's, and the key if the model chooses it. */
257
- function inputOf(target: Target, { input, key }: TargetOptions<z.ZodObject | undefined>) {
258
- const shape = input?.shape ?? {};
259
- if (!keyed(target) || key !== undefined) return z.object(shape);
260
- return z.object({ key: z.string().describe(`Which ${target.name}: its key`), ...shape });
261
- }
262
-
263
- /** The key, and the handler's input, of a tool call's input. */
264
- async function split(
265
- target: Target,
266
- options: TargetOptions<z.ZodObject | undefined>,
267
- all: Record<string, unknown>,
268
- ctx: restate.SessionContext,
269
- ) {
270
- if (!keyed(target)) return { key: undefined, parameter: options.input ? all : undefined };
271
- if (options.key !== undefined) {
272
- return { key: await configured(options.key, ctx), parameter: options.input ? all : undefined };
273
- }
274
- const { key, ...rest } = all as { key: string };
275
- return { key, parameter: options.input ? rest : undefined };
276
- }
277
-
278
- /**
279
- * A tool that calls `handler` of `target` and answers with its result:
280
- *
281
- * call(orders, 'status', {
282
- * description: 'The status of an order.',
283
- * input: z.object({ order: z.string() }),
284
- * })
285
- *
286
- * Of a virtual object, the model chooses the key, unless `key` gives it.
287
- */
288
- export const call = <M, S extends z.ZodObject | undefined = undefined>(
289
- target: Target<M>,
290
- handler: keyof M & string,
291
- options: TargetOptions<S>,
292
- ): Tool =>
293
- withSpec(
294
- ownTool({
295
- name: options.name ?? `${target.name}_${handler}`,
296
- description: options.description,
297
- input: inputOf(target, options),
298
- run: async (input, context) =>
299
- once(`${target.name}/${handler}`, input, context, async (c) =>
300
- invoke(c, {
301
- service: target.name,
302
- method: handler,
303
- workflow: 'workflow' in target,
304
- ...(await split(target, options, input, c.ctx)),
305
- }),
306
- ),
307
- }),
308
- { kind: 'call', target: target as Target, handler, options },
309
- );
310
-
311
- /**
312
- * A tool that sends to `handler` of `target`, without waiting for it: a
313
- * one-way call, made once, after `delay` if given (such as `{ minutes: 5 }`).
314
- */
315
- export const send = <M, S extends z.ZodObject | undefined = undefined>(
316
- target: Target<M>,
317
- handler: keyof M & string,
318
- options: TargetOptions<S> & { delay?: restate.Duration },
319
- ): Tool =>
320
- withSpec(
321
- ownTool({
322
- name: options.name ?? `${target.name}_${handler}`,
323
- description: options.description,
324
- input: inputOf(target, options),
325
- run: async (input, context) =>
326
- once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
327
- const { key, parameter } = await split(target, options, input, ctx);
328
- ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
329
- return sentTo(target.name, key, handler);
330
- }),
331
- }),
332
- { kind: 'send', target: target as Target, handler, options },
333
- );
334
-
335
- /** What a send tool answers: where it sent. */
336
- export const sentTo = (service: string, key: string | undefined, handler: string) =>
337
- `sent to ${service}${key === undefined ? '' : `/${key}`}/${handler}`;
338
-
339
- /**
340
- * A tool that runs the workflow `target` (its `run` handler) to the end, and
341
- * answers with its result. Each tool call is a workflow of its own, with an
342
- * id made of the agent's key and the tool call's id, unless `key` gives one.
343
- * A tool call made again (after a crash, or a suspension while the workflow
344
- * ran) waits for the run it started, and a `key` that ran before gets that
345
- * run's result ({@link runWorkflow}).
346
- */
347
- export const workflow = <S extends z.ZodObject | undefined = undefined>(
348
- target: restate.WorkflowDefinition<string, { run: unknown }>,
349
- options: TargetOptions<S>,
350
- ): Tool =>
351
- withSpec(
352
- ownTool({
353
- name: options.name ?? target.name,
354
- description: options.description,
355
- input: z.object(options.input?.shape ?? {}),
356
- run: async (input, context) =>
357
- once(target.name, input, context, async (c) =>
358
- runWorkflow(c.ctx, {
359
- service: target.name,
360
- key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
361
- input: options.input ? input : undefined,
362
- }),
363
- ),
364
- }),
365
- { kind: 'workflow', target: target as Target, options },
366
- );
367
-
368
- /** An object with a `chat` handler; another object needs subagent's `handler`. */
369
- type WithChat<M> = M extends { chat: unknown }
370
- ? unknown
371
- : { 'an agent with a chat handler, or a handler option': never };
372
-
373
- /**
374
- * A tool, named after `agent` (an agent, or any virtual object) unless `name` names it, that hands
375
- * a task to it: to the object keyed `<this key>.<task name>`, through its
376
- * `handler` (`chat`), and answers with its answer. Tasks of different names
377
- * run at once; the same name continues the same task. The model reads what
378
- * the agent is from its `description` (or `description` here).
379
- *
380
- * const coder = pi.agent({ name: 'coder', description: 'Builds and tests code in Python' });
381
- * const lead = pi.agent({ name: 'lead', tools: [subagent(coder)] });
382
- */
383
- export function subagent<M>(
384
- agent: restate.VirtualObjectDefinition<string, M> & WithChat<M>,
385
- options?: { description?: string; name?: string },
386
- ): Tool;
387
- /** A sub-agent through another of its handlers. */
388
- export function subagent<M>(
389
- agent: restate.VirtualObjectDefinition<string, M>,
390
- options: { description?: string; name?: string; handler: keyof M & string },
391
- ): Tool;
392
- export function subagent<M>(
393
- agent: restate.VirtualObjectDefinition<string, M>,
394
- {
395
- description = (agent as { description?: string }).description,
396
- name: toolName = agent.name,
397
- handler,
398
- }: { description?: string; name?: string; handler?: keyof M & string } = {},
399
- ): Tool {
400
- return withSpec(subagentTool(agent.name, toolName, description, handler ?? 'chat'), {
401
- kind: 'subagent',
402
- agent: agent.name,
403
- handler: handler ?? 'chat',
404
- });
405
- }
406
-
407
- /** {@link subagent}'s tool, without its spec. */
408
- function subagentTool(agentName: string, toolName: string, description: string | undefined, handler: string): Tool {
409
- return ownTool({
410
- name: toolName,
411
- description:
412
- `Hand a task to the ${agentName} agent${description ? ` (${description})` : ''}, and get its answer. ` +
413
- 'Tasks of different names run at once; the same name continues the same task.',
414
- input: z.object({
415
- name: z
416
- .string()
417
- .regex(/^[a-z0-9-]+$/)
418
- .describe('A short name for the task, such as "fizzbuzz"'),
419
- task: z.string().describe('The task in full: the agent sees nothing else'),
420
- }),
421
- run: async ({ name, task }, context) =>
422
- once(agentName, { name, task }, context, (c) =>
423
- invoke(c, { service: agentName, key: `${c.ctx.key}.${name}`, method: handler, parameter: task }),
424
- ),
425
- });
426
- }
427
-
428
- /**
429
- * A tool that waits for the signal `name` to the agent, and answers with its
430
- * value: a person's approval, say, or another system's result. The agent
431
- * waits without holding a process. With an `input`, the model says what it
432
- * waits for (such as the refund to approve), which `pending` shows.
433
- *
434
- * signal('approval', {
435
- * description: 'Wait for a manager to approve a refund.',
436
- * input: z.object({ order: z.string(), amount: z.number() }),
437
- * })
438
- *
439
- * Each wait has an id: `pending` (each `sessionObject()` has it) lists them, and
440
- * the agent's `signal` handler resolves one, by its id, or the oldest wait
441
- * for a name:
442
- *
443
- * curl localhost:8080/support/alice/pending
444
- * curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
445
- * curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved"}'
446
- *
447
- * It answers with the id of the wait it resolved, or `null` if none waited:
448
- * the signal is dropped then, unless it has `"keep": true`, which keeps it
449
- * for the next wait for its name.
450
- */
451
- export const signal = (name: string, options: { description: string; input?: z.ZodObject; name?: string }): Tool =>
452
- withSpec(
453
- ownTool({
454
- name: options.name ?? `wait_for_${name}`,
455
- description: options.description,
456
- input: z.object(options.input?.shape ?? {}),
457
- run: async (input, context) => wait(context, name, input, { shown: options.input !== undefined }),
458
- }),
459
- { kind: 'signal', name, shown: options.input !== undefined },
460
- );
461
-
462
- /**
463
- * Wait for signal `name` as tool call `toolCall`, once however often it runs;
464
- * `pending` shows `input` if `shown`. `rejoin` and `approval` are
465
- * {@link callOf}'s.
466
- */
467
- const wait = async (
468
- toolCall: ToolCall,
469
- name: string,
470
- input: unknown,
471
- { shown, rejoin, approval }: { shown: boolean; rejoin?: boolean; approval?: boolean },
472
- ): Promise<unknown> => {
473
- // Before the call is recorded: an object without a companion fails the turn, once (`NoCompanion`).
474
- const companion = companionHere(toolCall.ctx, 'a wait for a signal');
475
- return once(
476
- `signal/${name}`,
477
- input,
478
- toolCall,
479
- async ({ ctx, idempotencyKey: id }) =>
480
- ctx.rpc(companion, ctx.key, { idempotencyKey: id }).wait({ id, name, ...(shown ? { input } : {}) }),
481
- { rejoin, approval },
482
- );
483
- };
484
-
485
- /**
486
- * Wait for the signal `name` to the agent, for the model's tool call
487
- * `callId`, and answer with its value: what a {@link signal} tool does, for
488
- * a framework whose own tool calls wait for something outside (an approval,
489
- * say). The wait's id is `<invocation id>:<call id>`; `pending` lists it
490
- * (with `input`, if given), and `signal` resolves it. It is opened once
491
- * however often the tool call runs, and a crash goes on waiting on it.
492
- *
493
- * The wait is the tool call's alone: the framework stored its tool call
494
- * before it waits, so a retried attempt waits again under the same id. A new
495
- * call with the same input (the model asking again, after the first's
496
- * answer) waits anew, as its answer is not the earlier call's.
497
- *
498
- * With `approval`, the tool call runs only after the wait: the wait's
499
- * answer is not the call's, so a turn stopped before the call's result is
500
- * stored reports the call as not done, rather than done.
501
- *
502
- * With `rejoin`, for a framework that makes a call cut off by a crash again
503
- * under a new id (the DeepSeek Harness), the call joins the wait an earlier
504
- * attempt opened with the same input, as Restate's own tools do: the call
505
- * made again, waiting on (or getting the answer of) the same wait, until
506
- * the earlier call's result is stored. Within one attempt, a call with the
507
- * same input waits anew.
508
- */
509
- export const waitFor = (
510
- ctx: restate.SessionContext,
511
- callId: string,
512
- name: string,
513
- input?: unknown,
514
- { approval = false, rejoin = false }: { approval?: boolean; rejoin?: boolean } = {},
515
- ): Promise<unknown> => wait({ ctx, callId }, name, input ?? null, { shown: input !== undefined, rejoin, approval });
package/src/webhook.ts DELETED
@@ -1,161 +0,0 @@
1
- // Webhooks into agents: a Restate service whose one handler, `webhook`,
2
- // takes another system's webhook (Linear's, GitHub's...), checks its
3
- // signature, and delivers it to agents, as a message saying where it comes
4
- // from: to the message an agent answers, if it answers one, or else as a
5
- // message of its own.
6
- //
7
- // const issues = webhook({
8
- // name: 'linear',
9
- // auth: { header: 'linear-signature', secret: process.env.LINEAR_WEBHOOK_SECRET! },
10
- // idempotencyHeader: 'linear-delivery',
11
- // route: [triage],
12
- // key: ({ data }) => data.identifier,
13
- // });
14
- // await serve(issues, triage);
15
- //
16
- // The other system posts to Restate's ingress, at `/<name>/webhook`.
17
- import { createHmac, timingSafeEqual } from 'node:crypto';
18
- import { sdk as restate } from '@restatedev/sessions/internal';
19
- import { deliver, hasCompanion } from './companion.ts';
20
-
21
- /** How a webhook is signed: the HMAC-SHA256 of its body with `secret`, in hex, in the request's `header`. */
22
- export interface WebhookAuth {
23
- /** The header with the signature, such as `linear-signature` or `X-Hub-Signature-256` (GitHub's `sha256=` prefix is taken too), in any case. */
24
- header: string;
25
- /** The webhook's signing secret, which the other system shows when the webhook is made. */
26
- secret: string;
27
- }
28
-
29
- /** An agent (an `sessionObject()` or `agent()` of @restatedev/agents, with a `chat` handler) that webhooks go to. */
30
- type Route = restate.VirtualObjectDefinition<string, { chat: unknown }>;
31
-
32
- /**
33
- * A delivery's body: JSON, as the other system sends it, read as it is (it is
34
- * theirs to shape, not checked here).
35
- */
36
- // oxlint-disable-next-line typescript/no-explicit-any
37
- export type WebhookEvent = Record<string, any>;
38
-
39
- /** A webhook service's options. */
40
- export interface WebhookOptions<P extends string = string> {
41
- /** The service's name, which its URL starts with: `/<name>/webhook`. */
42
- name: P;
43
- /** What the webhook is, for the UI and the admin API. */
44
- description?: string;
45
- /** Its signature: a webhook without it is refused (401). Without `auth`, any request is taken. */
46
- auth?: WebhookAuth;
47
- /**
48
- * The header with the delivery's id, which a delivery sent again has too
49
- * (such as `linear-delivery`): it reaches the same message, not a second
50
- * one. Without it, each request is a delivery of its own. In any case, as
51
- * header names are.
52
- */
53
- idempotencyHeader?: string;
54
- /** The agents each delivery goes to. */
55
- route: Route[];
56
- /**
57
- * The key of the agents' object that a delivery goes to, from its body
58
- * (the issue, say: one conversation per issue), or undefined to drop the
59
- * delivery. By default, the delivery's id: a conversation per delivery.
60
- * The event is the body's JSON, untyped: `key: ({ data }) => data.identifier`.
61
- */
62
- key?(this: void, event: WebhookEvent): string | undefined;
63
- /**
64
- * What of a delivery the agents read, from its body: by default, all of
65
- * it. Some systems send much more than an agent needs (GitHub sends the
66
- * whole repository with each event): `message: ({ comment }) => ({ body: comment.body })`.
67
- */
68
- message?(this: void, event: WebhookEvent): unknown;
69
- }
70
-
71
- /**
72
- * The message an agent gets for a webhook's delivery: its body, as JSON, in
73
- * a `<webhook>` element that says which webhook, and which delivery.
74
- *
75
- * <webhook name="linear" delivery="5d2…">
76
- * {"action": "create", "type": "Issue", ...}
77
- * </webhook>
78
- */
79
- export const webhookMessage = (name: string, delivery: string, event: unknown) =>
80
- `<webhook name="${name}" delivery="${delivery}">\n${JSON.stringify(event, null, 2)}\n</webhook>`;
81
-
82
- /** Whether `signature` is the HMAC-SHA256 of `body` with `secret`, in hex. */
83
- const signed = (body: Uint8Array, signature: string | undefined, secret: string) => {
84
- const expected = createHmac('sha256', secret).update(body).digest();
85
- const given = Buffer.from((signature ?? '').replace(/^sha256=/, ''), 'hex');
86
- return given.length === expected.length && timingSafeEqual(given, expected);
87
- };
88
-
89
- /** `body` as a JSON object, or a terminal error (400) if it is not. */
90
- const parsed = (body: Uint8Array): WebhookEvent => {
91
- let event: unknown;
92
- try {
93
- event = JSON.parse(new TextDecoder().decode(body));
94
- } catch {
95
- throw new restate.TerminalError('The webhook is not JSON', { errorCode: 400 });
96
- }
97
- if (typeof event !== 'object' || event === null || Array.isArray(event)) {
98
- throw new restate.TerminalError('The webhook is not a JSON object', { errorCode: 400 });
99
- }
100
- return event;
101
- };
102
-
103
- /**
104
- * A webhook into agents: a service `name`, whose `webhook` handler checks a
105
- * delivery's signature, and delivers it to each agent of `route`, keyed by
106
- * `key`, as a {@link webhookMessage}: a message of its own (as `chat`),
107
- * which the agent answers after the messages before it. It answers once the
108
- * deliveries are sent, not answered: a system that waits seconds for an
109
- * answer (Linear, GitHub) gets one at once. What it is (its routes, auth and
110
- * idempotency) is in the handler's metadata, which the admin API shows.
111
- */
112
- export const webhook = <P extends string>({
113
- name,
114
- description,
115
- auth,
116
- idempotencyHeader,
117
- route,
118
- key,
119
- message,
120
- }: WebhookOptions<P>) => {
121
- if (route.length === 0) throw new Error(`webhook ${name}: route it to at least one agent`);
122
- for (const agent of route) {
123
- if (!hasCompanion(agent)) throw new Error(`webhook ${name}: ${agent.name} is not a sessionObject() or agent()`);
124
- }
125
- if (auth && !auth.secret) throw new Error(`webhook ${name}: its auth has no secret (unset in the environment?)`);
126
- const what = description ?? `A webhook into ${route.map((r) => r.name).join(', ')}`;
127
- // Restate gives a request's headers by their names in lower case.
128
- const signatureHeader = auth?.header.toLowerCase();
129
- const deliveryHeader = idempotencyHeader?.toLowerCase();
130
- return restate.service({
131
- name,
132
- description: what,
133
- handlers: {
134
- webhook: restate.handlers.handler(
135
- {
136
- input: restate.serde.binary,
137
- accept: '*/*',
138
- description: what,
139
- metadata: {
140
- 'restate-agents.kind': 'webhook',
141
- 'restate-agents.routes': route.map((r) => r.name).join(','),
142
- 'restate-agents.auth': auth ? `hmac-sha256:${auth.header}` : 'none',
143
- ...(idempotencyHeader ? { 'restate-agents.idempotency-header': idempotencyHeader } : {}),
144
- },
145
- },
146
- async (ctx: restate.Context, body: Uint8Array) => {
147
- const headers = ctx.request().headers;
148
- if (auth && !signed(body, headers.get(signatureHeader!), auth.secret)) {
149
- throw new restate.TerminalError(`Not signed: no valid ${auth.header}`, { errorCode: 401 });
150
- }
151
- const event = parsed(body);
152
- const delivery = (deliveryHeader && headers.get(deliveryHeader)) || ctx.request().id;
153
- const to = key ? key(event) : delivery;
154
- if (to === undefined) return;
155
- const text = webhookMessage(name, delivery, message ? message(event) : event);
156
- for (const agent of route) deliver(ctx, agent, to, text, { idempotencyKey: `webhook:${name}:${delivery}` });
157
- },
158
- ),
159
- },
160
- });
161
- };