@restatedev/agents 0.3.0 → 0.4.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 (136) hide show
  1. package/README.md +89 -49
  2. package/dist/calls.d.ts +29 -5
  3. package/dist/calls.d.ts.map +1 -1
  4. package/dist/calls.js +77 -10
  5. package/dist/calls.js.map +1 -1
  6. package/dist/claude/index.d.ts +36 -7
  7. package/dist/claude/index.d.ts.map +1 -1
  8. package/dist/claude/index.js +232 -151
  9. package/dist/claude/index.js.map +1 -1
  10. package/dist/client.d.ts +12 -3
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js.map +1 -1
  13. package/dist/common.d.ts +151 -70
  14. package/dist/common.d.ts.map +1 -1
  15. package/dist/common.js +246 -204
  16. package/dist/common.js.map +1 -1
  17. package/dist/conversation.d.ts +466 -0
  18. package/dist/conversation.d.ts.map +1 -0
  19. package/dist/conversation.js +1247 -0
  20. package/dist/conversation.js.map +1 -0
  21. package/dist/deepseek/index.d.ts +38 -5
  22. package/dist/deepseek/index.d.ts.map +1 -1
  23. package/dist/deepseek/index.js +322 -106
  24. package/dist/deepseek/index.js.map +1 -1
  25. package/dist/deepseek/persistence.d.ts +9 -3
  26. package/dist/deepseek/persistence.d.ts.map +1 -1
  27. package/dist/deepseek/persistence.js +12 -6
  28. package/dist/deepseek/persistence.js.map +1 -1
  29. package/dist/index.d.ts +2 -2
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +2 -3
  32. package/dist/index.js.map +1 -1
  33. package/dist/langgraph/checkpointer.d.ts +16 -2
  34. package/dist/langgraph/checkpointer.d.ts.map +1 -1
  35. package/dist/langgraph/checkpointer.js +133 -26
  36. package/dist/langgraph/checkpointer.js.map +1 -1
  37. package/dist/langgraph/context.d.ts +10 -0
  38. package/dist/langgraph/context.d.ts.map +1 -0
  39. package/dist/langgraph/context.js +21 -0
  40. package/dist/langgraph/context.js.map +1 -0
  41. package/dist/langgraph/errors.d.ts +16 -0
  42. package/dist/langgraph/errors.d.ts.map +1 -0
  43. package/dist/langgraph/errors.js +30 -0
  44. package/dist/langgraph/errors.js.map +1 -0
  45. package/dist/langgraph/graph.d.ts +25 -0
  46. package/dist/langgraph/graph.d.ts.map +1 -0
  47. package/dist/langgraph/graph.js +346 -0
  48. package/dist/langgraph/graph.js.map +1 -0
  49. package/dist/langgraph/index.d.ts +65 -12
  50. package/dist/langgraph/index.d.ts.map +1 -1
  51. package/dist/langgraph/index.js +227 -171
  52. package/dist/langgraph/index.js.map +1 -1
  53. package/dist/langgraph/nodes.d.ts +70 -0
  54. package/dist/langgraph/nodes.d.ts.map +1 -0
  55. package/dist/langgraph/nodes.js +145 -0
  56. package/dist/langgraph/nodes.js.map +1 -0
  57. package/dist/messages.d.ts +18 -0
  58. package/dist/messages.d.ts.map +1 -0
  59. package/dist/messages.js +182 -0
  60. package/dist/messages.js.map +1 -0
  61. package/dist/object.d.ts +65 -23
  62. package/dist/object.d.ts.map +1 -1
  63. package/dist/object.js +121 -35
  64. package/dist/object.js.map +1 -1
  65. package/dist/output.d.ts +15 -7
  66. package/dist/output.d.ts.map +1 -1
  67. package/dist/output.js +44 -26
  68. package/dist/output.js.map +1 -1
  69. package/dist/pi/index.d.ts +39 -11
  70. package/dist/pi/index.d.ts.map +1 -1
  71. package/dist/pi/index.js +281 -77
  72. package/dist/pi/index.js.map +1 -1
  73. package/dist/pi/storage.d.ts +29 -4
  74. package/dist/pi/storage.d.ts.map +1 -1
  75. package/dist/pi/storage.js +18 -6
  76. package/dist/pi/storage.js.map +1 -1
  77. package/dist/signals.d.ts +74 -4
  78. package/dist/signals.d.ts.map +1 -1
  79. package/dist/signals.js +144 -15
  80. package/dist/signals.js.map +1 -1
  81. package/dist/steering.d.ts +31 -0
  82. package/dist/steering.d.ts.map +1 -0
  83. package/dist/steering.js +45 -0
  84. package/dist/steering.js.map +1 -0
  85. package/dist/tools.d.ts +28 -0
  86. package/dist/tools.d.ts.map +1 -1
  87. package/dist/tools.js +34 -5
  88. package/dist/tools.js.map +1 -1
  89. package/package.json +33 -37
  90. package/src/calls.ts +107 -15
  91. package/src/claude/README.md +41 -20
  92. package/src/claude/index.ts +266 -178
  93. package/src/client.ts +14 -3
  94. package/src/common.ts +317 -232
  95. package/src/conversation.ts +1527 -0
  96. package/src/deepseek/README.md +78 -11
  97. package/src/deepseek/index.ts +384 -137
  98. package/src/deepseek/persistence.ts +11 -8
  99. package/src/index.ts +13 -4
  100. package/src/langgraph/README.md +115 -25
  101. package/src/langgraph/checkpointer.ts +168 -28
  102. package/src/langgraph/context.ts +27 -0
  103. package/src/langgraph/errors.ts +26 -0
  104. package/src/langgraph/graph.ts +396 -0
  105. package/src/langgraph/index.ts +326 -181
  106. package/src/langgraph/nodes.ts +243 -0
  107. package/src/messages.ts +244 -0
  108. package/src/object.ts +167 -38
  109. package/src/output.ts +52 -31
  110. package/src/pi/README.md +18 -3
  111. package/src/pi/index.ts +346 -78
  112. package/src/pi/storage.ts +20 -7
  113. package/src/signals.ts +225 -19
  114. package/src/steering.ts +67 -0
  115. package/src/tools.ts +61 -8
  116. package/dist/claude/conversation.d.ts +0 -33
  117. package/dist/claude/conversation.d.ts.map +0 -1
  118. package/dist/claude/conversation.js +0 -95
  119. package/dist/claude/conversation.js.map +0 -1
  120. package/dist/log.d.ts +0 -29
  121. package/dist/log.d.ts.map +0 -1
  122. package/dist/log.js +0 -146
  123. package/dist/log.js.map +0 -1
  124. package/dist/opencode/db.d.ts +0 -40
  125. package/dist/opencode/db.d.ts.map +0 -1
  126. package/dist/opencode/db.js +0 -161
  127. package/dist/opencode/db.js.map +0 -1
  128. package/dist/opencode/index.d.ts +0 -100
  129. package/dist/opencode/index.d.ts.map +0 -1
  130. package/dist/opencode/index.js +0 -436
  131. package/dist/opencode/index.js.map +0 -1
  132. package/src/claude/conversation.ts +0 -114
  133. package/src/log.ts +0 -194
  134. package/src/opencode/README.md +0 -125
  135. package/src/opencode/db.ts +0 -223
  136. package/src/opencode/index.ts +0 -559
package/src/log.ts DELETED
@@ -1,194 +0,0 @@
1
- // An agent's conversation as clients read it: a log in the object's
2
- // database, kept in step with the framework's transcript each time the agent
3
- // publishes a change (`transcribing` in common.ts), and read by `messages`
4
- // and `sync`.
5
- //
6
- // Each message has an `id` that never changes, and a `seq`: the sequence
7
- // number of its last change, which is the cursor. A message that grows in
8
- // place (a tool call's output comes) keeps its id and takes a new `seq`; a
9
- // transcript replaced (compacted, reset) leaves its messages in the log, and
10
- // the messages after them are new ones. So a client reads from a cursor, and
11
- // gets each message that is new or changed since, once.
12
- //
13
- // `clear` forgets the log with the rest of the conversation, but not where it
14
- // got to: the next conversation's ids and cursors go on from there (its
15
- // start, a row of `restate_agent_log_start`), so a client following it reads
16
- // on, and drops the messages before `first`.
17
- import type { DatabaseReader, DatabaseWriter, SessionContext } from '@restatedev/sessions';
18
- import { Schema, ScopeKey } from '@restatedev/sessions/internal';
19
- import type { ChatMessage, Messages, MessagesRequest } from './common.ts';
20
-
21
- const TABLE = 'restate_agent_log';
22
-
23
- /** Where the log starts: past the ids and cursors of the conversations `clear` forgot. */
24
- export interface Start {
25
- /** The cursor it starts at. */
26
- seq: number;
27
- /** Its first message's id. */
28
- id: number;
29
- }
30
-
31
- /** A message as the transcript gives it: its role and parts, without an id. */
32
- export type Said = Omit<ChatMessage, 'id'>;
33
-
34
- const SCHEMA = new Schema('restate-agents.log', [
35
- `CREATE TABLE ${TABLE} (
36
- id INTEGER PRIMARY KEY,
37
- seq INTEGER NOT NULL UNIQUE,
38
- position INTEGER UNIQUE,
39
- message TEXT NOT NULL
40
- )`,
41
- // Where the log starts, which `clear` sets: no row before.
42
- `CREATE TABLE ${TABLE}_start (
43
- row INTEGER PRIMARY KEY CHECK (row = 0),
44
- seq INTEGER NOT NULL,
45
- id INTEGER NOT NULL
46
- )`,
47
- ]);
48
-
49
- /** Where the log of `db` starts, if `clear` set it. */
50
- const startOf = async (db: DatabaseReader): Promise<Start | undefined> =>
51
- db.get<Start>(`SELECT seq, id FROM ${TABLE}_start`);
52
-
53
- /**
54
- * Start the log at `start`, in the transaction `tx` of `clear` that emptied
55
- * the database: the next conversation's ids and cursors go on from there.
56
- */
57
- export async function restart(tx: DatabaseWriter, start: Start) {
58
- await tx.execute(`INSERT OR REPLACE INTO ${TABLE}_start (row, seq, id) VALUES (0, ?, ?)`, [start.seq, start.id]);
59
- }
60
-
61
- /** A message of the log's head, the transcript as last stored: its id, and the message, also as JSON. */
62
- interface Row {
63
- id: number;
64
- message: Said;
65
- json: string;
66
- }
67
-
68
- /** The log's head as a session stored it last, with the last cursor and the next id. */
69
- interface Head {
70
- rows: Row[];
71
- seq: number;
72
- next: number;
73
- }
74
-
75
- /**
76
- * The log's head, as the attempt's last `sync` stored it: the next compares
77
- * the transcript with it, rather than read the whole log again at each step.
78
- */
79
- const HEAD = new ScopeKey<Head>('the log');
80
-
81
- /** The log's head in the attempt of `ctx`: as it stored it last, or else as the log has it. */
82
- async function headOf(ctx: SessionContext): Promise<Head> {
83
- const cached = HEAD.get(ctx);
84
- if (cached) return cached;
85
- const { db } = ctx;
86
- const rows = (await db.values(`SELECT id, message FROM ${TABLE} WHERE position IS NOT NULL ORDER BY position`)).map(
87
- ([id, json]) => ({ id: Number(id), message: JSON.parse(String(json)) as Said, json: String(json) }),
88
- );
89
- const { last, next } = (await db.get<{ last: number | null; next: number | null }>(
90
- `SELECT MAX(seq) AS last, MAX(id) + 1 AS next FROM ${TABLE}`,
91
- ))!;
92
- if (last !== null) return { rows, seq: last, next: next! };
93
- const from = (await startOf(db)) ?? { seq: 0, id: 0 };
94
- return { rows, seq: from.seq, next: from.id };
95
- }
96
-
97
- /**
98
- * Store the transcript's `messages`, in order, in the log: those that
99
- * changed since the last time, in one transaction.
100
- */
101
- export async function sync(ctx: SessionContext, messages: Said[]) {
102
- const { db } = ctx;
103
- await SCHEMA.ensure(db);
104
- const head = await headOf(ctx);
105
- // A message the transcript did not change is the one stored (see Transcript in common.ts):
106
- // only the others are compared, as JSON.
107
- const jsons: string[] = [];
108
- const jsonOf = (position: number) => (jsons[position] ??= JSON.stringify(messages[position]));
109
- const unchanged = (position: number) => {
110
- const row = head.rows[position]!;
111
- return row.message === messages[position] || row.json === jsonOf(position);
112
- };
113
- const both = Math.min(head.rows.length, messages.length);
114
- let same = 0;
115
- while (same < both && unchanged(same)) same += 1;
116
- let grown = same;
117
- while (grown < both && grownFrom(messages[grown]!, head.rows[grown]!.message)) grown += 1;
118
- if (same === head.rows.length && same === messages.length) return;
119
- let { seq, next: id } = head;
120
- const rows = head.rows.slice(0, same);
121
- try {
122
- await db.transaction(async (tx) => {
123
- for (let position = same; position < grown; position += 1) {
124
- const row = { id: head.rows[position]!.id, message: messages[position]!, json: jsonOf(position) };
125
- await tx.execute(`UPDATE ${TABLE} SET seq = ?, message = ? WHERE id = ?`, [(seq += 1), row.json, row.id]);
126
- rows.push(row);
127
- }
128
- // The rest of the transcript as it was is replaced: its messages stay in the log, out of it.
129
- await tx.execute(`UPDATE ${TABLE} SET position = NULL WHERE position >= ?`, [grown]);
130
- for (let position = grown; position < messages.length; position += 1) {
131
- const row = { id: id++, message: messages[position]!, json: jsonOf(position) };
132
- await tx.execute(`INSERT INTO ${TABLE} VALUES (?, ?, ?, ?)`, [row.id, (seq += 1), position, row.json]);
133
- rows.push(row);
134
- }
135
- });
136
- } catch (error) {
137
- // Rolled back: the log is as it was, which the next sync reads again.
138
- HEAD.delete(ctx);
139
- throw error;
140
- }
141
- HEAD.set(ctx, { rows, seq, next: id });
142
- }
143
-
144
- /**
145
- * A page of the log. With `cursor`: the messages new or changed since it,
146
- * by when they changed, and the cursor to read on from. Without: the latest
147
- * `limit` messages (or those before `before`, an id), oldest first, and the
148
- * cursor to follow the conversation from.
149
- */
150
- export async function page(db: DatabaseReader, { limit = 50, before, cursor }: MessagesRequest): Promise<Messages> {
151
- await SCHEMA.ensure(db);
152
- const start = await startOf(db);
153
- const first = start ? { first: start.id } : {};
154
- if (cursor !== undefined) {
155
- const rows = await db.values(`SELECT id, message, seq FROM ${TABLE} WHERE seq > ? ORDER BY seq LIMIT ?`, [
156
- cursor,
157
- limit + 1,
158
- ]);
159
- const shown = rows.slice(0, limit);
160
- return {
161
- messages: shown.map(message),
162
- more: rows.length > limit,
163
- cursor: shown.length > 0 ? Number(shown.at(-1)![2]) : cursor,
164
- ...first,
165
- };
166
- }
167
- const { now } = (await db.get<{ now: number }>(`SELECT COALESCE(MAX(seq), ?) AS now FROM ${TABLE}`, [
168
- start?.seq ?? 0,
169
- ]))!;
170
- const rows = await db.values(`SELECT id, message FROM ${TABLE} WHERE id < ? ORDER BY id DESC LIMIT ?`, [
171
- before ?? Number.MAX_SAFE_INTEGER,
172
- limit + 1,
173
- ]);
174
- return {
175
- messages: rows.slice(0, limit).toReversed().map(message),
176
- more: rows.length > limit,
177
- cursor: now,
178
- ...first,
179
- };
180
- }
181
-
182
- /** A row of the log, as `messages` gives it. */
183
- const message = ([id, m]: unknown[]): ChatMessage => ({ id: Number(id), ...(JSON.parse(String(m)) as Said) });
184
-
185
- /** Whether `now` is `was` grown in place: the same role and parts, with more (a tool call's output, say). */
186
- function grownFrom(now: Said, was: Said) {
187
- if (was.role !== now.role || now.parts.length < was.parts.length) return false;
188
- return was.parts.every((part, i) => {
189
- const other = now.parts[i]!;
190
- if (part.type !== other.type) return false;
191
- if (part.type === 'text') return other.type === 'text' && other.text.startsWith(part.text);
192
- return other.type === 'tool' && other.id === part.id;
193
- });
194
- }
@@ -1,125 +0,0 @@
1
- # OpenCode
2
-
3
- [OpenCode](https://opencode.ai) 2.0 can run embedded: `@opencode/sdk` hosts
4
- the whole OpenCode server in your process, with no HTTP listener. Here it
5
- runs in the agent's virtual object, and OpenCode's database (sessions,
6
- messages, the inbox, durable events) is an SQL database of the key's own,
7
- in the object's state beside `ctx.db` (`database` of @restatedev/sessions): OpenCode
8
- boots only on a database that is empty or its own, so its tables are alone
9
- there, and `ctx.db` keeps the conversation's log and the tables of yours
10
- ([SQL in Restate virtual objects](../../../sessions/README.md)). The integration
11
- pins OpenCode 2.0.32 exactly, with the Effect release it is built on (4.0.1);
12
- OpenCode needs Node 24.
13
-
14
- ## Use
15
-
16
- ```ts
17
- import { serve } from '@restatedev/agents';
18
- import * as opencode from '@restatedev/agents/opencode';
19
-
20
- const coder = opencode.agent({ name: 'coder', workspace: '/work/coder' });
21
- await serve(coder);
22
- ```
23
-
24
- | Option | What |
25
- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
26
- | `model` | `provider/model-id`, of any provider OpenCode serves; or else `MODEL`, or else `openai/gpt-6-sol` (`OPENAI_API_KEY`) |
27
- | `system` | The system prompt |
28
- | `tools` | `tool()`s and Restate's tools of `@restatedev/agents`, or OpenCode tools of your own (`OpenCodeTool`) |
29
- | `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)) |
30
- | `workspace` | A directory of the local machine to work in, with OpenCode's own tools (read, write, edit, bash, glob, grep...), or a function of the context that gives one (`(ctx) => \`/work/${ctx.key}\``); use a sandbox. Without one, the agent has only `tools` |
31
- | `plugins` | OpenCode plugins of your own (`@opencode/plugin`), such as one that denies edits outside `src/` ([`examples/intermediate/review.ts`](../../../examples/intermediate/review.ts)) |
32
-
33
- For a session object of your own, `opencode.chat(options)` is the handler and
34
- `opencode.messages()` the view (with it, the agent's `clear` empties
35
- OpenCode's database too); `options` may be a function of the invocation's
36
- context, such as a directory for each key:
37
-
38
- ```ts
39
- chat: opencode.chat((ctx) => ({ workspace: `/work/${ctx.key}` })),
40
- ```
41
-
42
- `opencode.prompt(ctx, text, options)` answers a prompt in a handler of your
43
- own. For more than a prompt, `withOpenCode(ctx, options, work)` runs `work`
44
- with OpenCode: `prompt(text)` answers a prompt once, and `host` is OpenCode's
45
- client.
46
-
47
- ## Through crashes
48
-
49
- [`db.ts`](db.ts) (`@restatedev/agents/opencode/db`) boots OpenCode's embedded
50
- host on its database: an Effect `SqlClient` through
51
- `Database.configuredClient`, OpenCode's seam for an injected client, each
52
- OpenCode transaction an SQL transaction. The handler is not replayed: a
53
- retried attempt boots OpenCode again, on the stored database, and OpenCode
54
- resumes interrupted work on its own: it records an execution claim when a
55
- turn starts, and resumes every claimed turn when it boots.
56
-
57
- - **Restate decides how often a turn is retried.** OpenCode fails a turn
58
- after ten resumes; here `openOpenCode` replaces its restart service with
59
- one without a limit, and the object's retry policy decides.
60
- - **A tool runs only once its call is stored.** OpenCode stores the model's
61
- reply, with its tool calls, before the tools run.
62
- - **A tool call that was running has an interrupted outcome.** Resuming gives
63
- it an "interrupted" result, and asks the model to continue without
64
- repeating completed work. A tool that must not run twice needs a way for a
65
- retry to name the call it retries (the bank agent's `transfer` takes
66
- `retryOf`). Restate's own tools
67
- (`call`, `send`, `workflow`, `subagent`, `signal`) need none: made again
68
- with the same input, the call is the one the cut-off call made, which
69
- matters for a long one, such as a wait for an approval, since a suspension
70
- (after Restate's inactivity timeout) restarts the handler too.
71
- - **A tool's error fails the attempt**, and Restate retries it; a
72
- `restate.TerminalError` of a `@restatedev/agents` tool is its answer to the
73
- model. The failed attempt stores nothing more, so its retry finds the call
74
- interrupted, as above.
75
- - **A message is answered once per invocation**: the invocation id is its
76
- OpenCode message id, and a retried attempt returns the answer of the turn
77
- that answered it. A prompt that a crash interrupted is finished before the
78
- next one starts.
79
-
80
- ## Notes
81
-
82
- - **Embedded.** OpenCode runs in the handler's own process: its client calls
83
- the server's HTTP router through an in-process `fetch`. Without a
84
- `workspace` it spawns nothing (the workerd profile's shell, terminal, file
85
- and version control services are disabled); with one, its own tools run on
86
- the local machine. The only other traffic out is the model's, to its
87
- provider's API.
88
- - **The Promise API's `OpenCode.create(options)` ignores its second
89
- argument** (the layer replacements), though its types declare it; the
90
- Effect API's `create` honours it.
91
- - **A prompt waits in the inbox before it is a message**, and a prompt
92
- queued while a turn runs is answered in that turn's run. So a new prompt
93
- waits for an unfinished one.
94
- - **Cost.** A prompt makes some hundreds of SQL statements; booting OpenCode
95
- takes about 100 ms per attempt, after a one-time import of about 2 s per
96
- process.
97
-
98
- ## Run
99
-
100
- ```sh
101
- cd packages/examples && OPENAI_API_KEY=… node basic/opencode.ts
102
- ```
103
-
104
- With a Restate server, and the agent registered with it: see
105
- [Run an example](../../../examples/README.md#run-an-example).
106
- [`examples/intermediate/coding.ts`](../../../examples/intermediate/coding.ts) has OpenCode coders,
107
- each with a workspace, under a pi coordinator.
108
-
109
- ## Tests
110
-
111
- The tests run on a scripted model, [`test/fakes/opencode.ts`](../../test/fakes/opencode.ts),
112
- an AI SDK language model that OpenCode calls through a plugin's `language`
113
- hook, and makes a fresh tool call id for every call (`pnpm --filter @restatedev/agents test opencode`,
114
- from the repository root):
115
-
116
- - [`test/storage/opencode.test.ts`](../../test/storage/opencode.test.ts):
117
- the Effect `SqlClient` of `db.ts`.
118
- - [`test/opencode.test.ts`](../../test/opencode.test.ts):
119
- each point above, with crashes that stop an attempt in a tool call, or
120
- at any of its state requests; the
121
- system prompt; and `messages`. With a transfer tool that ignores `retryOf`,
122
- four of its tests fail.
123
- - [`test/opencode.ts`](../../test/opencode.ts): the
124
- bank agent, through crashes in [the crash test](../../../e2e/crash.ts)
125
- (`pnpm --filter e2e crash`): every message moves money exactly once.
@@ -1,223 +0,0 @@
1
- // OpenCode on the object's database: `openOpenCode(db, fence, options)` boots
2
- // OpenCode 2.0's embedded host (@opencode/sdk) with its database in a
3
- // SQL session, `ctx.db`.
4
- //
5
- // The host is OpenCode's workerd profile, the one it boots in a Cloudflare
6
- // Durable Object: no local filesystem, shell, terminal or version control,
7
- // config given inline, plugins given in code. Only its database differs. The
8
- // workerd profile reads a Durable Object's SQLite, whose `exec` is
9
- // synchronous; here OpenCode gets an Effect SqlClient instead, which is
10
- // asynchronous, through `Database.configuredClient` (OpenCode's), the seam OpenCode keeps
11
- // for an injected client. Each transaction is an SQL transaction, and the
12
- // session runs statements one at a time, as OpenCode's own clients do.
13
- //
14
- // `fence.closed` refuses every statement from then on: an attempt that is
15
- // giving up stores nothing more, as Restate fences an attempt that a newer
16
- // one replaced.
17
- import { Context, Effect, Exit, Layer, Option, Scope } from 'effect';
18
- import { Reactivity } from 'effect/reactivity';
19
- import { SqlClient, Statement } from 'effect/sql';
20
- import { SqlError, UnknownError } from 'effect/sql/SqlError';
21
- import type { Connection } from 'effect/sql/SqlConnection';
22
- import { Database as OpenCodeDatabase } from '@opencode/core/database/database';
23
- import { SessionRestart } from '@opencode/core/session/execution/restart';
24
- import { ServerWorkerd } from '@opencode/server/workerd';
25
- import { fromPromise } from '@opencode/core/plugin/promise';
26
- import { OpenCode } from '@opencode/sdk/effect';
27
- import type { Plugin } from '@opencode/plugin';
28
- import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
29
-
30
- /** Closed: every later statement fails. */
31
- export interface Fence {
32
- closed: boolean;
33
- }
34
-
35
- const error = (operation: string, cause: unknown) =>
36
- new SqlError({
37
- reason: new UnknownError({
38
- cause,
39
- message: cause instanceof Error ? cause.message : String(cause),
40
- operation,
41
- }),
42
- });
43
-
44
- /** The connection inside a transaction, for statements of that transaction. */
45
- const InTransaction = Context.Service<SqlClient.TransactionConnection, SqlClient.TransactionConnection.Service>(
46
- '@restatedev/agents/OpenCodeTransaction',
47
- );
48
-
49
- /**
50
- * A connection whose statements go to `target`: the session, which runs one
51
- * call at a time and holds them while a transaction runs, or that
52
- * transaction's database. Each is refused once `fence` closes.
53
- */
54
- function connection(target: DatabaseWriter, fence: Fence): Connection {
55
- // Effect binds what the compiler made of OpenCode's values: SQL values.
56
- const exec = <T>(read: (sql: string, params: SqlValue[]) => Promise<T>, sql: string, params: readonly unknown[]) =>
57
- Effect.tryPromise({
58
- try: async () => {
59
- if (fence.closed) throw new Error('the attempt is over');
60
- return read(sql, params as SqlValue[]);
61
- },
62
- catch: (cause) => error('execute', cause),
63
- });
64
- const run = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.query(s, p), sql, params);
65
- const runValues = (sql: string, params: readonly unknown[] = []) => exec((s, p) => target.values(s, p), sql, params);
66
- const transformed: Connection['execute'] = (sql, params, transformRows) =>
67
- transformRows ? Effect.map(run(sql, params), transformRows) : run(sql, params);
68
- return {
69
- execute: transformed,
70
- executeRaw: (sql, params) => run(sql, params),
71
- executeValues: (sql, params) => runValues(sql, params),
72
- executeValuesUnprepared: (sql, params) => runValues(sql, params),
73
- executeUnprepared: transformed,
74
- executeStream: () => {
75
- throw new Error('executeStream is not supported');
76
- },
77
- };
78
- }
79
-
80
- /** An Effect SqlClient over `db`, with its statements refused once `fence` closes. */
81
- export function sqlClient(db: Database, fence: Fence): Layer.Layer<SqlClient.SqlClient> {
82
- // `effect` as one SQL transaction: it commits when `effect` succeeds
83
- // and rolls back when it fails. Its statements go to the transaction's
84
- // database.
85
- const withTransaction = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
86
- Effect.withFiber<A, E | SqlError, R>((fiber) => {
87
- if (Option.isSome(Context.getOption(fiber.context, InTransaction))) {
88
- return Effect.fail(error('transaction', new Error('nested transactions are not supported')));
89
- }
90
- return Effect.callback<A, E | SqlError, R>((resume) => {
91
- const rollback = new Error('rollback');
92
- let interrupted = false;
93
- let resumed = false;
94
- // Settles when the transaction has committed, or rejects: with
95
- // `rollback` once `effect` failed, or with the error of BEGIN or COMMIT.
96
- const ended: Promise<void> = db.transaction(
97
- (tx) =>
98
- new Promise<void>((resolve, reject) => {
99
- if (interrupted) return reject(rollback);
100
- const inner = Effect.provideContext(
101
- effect,
102
- Context.add(fiber.context, InTransaction, [connection(tx, fence), 0]),
103
- );
104
- resumed = true;
105
- resume(
106
- // A finalizer, so that the body settles however `effect`
107
- // ends, an interruption included: otherwise the transaction
108
- // would hold the session for good.
109
- Effect.onExit(inner, (exit) => {
110
- if (Exit.isSuccess(exit)) {
111
- resolve();
112
- return Effect.void;
113
- }
114
- reject(rollback);
115
- return Effect.promise(() => settled);
116
- }).pipe(
117
- // The commit is part of the transaction: if it fails, so
118
- // does the transaction.
119
- Effect.flatMap((value) =>
120
- Effect.as(Effect.tryPromise({ try: () => ended, catch: (e) => error('commit', e) }), value),
121
- ),
122
- ),
123
- );
124
- }),
125
- );
126
- const settled = ended.catch((cause: unknown) => {
127
- // BEGIN failed: `effect` never ran.
128
- if (!resumed && cause !== rollback) resume(Effect.fail(error('transaction', cause)));
129
- });
130
- return Effect.suspend(() => {
131
- interrupted = true;
132
- return Effect.promise(() => settled);
133
- });
134
- });
135
- });
136
-
137
- const make = Effect.gen(function* () {
138
- const client = yield* SqlClient.make({
139
- acquirer: Effect.succeed(connection(db, fence)),
140
- compiler: Statement.makeCompilerSqlite(),
141
- spanAttributes: [['db.system.name', 'sqlite']],
142
- transactionService: InTransaction,
143
- });
144
- return Object.assign(client, { withTransaction, transactionStatements: false });
145
- });
146
- return Layer.effect(SqlClient.SqlClient, make).pipe(Layer.provide(Reactivity.layer));
147
- }
148
-
149
- export interface OpenOptions {
150
- /** OpenCode plugins: models, tools, agents. */
151
- plugins?: Plugin.Plugin[];
152
- /** OpenCode's config (opencode.json), inline. */
153
- config?: Record<string, unknown>;
154
- /**
155
- * OpenCode's own filesystem, search and shell, on the local machine, for
156
- * its built-in tools (read, write, edit, bash, glob, grep...) in a
157
- * session's directory. Without it, the workerd profile has none.
158
- */
159
- local?: boolean;
160
- /**
161
- * Resume the turns a previous attempt left unfinished, as OpenCode does
162
- * when it boots (default true). A reader beside a running turn does not.
163
- */
164
- resume?: boolean;
165
- }
166
-
167
- /** A booted OpenCode: `call` runs one of `client`'s calls (which return Effects); `close` shuts it down. */
168
- export interface Host {
169
- client: OpenCode.Interface;
170
- call<A, E, R>(effect: Effect.Effect<A, E, R>): Promise<A>;
171
- close(): Promise<void>;
172
- }
173
-
174
- /**
175
- * How OpenCode resumes the turns a previous attempt left unfinished when it
176
- * boots: each, however often it crashed (Restate's retry policy decides how
177
- * often an attempt is retried), or, without `resume`, none.
178
- */
179
- const restarts = (resume: boolean) =>
180
- resume
181
- ? SessionRestart.layer({ maxAttempts: Infinity })
182
- : Layer.succeed(SessionRestart.Service, { resumeSuspendedSessions: Effect.void });
183
-
184
- /**
185
- * Boot OpenCode with its database in `db`. Booting resumes the turns a
186
- * previous attempt left unfinished. Close the host when done.
187
- */
188
- export async function openOpenCode(
189
- db: Database,
190
- fence: Fence,
191
- { plugins = [], config = {}, local = false, resume = true }: OpenOptions,
192
- ): Promise<Host> {
193
- // The workerd profile, but for its database, which comes first. (The
194
- // Promise API's OpenCode.create takes no replacements; the Effect API's does.)
195
- const profile = { storage: undefined as never, models: { fetch: false } };
196
- // In 2.0.27's order: database, process spawner, snapshot, version control,
197
- // filesystem, filesystem search, pty, plugin discovery. Local keeps the
198
- // stubs of snapshots, the pty and plugin discovery only.
199
- const [, spawner, snapshot, vcs, fs, search, pty, discovery] = ServerWorkerd.replacements(profile);
200
- const rest = local ? [snapshot, pty, discovery] : [spawner, snapshot, vcs, fs, search, pty, discovery];
201
- const scope = Scope.makeUnsafe();
202
- const client = await Effect.runPromise(
203
- OpenCode.create(
204
- {
205
- ...ServerWorkerd.serverOptions({ ...profile, config: { content: JSON.stringify(config) } }),
206
- plugins: plugins.map(fromPromise),
207
- },
208
- {
209
- overrides: [
210
- OpenCodeDatabase.node.replace(OpenCodeDatabase.configuredClient(sqlClient(db, fence))),
211
- ...rest,
212
- SessionRestart.node.replace(SessionRestart.node.mapLayer(() => restarts(resume) as never)),
213
- ],
214
- },
215
- ).pipe(Scope.provide(scope)),
216
- );
217
- return {
218
- client,
219
- // The client's calls need nothing more: OpenCode provided it all.
220
- call: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.runPromise(effect as Effect.Effect<A, E>),
221
- close: () => Effect.runPromise(Scope.close(scope, Exit.void)),
222
- };
223
- }