@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/dist/tools.js DELETED
@@ -1,305 +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, configured, ToolError } from './common.js';
16
- import { callOf } from './calls.js';
17
- import { companionHere, NoCompanion } from './companion.js';
18
- const TOOL = Symbol.for('restate-agents.tool');
19
- const SPEC = Symbol.for('restate-agents.tool-spec');
20
- /** `t`, saying what it does: see {@link ToolSpec}. */
21
- const withSpec = (t, spec) => Object.defineProperty(t, SPEC, { value: spec });
22
- /** What tool `t` does: see {@link ToolSpec}. */
23
- export const specOf = (t) => t[SPEC];
24
- /** The JSON schema of `t`'s input, which a framework offers the model. */
25
- export const jsonSchemaOf = (t) => z.toJSONSchema(t.input);
26
- /** Whether `value` is a {@link Tool}, rather than a framework's own. */
27
- export const isTool = (value) => typeof value === 'object' && value !== null && TOOL in value;
28
- /** A result as text: a string as it is, nothing as "done", anything else as JSON. */
29
- export const text = (value) => typeof value === 'string' ? value : value === null || value === undefined ? 'done' : JSON.stringify(value);
30
- /**
31
- * A tool, for any framework's agent:
32
- *
33
- * const weather = tool({
34
- * name: 'get_weather',
35
- * description: 'The current weather in a city.',
36
- * input: z.object({ city: z.string() }),
37
- * run: async ({ city }) => `Sunny in ${city}`,
38
- * });
39
- *
40
- * `run` returns the result (or a promise of it), text or anything JSON; it
41
- * gets the agent's `ctx`, the tool call's `callId`, and an `idempotencyKey`
42
- * made of both, for what the tool must do once. A `restate.TerminalError` it throws (or
43
- * a Restate call it makes fails with) is its answer, `Error: <message>`, for
44
- * the model to act on; and so are arguments that do not fit `input`, which
45
- * `run` never sees.
46
- *
47
- * A tool does not keep its attempt alive: one that works for longer than
48
- * Restate's inactivity timeout (a minute, by default) is cut off, and done
49
- * again from the start of the turn, by every attempt. One that must work
50
- * that long sets `keepalive`, and runs in `ctx.working`; it keeps long waits
51
- * on Restate (a call, a signal) out of its `run`, or holds its process for
52
- * as long as they take.
53
- */
54
- export const tool = (options) => withSpec(ownTool(options), { kind: 'run', run: options.run });
55
- /** {@link tool}, without its spec: Restate's tools give their own. */
56
- const ownTool = (options) => ({
57
- [TOOL]: true,
58
- name: options.name,
59
- description: options.description,
60
- input: options.input,
61
- run: async (args, { ctx, callId }) => {
62
- // Arguments that do not fit: the model's to fix. Failing the attempt
63
- // instead, a retry would meet the same stored call again, and fail again.
64
- const parsed = options.input.safeParse(args);
65
- if (!parsed.success)
66
- return `Error: the arguments do not fit the tool's input: ${z.prettifyError(parsed.error)}`;
67
- const input = parsed.data;
68
- try {
69
- const run = () => options.run(input, { ctx, callId, idempotencyKey: `${ctx.request.id}:${callId}` });
70
- return text(await (options.keepalive ? ctx.working(run) : run()));
71
- }
72
- catch (error) {
73
- // The turn stopped (its invocation was cancelled, or its attempt
74
- // ended): it ends, rather than the model going on with the tool's error
75
- // as its answer (such as the failure of a call that the cancellation
76
- // cancelled).
77
- const turn = stopSignalOf(ctx);
78
- if (turn?.aborted)
79
- throw turn.reason;
80
- if (error instanceof restate.CancelledError)
81
- throw error;
82
- // An object without a companion, waiting for a signal: a programming error, which fails the turn once,
83
- // rather than an answer for the model to act on.
84
- if (error instanceof NoCompanion)
85
- throw error;
86
- // A terminal error is the tool's answer, which the model can act on; any
87
- // other error fails the attempt, which Restate retries.
88
- if (error instanceof restate.TerminalError)
89
- return `Error: ${error.message}`;
90
- throw new ToolError(options.name, error);
91
- }
92
- },
93
- });
94
- /**
95
- * `body`, a Restate call of tool `name` with `input`, made once however often
96
- * the tool call runs (see calls.ts): it gets the id of the call, which an
97
- * earlier attempt may have made, and so its idempotency key.
98
- */
99
- async function once(name, input, context, body, options) {
100
- const { ctx } = context;
101
- const call = await callOf(ctx, name, input, context.callId, options);
102
- try {
103
- const result = await body({ ctx, callId: call.id, idempotencyKey: `${ctx.request.id}:${call.id}` });
104
- await call.answered();
105
- return result;
106
- }
107
- catch (error) {
108
- // A terminal error answers the call; any other fails the attempt, and the
109
- // retry makes the call again.
110
- if (error instanceof restate.TerminalError)
111
- await call.answered(`Error: ${error.message}`);
112
- throw error;
113
- }
114
- }
115
- /** Whether a target is keyed: a virtual object (key) or a workflow (id). */
116
- export const keyed = (target) => 'object' in target || 'workflow' in target;
117
- /**
118
- * Call `method` of `service`, with JSON in and out, once per tool call (see
119
- * {@link ToolContext}): the call's idempotency key makes the call a new
120
- * attempt makes again (after a crash, or a suspension) the one the first
121
- * made, whose result it gets. A workflow's `run` runs instead ({@link runWorkflow}).
122
- */
123
- const invoke = ({ ctx, idempotencyKey }, target) => target.workflow && target.method === 'run'
124
- ? runWorkflow(ctx, { service: target.service, key: target.key, input: target.parameter })
125
- : ctx.rpc({
126
- service: target.service,
127
- handler: target.method,
128
- key: target.key,
129
- input: target.parameter,
130
- idempotencyKey,
131
- });
132
- /**
133
- * Run workflow `service` (its `run` handler) with id `key` and `input` to its
134
- * end, and resolve to its result: a call of it, whose result it does not wait
135
- * for, then a wait for the run by the call's invocation id. A workflow's
136
- * `run` runs once per id: Restate refuses a second call of it, whatever the
137
- * call's idempotency key, but that call's invocation id is the run's. So a
138
- * new attempt (after a crash, or a suspension while the run went on) that
139
- * makes the call again waits for the run an earlier attempt started, and
140
- * only the first starts one; and a fixed id that ran before gets its run's
141
- * result. It is a call, not a send: stopping the turn cancels the run, as it
142
- * cancels the turn's other calls (`cancelCalls`). The Python SDK's
143
- * `run_workflow` sends instead, and so leaves the run going.
144
- */
145
- export const runWorkflow = async (ctx, { service, key, input }) => attach(ctx, await start(ctx, { service, handler: 'run', key, input }));
146
- /** The tool's input: the handler's, and the key if the model chooses it. */
147
- function inputOf(target, { input, key }) {
148
- const shape = input?.shape ?? {};
149
- if (!keyed(target) || key !== undefined)
150
- return z.object(shape);
151
- return z.object({ key: z.string().describe(`Which ${target.name}: its key`), ...shape });
152
- }
153
- /** The key, and the handler's input, of a tool call's input. */
154
- async function split(target, options, all, ctx) {
155
- if (!keyed(target))
156
- return { key: undefined, parameter: options.input ? all : undefined };
157
- if (options.key !== undefined) {
158
- return { key: await configured(options.key, ctx), parameter: options.input ? all : undefined };
159
- }
160
- const { key, ...rest } = all;
161
- return { key, parameter: options.input ? rest : undefined };
162
- }
163
- /**
164
- * A tool that calls `handler` of `target` and answers with its result:
165
- *
166
- * call(orders, 'status', {
167
- * description: 'The status of an order.',
168
- * input: z.object({ order: z.string() }),
169
- * })
170
- *
171
- * Of a virtual object, the model chooses the key, unless `key` gives it.
172
- */
173
- export const call = (target, handler, options) => withSpec(ownTool({
174
- name: options.name ?? `${target.name}_${handler}`,
175
- description: options.description,
176
- input: inputOf(target, options),
177
- run: async (input, context) => once(`${target.name}/${handler}`, input, context, async (c) => invoke(c, {
178
- service: target.name,
179
- method: handler,
180
- workflow: 'workflow' in target,
181
- ...(await split(target, options, input, c.ctx)),
182
- })),
183
- }), { kind: 'call', target: target, handler, options });
184
- /**
185
- * A tool that sends to `handler` of `target`, without waiting for it: a
186
- * one-way call, made once, after `delay` if given (such as `{ minutes: 5 }`).
187
- */
188
- export const send = (target, handler, options) => withSpec(ownTool({
189
- name: options.name ?? `${target.name}_${handler}`,
190
- description: options.description,
191
- input: inputOf(target, options),
192
- run: async (input, context) => once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
193
- const { key, parameter } = await split(target, options, input, ctx);
194
- ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
195
- return sentTo(target.name, key, handler);
196
- }),
197
- }), { kind: 'send', target: target, handler, options });
198
- /** What a send tool answers: where it sent. */
199
- export const sentTo = (service, key, handler) => `sent to ${service}${key === undefined ? '' : `/${key}`}/${handler}`;
200
- /**
201
- * A tool that runs the workflow `target` (its `run` handler) to the end, and
202
- * answers with its result. Each tool call is a workflow of its own, with an
203
- * id made of the agent's key and the tool call's id, unless `key` gives one.
204
- * A tool call made again (after a crash, or a suspension while the workflow
205
- * ran) waits for the run it started, and a `key` that ran before gets that
206
- * run's result ({@link runWorkflow}).
207
- */
208
- export const workflow = (target, options) => withSpec(ownTool({
209
- name: options.name ?? target.name,
210
- description: options.description,
211
- input: z.object(options.input?.shape ?? {}),
212
- run: async (input, context) => once(target.name, input, context, async (c) => runWorkflow(c.ctx, {
213
- service: target.name,
214
- key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
215
- input: options.input ? input : undefined,
216
- })),
217
- }), { kind: 'workflow', target: target, options });
218
- export function subagent(agent, { description = agent.description, name: toolName = agent.name, handler, } = {}) {
219
- return withSpec(subagentTool(agent.name, toolName, description, handler ?? 'chat'), {
220
- kind: 'subagent',
221
- agent: agent.name,
222
- handler: handler ?? 'chat',
223
- });
224
- }
225
- /** {@link subagent}'s tool, without its spec. */
226
- function subagentTool(agentName, toolName, description, handler) {
227
- return ownTool({
228
- name: toolName,
229
- description: `Hand a task to the ${agentName} agent${description ? ` (${description})` : ''}, and get its answer. ` +
230
- 'Tasks of different names run at once; the same name continues the same task.',
231
- input: z.object({
232
- name: z
233
- .string()
234
- .regex(/^[a-z0-9-]+$/)
235
- .describe('A short name for the task, such as "fizzbuzz"'),
236
- task: z.string().describe('The task in full: the agent sees nothing else'),
237
- }),
238
- run: async ({ name, task }, context) => once(agentName, { name, task }, context, (c) => invoke(c, { service: agentName, key: `${c.ctx.key}.${name}`, method: handler, parameter: task })),
239
- });
240
- }
241
- /**
242
- * A tool that waits for the signal `name` to the agent, and answers with its
243
- * value: a person's approval, say, or another system's result. The agent
244
- * waits without holding a process. With an `input`, the model says what it
245
- * waits for (such as the refund to approve), which `pending` shows.
246
- *
247
- * signal('approval', {
248
- * description: 'Wait for a manager to approve a refund.',
249
- * input: z.object({ order: z.string(), amount: z.number() }),
250
- * })
251
- *
252
- * Each wait has an id: `pending` (each `sessionObject()` has it) lists them, and
253
- * the agent's `signal` handler resolves one, by its id, or the oldest wait
254
- * for a name:
255
- *
256
- * curl localhost:8080/support/alice/pending
257
- * curl localhost:8080/support/alice/signal --json '{"id": "inv_1f…:toolu_01", "value": "approved"}'
258
- * curl localhost:8080/support/alice/signal --json '{"name": "approval", "value": "approved"}'
259
- *
260
- * It answers with the id of the wait it resolved, or `null` if none waited:
261
- * the signal is dropped then, unless it has `"keep": true`, which keeps it
262
- * for the next wait for its name.
263
- */
264
- export const signal = (name, options) => withSpec(ownTool({
265
- name: options.name ?? `wait_for_${name}`,
266
- description: options.description,
267
- input: z.object(options.input?.shape ?? {}),
268
- run: async (input, context) => wait(context, name, input, { shown: options.input !== undefined }),
269
- }), { kind: 'signal', name, shown: options.input !== undefined });
270
- /**
271
- * Wait for signal `name` as tool call `toolCall`, once however often it runs;
272
- * `pending` shows `input` if `shown`. `rejoin` and `approval` are
273
- * {@link callOf}'s.
274
- */
275
- const wait = async (toolCall, name, input, { shown, rejoin, approval }) => {
276
- // Before the call is recorded: an object without a companion fails the turn, once (`NoCompanion`).
277
- const companion = companionHere(toolCall.ctx, 'a wait for a signal');
278
- return once(`signal/${name}`, input, toolCall, async ({ ctx, idempotencyKey: id }) => ctx.rpc(companion, ctx.key, { idempotencyKey: id }).wait({ id, name, ...(shown ? { input } : {}) }), { rejoin, approval });
279
- };
280
- /**
281
- * Wait for the signal `name` to the agent, for the model's tool call
282
- * `callId`, and answer with its value: what a {@link signal} tool does, for
283
- * a framework whose own tool calls wait for something outside (an approval,
284
- * say). The wait's id is `<invocation id>:<call id>`; `pending` lists it
285
- * (with `input`, if given), and `signal` resolves it. It is opened once
286
- * however often the tool call runs, and a crash goes on waiting on it.
287
- *
288
- * The wait is the tool call's alone: the framework stored its tool call
289
- * before it waits, so a retried attempt waits again under the same id. A new
290
- * call with the same input (the model asking again, after the first's
291
- * answer) waits anew, as its answer is not the earlier call's.
292
- *
293
- * With `approval`, the tool call runs only after the wait: the wait's
294
- * answer is not the call's, so a turn stopped before the call's result is
295
- * stored reports the call as not done, rather than done.
296
- *
297
- * With `rejoin`, for a framework that makes a call cut off by a crash again
298
- * under a new id (the DeepSeek Harness), the call joins the wait an earlier
299
- * attempt opened with the same input, as Restate's own tools do: the call
300
- * made again, waiting on (or getting the answer of) the same wait, until
301
- * the earlier call's result is stored. Within one attempt, a call with the
302
- * same input waits anew.
303
- */
304
- export const waitFor = (ctx, callId, name, input, { approval = false, rejoin = false } = {}) => wait({ ctx, callId }, name, input ?? null, { shown: input !== undefined, rejoin, approval });
305
- //# sourceMappingURL=tools.js.map
package/dist/tools.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"tools.js","sourceRoot":"","sources":["../src/tools.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,4EAA4E;AAC5E,wEAAwE;AACxE,sCAAsC;AACtC,EAAE;AACF,4EAA4E;AAC5E,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,2EAA2E;AAC3E,qEAAqE;AACrE,OAAO,KAAK,OAAO,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,YAAY,EAAkB,UAAU,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAClF,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AACpC,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAE5D,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,qBAAqB,CAAC,CAAC;AAC/C,MAAM,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,0BAA0B,CAAC,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C,KAAK,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EACrG,EAAE,MAAM,EAAE,QAAQ,EAAE,CACrB,CAAC;AACJ,CAAC,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,CAAC,MAAM,OAAO,GAAG,CACrB,GAA2B,EAC3B,MAAc,EACd,IAAY,EACZ,KAAe,EACf,EAAE,QAAQ,GAAG,KAAK,EAAE,MAAM,GAAG,KAAK,EAAE,GAA6C,EAAE,EACjE,EAAE,CAAC,IAAI,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,KAAK,IAAI,IAAI,EAAE,EAAE,KAAK,EAAE,KAAK,KAAK,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC"}
package/dist/webhook.d.ts DELETED
@@ -1,71 +0,0 @@
1
- import { sdk as restate } from '@restatedev/sessions/internal';
2
- /** How a webhook is signed: the HMAC-SHA256 of its body with `secret`, in hex, in the request's `header`. */
3
- export interface WebhookAuth {
4
- /** The header with the signature, such as `linear-signature` or `X-Hub-Signature-256` (GitHub's `sha256=` prefix is taken too), in any case. */
5
- header: string;
6
- /** The webhook's signing secret, which the other system shows when the webhook is made. */
7
- secret: string;
8
- }
9
- /** An agent (an `sessionObject()` or `agent()` of @restatedev/agents, with a `chat` handler) that webhooks go to. */
10
- type Route = restate.VirtualObjectDefinition<string, {
11
- chat: unknown;
12
- }>;
13
- /**
14
- * A delivery's body: JSON, as the other system sends it, read as it is (it is
15
- * theirs to shape, not checked here).
16
- */
17
- export type WebhookEvent = Record<string, any>;
18
- /** A webhook service's options. */
19
- export interface WebhookOptions<P extends string = string> {
20
- /** The service's name, which its URL starts with: `/<name>/webhook`. */
21
- name: P;
22
- /** What the webhook is, for the UI and the admin API. */
23
- description?: string;
24
- /** Its signature: a webhook without it is refused (401). Without `auth`, any request is taken. */
25
- auth?: WebhookAuth;
26
- /**
27
- * The header with the delivery's id, which a delivery sent again has too
28
- * (such as `linear-delivery`): it reaches the same message, not a second
29
- * one. Without it, each request is a delivery of its own. In any case, as
30
- * header names are.
31
- */
32
- idempotencyHeader?: string;
33
- /** The agents each delivery goes to. */
34
- route: Route[];
35
- /**
36
- * The key of the agents' object that a delivery goes to, from its body
37
- * (the issue, say: one conversation per issue), or undefined to drop the
38
- * delivery. By default, the delivery's id: a conversation per delivery.
39
- * The event is the body's JSON, untyped: `key: ({ data }) => data.identifier`.
40
- */
41
- key?(this: void, event: WebhookEvent): string | undefined;
42
- /**
43
- * What of a delivery the agents read, from its body: by default, all of
44
- * it. Some systems send much more than an agent needs (GitHub sends the
45
- * whole repository with each event): `message: ({ comment }) => ({ body: comment.body })`.
46
- */
47
- message?(this: void, event: WebhookEvent): unknown;
48
- }
49
- /**
50
- * The message an agent gets for a webhook's delivery: its body, as JSON, in
51
- * a `<webhook>` element that says which webhook, and which delivery.
52
- *
53
- * <webhook name="linear" delivery="5d2…">
54
- * {"action": "create", "type": "Issue", ...}
55
- * </webhook>
56
- */
57
- export declare const webhookMessage: (name: string, delivery: string, event: unknown) => string;
58
- /**
59
- * A webhook into agents: a service `name`, whose `webhook` handler checks a
60
- * delivery's signature, and delivers it to each agent of `route`, keyed by
61
- * `key`, as a {@link webhookMessage}: a message of its own (as `chat`),
62
- * which the agent answers after the messages before it. It answers once the
63
- * deliveries are sent, not answered: a system that waits seconds for an
64
- * answer (Linear, GitHub) gets one at once. What it is (its routes, auth and
65
- * idempotency) is in the handler's metadata, which the admin API shows.
66
- */
67
- export declare const webhook: <P extends string>({ name, description, auth, idempotencyHeader, route, key, message, }: WebhookOptions<P>) => restate.ServiceDefinition<P, {
68
- webhook: (ctx: restate.Context, input: Uint8Array<ArrayBufferLike>) => Promise<void>;
69
- }>;
70
- export {};
71
- //# sourceMappingURL=webhook.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"webhook.d.ts","sourceRoot":"","sources":["../src/webh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ooks 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.js';
20
- /**
21
- * The message an agent gets for a webhook's delivery: its body, as JSON, in
22
- * a `<webhook>` element that says which webhook, and which delivery.
23
- *
24
- * <webhook name="linear" delivery="5d2…">
25
- * {"action": "create", "type": "Issue", ...}
26
- * </webhook>
27
- */
28
- export const webhookMessage = (name, delivery, event) => `<webhook name="${name}" delivery="${delivery}">\n${JSON.stringify(event, null, 2)}\n</webhook>`;
29
- /** Whether `signature` is the HMAC-SHA256 of `body` with `secret`, in hex. */
30
- const signed = (body, signature, secret) => {
31
- const expected = createHmac('sha256', secret).update(body).digest();
32
- const given = Buffer.from((signature ?? '').replace(/^sha256=/, ''), 'hex');
33
- return given.length === expected.length && timingSafeEqual(given, expected);
34
- };
35
- /** `body` as a JSON object, or a terminal error (400) if it is not. */
36
- const parsed = (body) => {
37
- let event;
38
- try {
39
- event = JSON.parse(new TextDecoder().decode(body));
40
- }
41
- catch {
42
- throw new restate.TerminalError('The webhook is not JSON', { errorCode: 400 });
43
- }
44
- if (typeof event !== 'object' || event === null || Array.isArray(event)) {
45
- throw new restate.TerminalError('The webhook is not a JSON object', { errorCode: 400 });
46
- }
47
- return event;
48
- };
49
- /**
50
- * A webhook into agents: a service `name`, whose `webhook` handler checks a
51
- * delivery's signature, and delivers it to each agent of `route`, keyed by
52
- * `key`, as a {@link webhookMessage}: a message of its own (as `chat`),
53
- * which the agent answers after the messages before it. It answers once the
54
- * deliveries are sent, not answered: a system that waits seconds for an
55
- * answer (Linear, GitHub) gets one at once. What it is (its routes, auth and
56
- * idempotency) is in the handler's metadata, which the admin API shows.
57
- */
58
- export const webhook = ({ name, description, auth, idempotencyHeader, route, key, message, }) => {
59
- if (route.length === 0)
60
- throw new Error(`webhook ${name}: route it to at least one agent`);
61
- for (const agent of route) {
62
- if (!hasCompanion(agent))
63
- throw new Error(`webhook ${name}: ${agent.name} is not a sessionObject() or agent()`);
64
- }
65
- if (auth && !auth.secret)
66
- throw new Error(`webhook ${name}: its auth has no secret (unset in the environment?)`);
67
- const what = description ?? `A webhook into ${route.map((r) => r.name).join(', ')}`;
68
- // Restate gives a request's headers by their names in lower case.
69
- const signatureHeader = auth?.header.toLowerCase();
70
- const deliveryHeader = idempotencyHeader?.toLowerCase();
71
- return restate.service({
72
- name,
73
- description: what,
74
- handlers: {
75
- webhook: restate.handlers.handler({
76
- input: restate.serde.binary,
77
- accept: '*/*',
78
- description: what,
79
- metadata: {
80
- 'restate-agents.kind': 'webhook',
81
- 'restate-agents.routes': route.map((r) => r.name).join(','),
82
- 'restate-agents.auth': auth ? `hmac-sha256:${auth.header}` : 'none',
83
- ...(idempotencyHeader ? { 'restate-agents.idempotency-header': idempotencyHeader } : {}),
84
- },
85
- }, async (ctx, body) => {
86
- const headers = ctx.request().headers;
87
- if (auth && !signed(body, headers.get(signatureHeader), auth.secret)) {
88
- throw new restate.TerminalError(`Not signed: no valid ${auth.header}`, { errorCode: 401 });
89
- }
90
- const event = parsed(body);
91
- const delivery = (deliveryHeader && headers.get(deliveryHeader)) || ctx.request().id;
92
- const to = key ? key(event) : delivery;
93
- if (to === undefined)
94
- return;
95
- const text = webhookMessage(name, delivery, message ? message(event) : event);
96
- for (const agent of route)
97
- deliver(ctx, agent, to, text, { idempotencyKey: `webhook:${name}:${delivery}` });
98
- }),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