|
1
|
+ |
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+ |
import { homedir } from "node:os";
|
|
3
|
+ |
import { join } from "node:path";
|
|
4
|
+ |
|
|
5
|
+ |
import type { ReplyChunk, ReplySource } from "./coder-session.js";
|
|
6
|
+ |
import { systemPrompt } from "./coder-system.js";
|
|
7
|
+ |
import { accumulate, boundedResult, frames, parse, parseArguments } from "./coder-thread.js";
|
|
8
|
+ |
import type { CoderTool } from "./coder-tools.js";
|
|
9
|
+ |
|
|
10
|
+ |
/**
|
|
11
|
+ |
* A coder session answered by OpenCode Zen, on the credential opencode already
|
|
12
|
+ |
* holds on this machine.
|
|
13
|
+ |
*
|
|
14
|
+ |
* The reason this lane exists: Ox Alpha is free and unlimited there, and no
|
|
15
|
+ |
* OpenAgents deployment serves it — the model is in the server's catalog but
|
|
16
|
+ |
* its provider credential is not configured, so a thread opened on it is
|
|
17
|
+ |
* refused. Waiting for that credential to reach a deployment is a wait; the
|
|
18
|
+ |
* machine already has one.
|
|
19
|
+ |
*
|
|
20
|
+ |
* Zen is an OpenAI-compatible endpoint that takes tool calls, so this is the
|
|
21
|
+ |
* same wire shape the inference proxy speaks and the same turn loop. What it is
|
|
22
|
+ |
* not is `opencode` the agent: opencode's own server runs its own loop with its
|
|
23
|
+ |
* own tools, and a session driven through that would be running opencode's
|
|
24
|
+ |
* tools rather than this session's. Only the endpoint and the key are borrowed.
|
|
25
|
+ |
*
|
|
26
|
+ |
* Nothing here spends an OpenAgents grant and nothing reaches a thread, so a
|
|
27
|
+ |
* session on this lane keeps no server-side transcript.
|
|
28
|
+ |
*/
|
|
29
|
+ |
|
|
30
|
+ |
/** Where opencode keeps the credential this lane borrows. */
|
|
31
|
+ |
const AUTH_FILE = join(homedir(), ".local", "share", "opencode", "auth.json");
|
|
32
|
+ |
|
|
33
|
+ |
const ZEN_BASE = "https://opencode.ai/zen/v1";
|
|
34
|
+ |
|
|
35
|
+ |
/**
|
|
36
|
+ |
* The names a reader uses for a Zen model, mapped to what the API takes.
|
|
37
|
+ |
*
|
|
38
|
+ |
* `ox-alpha` is the name it is known by and `x-preview-f-free` is the slug it
|
|
39
|
+ |
* answers to; Zen itself calls it "Ox Alpha Free (Unlimited)". A reader who
|
|
40
|
+ |
* types the name it is called should not have to know the other one.
|
|
41
|
+ |
*/
|
|
42
|
+ |
const ALIASES: Record<string, string> = {
|
|
43
|
+ |
"ox-alpha": "x-preview-f-free",
|
|
44
|
+ |
"ox-alpha-free": "x-preview-f-free",
|
|
45
|
+ |
};
|
|
46
|
+ |
|
|
47
|
+ |
export const zenModelId = (asked: string): string => ALIASES[asked] ?? asked;
|
|
48
|
+ |
|
|
49
|
+ |
/**
|
|
50
|
+ |
* The credential, from the environment or from opencode's own store.
|
|
51
|
+ |
*
|
|
52
|
+ |
* Read rather than copied: this is opencode's key, it stays where opencode put
|
|
53
|
+ |
* it, and a session that finds none says so instead of calling without one.
|
|
54
|
+ |
*/
|
|
55
|
+ |
export const zenCredential = (
|
|
56
|
+ |
env: NodeJS.ProcessEnv = process.env,
|
|
57
|
+ |
authFile: string = AUTH_FILE,
|
|
58
|
+ |
): string | undefined => {
|
|
59
|
+ |
const named = env["OPENCODE_API_KEY"];
|
|
60
|
+ |
if (named !== undefined && named.length > 0) return named;
|
|
61
|
+ |
|
|
62
|
+ |
if (!existsSync(authFile)) return undefined;
|
|
63
|
+ |
try {
|
|
64
|
+ |
const store = JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>;
|
|
65
|
+ |
const entry = store["opencode"];
|
|
66
|
+ |
if (typeof entry !== "object" || entry === null) return undefined;
|
|
67
|
+ |
const key = (entry as Record<string, unknown>)["key"];
|
|
68
|
+ |
return typeof key === "string" && key.length > 0 ? key : undefined;
|
|
69
|
+ |
} catch {
|
|
70
|
+ |
return undefined;
|
|
71
|
+ |
}
|
|
72
|
+ |
};
|
|
73
|
+ |
|
|
74
|
+ |
const LANE = "You answer from Ox Alpha through OpenCode Zen, on this machine's own credential.";
|
|
75
|
+ |
|
|
76
|
+ |
/** How many rounds of tool calls one turn may take before it is stopped. */
|
|
77
|
+ |
const MAX_ROUNDS = 100;
|
|
78
|
+ |
|
|
79
|
+ |
type WireMessage =
|
|
80
|
+ |
| { readonly role: "system"; readonly content: string }
|
|
81
|
+ |
| { readonly role: "user"; readonly content: string }
|
|
82
|
+ |
| {
|
|
83
|
+ |
readonly role: "assistant";
|
|
84
|
+ |
readonly content: string;
|
|
85
|
+ |
readonly tool_calls?: ReadonlyArray<Record<string, unknown>>;
|
|
86
|
+ |
}
|
|
87
|
+ |
| { readonly role: "tool"; readonly tool_call_id: string; readonly content: string };
|
|
88
|
+ |
|
|
89
|
+ |
export class ZenReplySource implements ReplySource {
|
|
90
|
+ |
private readonly key: string;
|
|
91
|
+ |
private readonly slug: string;
|
|
92
|
+ |
private readonly transcript: WireMessage[] = [];
|
|
93
|
+ |
private tools: ReadonlyArray<CoderTool> = [];
|
|
94
|
+ |
private standing: string | undefined;
|
|
95
|
+ |
private steered: string[] = [];
|
|
96
|
+ |
private spentIn = 0;
|
|
97
|
+ |
private spentOut = 0;
|
|
98
|
+ |
private callCount = 0;
|
|
99
|
+ |
|
|
100
|
+ |
constructor(options: { readonly model: string; readonly key: string }) {
|
|
101
|
+ |
this.slug = zenModelId(options.model);
|
|
102
|
+ |
this.key = options.key;
|
|
103
|
+ |
}
|
|
104
|
+ |
|
|
105
|
+ |
get model(): string {
|
|
106
|
+ |
return this.slug === "x-preview-f-free" ? "ox-alpha" : this.slug;
|
|
107
|
+ |
}
|
|
108
|
+ |
|
|
109
|
+ |
get modelId(): string {
|
|
110
|
+ |
return this.slug;
|
|
111
|
+ |
}
|
|
112
|
+ |
|
|
113
|
+ |
/** What the status line shows in place of a thread budget: this lane has none. */
|
|
114
|
+ |
get budget(): string {
|
|
115
|
+ |
return `${String(this.callCount)} calls · ${String(this.spentIn + this.spentOut)} tok · free`;
|
|
116
|
+ |
}
|
|
117
|
+ |
|
|
118
|
+ |
useContext(standing: string): void {
|
|
119
|
+ |
this.standing = standing;
|
|
120
|
+ |
}
|
|
121
|
+ |
|
|
122
|
+ |
useTools(tools: ReadonlyArray<CoderTool>): void {
|
|
123
|
+ |
this.tools = tools;
|
|
124
|
+ |
}
|
|
125
|
+ |
|
|
126
|
+ |
toolDefinitions(): ReadonlyArray<Record<string, unknown>> {
|
|
127
|
+ |
return this.tools.map((tool) => ({
|
|
128
|
+ |
type: "function",
|
|
129
|
+ |
function: { name: tool.name, description: tool.description, parameters: tool.parameters },
|
|
130
|
+ |
}));
|
|
131
|
+ |
}
|
|
132
|
+ |
|
|
133
|
+ |
describeContext(): string {
|
|
134
|
+ |
const declarations =
|
|
135
|
+ |
this.tools.length === 0
|
|
136
|
+ |
? "No tools are declared to the model."
|
|
137
|
+ |
: `${String(this.tools.length)} tool${this.tools.length === 1 ? "" : "s"} declared to the model:\n\n${this.tools
|
|
138
|
+ |
.map(
|
|
139
|
+ |
(tool) =>
|
|
140
|
+ |
`- \`${tool.name}\`\n ${tool.description}\n parameters: ${JSON.stringify(tool.parameters)}`,
|
|
141
|
+ |
)
|
|
142
|
+ |
.join("\n\n")}`;
|
|
143
|
+ |
|
|
144
|
+ |
return [
|
|
145
|
+ |
`System message sent with every turn:\n\n${systemPrompt(this.tools, LANE, this.standing)}`,
|
|
146
|
+ |
"",
|
|
147
|
+ |
declarations,
|
|
148
|
+ |
].join("\n");
|
|
149
|
+ |
}
|
|
150
|
+ |
|
|
151
|
+ |
steer(text: string): boolean {
|
|
152
|
+ |
this.steered.push(text);
|
|
153
|
+ |
return true;
|
|
154
|
+ |
}
|
|
155
|
+ |
|
|
156
|
+ |
async *reply(prompt: string, signal: AbortSignal): AsyncIterable<ReplyChunk> {
|
|
157
|
+ |
if (!this.transcript.some((message) => message.role === "system")) {
|
|
158
|
+ |
this.transcript.unshift({
|
|
159
|
+ |
role: "system",
|
|
160
|
+ |
content: systemPrompt(this.tools, LANE, this.standing),
|
|
161
|
+ |
});
|
|
162
|
+ |
}
|
|
163
|
+ |
this.transcript.push({ role: "user", content: prompt });
|
|
164
|
+ |
|
|
165
|
+ |
for (let round = 0; round < MAX_ROUNDS; round += 1) {
|
|
166
|
+ |
if (signal.aborted) return;
|
|
167
|
+ |
|
|
168
|
+ |
// Read between two model calls rather than at the end of the turn, which
|
|
169
|
+ |
// is the difference between steering a model and waiting one out.
|
|
170
|
+ |
for (const said of this.steered.splice(0)) {
|
|
171
|
+ |
this.transcript.push({ role: "user", content: said });
|
|
172
|
+ |
}
|
|
173
|
+ |
|
|
174
|
+ |
const calls: Map<number, { id: string; name: string; args: string }> = new Map();
|
|
175
|
+ |
let assistant = "";
|
|
176
|
+ |
|
|
177
|
+ |
const response = await this.call(signal);
|
|
178
|
+ |
if (response === undefined || signal.aborted) return;
|
|
179
|
+ |
|
|
180
|
+ |
for await (const frame of frames(response, signal)) {
|
|
181
|
+ |
if (signal.aborted) return;
|
|
182
|
+ |
if (frame === "[DONE]") break;
|
|
183
|
+ |
|
|
184
|
+ |
const payload = parse(frame);
|
|
185
|
+ |
if (payload === undefined) continue;
|
|
186
|
+ |
|
|
187
|
+ |
const usage = payload["usage"];
|
|
188
|
+ |
if (typeof usage === "object" && usage !== null) this.spend(usage as Record<string, unknown>);
|
|
189
|
+ |
|
|
190
|
+ |
const choices = payload["choices"];
|
|
191
|
+ |
if (!Array.isArray(choices)) continue;
|
|
192
|
+ |
|
|
193
|
+ |
for (const choice of choices) {
|
|
194
|
+ |
const delta = (choice as Record<string, unknown>)["delta"];
|
|
195
|
+ |
if (typeof delta !== "object" || delta === null) continue;
|
|
196
|
+ |
const parts = delta as Record<string, unknown>;
|
|
197
|
+ |
|
|
198
|
+ |
const thought = parts["reasoning"] ?? parts["reasoning_content"];
|
|
199
|
+ |
if (typeof thought === "string" && thought.length > 0) {
|
|
200
|
+ |
yield { type: "reasoning", value: thought };
|
|
201
|
+ |
}
|
|
202
|
+ |
|
|
203
|
+ |
const content = parts["content"];
|
|
204
|
+ |
if (typeof content === "string" && content.length > 0) {
|
|
205
|
+ |
assistant += content;
|
|
206
|
+ |
yield { type: "text", value: content };
|
|
207
|
+ |
}
|
|
208
|
+ |
|
|
209
|
+ |
const toolCalls = parts["tool_calls"];
|
|
210
|
+ |
if (Array.isArray(toolCalls)) accumulate(calls, toolCalls);
|
|
211
|
+ |
}
|
|
212
|
+ |
}
|
|
213
|
+ |
|
|
214
|
+ |
const asked = [...calls.values()];
|
|
215
|
+ |
if (asked.length === 0) {
|
|
216
|
+ |
if (assistant.length > 0) this.transcript.push({ role: "assistant", content: assistant });
|
|
217
|
+ |
yield {
|
|
218
|
+ |
type: "usage",
|
|
219
|
+ |
promptTokens: this.spentIn,
|
|
220
|
+ |
completionTokens: this.spentOut,
|
|
221
|
+ |
calls: round + 1,
|
|
222
|
+ |
};
|
|
223
|
+ |
return;
|
|
224
|
+ |
}
|
|
225
|
+ |
|
|
226
|
+ |
// The assistant turn carries the calls it made, and every one of them is
|
|
227
|
+ |
// answered before the next round: a call whose result never follows is a
|
|
228
|
+ |
// transcript the provider refuses.
|
|
229
|
+ |
this.transcript.push({
|
|
230
|
+ |
role: "assistant",
|
|
231
|
+ |
content: assistant,
|
|
232
|
+ |
tool_calls: asked.map((call) => ({
|
|
233
|
+ |
id: call.id,
|
|
234
|
+ |
type: "function",
|
|
235
|
+ |
function: { name: call.name, arguments: call.args },
|
|
236
|
+ |
})),
|
|
237
|
+ |
});
|
|
238
|
+ |
|
|
239
|
+ |
for (const call of asked) {
|
|
240
|
+ |
yield { type: "tool_call", callId: call.id, name: call.name, arguments: call.args };
|
|
241
|
+ |
|
|
242
|
+ |
const tool = this.tools.find((candidate) => candidate.name === call.name);
|
|
243
|
+ |
const output =
|
|
244
|
+ |
tool === undefined
|
|
245
|
+ |
? `No tool called ${call.name} is declared in this session.`
|
|
246
|
+ |
: await tool
|
|
247
|
+ |
.run(parseArguments(call.args), signal)
|
|
248
|
+ |
.catch((cause: unknown) => `The tool failed: ${String(cause)}`);
|
|
249
|
+ |
|
|
250
|
+ |
this.transcript.push({
|
|
251
|
+ |
role: "tool",
|
|
252
|
+ |
tool_call_id: call.id,
|
|
253
|
+ |
content: boundedResult(output),
|
|
254
|
+ |
});
|
|
255
|
+ |
yield { type: "tool_result", callId: call.id, output, error: undefined };
|
|
256
|
+ |
}
|
|
257
|
+ |
}
|
|
258
|
+ |
|
|
259
|
+ |
yield {
|
|
260
|
+ |
type: "text",
|
|
261
|
+ |
value: `\n\nThe turn stopped after ${String(MAX_ROUNDS)} rounds of tool calls.`,
|
|
262
|
+ |
};
|
|
263
|
+ |
}
|
|
264
|
+ |
|
|
265
|
+ |
private async call(signal: AbortSignal): Promise<ReadableStream<Uint8Array> | undefined> {
|
|
266
|
+ |
this.callCount += 1;
|
|
267
|
+ |
|
|
268
|
+ |
const response = await fetch(`${ZEN_BASE}/chat/completions`, {
|
|
269
|
+ |
method: "POST",
|
|
270
|
+ |
signal,
|
|
271
|
+ |
headers: {
|
|
272
|
+ |
authorization: `Bearer ${this.key}`,
|
|
273
|
+ |
"content-type": "application/json",
|
|
274
|
+ |
accept: "text/event-stream",
|
|
275
|
+ |
},
|
|
276
|
+ |
body: JSON.stringify({
|
|
277
|
+ |
model: this.slug,
|
|
278
|
+ |
stream: true,
|
|
279
|
+ |
stream_options: { include_usage: true },
|
|
280
|
+ |
messages: this.transcript,
|
|
281
|
+ |
...(this.tools.length === 0
|
|
282
|
+ |
? {}
|
|
283
|
+ |
: {
|
|
284
|
+ |
tools: this.tools.map((tool) => ({
|
|
285
|
+ |
type: "function",
|
|
286
|
+ |
function: {
|
|
287
|
+ |
name: tool.name,
|
|
288
|
+ |
description: tool.description,
|
|
289
|
+ |
parameters: tool.parameters,
|
|
290
|
+ |
},
|
|
291
|
+ |
})),
|
|
292
|
+ |
}),
|
|
293
|
+ |
}),
|
|
294
|
+ |
}).catch((cause: unknown) => {
|
|
295
|
+ |
if (signal.aborted) return undefined;
|
|
296
|
+ |
throw new Error(`OpenCode Zen could not be reached: ${String(cause)}`);
|
|
297
|
+ |
});
|
|
298
|
+ |
|
|
299
|
+ |
if (response === undefined || signal.aborted) return undefined;
|
|
300
|
+ |
|
|
301
|
+ |
if (!response.ok) {
|
|
302
|
+ |
const detail = (await response.text().catch(() => "")).slice(0, 300);
|
|
303
|
+ |
throw new Error(
|
|
304
|
+ |
`OpenCode Zen refused the call (${String(response.status)})` +
|
|
305
|
+ |
(detail.length === 0 ? "." : `: ${detail}`),
|
|
306
|
+ |
);
|
|
307
|
+ |
}
|
|
308
|
+ |
|
|
309
|
+ |
return response.body ?? undefined;
|
|
310
|
+ |
}
|
|
311
|
+ |
|
|
312
|
+ |
private spend(usage: Record<string, unknown>): void {
|
|
313
|
+ |
const input = usage["prompt_tokens"];
|
|
314
|
+ |
const output = usage["completion_tokens"];
|
|
315
|
+ |
if (typeof input === "number") this.spentIn = input;
|
|
316
|
+ |
if (typeof output === "number") this.spentOut = output;
|
|
317
|
+ |
}
|
|
318
|
+ |
}
|