@restatedev/agents 0.0.0 → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +672 -2
- package/dist/calls.d.ts +29 -0
- package/dist/calls.d.ts.map +1 -0
- package/dist/calls.js +91 -0
- package/dist/calls.js.map +1 -0
- package/dist/claude/conversation.d.ts +33 -0
- package/dist/claude/conversation.d.ts.map +1 -0
- package/dist/claude/conversation.js +95 -0
- package/dist/claude/conversation.js.map +1 -0
- package/dist/claude/index.d.ts +77 -0
- package/dist/claude/index.d.ts.map +1 -0
- package/dist/claude/index.js +269 -0
- package/dist/claude/index.js.map +1 -0
- package/dist/client.d.ts +81 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +88 -0
- package/dist/client.js.map +1 -0
- package/dist/common.d.ts +261 -0
- package/dist/common.d.ts.map +1 -0
- package/dist/common.js +438 -0
- package/dist/common.js.map +1 -0
- package/dist/deepseek/index.d.ts +68 -0
- package/dist/deepseek/index.d.ts.map +1 -0
- package/dist/deepseek/index.js +363 -0
- package/dist/deepseek/index.js.map +1 -0
- package/dist/deepseek/persistence.d.ts +61 -0
- package/dist/deepseek/persistence.d.ts.map +1 -0
- package/dist/deepseek/persistence.js +224 -0
- package/dist/deepseek/persistence.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/langgraph/checkpointer.d.ts +29 -0
- package/dist/langgraph/checkpointer.d.ts.map +1 -0
- package/dist/langgraph/checkpointer.js +275 -0
- package/dist/langgraph/checkpointer.js.map +1 -0
- package/dist/langgraph/index.d.ts +66 -0
- package/dist/langgraph/index.d.ts.map +1 -0
- package/dist/langgraph/index.js +265 -0
- package/dist/langgraph/index.js.map +1 -0
- package/dist/log.d.ts +29 -0
- package/dist/log.d.ts.map +1 -0
- package/dist/log.js +145 -0
- package/dist/log.js.map +1 -0
- package/dist/object.d.ts +169 -0
- package/dist/object.d.ts.map +1 -0
- package/dist/object.js +221 -0
- package/dist/object.js.map +1 -0
- package/dist/opencode/db.d.ts +40 -0
- package/dist/opencode/db.d.ts.map +1 -0
- package/dist/opencode/db.js +161 -0
- package/dist/opencode/db.js.map +1 -0
- package/dist/opencode/index.d.ts +100 -0
- package/dist/opencode/index.d.ts.map +1 -0
- package/dist/opencode/index.js +436 -0
- package/dist/opencode/index.js.map +1 -0
- package/dist/output.d.ts +17 -0
- package/dist/output.d.ts.map +1 -0
- package/dist/output.js +81 -0
- package/dist/output.js.map +1 -0
- package/dist/pi/index.d.ts +89 -0
- package/dist/pi/index.d.ts.map +1 -0
- package/dist/pi/index.js +293 -0
- package/dist/pi/index.js.map +1 -0
- package/dist/pi/storage.d.ts +5 -0
- package/dist/pi/storage.d.ts.map +1 -0
- package/dist/pi/storage.js +41 -0
- package/dist/pi/storage.js.map +1 -0
- package/dist/signals.d.ts +154 -0
- package/dist/signals.d.ts.map +1 -0
- package/dist/signals.js +256 -0
- package/dist/signals.js.map +1 -0
- package/dist/tools.d.ts +158 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +211 -0
- package/dist/tools.js.map +1 -0
- package/dist/webhook.d.ts +71 -0
- package/dist/webhook.d.ts.map +1 -0
- package/dist/webhook.js +102 -0
- package/dist/webhook.js.map +1 -0
- package/package.json +218 -5
- package/src/calls.ts +138 -0
- package/src/claude/README.md +84 -0
- package/src/claude/conversation.ts +114 -0
- package/src/claude/index.ts +364 -0
- package/src/client.ts +176 -0
- package/src/common.ts +550 -0
- package/src/deepseek/README.md +110 -0
- package/src/deepseek/index.ts +464 -0
- package/src/deepseek/persistence.ts +293 -0
- package/src/index.ts +24 -0
- package/src/langgraph/README.md +87 -0
- package/src/langgraph/checkpointer.ts +364 -0
- package/src/langgraph/index.ts +349 -0
- package/src/log.ts +193 -0
- package/src/object.ts +319 -0
- package/src/opencode/README.md +125 -0
- package/src/opencode/db.ts +223 -0
- package/src/opencode/index.ts +559 -0
- package/src/output.ts +95 -0
- package/src/pi/README.md +105 -0
- package/src/pi/index.ts +382 -0
- package/src/pi/storage.ts +65 -0
- package/src/signals.ts +386 -0
- package/src/tools.ts +343 -0
- package/src/webhook.ts +161 -0
|
@@ -0,0 +1,559 @@
|
|
|
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
|
+
};
|
package/src/output.ts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// An agent's answer as data, with `output` (every framework's option): a zod
|
|
2
|
+
// object schema. The agent's reply is its answer, as JSON: the system prompt
|
|
3
|
+
// asks for it, with the schema, and each prompt again, at its end; the reply
|
|
4
|
+
// is checked against it. The
|
|
5
|
+
// prompt (and so `chat`) then answers with the value, as an RPC answers.
|
|
6
|
+
//
|
|
7
|
+
// const planner = claude.agent({ name: 'planner', output: Plan }); // chat answers with a Plan
|
|
8
|
+
//
|
|
9
|
+
// The JSON may be in a code fence, or after a sentence. A reply that is not
|
|
10
|
+
// such JSON is answered with what is wrong with it, once, for the agent to
|
|
11
|
+
// answer again; then the prompt fails (a terminal error), saying how the
|
|
12
|
+
// reply starts. A retried attempt resumes the conversation, so it reads the
|
|
13
|
+
// same reply.
|
|
14
|
+
import * as restate from '@restatedev/sessions';
|
|
15
|
+
import { z } from 'zod';
|
|
16
|
+
|
|
17
|
+
/** What a prompt answers: its text, or with `output`, the value of the agent's reply. */
|
|
18
|
+
export type Answer<O> = O extends z.ZodObject ? z.infer<O> : string;
|
|
19
|
+
|
|
20
|
+
/** What the system prompt asks for, with `output`: JSON of its schema, and nothing else. */
|
|
21
|
+
const format = (output: z.ZodObject) =>
|
|
22
|
+
'Your final reply is your answer, as JSON only (no other text): an object of this JSON schema.\n' +
|
|
23
|
+
JSON.stringify(z.toJSONSchema(output));
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* What each prompt ends with, with `output`: the system prompt's ask, again,
|
|
27
|
+
* where an agent reads it last (after a long run of tool calls, it may have
|
|
28
|
+
* drifted from its system prompt to a summary in prose).
|
|
29
|
+
*/
|
|
30
|
+
const reminder =
|
|
31
|
+
'\n\nWhen you are done, reply with your answer as JSON only, of the schema you were given: no other text.';
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The JSON `reply` holds: all of it, what a code fence (```json) holds, or
|
|
35
|
+
* else its object, from its first `{` to its last `}` (a model that ends a
|
|
36
|
+
* long run often says a sentence first: "Done. Here is the summary: {...}").
|
|
37
|
+
*/
|
|
38
|
+
function jsonOf(reply: string): unknown {
|
|
39
|
+
const fenced = /```(?:json)?\s*\n([^]*?)\n?```/.exec(reply)?.[1];
|
|
40
|
+
const object = reply.slice(reply.indexOf('{'), reply.lastIndexOf('}') + 1);
|
|
41
|
+
for (const text of [reply, fenced, object]) {
|
|
42
|
+
try {
|
|
43
|
+
if (text?.trim()) return JSON.parse(text);
|
|
44
|
+
} catch {
|
|
45
|
+
// the next
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The start of `reply`, for an error. */
|
|
52
|
+
const excerpt = (reply: string) => (reply.length > 300 ? `${reply.slice(0, 300)}…` : reply);
|
|
53
|
+
|
|
54
|
+
/** `reply` as a value of `output`, or what is wrong with it. */
|
|
55
|
+
function parsed<O extends z.ZodObject>(output: O, reply: string): { value: z.infer<O> } | { wrong: string } {
|
|
56
|
+
if (!reply.trim()) return { wrong: 'it is empty' };
|
|
57
|
+
const json = jsonOf(reply);
|
|
58
|
+
if (json === undefined) return { wrong: `it is not JSON: ${JSON.stringify(excerpt(reply))}` };
|
|
59
|
+
const result = output.safeParse(json);
|
|
60
|
+
return result.success ? { value: result.data } : { wrong: z.prettifyError(result.error) };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Answer `text` with a value of `output`: the agent's reply to it, parsed;
|
|
65
|
+
* one that is not is answered with what is wrong, once, for another reply.
|
|
66
|
+
*/
|
|
67
|
+
export async function answerWith<O extends z.ZodObject>(
|
|
68
|
+
text: string,
|
|
69
|
+
output: O,
|
|
70
|
+
prompt: (text: string) => Promise<string>,
|
|
71
|
+
): Promise<z.infer<O>> {
|
|
72
|
+
let answer = parsed(output, await prompt(text));
|
|
73
|
+
if ('wrong' in answer) {
|
|
74
|
+
const again = `Your reply is not the answer asked for: ${answer.wrong}\nReply again, with the JSON only.`;
|
|
75
|
+
answer = parsed(output, await prompt(again));
|
|
76
|
+
}
|
|
77
|
+
if ('wrong' in answer)
|
|
78
|
+
throw new restate.TerminalError(`The agent's reply is not the answer asked for: ${answer.wrong}`);
|
|
79
|
+
return answer.value;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* `prompt` (a framework's, of `options`), answering with a value of
|
|
84
|
+
* `options.output` if it has one, or else with the agent's text.
|
|
85
|
+
*/
|
|
86
|
+
export const withOutput = <T extends { system?: string; output?: z.ZodObject }>(
|
|
87
|
+
text: string,
|
|
88
|
+
options: T,
|
|
89
|
+
prompt: (text: string, options: T) => Promise<string>,
|
|
90
|
+
): Promise<Answer<T['output']>> => {
|
|
91
|
+
const { output } = options;
|
|
92
|
+
if (!output) return prompt(text, options) as Promise<Answer<T['output']>>;
|
|
93
|
+
const asked = { ...options, system: [options.system, format(output)].filter(Boolean).join('\n\n') };
|
|
94
|
+
return answerWith(text + reminder, output, (t) => prompt(t, asked)) as Promise<Answer<T['output']>>;
|
|
95
|
+
};
|