@restatedev/agents 0.0.0 → 0.1.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 (108) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +688 -2
  3. package/dist/calls.d.ts +29 -0
  4. package/dist/calls.d.ts.map +1 -0
  5. package/dist/calls.js +91 -0
  6. package/dist/calls.js.map +1 -0
  7. package/dist/claude/conversation.d.ts +33 -0
  8. package/dist/claude/conversation.d.ts.map +1 -0
  9. package/dist/claude/conversation.js +95 -0
  10. package/dist/claude/conversation.js.map +1 -0
  11. package/dist/claude/index.d.ts +78 -0
  12. package/dist/claude/index.d.ts.map +1 -0
  13. package/dist/claude/index.js +269 -0
  14. package/dist/claude/index.js.map +1 -0
  15. package/dist/client.d.ts +83 -0
  16. package/dist/client.d.ts.map +1 -0
  17. package/dist/client.js +88 -0
  18. package/dist/client.js.map +1 -0
  19. package/dist/common.d.ts +284 -0
  20. package/dist/common.d.ts.map +1 -0
  21. package/dist/common.js +475 -0
  22. package/dist/common.js.map +1 -0
  23. package/dist/deepseek/index.d.ts +69 -0
  24. package/dist/deepseek/index.d.ts.map +1 -0
  25. package/dist/deepseek/index.js +381 -0
  26. package/dist/deepseek/index.js.map +1 -0
  27. package/dist/deepseek/persistence.d.ts +61 -0
  28. package/dist/deepseek/persistence.d.ts.map +1 -0
  29. package/dist/deepseek/persistence.js +224 -0
  30. package/dist/deepseek/persistence.js.map +1 -0
  31. package/dist/index.d.ts +15 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +37 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/langgraph/checkpointer.d.ts +29 -0
  36. package/dist/langgraph/checkpointer.d.ts.map +1 -0
  37. package/dist/langgraph/checkpointer.js +275 -0
  38. package/dist/langgraph/checkpointer.js.map +1 -0
  39. package/dist/langgraph/index.d.ts +67 -0
  40. package/dist/langgraph/index.d.ts.map +1 -0
  41. package/dist/langgraph/index.js +265 -0
  42. package/dist/langgraph/index.js.map +1 -0
  43. package/dist/log.d.ts +29 -0
  44. package/dist/log.d.ts.map +1 -0
  45. package/dist/log.js +145 -0
  46. package/dist/log.js.map +1 -0
  47. package/dist/object.d.ts +181 -0
  48. package/dist/object.d.ts.map +1 -0
  49. package/dist/object.js +232 -0
  50. package/dist/object.js.map +1 -0
  51. package/dist/opencode/db.d.ts +40 -0
  52. package/dist/opencode/db.d.ts.map +1 -0
  53. package/dist/opencode/db.js +161 -0
  54. package/dist/opencode/db.js.map +1 -0
  55. package/dist/opencode/index.d.ts +101 -0
  56. package/dist/opencode/index.d.ts.map +1 -0
  57. package/dist/opencode/index.js +464 -0
  58. package/dist/opencode/index.js.map +1 -0
  59. package/dist/output.d.ts +17 -0
  60. package/dist/output.d.ts.map +1 -0
  61. package/dist/output.js +81 -0
  62. package/dist/output.js.map +1 -0
  63. package/dist/pi/index.d.ts +90 -0
  64. package/dist/pi/index.d.ts.map +1 -0
  65. package/dist/pi/index.js +313 -0
  66. package/dist/pi/index.js.map +1 -0
  67. package/dist/pi/storage.d.ts +5 -0
  68. package/dist/pi/storage.d.ts.map +1 -0
  69. package/dist/pi/storage.js +41 -0
  70. package/dist/pi/storage.js.map +1 -0
  71. package/dist/signals.d.ts +195 -0
  72. package/dist/signals.d.ts.map +1 -0
  73. package/dist/signals.js +258 -0
  74. package/dist/signals.js.map +1 -0
  75. package/dist/tools.d.ts +158 -0
  76. package/dist/tools.d.ts.map +1 -0
  77. package/dist/tools.js +211 -0
  78. package/dist/tools.js.map +1 -0
  79. package/dist/webhook.d.ts +73 -0
  80. package/dist/webhook.d.ts.map +1 -0
  81. package/dist/webhook.js +104 -0
  82. package/dist/webhook.js.map +1 -0
  83. package/package.json +218 -5
  84. package/src/calls.ts +138 -0
  85. package/src/claude/README.md +84 -0
  86. package/src/claude/conversation.ts +114 -0
  87. package/src/claude/index.ts +364 -0
  88. package/src/client.ts +179 -0
  89. package/src/common.ts +593 -0
  90. package/src/deepseek/README.md +110 -0
  91. package/src/deepseek/index.ts +487 -0
  92. package/src/deepseek/persistence.ts +293 -0
  93. package/src/index.ts +60 -0
  94. package/src/langgraph/README.md +87 -0
  95. package/src/langgraph/checkpointer.ts +364 -0
  96. package/src/langgraph/index.ts +349 -0
  97. package/src/log.ts +193 -0
  98. package/src/object.ts +343 -0
  99. package/src/opencode/README.md +125 -0
  100. package/src/opencode/db.ts +223 -0
  101. package/src/opencode/index.ts +595 -0
  102. package/src/output.ts +95 -0
  103. package/src/pi/README.md +105 -0
  104. package/src/pi/index.ts +402 -0
  105. package/src/pi/storage.ts +65 -0
  106. package/src/signals.ts +426 -0
  107. package/src/tools.ts +343 -0
  108. package/src/webhook.ts +163 -0
package/src/tools.ts ADDED
@@ -0,0 +1,343 @@
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
+ import * as restate from '@restatedev/sessions';
10
+ import { z } from 'zod';
11
+ import { stopSignalOf, type Configure, configured, ToolError } from './common.ts';
12
+ import { callOf } from './calls.ts';
13
+ import { signals, signalsOf } from './signals.ts';
14
+
15
+ const TOOL = Symbol.for('restate-agents.tool');
16
+
17
+ /** A tool call: the agent's context, and the id of the model's call. */
18
+ export interface ToolCall {
19
+ /** The agent's context: Restate calls, `ctx.key`, `ctx.db`... */
20
+ ctx: restate.SessionContext;
21
+ /** The id of the model's tool call: the same when a crash runs the call again. */
22
+ callId: string;
23
+ }
24
+
25
+ /** What a tool's `run` gets besides its input. */
26
+ export interface ToolContext extends ToolCall {
27
+ /**
28
+ * The tool call's idempotency key, `<invocation id>:<call id>`: for a call
29
+ * the tool makes once, however often it runs (a Restate call's
30
+ * `idempotencyKey`, or a payment API's).
31
+ */
32
+ idempotencyKey: string;
33
+ }
34
+
35
+ /** A tool of any framework: see {@link tool}. */
36
+ export interface Tool {
37
+ readonly [TOOL]: true;
38
+ readonly name: string;
39
+ readonly description: string;
40
+ /** The input: a zod object. A framework offers it to the model as its JSON schema ({@link jsonSchemaOf}). */
41
+ readonly input: z.ZodObject;
42
+ /**
43
+ * Its result, as text for the model, of the model's arguments as they came:
44
+ * `run` checks them against `input`, and answers arguments that do not fit
45
+ * with what is wrong, for the model to call it again.
46
+ */
47
+ run(args: unknown, call: ToolCall): Promise<string>;
48
+ }
49
+
50
+ /** The JSON schema of `t`'s input, which a framework offers the model. */
51
+ export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<string, unknown>;
52
+
53
+ /** Whether `value` is a {@link Tool}, rather than a framework's own. */
54
+ export const isTool = (value: unknown): value is Tool => typeof value === 'object' && value !== null && TOOL in value;
55
+
56
+ /** A result as text: a string as it is, nothing as "done", anything else as JSON. */
57
+ const text = (value: unknown) =>
58
+ typeof value === 'string' ? value : value === null || value === undefined ? 'done' : JSON.stringify(value);
59
+
60
+ /**
61
+ * A tool, for any framework's agent:
62
+ *
63
+ * const weather = tool({
64
+ * name: 'get_weather',
65
+ * description: 'The current weather in a city.',
66
+ * input: z.object({ city: z.string() }),
67
+ * run: async ({ city }) => `Sunny in ${city}`,
68
+ * });
69
+ *
70
+ * `run` returns the result (or a promise of it), text or anything JSON; it
71
+ * gets the agent's `ctx`, the tool call's `callId`, and an `idempotencyKey`
72
+ * made of both, for what the tool must do once. A `restate.TerminalError` it throws (or
73
+ * a Restate call it makes fails with) is its answer, `Error: <message>`, for
74
+ * the model to act on; and so are arguments that do not fit `input`, which
75
+ * `run` never sees.
76
+ */
77
+ export const tool = <S extends z.ZodObject>(options: {
78
+ name: string;
79
+ description: string;
80
+ input: S;
81
+ run: (input: z.infer<S>, context: ToolContext) => unknown;
82
+ }): Tool => ({
83
+ [TOOL]: true,
84
+ name: options.name,
85
+ description: options.description,
86
+ input: options.input,
87
+ run: async (args, { ctx, callId }) => {
88
+ // Arguments that do not fit: the model's to fix. Failing the attempt
89
+ // instead, a retry would meet the same stored call again, and fail again.
90
+ const parsed = options.input.safeParse(args);
91
+ if (!parsed.success) return `Error: the arguments do not fit the tool's input: ${z.prettifyError(parsed.error)}`;
92
+ const input = parsed.data;
93
+ try {
94
+ return text(await options.run(input, { ctx, callId, idempotencyKey: `${ctx.request.id}:${callId}` }));
95
+ } catch (error) {
96
+ // The turn stopped (its invocation was cancelled, or its attempt
97
+ // ended): it ends, rather than the model going on with the tool's error
98
+ // as its answer (such as the failure of a call that the cancellation
99
+ // cancelled).
100
+ const turn = stopSignalOf(ctx);
101
+ if (turn?.aborted) throw turn.reason;
102
+ if (error instanceof restate.CancelledError) throw error;
103
+ // A terminal error is the tool's answer, which the model can act on; any
104
+ // other error fails the attempt, which Restate retries.
105
+ if (error instanceof restate.TerminalError) return `Error: ${error.message}`;
106
+ throw new ToolError(options.name, error);
107
+ }
108
+ },
109
+ });
110
+
111
+ /**
112
+ * `body`, a Restate call of tool `name` with `input`, made once however often
113
+ * the tool call runs (see calls.ts): it gets the id of the call, which an
114
+ * earlier attempt may have made, and so its idempotency key.
115
+ */
116
+ async function once<T>(name: string, input: unknown, context: ToolCall, body: (call: ToolContext) => Promise<T>) {
117
+ const { ctx } = context;
118
+ const call = await callOf(ctx, name, input, context.callId);
119
+ try {
120
+ const result = await body({ ctx, callId: call.id, idempotencyKey: `${ctx.request.id}:${call.id}` });
121
+ await call.answered();
122
+ return result;
123
+ } catch (error) {
124
+ // A terminal error answers the call; any other fails the attempt, and the
125
+ // retry makes the call again.
126
+ if (error instanceof restate.TerminalError) await call.answered(`Error: ${error.message}`);
127
+ throw error;
128
+ }
129
+ }
130
+
131
+ /** A service, virtual object or workflow, as its definition (`restate.service(...)` and so on), of handlers `M`. */
132
+ type Target<M = unknown> =
133
+ | restate.ServiceDefinition<string, M>
134
+ | restate.VirtualObjectDefinition<string, M>
135
+ | restate.WorkflowDefinition<string, M>;
136
+ /** Whether a target is keyed: a virtual object (key) or a workflow (id). */
137
+ const keyed = (target: Target) => 'object' in target || 'workflow' in target;
138
+
139
+ /** Call `method` of `service`, with JSON in and out, once per tool call (see {@link ToolContext}). */
140
+ const invoke = (
141
+ { ctx, idempotencyKey }: ToolContext,
142
+ target: { service: string; method: string; key?: string; parameter: unknown },
143
+ ) =>
144
+ ctx.rpc({
145
+ service: target.service,
146
+ handler: target.method,
147
+ key: target.key,
148
+ input: target.parameter,
149
+ idempotencyKey,
150
+ });
151
+
152
+ interface TargetOptions<S extends z.ZodObject | undefined> {
153
+ /** The tool's name, for the model; by default the handler's, such as `orders_status`. */
154
+ name?: string;
155
+ /** What it does, for the model. */
156
+ description: string;
157
+ /** The handler's input: a zod object, which the model fills in. Without one, the handler takes none. */
158
+ input?: S;
159
+ /**
160
+ * For a virtual object, its key (or the workflow's id): fixed, or for an
161
+ * invocation. Without one, the model chooses it.
162
+ */
163
+ key?: Configure<string>;
164
+ }
165
+
166
+ /** The tool's input: the handler's, and the key if the model chooses it. */
167
+ function inputOf(target: Target, { input, key }: TargetOptions<z.ZodObject | undefined>) {
168
+ const shape = input?.shape ?? {};
169
+ if (!keyed(target) || key !== undefined) return z.object(shape);
170
+ return z.object({ key: z.string().describe(`Which ${target.name}: its key`), ...shape });
171
+ }
172
+
173
+ /** The key, and the handler's input, of a tool call's input. */
174
+ async function split(
175
+ target: Target,
176
+ options: TargetOptions<z.ZodObject | undefined>,
177
+ all: Record<string, unknown>,
178
+ ctx: restate.SessionContext,
179
+ ) {
180
+ if (!keyed(target)) return { key: undefined, parameter: options.input ? all : undefined };
181
+ if (options.key !== undefined) {
182
+ return { key: await configured(options.key, ctx), parameter: options.input ? all : undefined };
183
+ }
184
+ const { key, ...rest } = all as { key: string };
185
+ return { key, parameter: options.input ? rest : undefined };
186
+ }
187
+
188
+ /**
189
+ * A tool that calls `handler` of `target` and answers with its result:
190
+ *
191
+ * call(orders, 'status', {
192
+ * description: 'The status of an order.',
193
+ * input: z.object({ order: z.string() }),
194
+ * })
195
+ *
196
+ * Of a virtual object, the model chooses the key, unless `key` gives it.
197
+ */
198
+ export const call = <M, S extends z.ZodObject | undefined = undefined>(
199
+ target: Target<M>,
200
+ handler: keyof M & string,
201
+ options: TargetOptions<S>,
202
+ ): Tool =>
203
+ tool({
204
+ name: options.name ?? `${target.name}_${handler}`,
205
+ description: options.description,
206
+ input: inputOf(target, options),
207
+ run: async (input, context) =>
208
+ once(`${target.name}/${handler}`, input, context, async (c) =>
209
+ invoke(c, { service: target.name, method: handler, ...(await split(target, options, input, c.ctx)) }),
210
+ ),
211
+ });
212
+
213
+ /**
214
+ * A tool that sends to `handler` of `target`, without waiting for it: a
215
+ * one-way call, made once, after `delay` if given (such as `{ minutes: 5 }`).
216
+ */
217
+ export const send = <M, S extends z.ZodObject | undefined = undefined>(
218
+ target: Target<M>,
219
+ handler: keyof M & string,
220
+ options: TargetOptions<S> & { delay?: restate.Duration },
221
+ ): Tool =>
222
+ tool({
223
+ name: options.name ?? `${target.name}_${handler}`,
224
+ description: options.description,
225
+ input: inputOf(target, options),
226
+ run: async (input, context) =>
227
+ once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
228
+ const { key, parameter } = await split(target, options, input, ctx);
229
+ ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
230
+ return `sent to ${target.name}${key === undefined ? '' : `/${key}`}/${handler}`;
231
+ }),
232
+ });
233
+
234
+ /**
235
+ * A tool that runs the workflow `target` (its `run` handler) to the end, and
236
+ * answers with its result. Each tool call is a workflow of its own, with an
237
+ * id made of the agent's key and the tool call's id, unless `key` gives one.
238
+ */
239
+ export const workflow = <S extends z.ZodObject | undefined = undefined>(
240
+ target: restate.WorkflowDefinition<string, { run: unknown }>,
241
+ options: TargetOptions<S>,
242
+ ): Tool =>
243
+ tool({
244
+ name: options.name ?? target.name,
245
+ description: options.description,
246
+ input: z.object(options.input?.shape ?? {}),
247
+ run: async (input, context) =>
248
+ once(target.name, input, context, async (c) =>
249
+ invoke(c, {
250
+ service: target.name,
251
+ method: 'run',
252
+ key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
253
+ parameter: options.input ? input : undefined,
254
+ }),
255
+ ),
256
+ });
257
+
258
+ /** An object with a `chat` handler; another object needs subagent's `handler`. */
259
+ type WithChat<M> = M extends { chat: unknown }
260
+ ? unknown
261
+ : { 'an agent with a chat handler, or a handler option': never };
262
+
263
+ /**
264
+ * A tool, named after `agent` (an agent, or any virtual object) unless `name` names it, that hands
265
+ * a task to it: to the object keyed `<this key>.<task name>`, through its
266
+ * `handler` (`chat`), and answers with its answer. Tasks of different names
267
+ * run at once; the same name continues the same task. The model reads what
268
+ * the agent is from its `description` (or `description` here).
269
+ *
270
+ * const coder = pi.agent({ name: 'coder', description: 'Builds and tests code in Python' });
271
+ * const lead = pi.agent({ name: 'lead', tools: [subagent(coder)] });
272
+ */
273
+ export function subagent<M>(
274
+ agent: restate.VirtualObjectDefinition<string, M> & WithChat<M>,
275
+ options?: { description?: string; name?: string },
276
+ ): Tool;
277
+ /** A sub-agent through another of its handlers. */
278
+ export function subagent<M>(
279
+ agent: restate.VirtualObjectDefinition<string, M>,
280
+ options: { description?: string; name?: string; handler: keyof M & string },
281
+ ): Tool;
282
+ export function subagent<M>(
283
+ agent: restate.VirtualObjectDefinition<string, M>,
284
+ {
285
+ description = (agent as { description?: string }).description,
286
+ name: toolName = agent.name,
287
+ handler,
288
+ }: { description?: string; name?: string; handler?: keyof M & string } = {},
289
+ ): Tool {
290
+ return tool({
291
+ name: toolName,
292
+ description:
293
+ `Hand a task to the ${agent.name} agent${description ? ` (${description})` : ''}, and get its answer. ` +
294
+ 'Tasks of different names run at once; the same name continues the same task.',
295
+ input: z.object({
296
+ name: z
297
+ .string()
298
+ .regex(/^[a-z0-9-]+$/)
299
+ .describe('A short name for the task, such as "fizzbuzz"'),
300
+ task: z.string().describe('The task in full: the agent sees nothing else'),
301
+ }),
302
+ run: async ({ name, task }, context) =>
303
+ once(agent.name, { name, task }, context, (c) =>
304
+ invoke(c, { service: agent.name, key: `${c.ctx.key}.${name}`, method: handler ?? 'chat', parameter: task }),
305
+ ),
306
+ });
307
+ }
308
+
309
+ /**
310
+ * A tool that waits for the signal `name` to the agent, and answers with its
311
+ * value: a person's approval, say, or another system's result. The agent
312
+ * waits without holding a process. With an `input`, the model says what it
313
+ * waits for (such as the refund to approve), which `pending` shows.
314
+ *
315
+ * signal('approval', {
316
+ * description: 'Wait for a manager to approve a refund.',
317
+ * input: z.object({ order: z.string(), amount: z.number() }),
318
+ * })
319
+ *
320
+ * Each wait has an id: `pending` (each `sessionObject()` has it) lists them, and
321
+ * the agent's `signal` handler resolves one, by its id, or the oldest wait
322
+ * for a name:
323
+ *
324
+ * curl localhost:8080/support/alice/pending
325
+ * curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
326
+ * curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved"}'
327
+ *
328
+ * It answers with the id of the wait it resolved, or `null` if none waited:
329
+ * the signal is dropped then, unless it has `"keep": true`, which keeps it
330
+ * for the next wait for its name.
331
+ */
332
+ export const signal = (name: string, options: { description: string; input?: z.ZodObject; name?: string }): Tool =>
333
+ tool({
334
+ name: options.name ?? `wait_for_${name}`,
335
+ description: options.description,
336
+ input: z.object(options.input?.shape ?? {}),
337
+ run: async (input, context) =>
338
+ once(`signal/${name}`, input, context, async ({ ctx, idempotencyKey: id }) =>
339
+ ctx
340
+ .rpc(signals, signalsOf(ctx), { idempotencyKey: id })
341
+ .wait({ id, name, ...(options.input ? { input } : {}) }),
342
+ ),
343
+ });
package/src/webhook.ts ADDED
@@ -0,0 +1,163 @@
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 './signals.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}, through the agent's `signals`: to the
107
+ * message the agent answers, if any, which takes it at its next step (as
108
+ * `steer`), or else as a message of its own (as `chat`). A turn that ends,
109
+ * or is stopped, before it takes it answers it after. It answers once the
110
+ * deliveries are sent, not answered: a system that waits seconds for an
111
+ * answer (Linear, GitHub) gets one at once. What it is (its routes, auth and
112
+ * idempotency) is in the handler's metadata, which the admin API shows.
113
+ */
114
+ export const webhook = <P extends string>({
115
+ name,
116
+ description,
117
+ auth,
118
+ idempotencyHeader,
119
+ route,
120
+ key,
121
+ message,
122
+ }: WebhookOptions<P>) => {
123
+ if (route.length === 0) throw new Error(`webhook ${name}: route it to at least one agent`);
124
+ for (const agent of route) {
125
+ if (!hasCompanion(agent)) throw new Error(`webhook ${name}: ${agent.name} is not a sessionObject() or agent()`);
126
+ }
127
+ if (auth && !auth.secret) throw new Error(`webhook ${name}: its auth has no secret (unset in the environment?)`);
128
+ const what = description ?? `A webhook into ${route.map((r) => r.name).join(', ')}`;
129
+ // Restate gives a request's headers by their names in lower case.
130
+ const signatureHeader = auth?.header.toLowerCase();
131
+ const deliveryHeader = idempotencyHeader?.toLowerCase();
132
+ return restate.service({
133
+ name,
134
+ description: what,
135
+ handlers: {
136
+ webhook: restate.handlers.handler(
137
+ {
138
+ input: restate.serde.binary,
139
+ accept: '*/*',
140
+ description: what,
141
+ metadata: {
142
+ 'restate-agents.kind': 'webhook',
143
+ 'restate-agents.routes': route.map((r) => r.name).join(','),
144
+ 'restate-agents.auth': auth ? `hmac-sha256:${auth.header}` : 'none',
145
+ ...(idempotencyHeader ? { 'restate-agents.idempotency-header': idempotencyHeader } : {}),
146
+ },
147
+ },
148
+ async (ctx: restate.Context, body: Uint8Array) => {
149
+ const headers = ctx.request().headers;
150
+ if (auth && !signed(body, headers.get(signatureHeader!), auth.secret)) {
151
+ throw new restate.TerminalError(`Not signed: no valid ${auth.header}`, { errorCode: 401 });
152
+ }
153
+ const event = parsed(body);
154
+ const delivery = (deliveryHeader && headers.get(deliveryHeader)) || ctx.request().id;
155
+ const to = key ? key(event) : delivery;
156
+ if (to === undefined) return;
157
+ const text = webhookMessage(name, delivery, message ? message(event) : event);
158
+ for (const agent of route) deliver(ctx, agent, to, text, { idempotencyKey: `webhook:${name}:${delivery}` });
159
+ },
160
+ ),
161
+ },
162
+ });
163
+ };