@restatedev/agents 0.7.0 → 0.8.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 (81) hide show
  1. package/README.md +29 -5
  2. package/dist/agentlib/agent.d.ts +32 -0
  3. package/dist/agentlib/agent.d.ts.map +1 -0
  4. package/dist/agentlib/agent.js +172 -0
  5. package/dist/agentlib/agent.js.map +1 -0
  6. package/dist/agentlib/index.d.ts +5 -0
  7. package/dist/agentlib/index.d.ts.map +1 -0
  8. package/dist/agentlib/index.js +15 -0
  9. package/dist/agentlib/index.js.map +1 -0
  10. package/dist/agentlib/messages.d.ts +39 -0
  11. package/dist/agentlib/messages.d.ts.map +1 -0
  12. package/dist/agentlib/messages.js +177 -0
  13. package/dist/agentlib/messages.js.map +1 -0
  14. package/dist/agentlib/model.d.ts +29 -0
  15. package/dist/agentlib/model.d.ts.map +1 -0
  16. package/dist/agentlib/model.js +131 -0
  17. package/dist/agentlib/model.js.map +1 -0
  18. package/dist/agentlib/options.d.ts +58 -0
  19. package/dist/agentlib/options.d.ts.map +1 -0
  20. package/dist/agentlib/options.js +2 -0
  21. package/dist/agentlib/options.js.map +1 -0
  22. package/dist/agentlib/runtime.d.ts +37 -0
  23. package/dist/agentlib/runtime.d.ts.map +1 -0
  24. package/dist/agentlib/runtime.js +216 -0
  25. package/dist/agentlib/runtime.js.map +1 -0
  26. package/dist/agentlib/state.d.ts +114 -0
  27. package/dist/agentlib/state.d.ts.map +1 -0
  28. package/dist/agentlib/state.js +52 -0
  29. package/dist/agentlib/state.js.map +1 -0
  30. package/dist/agentlib/steering.d.ts +23 -0
  31. package/dist/agentlib/steering.d.ts.map +1 -0
  32. package/dist/agentlib/steering.js +48 -0
  33. package/dist/agentlib/steering.js.map +1 -0
  34. package/dist/agentlib/tools.d.ts +33 -0
  35. package/dist/agentlib/tools.d.ts.map +1 -0
  36. package/dist/agentlib/tools.js +243 -0
  37. package/dist/agentlib/tools.js.map +1 -0
  38. package/dist/agentlib/turn.d.ts +82 -0
  39. package/dist/agentlib/turn.d.ts.map +1 -0
  40. package/dist/agentlib/turn.js +253 -0
  41. package/dist/agentlib/turn.js.map +1 -0
  42. package/dist/common.d.ts +8 -0
  43. package/dist/common.d.ts.map +1 -1
  44. package/dist/common.js +12 -0
  45. package/dist/common.js.map +1 -1
  46. package/dist/companion.d.ts +2 -1
  47. package/dist/companion.d.ts.map +1 -1
  48. package/dist/companion.js.map +1 -1
  49. package/dist/deepseek/index.d.ts +2 -6
  50. package/dist/deepseek/index.d.ts.map +1 -1
  51. package/dist/deepseek/index.js +3 -14
  52. package/dist/deepseek/index.js.map +1 -1
  53. package/dist/index.d.ts +5 -3
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +6 -4
  56. package/dist/index.js.map +1 -1
  57. package/dist/opencode/index.d.ts.map +1 -1
  58. package/dist/opencode/index.js +11 -18
  59. package/dist/opencode/index.js.map +1 -1
  60. package/dist/tools.d.ts +53 -2
  61. package/dist/tools.d.ts.map +1 -1
  62. package/dist/tools.js +32 -15
  63. package/dist/tools.js.map +1 -1
  64. package/package.json +28 -4
  65. package/src/agentlib/README.md +229 -0
  66. package/src/agentlib/agent.ts +214 -0
  67. package/src/agentlib/index.ts +16 -0
  68. package/src/agentlib/messages.ts +207 -0
  69. package/src/agentlib/model.ts +150 -0
  70. package/src/agentlib/options.ts +62 -0
  71. package/src/agentlib/runtime.ts +252 -0
  72. package/src/agentlib/state.ts +93 -0
  73. package/src/agentlib/steering.ts +53 -0
  74. package/src/agentlib/tools.ts +353 -0
  75. package/src/agentlib/turn.ts +302 -0
  76. package/src/common.ts +15 -0
  77. package/src/companion.ts +2 -1
  78. package/src/deepseek/index.ts +5 -18
  79. package/src/index.ts +6 -4
  80. package/src/opencode/index.ts +12 -17
  81. package/src/tools.ts +118 -52
@@ -75,13 +75,14 @@ import {
75
75
  RETURNED_UNRECORDED,
76
76
  stopSignalOf,
77
77
  toolCallStarted,
78
+ approves,
78
79
  } from '../common.ts';
79
80
  import { answerOnce, type Items, type Parsed, type Run, type Turn } from '../conversation.ts';
80
81
  import { tookSteers } from '../steering.ts';
81
82
  import { conversationView } from '../messages.ts';
82
83
  import { type Answer, withChecked } from '../output.ts';
83
84
  import { type Definition, sessionObject } from '../object.ts';
84
- import { isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
85
+ import { type Approval, isTool, jsonSchemaOf, type Tool as AnyTool, waitFor } from '../tools.ts';
85
86
  import type { z } from 'zod';
86
87
  import { SqlSessionPersistence } from './persistence.ts';
87
88
 
@@ -283,24 +284,10 @@ const native = (t: AnyTool, ctx: restate.SessionContext): ToolDefinition =>
283
284
  /** The signal that a tool call waits for, to the agent, when it needs a person's approval (`approval`). */
284
285
  export const APPROVAL = 'approval';
285
286
 
286
- /** Which tool calls wait for a person's approval: the names of their tools, or a function of a call that says whether it does. */
287
- export type Approval = readonly string[] | ((call: { name: string; args: unknown }) => boolean);
287
+ export type { Approval };
288
288
 
289
- /** The texts that approve a tool call, whatever their case. */
290
- const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
291
-
292
- /**
293
- * What the value of an {@link APPROVAL} signal decides about its tool call:
294
- * `true`, `{ "approved": true }`, or a text such as "approved" or "yes"
295
- * approves it once; anything else rejects it, so a value that does not say
296
- * "approved" never runs the tool.
297
- */
298
- const decided = (value: unknown): ApprovalOutcome =>
299
- value === true ||
300
- (typeof value === 'string' && APPROVED.has(value.trim().toLowerCase())) ||
301
- (typeof value === 'object' && value !== null && (value as { approved?: unknown }).approved === true)
302
- ? 'allowed-once'
303
- : 'rejected';
289
+ /** What the value of an {@link APPROVAL} signal decides about its tool call (see `approves`): approved once, or rejected. */
290
+ const decided = (value: unknown): ApprovalOutcome => (approves(value) ? 'allowed-once' : 'rejected');
304
291
 
305
292
  /**
306
293
  * Have the harness of the agent of `agentCtx` ask for an approval before
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  // @restatedev/agents: agent frameworks in Restate session objects. Each framework
2
- // is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek); this is what they share: session objects, tools for
2
+ // is a subpath (@restatedev/agents/pi, /langgraph, /claude, /deepseek, /opencode, /agentlib); this is what they share: session objects, tools for
3
3
  // any of them, and the tools that are Restate itself.
4
4
 
5
5
  export {
@@ -32,8 +32,10 @@ export { call, send, signal, subagent, tool, workflow, type Tool, type ToolCall,
32
32
  export { webhook, webhookMessage, type WebhookAuth, type WebhookEvent, type WebhookOptions } from './webhook.ts';
33
33
 
34
34
  /**
35
- * @restatedev/sessions' `serve`: the services on PORT, with what they need
36
- * beside them (each agent's companion); and `served`, those services, for
37
- * an endpoint of your own (`restate.endpoint()`).
35
+ * @restatedev/sessions' `serve`: the services on PORT, or connected out to
36
+ * Restate Cloud where RESTATE_CONNECT_KEY is set, either way with what they
37
+ * need beside them (each agent's companion); and `served`, those services,
38
+ * for an endpoint of your own (`restate.endpoint()`), or for the SDK's own
39
+ * `restate.connect`, which without it leaves the companions unserved.
38
40
  */
39
41
  export { serve, served } from '@restatedev/sessions';
@@ -96,6 +96,7 @@ import {
96
96
  RETURNED_UNRECORDED,
97
97
  stopSignalOf,
98
98
  toolCallStarted,
99
+ approves,
99
100
  } from '../common.ts';
100
101
  import { answerOnce, invocationOf, type Call, type Items, type Parsed, STEPS, type Turn } from '../conversation.ts';
101
102
  import { conversationView } from '../messages.ts';
@@ -797,27 +798,21 @@ function toolsPlugin(
797
798
  /** The signal that an OpenCode tool call waits for, to the agent, when OpenCode asks for a permission (`approval`). */
798
799
  export const APPROVAL = 'approval';
799
800
 
800
- /** The texts that approve an ask, whatever their case. */
801
- const APPROVED: ReadonlySet<string> = new Set(['approved', 'approve', 'yes', 'ok', 'allow', 'allowed']);
802
-
803
801
  /**
804
- * What the value of an {@link APPROVAL} signal decides: `true`,
805
- * `{ "approved": true }`, or a text such as "approved" or "yes" allows;
806
- * anything else denies, with the reason it gives, if any (a text, or
802
+ * What the value of an {@link APPROVAL} signal decides (see `approves`):
803
+ * it allows, or denies with the reason it gives, if any (a text, or
807
804
  * `{ "reason": "..." }`).
808
805
  */
809
806
  function decided(value: unknown): { allowed: true } | { allowed: false; reason?: string } {
810
- if (value === true) return { allowed: true };
811
- if (typeof value === 'string') {
812
- const text = value.trim();
813
- return APPROVED.has(text.toLowerCase()) ? { allowed: true } : { allowed: false, ...(text ? { reason: text } : {}) };
814
- }
815
- if (typeof value === 'object' && value !== null) {
816
- const { approved, reason } = value as { approved?: unknown; reason?: unknown };
817
- if (approved === true) return { allowed: true };
818
- return { allowed: false, ...(typeof reason === 'string' && reason.trim() ? { reason: reason.trim() } : {}) };
819
- }
820
- return { allowed: false };
807
+ if (approves(value)) return { allowed: true };
808
+ const given =
809
+ typeof value === 'string'
810
+ ? value
811
+ : typeof value === 'object' && value !== null
812
+ ? (value as { reason?: unknown }).reason
813
+ : undefined;
814
+ const reason = typeof given === 'string' ? given.trim() : '';
815
+ return { allowed: false, ...(reason ? { reason } : {}) };
821
816
  }
822
817
 
823
818
  /**
package/src/tools.ts CHANGED
@@ -17,6 +17,7 @@ import { callOf } from './calls.ts';
17
17
  import { companionHere, NoCompanion } from './companion.ts';
18
18
 
19
19
  const TOOL = Symbol.for('restate-agents.tool');
20
+ const SPEC = Symbol.for('restate-agents.tool-spec');
20
21
 
21
22
  /** A tool call: the agent's context, and the id of the model's call. */
22
23
  export interface ToolCall {
@@ -51,6 +52,38 @@ export interface Tool {
51
52
  run(args: unknown, call: ToolCall): Promise<string>;
52
53
  }
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
+
54
87
  /** The JSON schema of `t`'s input, which a framework offers the model. */
55
88
  export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<string, unknown>;
56
89
 
@@ -58,7 +91,7 @@ export const jsonSchemaOf = (t: Tool) => z.toJSONSchema(t.input) as Record<strin
58
91
  export const isTool = (value: unknown): value is Tool => typeof value === 'object' && value !== null && TOOL in value;
59
92
 
60
93
  /** A result as text: a string as it is, nothing as "done", anything else as JSON. */
61
- const text = (value: unknown) =>
94
+ export const text = (value: unknown) =>
62
95
  typeof value === 'string' ? value : value === null || value === undefined ? 'done' : JSON.stringify(value);
63
96
 
64
97
  /**
@@ -83,6 +116,14 @@ export const tool = <S extends z.ZodObject>(options: {
83
116
  description: string;
84
117
  input: S;
85
118
  run: (input: z.infer<S>, context: ToolContext) => unknown;
119
+ }): Tool => withSpec(ownTool(options), { kind: 'run', run: options.run });
120
+
121
+ /** {@link tool}, without its spec: Restate's tools give their own. */
122
+ const ownTool = <S extends z.ZodObject>(options: {
123
+ name: string;
124
+ description: string;
125
+ input: S;
126
+ run: (input: z.infer<S>, context: ToolContext) => unknown;
86
127
  }): Tool => ({
87
128
  [TOOL]: true,
88
129
  name: options.name,
@@ -142,12 +183,12 @@ async function once<T>(
142
183
  }
143
184
 
144
185
  /** A service, virtual object or workflow, as its definition (`restate.service(...)` and so on), of handlers `M`. */
145
- type Target<M = unknown> =
186
+ export type Target<M = unknown> =
146
187
  | restate.ServiceDefinition<string, M>
147
188
  | restate.VirtualObjectDefinition<string, M>
148
189
  | restate.WorkflowDefinition<string, M>;
149
190
  /** Whether a target is keyed: a virtual object (key) or a workflow (id). */
150
- const keyed = (target: Target) => 'object' in target || 'workflow' in target;
191
+ export const keyed = (target: Target) => 'object' in target || 'workflow' in target;
151
192
 
152
193
  /**
153
194
  * Call `method` of `service`, with JSON in and out, once per tool call (see
@@ -187,7 +228,7 @@ export const runWorkflow = async (
187
228
  { service, key, input }: { service: string; key: string; input: unknown },
188
229
  ): Promise<unknown> => attach(ctx, await start(ctx, { service, handler: 'run', key, input }));
189
230
 
190
- interface TargetOptions<S extends z.ZodObject | undefined> {
231
+ export interface TargetOptions<S extends z.ZodObject | undefined> {
191
232
  /** The tool's name, for the model; by default the handler's, such as `orders_status`. */
192
233
  name?: string;
193
234
  /** What it does, for the model. */
@@ -238,20 +279,23 @@ export const call = <M, S extends z.ZodObject | undefined = undefined>(
238
279
  handler: keyof M & string,
239
280
  options: TargetOptions<S>,
240
281
  ): Tool =>
241
- tool({
242
- name: options.name ?? `${target.name}_${handler}`,
243
- description: options.description,
244
- input: inputOf(target, options),
245
- run: async (input, context) =>
246
- once(`${target.name}/${handler}`, input, context, async (c) =>
247
- invoke(c, {
248
- service: target.name,
249
- method: handler,
250
- workflow: 'workflow' in target,
251
- ...(await split(target, options, input, c.ctx)),
252
- }),
253
- ),
254
- });
282
+ withSpec(
283
+ ownTool({
284
+ name: options.name ?? `${target.name}_${handler}`,
285
+ description: options.description,
286
+ input: inputOf(target, options),
287
+ run: async (input, context) =>
288
+ once(`${target.name}/${handler}`, input, context, async (c) =>
289
+ invoke(c, {
290
+ service: target.name,
291
+ method: handler,
292
+ workflow: 'workflow' in target,
293
+ ...(await split(target, options, input, c.ctx)),
294
+ }),
295
+ ),
296
+ }),
297
+ { kind: 'call', target: target as Target, handler, options },
298
+ );
255
299
 
256
300
  /**
257
301
  * A tool that sends to `handler` of `target`, without waiting for it: a
@@ -262,17 +306,24 @@ export const send = <M, S extends z.ZodObject | undefined = undefined>(
262
306
  handler: keyof M & string,
263
307
  options: TargetOptions<S> & { delay?: restate.Duration },
264
308
  ): Tool =>
265
- tool({
266
- name: options.name ?? `${target.name}_${handler}`,
267
- description: options.description,
268
- input: inputOf(target, options),
269
- run: async (input, context) =>
270
- once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
271
- const { key, parameter } = await split(target, options, input, ctx);
272
- ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
273
- return `sent to ${target.name}${key === undefined ? '' : `/${key}`}/${handler}`;
274
- }),
275
- });
309
+ withSpec(
310
+ ownTool({
311
+ name: options.name ?? `${target.name}_${handler}`,
312
+ description: options.description,
313
+ input: inputOf(target, options),
314
+ run: async (input, context) =>
315
+ once(`${target.name}/${handler}`, input, context, async ({ ctx, idempotencyKey }) => {
316
+ const { key, parameter } = await split(target, options, input, ctx);
317
+ ctx.send({ service: target.name, handler, key, input: parameter, delay: options.delay, idempotencyKey });
318
+ return sentTo(target.name, key, handler);
319
+ }),
320
+ }),
321
+ { kind: 'send', target: target as Target, handler, options },
322
+ );
323
+
324
+ /** What a send tool answers: where it sent. */
325
+ export const sentTo = (service: string, key: string | undefined, handler: string) =>
326
+ `sent to ${service}${key === undefined ? '' : `/${key}`}/${handler}`;
276
327
 
277
328
  /**
278
329
  * A tool that runs the workflow `target` (its `run` handler) to the end, and
@@ -286,19 +337,22 @@ export const workflow = <S extends z.ZodObject | undefined = undefined>(
286
337
  target: restate.WorkflowDefinition<string, { run: unknown }>,
287
338
  options: TargetOptions<S>,
288
339
  ): Tool =>
289
- tool({
290
- name: options.name ?? target.name,
291
- description: options.description,
292
- input: z.object(options.input?.shape ?? {}),
293
- run: async (input, context) =>
294
- once(target.name, input, context, async (c) =>
295
- runWorkflow(c.ctx, {
296
- service: target.name,
297
- key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
298
- input: options.input ? input : undefined,
299
- }),
300
- ),
301
- });
340
+ withSpec(
341
+ ownTool({
342
+ name: options.name ?? target.name,
343
+ description: options.description,
344
+ input: z.object(options.input?.shape ?? {}),
345
+ run: async (input, context) =>
346
+ once(target.name, input, context, async (c) =>
347
+ runWorkflow(c.ctx, {
348
+ service: target.name,
349
+ key: options.key === undefined ? `${c.ctx.key}-${c.callId}` : await configured(options.key, c.ctx),
350
+ input: options.input ? input : undefined,
351
+ }),
352
+ ),
353
+ }),
354
+ { kind: 'workflow', target: target as Target, options },
355
+ );
302
356
 
303
357
  /** An object with a `chat` handler; another object needs subagent's `handler`. */
304
358
  type WithChat<M> = M extends { chat: unknown }
@@ -332,10 +386,19 @@ export function subagent<M>(
332
386
  handler,
333
387
  }: { description?: string; name?: string; handler?: keyof M & string } = {},
334
388
  ): Tool {
335
- return tool({
389
+ return withSpec(subagentTool(agent.name, toolName, description, handler ?? 'chat'), {
390
+ kind: 'subagent',
391
+ agent: agent.name,
392
+ handler: handler ?? 'chat',
393
+ });
394
+ }
395
+
396
+ /** {@link subagent}'s tool, without its spec. */
397
+ function subagentTool(agentName: string, toolName: string, description: string | undefined, handler: string): Tool {
398
+ return ownTool({
336
399
  name: toolName,
337
400
  description:
338
- `Hand a task to the ${agent.name} agent${description ? ` (${description})` : ''}, and get its answer. ` +
401
+ `Hand a task to the ${agentName} agent${description ? ` (${description})` : ''}, and get its answer. ` +
339
402
  'Tasks of different names run at once; the same name continues the same task.',
340
403
  input: z.object({
341
404
  name: z
@@ -345,8 +408,8 @@ export function subagent<M>(
345
408
  task: z.string().describe('The task in full: the agent sees nothing else'),
346
409
  }),
347
410
  run: async ({ name, task }, context) =>
348
- once(agent.name, { name, task }, context, (c) =>
349
- invoke(c, { service: agent.name, key: `${c.ctx.key}.${name}`, method: handler ?? 'chat', parameter: task }),
411
+ once(agentName, { name, task }, context, (c) =>
412
+ invoke(c, { service: agentName, key: `${c.ctx.key}.${name}`, method: handler, parameter: task }),
350
413
  ),
351
414
  });
352
415
  }
@@ -375,12 +438,15 @@ export function subagent<M>(
375
438
  * for the next wait for its name.
376
439
  */
377
440
  export const signal = (name: string, options: { description: string; input?: z.ZodObject; name?: string }): Tool =>
378
- tool({
379
- name: options.name ?? `wait_for_${name}`,
380
- description: options.description,
381
- input: z.object(options.input?.shape ?? {}),
382
- run: async (input, context) => wait(context, name, input, { shown: options.input !== undefined }),
383
- });
441
+ withSpec(
442
+ ownTool({
443
+ name: options.name ?? `wait_for_${name}`,
444
+ description: options.description,
445
+ input: z.object(options.input?.shape ?? {}),
446
+ run: async (input, context) => wait(context, name, input, { shown: options.input !== undefined }),
447
+ }),
448
+ { kind: 'signal', name, shown: options.input !== undefined },
449
+ );
384
450
 
385
451
  /**
386
452
  * Wait for signal `name` as tool call `toolCall`, once however often it runs;