@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/calls.ts ADDED
@@ -0,0 +1,138 @@
1
+ // The Restate calls of an invocation's tools (`call`, `signal`, `subagent`...
2
+ // of tools.ts), kept in the object's database (`restate_agent_calls`) so that
3
+ // a call is made once, however often its tool call runs.
4
+ //
5
+ // A crash or a suspension restarts the handler. pi, Claude and LangGraph then
6
+ // run a tool call that was cut off again, with its id. OpenCode and the
7
+ // DeepSeek Harness tell the model it was interrupted instead, and the model
8
+ // makes it again with a new id: made with the same tool and input, it is the
9
+ // call an earlier attempt made, so it takes that call's id, and so the same
10
+ // idempotency key: the same Restate call (a wait for a signal, a sub-agent's
11
+ // task), which it waits for again, or whose answer it gets.
12
+ //
13
+ // A call is kept until the framework's transcript has its result under the
14
+ // last id it was made with ({@link settle}, at each publish, and before each
15
+ // tool call): one that answered just before a crash, whose result the
16
+ // framework had not stored, is made again as the same call. An error there
17
+ // is not its result (OpenCode gives the call it interrupted one, and the
18
+ // model makes it again), unless the call answered with that error: a
19
+ // terminal error is its result too. Once stored, the model has its result,
20
+ // and an identical call it makes later is a call of its own.
21
+ import type * as restate from '@restatedev/sessions';
22
+ import { Schema } from '@restatedev/sessions/internal';
23
+ import { randomUUID } from 'node:crypto';
24
+
25
+ /** A tool's call: the tool, its input as JSON, the ids it was made with (the first is its own), and the attempt that last made it. */
26
+ interface Call {
27
+ tool: string;
28
+ input: string;
29
+ ids: string[];
30
+ attempt: string;
31
+ /** Answered, until the transcript has its result. */
32
+ done?: true;
33
+ /** It answered with this error (`Error: <message>`), a terminal one: its result, as the transcript has it. */
34
+ failed?: string;
35
+ }
36
+
37
+ /** The calls an invocation's tools made that the transcript has no result of yet. */
38
+ interface Calls {
39
+ invocation: string;
40
+ calls: Call[];
41
+ }
42
+
43
+ /** The table of the {@link Calls}: one row, of the invocation whose calls they are. */
44
+ const SCHEMA = new Schema('restate-agents.calls', [
45
+ `CREATE TABLE restate_agent_calls (
46
+ row INTEGER PRIMARY KEY CHECK (row = 0),
47
+ invocation TEXT NOT NULL,
48
+ calls TEXT NOT NULL
49
+ )`,
50
+ ]);
51
+
52
+ /** What the calls need of a handler's context. */
53
+ type CallsContext = Pick<restate.SessionContext, 'db' | 'request'>;
54
+
55
+ /** Store `calls`, committed before the call they record is made. */
56
+ async function store(ctx: CallsContext, { invocation, calls }: Calls) {
57
+ await ctx.db.execute('INSERT OR REPLACE INTO restate_agent_calls (row, invocation, calls) VALUES (0, ?, ?)', [
58
+ invocation,
59
+ JSON.stringify(calls),
60
+ ]);
61
+ }
62
+
63
+ /** The calls of `invocation`, as stored: none if the row is another invocation's. */
64
+ async function load(ctx: CallsContext, invocation: string): Promise<Calls> {
65
+ await SCHEMA.ensure(ctx.db);
66
+ const row = await ctx.db.get<{ invocation: string; calls: string }>(
67
+ 'SELECT invocation, calls FROM restate_agent_calls',
68
+ );
69
+ return row?.invocation === invocation
70
+ ? { invocation, calls: JSON.parse(row.calls) as Call[] }
71
+ : { invocation, calls: [] };
72
+ }
73
+
74
+ /** Each attempt's id, and its calls, by its context. */
75
+ const attempts = new WeakMap<object, { id: string; calls: Promise<Calls> }>();
76
+
77
+ /** The attempt of `ctx`: its id, and the calls of its invocation. */
78
+ function attemptOf(ctx: CallsContext) {
79
+ let attempt = attempts.get(ctx);
80
+ if (!attempt) {
81
+ const calls = load(ctx, ctx.request.id);
82
+ attempt = { id: randomUUID(), calls };
83
+ attempts.set(ctx, attempt);
84
+ }
85
+ return attempt;
86
+ }
87
+
88
+ /**
89
+ * The call of tool `tool` with `input` that tool call `callId` makes: the
90
+ * one it made before (a run again), or the one an earlier attempt made with
91
+ * the same tool and input (made again under a new id), or else a new one.
92
+ * `run(id)` makes it with its own id, and stores that it answered.
93
+ */
94
+ export async function callOf(ctx: CallsContext, tool: string, input: unknown, callId: string) {
95
+ const attempt = attemptOf(ctx);
96
+ const state = await attempt.calls;
97
+ const json = JSON.stringify(input);
98
+ let call =
99
+ state.calls.find((c) => c.ids.includes(callId)) ??
100
+ state.calls.find((c) => c.attempt !== attempt.id && c.tool === tool && c.input === json);
101
+ if (call) {
102
+ call.attempt = attempt.id;
103
+ if (!call.ids.includes(callId)) call.ids.push(callId);
104
+ } else {
105
+ state.calls.push((call = { tool, input: json, ids: [callId], attempt: attempt.id }));
106
+ }
107
+ await store(ctx, state);
108
+ const made = call;
109
+ return {
110
+ id: made.ids[0]!,
111
+ /**
112
+ * It answered, with `failed` if a terminal error answered it: kept until
113
+ * the transcript has its result.
114
+ */
115
+ async answered(failed?: string) {
116
+ made.done = true;
117
+ if (failed !== undefined) made.failed = failed;
118
+ await store(ctx, state);
119
+ },
120
+ };
121
+ }
122
+
123
+ /**
124
+ * Forget the calls that answered whose result the framework stored: those
125
+ * of which `stored(id, failed)` is true for the last id they were made with,
126
+ * `failed` the error that answered the call, if one did. Called
127
+ * at each publish, and before each tool call, with the transcript as the
128
+ * framework stored it: also in an attempt that made no call yet, which would
129
+ * otherwise take one an earlier attempt made, and the model has the result
130
+ * of.
131
+ */
132
+ export async function settle(ctx: CallsContext, stored: (id: string, failed?: string) => boolean) {
133
+ const state = await attemptOf(ctx).calls;
134
+ const kept = state.calls.filter((c) => !c.done || !stored(c.ids.at(-1)!, c.failed));
135
+ if (kept.length === state.calls.length) return;
136
+ state.calls = kept;
137
+ await store(ctx, state);
138
+ }
@@ -0,0 +1,84 @@
1
+ # Claude
2
+
3
+ The Anthropic SDK's tool runner (`client.beta.messages.toolRunner` in
4
+ [`@anthropic-ai/sdk`](https://github.com/anthropics/anthropic-sdk-typescript))
5
+ is a light agent harness: the tool-calling loop, in the process, with nothing
6
+ stored. It keeps the conversation in its params, so an agent built on it is
7
+ durable when the conversation is: here it is in the agent's SQL database
8
+ ([SQL in Restate virtual objects](../../../sessions/README.md)).
9
+
10
+ It is lighter than the Claude Agent SDK, which runs Claude Code as a
11
+ subprocess. Claude Code's own tools (bash, read, write, edit, glob, grep)
12
+ come to the runner as `betaAgentToolset20260401` from
13
+ `@anthropic-ai/sdk/tools/agent-toolset/node`; the agent takes whatever tools
14
+ you give it.
15
+
16
+ ## Use
17
+
18
+ ```ts
19
+ import { serve } from '@restatedev/agents';
20
+ import * as claude from '@restatedev/agents/claude';
21
+ import { weather } from './weather.ts';
22
+
23
+ const assistant = claude.agent({ name: 'assistant', system: 'Answer briefly.', tools: [weather] });
24
+ await serve(assistant);
25
+ ```
26
+
27
+ | Option | What |
28
+ | ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
29
+ | `model` | `anthropic/model-id`; or else `MODEL`, or else `anthropic/claude-sonnet-5-5` (`ANTHROPIC_API_KEY`) |
30
+ | `system` | The system prompt |
31
+ | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or the SDK's runnable tools (such as `betaZodTool`) |
32
+ | `output` | A zod object: the answer as data, which the agent replies with as JSON, and `chat` answers with (see [Structured answers](../../README.md#structured-answers)) |
33
+ | `client` | The Anthropic client (a base URL or a proxy of your own, say); by default one with `ANTHROPIC_API_KEY` |
34
+ | `maxTokens` | The most tokens of each of the model's replies (default 16000): a reply cut off there fails its message (a terminal error) |
35
+ | `effort` | How much effort the model puts into each reply: `low`, `medium`, `high`, `xhigh` or `max` (default: the model's) |
36
+
37
+ For a session object of your own, `claude.chat(options)` is the handler and
38
+ `claude.messages()` the view; `options` may be a function of the
39
+ invocation's context (each user's system prompt, say). `claude.prompt(ctx,
40
+ text, options)` answers a prompt in a handler of your own, once, however
41
+ often the handler runs; each prompt of an invocation is a prompt of its own.
42
+
43
+ ## Through crashes
44
+
45
+ The conversation ([`conversation.ts`](conversation.ts)) is the messages in
46
+ the object's database, in order, each with the invocation it belongs to, and
47
+ the answer to each. The handler is not replayed: a retried attempt runs it
48
+ again from the start, with the stored messages.
49
+
50
+ - **Each reply is stored before its tools run, and their results before the
51
+ next request.** So a crash during the tools resumes them with the same tool
52
+ call ids, without asking the model again.
53
+ - **A tool is idempotent by its tool call id** (`callId` of `tool()`'s
54
+ `run`, or `callId(context)` for the SDK's tools), which it passes on, such
55
+ as in an idempotency key.
56
+ - **A tool's error fails the attempt**, and Restate retries it; a
57
+ `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
58
+ model.
59
+ - **A message is answered once per invocation**: its answer is stored with
60
+ the model's last reply, and a retried attempt returns it. A message that a
61
+ crash interrupted is finished before the next one starts.
62
+
63
+ ## Run
64
+
65
+ ```sh
66
+ cd packages/examples && ANTHROPIC_API_KEY=… node basic/claude.ts
67
+ ```
68
+
69
+ With a Restate server, and the agent registered with it: see
70
+ [Run an example](../../../examples/README.md#run-an-example).
71
+
72
+ ## Tests
73
+
74
+ The tests run on a scripted model, [`test/fakes/claude.ts`](../../test/fakes/claude.ts)
75
+ (`pnpm --filter @restatedev/agents test claude`, from the repository root):
76
+
77
+ - [`test/claude.test.ts`](../../test/claude.test.ts):
78
+ each point above, with crashes that stop an attempt in a tool call, or at
79
+ any of its state requests, and abandon it, keeping what it committed; and
80
+ `messages`.
81
+ - [`test/claude.ts`](../../test/claude.ts): the bank
82
+ agent, whose tools move money in the [ledger](../../../sessions/test/ledger.ts),
83
+ through crashes in [the crash test](../../../e2e/crash.ts)
84
+ (`pnpm --filter e2e crash`): every message moves money exactly once.
@@ -0,0 +1,114 @@
1
+ // A conversation with Claude in a Restate virtual object's database: its
2
+ // messages, in order, each with the id of the prompt it belongs to, and the
3
+ // answer to each prompt.
4
+ //
5
+ // It is the only state of the tool runner (@anthropic-ai/sdk's agent loop),
6
+ // which keeps the conversation in its params: an attempt starts a runner with
7
+ // the stored messages, and stores each message the runner adds.
8
+
9
+ import type Anthropic from '@anthropic-ai/sdk';
10
+ import type { Database } from '@restatedev/sessions';
11
+ import { Schema } from '@restatedev/sessions/internal';
12
+
13
+ type MessageParam = Anthropic.Beta.Messages.BetaMessageParam;
14
+
15
+ const SCHEMA = new Schema('restate-agents.claude', [
16
+ 'CREATE TABLE restate_claude_messages (seq INTEGER PRIMARY KEY, prompt TEXT NOT NULL, message TEXT NOT NULL)',
17
+ 'CREATE TABLE restate_claude_answers (prompt TEXT PRIMARY KEY, answer TEXT NOT NULL)',
18
+ ]);
19
+
20
+ /** The conversation in the object's database: the tool runner's messages, and each prompt's answer. */
21
+ export class Conversation {
22
+ #db: Database;
23
+ /** Cancelled: a run cut off then stores nothing more. */
24
+ #closed = false;
25
+
26
+ constructor(db: Database) {
27
+ this.#db = db;
28
+ }
29
+
30
+ /** The conversation in `db` (`ctx.db`). */
31
+ static async open(db: Database): Promise<Conversation> {
32
+ await SCHEMA.ensure(db);
33
+ return new Conversation(db);
34
+ }
35
+
36
+ /** The answer to prompt `id`, or undefined. */
37
+ async answer(id: string): Promise<string | undefined> {
38
+ const [row] = await this.#db.values('SELECT answer FROM restate_claude_answers WHERE prompt = ?', [id]);
39
+ return row?.[0] as string | undefined;
40
+ }
41
+
42
+ /** The messages, in order. */
43
+ async messages(): Promise<MessageParam[]> {
44
+ const rows = await this.#db.values('SELECT message FROM restate_claude_messages ORDER BY seq');
45
+ return rows.map(([message]) => JSON.parse(String(message)));
46
+ }
47
+
48
+ /** The messages stored after `seq`, in order, each with its own `seq`. */
49
+ async since(seq: number): Promise<[seq: number, message: MessageParam][]> {
50
+ const rows = await this.#db.values('SELECT seq, message FROM restate_claude_messages WHERE seq > ? ORDER BY seq', [
51
+ seq,
52
+ ]);
53
+ return rows.map(([at, message]) => [Number(at), JSON.parse(String(message)) as MessageParam]);
54
+ }
55
+
56
+ /** The prompt being answered: the last message's, unless it is answered. */
57
+ async pending(): Promise<string | undefined> {
58
+ const [row] = await this.#db.values(
59
+ 'SELECT prompt FROM restate_claude_messages WHERE prompt NOT IN (SELECT prompt FROM restate_claude_answers) ORDER BY seq DESC LIMIT 1',
60
+ );
61
+ return row?.[0] as string | undefined;
62
+ }
63
+
64
+ /**
65
+ * Close prompt `id`, which was cancelled: a result for each tool call of
66
+ * the last reply that has none, then `text` as the reply and the answer.
67
+ */
68
+ async cancel(id: string, text: string): Promise<void> {
69
+ this.#closed = true;
70
+ await this.close(id, text);
71
+ }
72
+
73
+ /**
74
+ * Close prompt `id` with `text` as its last reply and its answer, after
75
+ * `reply` if given (a reply that cannot go on: cut off, or declined): first
76
+ * a result of `text` for each tool call of the last reply that has none.
77
+ */
78
+ async close(id: string, text: string, reply?: MessageParam): Promise<void> {
79
+ const calls = toolUses(reply ?? (await this.messages()).at(-1));
80
+ const results = calls.map((call) => ({
81
+ type: 'tool_result' as const,
82
+ tool_use_id: call.id,
83
+ content: text,
84
+ is_error: true,
85
+ }));
86
+ const closing: MessageParam[] = results.length > 0 ? [{ role: 'user', content: results }] : [];
87
+ await this.#store(id, [...(reply ? [reply] : []), ...closing, { role: 'assistant', content: text }], text);
88
+ }
89
+
90
+ /** Store `messages` of prompt `id`, and its `answer` if given, in one transaction. */
91
+ append(id: string, messages: MessageParam[], answer?: string): Promise<void> {
92
+ if (this.#closed) return Promise.reject(new Error('the conversation was cancelled'));
93
+ return this.#store(id, messages, answer);
94
+ }
95
+
96
+ #store(id: string, messages: MessageParam[], answer?: string): Promise<void> {
97
+ return this.#db.transaction(async (tx) => {
98
+ for (const message of messages) {
99
+ await tx.execute('INSERT INTO restate_claude_messages (prompt, message) VALUES (?, ?)', [
100
+ id,
101
+ JSON.stringify(message),
102
+ ]);
103
+ }
104
+ if (answer !== undefined)
105
+ await tx.execute('INSERT INTO restate_claude_answers (prompt, answer) VALUES (?, ?)', [id, answer]);
106
+ });
107
+ }
108
+ }
109
+
110
+ /** The tool calls of `message`, if it is the assistant's. */
111
+ const toolUses = (message: MessageParam | undefined) =>
112
+ message?.role === 'assistant' && Array.isArray(message.content)
113
+ ? message.content.filter((b) => b.type === 'tool_use')
114
+ : [];