@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
@@ -1,559 +0,0 @@
1
- // OpenCode 2.0 agents in Restate virtual objects: OpenCode for each
2
- // invocation, with its database in the object's state.
3
- //
4
- // const coder = opencode.agent({ name: 'coder', workspace: (ctx) => `/work/${ctx.key}` });
5
- //
6
- // or a handler of an object of your own: `handlers: { chat: opencode.chat() }`,
7
- // with options for each invocation: `opencode.chat(async (ctx) => ({ workspace }))`
8
- //
9
- // or, for more than a prompt:
10
- //
11
- // review: (ctx, task) => withOpenCode(ctx, { tools }, async ({ prompt }) => [await prompt(task), await prompt('Review it')]),
12
- //
13
- // The model is `model`, MODEL, or else openai/gpt-6-sol,
14
- // which OpenCode's own providers serve, with the provider's API key (such as
15
- // OPENAI_API_KEY).
16
- //
17
- // It runs `work` over a database of the key's own, beside `ctx.db`
18
- // (`database`): OpenCode's tables are alone there (db.ts), as OpenCode
19
- // boots only on a database that is empty or its own, and each OpenCode
20
- // transaction is an SQL transaction in it, stored in order with everything
21
- // else the handler does. `ctx.db` keeps the conversation's log, and the
22
- // tables of yours.
23
- // OpenCode is booted with `plugins` and a plugin of the `tools`, and closed at
24
- // the end.
25
- //
26
- // A retried attempt (a crash, a lost connection) boots OpenCode again, and
27
- // OpenCode resumes the turn the last attempt left unfinished: it records an
28
- // execution claim when a turn starts and releases it when the turn ends, and
29
- // resumes every claimed turn when it boots. A prompt is submitted once, by its
30
- // id (OpenCode's message id), and an answered prompt returns its answer.
31
- //
32
- // A resumed turn gives a tool call that was running an "interrupted" result
33
- // and asks the model to continue, so a tool that must not run twice needs a
34
- // way for the model to name the call it retries (such as a `retryOf`
35
- // argument). A tool that throws fails the attempt rather than hand the error
36
- // to the model: from then on the attempt stores nothing (its fence closes),
37
- // and the next attempt finds the call interrupted.
38
- import * as restate from '@restatedev/sessions';
39
- import { database, reset } from '@restatedev/sessions/internal';
40
- import { mkdir } from 'node:fs/promises';
41
- import type { Plugin } from '@opencode/plugin';
42
- import type { StandardSchemaV1 } from '@standard-schema/spec';
43
- import {
44
- alsoClearing,
45
- chatHandler,
46
- CHECK_MODEL,
47
- checkModelName,
48
- type Configure,
49
- configured,
50
- messagesHandler,
51
- modelOf,
52
- nextPromptId,
53
- providerOf,
54
- refusal,
55
- REFUSED,
56
- stopSignalOf,
57
- toolCallEnded,
58
- toolCallStarted,
59
- transcribing,
60
- Transcript,
61
- } from '../common.ts';
62
- import { type Answer, withOutput } from '../output.ts';
63
- import type { z } from 'zod';
64
- import { type Definition, sessionObject } from '../object.ts';
65
- import { isTool, type Tool as AnyTool } from '../tools.ts';
66
-
67
- import { type Fence, type Host, openOpenCode } from './db.ts';
68
-
69
- /** An OpenCode model reference. */
70
- export interface ModelRef {
71
- providerID: string;
72
- id: string;
73
- }
74
-
75
- /** `provider/model-id` as OpenCode names it. */
76
- const modelRef = (name: string): ModelRef => {
77
- const [providerID, id] = providerOf(name);
78
- return { providerID, id };
79
- };
80
-
81
- /** An OpenCode tool of your own: `execute` gets the input and the tool call's id. */
82
- export interface OpenCodeTool<Input = unknown> {
83
- name: string;
84
- description: string;
85
- input: StandardSchemaV1<unknown, Input>;
86
- execute(input: Input, callId: string): Promise<string>;
87
- }
88
-
89
- /**
90
- * `t` as an OpenCode tool. OpenCode checks the arguments against `t.input`,
91
- * and answers the model with what is wrong; those that fit reach `t.run` as
92
- * the model gave them, which parses them itself.
93
- */
94
- const native = (t: AnyTool, ctx: restate.SessionContext): OpenCodeTool => {
95
- const standard = t.input['~standard'];
96
- const input: StandardSchemaV1 = {
97
- '~standard': {
98
- ...standard,
99
- validate: (args) => {
100
- const result = standard.validate(args) as StandardSchemaV1.Result<unknown>;
101
- return result.issues ? result : { value: args };
102
- },
103
- },
104
- };
105
- return { name: t.name, description: t.description, input, execute: (args, callId) => t.run(args, { ctx, callId }) };
106
- };
107
-
108
- /** The session every prompt goes to. */
109
- const SESSION = 'ses_root';
110
-
111
- /** The key's database where OpenCode's tables are, apart from `ctx.db`. */
112
- const DATABASE = 'restate-agents.opencode';
113
-
114
- /** What `work` gets: `prompt(text)`, and the OpenCode `host` for anything else. */
115
- export interface OpenCodeSession {
116
- host: Host;
117
- /** Answer `text`, once per prompt `id`, with the answer's text. By default, each prompt of an invocation has an id of its own, the same on every attempt. */
118
- prompt: (text: string, id?: string) => Promise<string>;
119
- }
120
-
121
- /** An agent's options: `chat`, `prompt` and `withOpenCode` take them. */
122
- export interface Options<O extends z.ZodObject | undefined = z.ZodObject | undefined> {
123
- /** The model of the session, as `provider/model-id`: MODEL, or else openai/gpt-6-sol. */
124
- model?: string | ModelRef;
125
- /** The system prompt: who the agent is, and how it answers. */
126
- system?: string;
127
- /** The agent's tools, which replace OpenCode's own: `tool()`s, Restate's (`call`, `signal`...), or OpenCode tools of your own. */
128
- tools?: (AnyTool | OpenCodeTool)[];
129
- /**
130
- * A directory of the local machine, made if missing: OpenCode keeps its own tools (read,
131
- * write, edit, bash, glob, grep...) there, besides `tools`, and the
132
- * session works in it. Or a function of the invocation's context that
133
- * gives one: `(ctx) => \`/work/${ctx.key}\``, a directory per key; or makes
134
- * one, such as a git worktree (it runs at each attempt: make it idempotent).
135
- */
136
- workspace?: string | ((ctx: restate.SessionContext) => string | Promise<string>);
137
- /** OpenCode plugins, such as the one of the model. */
138
- plugins?: Plugin.Plugin[];
139
- /**
140
- * The answer as data: a zod object, whose JSON the agent replies with
141
- * (checked), and `chat` and `prompt` answer with (see output.ts).
142
- */
143
- output?: O;
144
- }
145
-
146
- /** An OpenCode plugin that adds `system` to the session's system prompt. */
147
- const systemPlugin = (system: string): Plugin.Plugin => ({
148
- id: 'restate-agents.system',
149
- async setup(ctx) {
150
- const hook = await ctx.session.hook('context', (request) => {
151
- request.system.push({ type: 'text', text: system });
152
- });
153
- return () => hook.dispose();
154
- },
155
- });
156
-
157
- /** An OpenCode plugin whose tools are `tools`, and only those. */
158
- function toolsPlugin(tools: OpenCodeTool[], fail: (error: unknown) => Promise<never>, builtins = false): Plugin.Plugin {
159
- return {
160
- id: 'restate-agents.tools',
161
- async setup(ctx) {
162
- const transform = await ctx.tool.transform((editor) => {
163
- // Without a workspace, no filesystem, shell or web: the agent acts
164
- // through its tools.
165
- if (!builtins) for (const { id } of editor.list()) editor.remove(id);
166
- for (const t of tools) {
167
- editor.add({
168
- name: t.name,
169
- description: t.description,
170
- input: t.input,
171
- // Offered to the model as a tool, not in a code-mode script.
172
- options: { codemode: false },
173
- execute: async (input, context) => {
174
- try {
175
- return { content: await t.execute(input, context.id) };
176
- } catch (error) {
177
- return fail(error);
178
- }
179
- },
180
- });
181
- }
182
- });
183
- return () => transform.dispose();
184
- },
185
- };
186
- }
187
-
188
- /**
189
- * An OpenCode plugin that publishes each tool call as it starts and ends,
190
- * for the clients that follow the conversation.
191
- */
192
- const followPlugin = (ctx: restate.SessionContext, fail: (error: unknown) => Promise<never>): Plugin.Plugin => ({
193
- id: 'restate-agents.follow',
194
- async setup(plugin) {
195
- const before = await plugin.tool.hook('execute.before', async () => {
196
- await toolCallStarted(ctx).catch(fail);
197
- });
198
- const after = await plugin.tool.hook('execute.after', async () => {
199
- await toolCallEnded(ctx).catch(fail);
200
- });
201
- return async () => {
202
- await before.dispose();
203
- await after.dispose();
204
- };
205
- },
206
- });
207
-
208
- /** OpenCode's message id of prompt `id`: letters, digits, `_` and `-`. */
209
- const messageIdOf = (id: string) => `msg_${id.replace(/[^\w-]/g, '_')}`;
210
-
211
- /** A part of an assistant message: text, or a tool call (`id`, `name`, and its `state`). */
212
- interface Content {
213
- type: string;
214
- text?: string;
215
- id?: string;
216
- name?: string;
217
- state?: { status?: string; input?: unknown; content?: Content[]; error?: { message?: string } };
218
- }
219
-
220
- /** The text of `content`. */
221
- const textOf = (content: Content[] = []) =>
222
- content.flatMap((c) => (c.type === 'text' && c.text ? [c.text] : [])).join('');
223
-
224
- /** A message of the session's transcript, as far as a prompt's outcome and `messages` go. */
225
- interface Message {
226
- id: string;
227
- type: string;
228
- outcome?: string;
229
- /** A user message's text. */
230
- text?: string;
231
- content?: Content[];
232
- error?: { message?: string };
233
- }
234
-
235
- /** The prompts waiting in the session's inbox, until their turn starts, oldest first. */
236
- const inbox = (host: Host): Promise<{ id: string; payload: { text: string } }[]> =>
237
- host.call(host.client.session.inbox.list({ sessionID: SESSION as never }));
238
-
239
- /** The session's messages, a page at a time, oldest or newest first. */
240
- async function* messagePages(host: Host, order: 'asc' | 'desc'): AsyncGenerator<Message[]> {
241
- const sessionID = SESSION as never;
242
- for (let cursor: string | undefined; ;) {
243
- const page: { data: Message[]; cursor: { next?: string | null } } = await host.call(
244
- host.client.message.list(cursor === undefined ? { sessionID, order, limit: 50 } : { sessionID, cursor }),
245
- );
246
- yield page.data;
247
- cursor = page.cursor.next ?? undefined;
248
- if (cursor === undefined) return;
249
- }
250
- }
251
-
252
- /** The session's messages, oldest first. */
253
- async function sessionMessages(host: Host): Promise<Message[]> {
254
- const all: Message[] = [];
255
- for await (const page of messagePages(host, 'asc')) all.push(...page);
256
- return all;
257
- }
258
-
259
- /** Where a prompt is: not in the session, its turn running, or ended with an answer or a failure. */
260
- type Outcome =
261
- | { state: 'absent' | 'running' }
262
- | { state: 'answered'; text: string }
263
- | { state: 'failed'; reason: string };
264
-
265
- /** Where prompt `messageId` is (see {@link Outcome}). */
266
- async function outcome(host: Host, messageId: string): Promise<Outcome> {
267
- if ((await inbox(host)).some((item) => item.id === messageId)) return { state: 'running' };
268
- const after = await messagesAfter(host, messageId);
269
- return after ? turnOutcome(after) : { state: 'absent' };
270
- }
271
-
272
- /** The messages after prompt `messageId`, oldest first; undefined if the session does not have it. */
273
- async function messagesAfter(host: Host, messageId: string): Promise<Message[] | undefined> {
274
- const after: Message[] = [];
275
- for await (const page of messagePages(host, 'desc')) {
276
- const at = page.findIndex((m) => m.id === messageId);
277
- after.unshift(...(at < 0 ? page : page.slice(0, at)).toReversed());
278
- if (at >= 0) return after;
279
- }
280
- return undefined;
281
- }
282
-
283
- /**
284
- * How the turn of the messages `after` a prompt ended: at an idle marker, or
285
- * where the next prompt, queued while it ran, starts. Running, if neither
286
- * came yet.
287
- */
288
- function turnOutcome(after: Message[]): Outcome {
289
- let last: Message | undefined;
290
- for (const m of after) {
291
- if (m.type === 'idle') return ended(last, m.outcome);
292
- if (m.type === 'user' && last !== undefined) return ended(last, 'succeeded');
293
- if (m.type === 'assistant') last = m;
294
- }
295
- return { state: 'running' };
296
- }
297
-
298
- /** The outcome of a turn that ended `how`, with `last`, its last assistant message: its text, or its error. */
299
- function ended(last: Message | undefined, how: string | undefined): Outcome {
300
- const error = last?.error?.message;
301
- if (how === 'succeeded' && error === undefined) return { state: 'answered', text: textOf(last?.content) };
302
- return { state: 'failed', reason: error ?? how ?? 'failed' };
303
- }
304
-
305
- /** The id of the session's latest prompt, if any. */
306
- async function lastPrompt(host: Host): Promise<string | undefined> {
307
- const queued = (await inbox(host)).at(-1);
308
- if (queued) return queued.id;
309
- for await (const page of messagePages(host, 'desc')) {
310
- const user = page.find((m) => m.type === 'user');
311
- if (user) return user.id;
312
- }
313
- return undefined;
314
- }
315
-
316
- /** Whether a turn of the session runs. */
317
- const active = async (host: Host) => {
318
- const turns: Record<string, unknown> = await host.call(host.client.session.active());
319
- return turns[SESSION] !== undefined;
320
- };
321
-
322
- /**
323
- * Start the session's queued prompts, if no turn runs them. OpenCode resumes
324
- * the turns it claimed when it boots, but a crash between a prompt's queueing
325
- * and its turn's claim leaves it in the inbox with nothing to run it: sent
326
- * again, by its id, it starts.
327
- */
328
- async function startInbox(host: Host) {
329
- if (await active(host)) return;
330
- const [first] = await inbox(host);
331
- if (first === undefined) return;
332
- await host.call(
333
- host.client.session.prompt({
334
- sessionID: SESSION as never,
335
- id: first.id as never,
336
- text: first.payload.text,
337
- delivery: 'queue',
338
- resume: true,
339
- }),
340
- );
341
- }
342
-
343
- /** The session, made with `model` (working in `workspace`, if given) unless it is there already. */
344
- async function openSession(host: Host, model: ModelRef, workspace: string | undefined) {
345
- const { session } = host.client;
346
- const sessionID = SESSION as never;
347
- const exists = await host.call(session.get({ sessionID })).then(
348
- () => true,
349
- () => false,
350
- );
351
- if (exists) return;
352
- const location = workspace ? { location: { directory: workspace as never } } : {};
353
- await host.call(session.create({ id: sessionID, model: model as never, agent: 'build' as never, ...location }));
354
- }
355
-
356
- /**
357
- * Queue prompt `messageId`, unless the session has it. A prompt that a crash
358
- * interrupted finishes first: queued now, the new prompt would join its
359
- * resumed turn.
360
- */
361
- async function submit(host: Host, messageId: string, text: string) {
362
- if ((await outcome(host, messageId)).state !== 'absent') return;
363
- const last = await lastPrompt(host);
364
- if (last !== undefined) await settled(host, last);
365
- await host.call(
366
- host.client.session.prompt({
367
- sessionID: SESSION as never,
368
- id: messageId as never,
369
- text,
370
- delivery: 'queue',
371
- resume: true,
372
- }),
373
- );
374
- }
375
-
376
- /** How long a prompt's turn may be neither running nor ended: one resumed at boot starts well within it. */
377
- const STALLED_MS = 5_000;
378
-
379
- /**
380
- * The outcome of prompt `messageId`, once its turn has ended. A turn that
381
- * neither runs nor ends for {@link STALLED_MS} (OpenCode lost it) fails the
382
- * attempt: the retry boots OpenCode again, which resumes the turns it claimed.
383
- */
384
- async function settled(host: Host, messageId: string): Promise<Outcome> {
385
- for (let idleSince = Date.now(); ;) {
386
- const now = await outcome(host, messageId);
387
- if (now.state !== 'running') return now;
388
- await startInbox(host);
389
- await host.call(host.client.session.wait({ sessionID: SESSION as never }));
390
- if (await active(host)) {
391
- idleSince = Date.now();
392
- continue;
393
- }
394
- if (Date.now() - idleSince > STALLED_MS) {
395
- throw new Error(`prompt ${messageId}: its turn has neither run nor ended for ${STALLED_MS / 1000} s`);
396
- }
397
- // A turn resumed at boot may not have started yet.
398
- await new Promise((resolve) => setTimeout(resolve, 20));
399
- }
400
- }
401
-
402
- /**
403
- * `failure`, once it comes. A cancellation first interrupts the session's
404
- * turn, which OpenCode records, so the next prompt does not resume it.
405
- */
406
- async function interruptOn(host: Host, failure: Promise<never>): Promise<never> {
407
- try {
408
- return await failure;
409
- } catch (error) {
410
- if (error instanceof restate.CancelledError) {
411
- await host.call(host.client.session.interrupt({ sessionID: SESSION as never }));
412
- }
413
- throw error;
414
- }
415
- }
416
-
417
- /**
418
- * Run `work(opencode)` with OpenCode over the object's database: `model` is
419
- * the session's model, `plugins` OpenCode plugins (such as the model's), and
420
- * `tools` the agent's tools. `opencode` has `prompt(text)`, and the
421
- * OpenCode `host` for anything else.
422
- */
423
- export const withOpenCode = async <T>(
424
- ctx: restate.SessionContext,
425
- { plugins = [], model: named, system, tools = [], workspace: where }: Options,
426
- work: (opencode: OpenCodeSession) => Promise<T>,
427
- ): Promise<T> => {
428
- const model = typeof named === 'object' ? named : modelRef(modelOf(named));
429
- const workspace = typeof where === 'function' ? await where(ctx) : where;
430
- if (workspace) await mkdir(workspace, { recursive: true });
431
- const fence: Fence = { closed: false };
432
- const { promise: failure, reject: failed } = Promise.withResolvers<never>();
433
- failure.catch(() => {});
434
- // A tool's error ends the attempt: nothing more is stored, and the tool
435
- // call never returns, so OpenCode does not go on without it; an attempt
436
- // that ends first does the same. A cancelled invocation, whenever it comes,
437
- // interrupts the session's turn instead (interruptOn).
438
- let cancelled: restate.CancelledError | undefined;
439
- const fail = (error: unknown) => {
440
- if (error instanceof restate.CancelledError) cancelled = error;
441
- else fence.closed = true;
442
- failed(error);
443
- return new Promise<never>(() => {});
444
- };
445
- const turn = stopSignalOf(ctx);
446
- const onStop = () => void fail(turn!.reason);
447
- turn?.addEventListener('abort', onStop, { once: true });
448
- const host = await openOpenCode(database(ctx.db, DATABASE), fence, {
449
- plugins: [
450
- ...plugins,
451
- followPlugin(ctx, fail),
452
- toolsPlugin(
453
- tools.map((t) => (isTool(t) ? native(t, ctx) : t)),
454
- fail,
455
- workspace !== undefined,
456
- ),
457
- ...(system ? [systemPlugin(system)] : []),
458
- ],
459
- config: { default_agent: 'build' },
460
- local: workspace !== undefined,
461
- });
462
-
463
- const prompt = async (text: string, id = nextPromptId(ctx)) => {
464
- const messageId = messageIdOf(id);
465
- await openSession(host, model, workspace);
466
- await submit(host, messageId, text);
467
- const now = await settled(host, messageId);
468
- if (now.state === 'answered') return now.text;
469
- if (now.state !== 'failed') throw new Error(`prompt ${id} is not in the session`);
470
- // A prompt the cancellation's interrupt ended fails with the cancellation.
471
- if (cancelled) throw cancelled;
472
- // Its provider's refusal (a missing API key, say) is REFUSED, as for the other frameworks.
473
- const message = `prompt ${id} unanswered: ${now.reason}`;
474
- if (!refusal(new Error(now.reason))) throw new restate.TerminalError(message);
475
- const of = `the model ${model.providerID}/${model.id}: ${CHECK_MODEL}`;
476
- throw new restate.TerminalError(`${message} (${of})`, { errorCode: REFUSED });
477
- };
478
-
479
- try {
480
- // The log reads the session through this host, while it is open.
481
- const read = () => transcribe(host);
482
- return await transcribing(ctx, read, () => Promise.race([interruptOn(host, failure), work({ host, prompt })]));
483
- } finally {
484
- turn?.removeEventListener('abort', onStop);
485
- await host.close();
486
- }
487
- };
488
-
489
- /** {@link prompt}, answering with the agent's text. */
490
- const promptText = (ctx: restate.SessionContext, text: string, options: Options): Promise<string> =>
491
- withOpenCode(ctx, options, (session) => session.prompt(text));
492
-
493
- /**
494
- * Answer `text`, once: a retried attempt resumes the same prompt. Each prompt
495
- * of an invocation is a prompt of its own.
496
- * With `output`, it answers with the value the agent replies with (see
497
- * output.ts), not its text.
498
- */
499
- export const prompt = <O extends z.ZodObject | undefined = undefined>(
500
- ctx: restate.SessionContext,
501
- text: string,
502
- options: Options<O> = {},
503
- ): Promise<Answer<O>> => withOutput(text, options, (t, o) => promptText(ctx, t, o)) as Promise<Answer<O>>;
504
-
505
- /**
506
- * A chat handler: each message an invocation, the session in the object's
507
- * database, with `options`, or the options a function of the invocation's
508
- * context gives (each user's workspace, say). It takes the message as plain
509
- * text (`curl -d 'Hi'`) or as a JSON string (`curl --json '"Hi"'`).
510
- */
511
- export const chat = <O extends z.ZodObject | undefined = undefined>(options: Configure<Options<O>> = {}) => {
512
- if (typeof options === 'object' && typeof options.model !== 'object') checkModelName('opencode', options.model);
513
- return chatHandler(async (ctx, message) => prompt(ctx, message, await configured(options, ctx)));
514
- };
515
-
516
- /**
517
- * A handler of the conversation as clients read it: a page at a time, or
518
- * what is new or changed since a cursor, from the log each change writes
519
- * (log.ts). It answers while a message is answered.
520
- */
521
- export const messages = () =>
522
- // OpenCode's tables are in a database of their own, which `clear` empties too.
523
- alsoClearing(messagesHandler(), (ctx) => database(ctx.db, DATABASE).transaction((tx) => reset(tx)));
524
-
525
- /** The session of `host`, as `messages` gives it. */
526
- const transcribe = async (host: Host) => {
527
- const transcript = new Transcript();
528
- for (const m of await sessionMessages(host)) {
529
- if (m.type === 'user') transcript.say('user', m.text);
530
- if (m.type !== 'assistant') continue;
531
- transcript.say('assistant', textOf(m.content));
532
- for (const c of m.content ?? []) {
533
- if (c.type !== 'tool' || !c.id || !c.state) continue;
534
- transcript.call(c.id, c.name ?? '', c.state.input);
535
- // A failed or interrupted call has its error, and perhaps no content.
536
- const output = c.state.content ? textOf(c.state.content) : c.state.error?.message;
537
- if (output !== undefined) transcript.result(c.id, output, c.state.status === 'error');
538
- }
539
- }
540
- return transcript;
541
- };
542
-
543
- /** An agent: a virtual object `name`, one per key, whose `chat` handler is {@link chat}, and `messages` {@link messages}. */
544
- export const agent = <P extends string, O extends z.ZodObject | undefined = undefined>({
545
- name,
546
- description,
547
- schema,
548
- background,
549
- ...options
550
- }: Options<O> & Definition<P>) => {
551
- return sessionObject({
552
- name,
553
- description,
554
- schema,
555
- background,
556
- handlers: { chat: chat(options) },
557
- views: { messages: messages() },
558
- });
559
- };