opencode-next 0.0.0-stage → 1.0.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.
@@ -0,0 +1,413 @@
1
+ /**
2
+ * Optional OpenCode v2-compatible Bun transport, ported from
3
+ * FishBottle7/opencode2dsh PR #110. The Bun runtime is supplied by the user;
4
+ * this module never downloads or installs it.
5
+ */
6
+ import { spawn, spawnSync } from 'node:child_process';
7
+ import { existsSync } from 'node:fs';
8
+ import { join, delimiter, isAbsolute } from 'node:path';
9
+ import { homedir, tmpdir } from 'node:os';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { createRequire } from 'node:module';
12
+ import { stableProjectId } from './client.js';
13
+
14
+ const require = createRequire(import.meta.url);
15
+
16
+ const WORKER_PATH = fileURLToPath(new URL('./bun-worker.mjs', import.meta.url));
17
+ const INFERENCE_PATHS = new Set([
18
+ '/inference/openai/v1/chat/completions',
19
+ '/inference/v1/chat/completions',
20
+ '/zen/v1/chat/completions',
21
+ '/inference/v1/responses',
22
+ '/inference/openai/v1/responses',
23
+ '/zen/v1/responses'
24
+ ]);
25
+ const activeRequests = new Set();
26
+
27
+ /** Resolve the configured Bun executable without invoking a shell. */
28
+ export function resolveBunPath(customPath) {
29
+ if (typeof customPath === 'string' && customPath.trim() !== '') {
30
+ const value = customPath.trim();
31
+ if (existsSync(value)) return value;
32
+ throw new Error(`Configured bunPath does not exist: ${value}`);
33
+ }
34
+
35
+ const exeName = process.platform === 'win32' ? 'bun.exe' : 'bun';
36
+ const candidates = [
37
+ process.env.APPDATA ? join(process.env.APPDATA, 'npm', 'node_modules', 'bun', 'bin', 'bun.exe') : null,
38
+ join(homedir(), '.bun', 'bin', exeName),
39
+ process.platform === 'win32' ? 'C:\\tools\\bun.exe' : '/usr/local/bin/bun',
40
+ process.platform === 'win32' ? null : '/usr/bin/bun'
41
+ ].filter(Boolean);
42
+
43
+ for (const candidate of candidates) {
44
+ if (existsSync(candidate)) return candidate;
45
+ }
46
+
47
+ // Scan PATH for verified absolute directories only (never relative CWD)
48
+ const pathDirs = (process.env.PATH || '').split(delimiter);
49
+ for (const dir of pathDirs) {
50
+ if (dir && isAbsolute(dir)) {
51
+ const candidate = join(dir, exeName);
52
+ if (existsSync(candidate)) return candidate;
53
+ }
54
+ }
55
+
56
+ throw new Error('Unable to locate a verified Bun executable. Please specify bunPath in settings.');
57
+ }
58
+
59
+ /** A Bun executable that can actually be spawned. Empty when none is installed. */
60
+ export function installedBunPath(customPath) {
61
+ try {
62
+ const resolved = resolveBunPath(customPath);
63
+ return resolved && existsSync(resolved) ? resolved : '';
64
+ } catch {
65
+ return '';
66
+ }
67
+ }
68
+
69
+ let lastInference = null;
70
+ let bunReportCache = null;
71
+
72
+ /** Remember the latest inference shape. Never store credentials or message text. */
73
+ export function noteInference(record) {
74
+ lastInference = { ...record, at: Date.now() };
75
+ }
76
+
77
+ export function lastInferenceReport() {
78
+ return lastInference;
79
+ }
80
+
81
+ /** Detect the Bun runtime this plugin can spawn. Cached briefly for the settings page. */
82
+ export function describeBunEnvironment(customPath, { refresh = false } = {}) {
83
+ const now = Date.now();
84
+ if (!refresh && bunReportCache && bunReportCache.customPath === (customPath || '') && now - bunReportCache.at < 30_000) {
85
+ return bunReportCache.value;
86
+ }
87
+ const path = installedBunPath(customPath);
88
+ let version = '';
89
+ let usable = false;
90
+ if (path) {
91
+ try {
92
+ const result = spawnSync(path, ['--version'], { windowsHide: true, timeout: 5000, encoding: 'utf8' });
93
+ version = String(result.stdout || '').trim();
94
+ usable = result.status === 0 && version.length > 0;
95
+ } catch {
96
+ usable = false;
97
+ }
98
+ }
99
+ const value = { installed: Boolean(path), path, version, usable };
100
+ bunReportCache = { at: now, customPath: customPath || '', value };
101
+ return value;
102
+ }
103
+
104
+ /** Exact-origin, exact-path allowlist for inference only. */
105
+ export function isEligibleInferenceUrl(input) {
106
+ try {
107
+ const url = new URL(input);
108
+ return url.origin === 'https://opencode.ai'
109
+ && !url.username && !url.password && !url.search && !url.hash
110
+ && INFERENCE_PATHS.has(url.pathname);
111
+ } catch {
112
+ return false;
113
+ }
114
+ }
115
+
116
+ /** Fields observed in the installed OpenCode 2.0.32 client. Not its prompt. */
117
+ export function environmentBlock(platform = process.platform) {
118
+ let directory = '.';
119
+ try { directory = process.cwd() || '.'; } catch { /* keep relative fallback */ }
120
+ let git = 'no';
121
+ try { if (existsSync(join(directory, '.git'))) git = 'yes'; } catch { /* not a git checkout */ }
122
+ let temp = 'the process temporary directory';
123
+ try { temp = tmpdir() || temp; } catch { /* keep generic label */ }
124
+ return [
125
+ '<env>',
126
+ ` Working directory: ${directory}`,
127
+ ` Workspace root folder: ${directory}`,
128
+ ` Is directory a git repo: ${git}`,
129
+ ` Platform: ${platform}`,
130
+ ` Prefer ${temp} over generic system temporary directories`,
131
+ '</env>'
132
+ ].join('\n');
133
+ }
134
+
135
+ const OFFICIAL_PREAMBLE_TEXT = "You are an AI agent running in OpenCode, a coding agent harness. Help the user accomplish their goals using the tools you have available.\n\n# Harness\n- Responses are rendered as GitHub-flavored Markdown.\n- `<system-reminder>` blocks are harness instructions, not user-authored content. Read and follow them.\n- Prefer parallelizing independent tool calls.\n- Use the edit tool for targeted changes to existing text files.\n- Use the write tool to create files or completely replace their content.\n\n# Communication\n- Use clear file paths when referring to files.\n- Keep responses clear and concise, and avoid unnecessary technical jargon.\n\n# Working in codebases\n- Keep changes consistent with the structure, naming, style, and patterns of the surrounding code.\n- Treat unfamiliar files or changes as potential user work and investigate before deleting or overwriting them.";
136
+
137
+ const FALLBACK_CODEMODE_BLOB = JSON.stringify({
138
+ total: 8,
139
+ shown: 8,
140
+ namespaces: [
141
+ {
142
+ name: "opencode",
143
+ description: "Tools for managing OpenCode itself, such as working with sessions and worktrees, searching the available models, and reading MCP resources.",
144
+ count: 8,
145
+ entries: [
146
+ { path: "opencode.list_mcp_resources", line: " - tools.opencode.list_mcp_resources(): Promise<unknown>" },
147
+ { path: "opencode.read_mcp_resource", line: " - tools.opencode.read_mcp_resource(): Promise<unknown>" },
148
+ { path: "opencode.models", line: " - tools.opencode.models(): Promise<unknown>" },
149
+ { path: "opencode.session_status", line: " - tools.opencode.session_status(): Promise<unknown>" }
150
+ ]
151
+ }
152
+ ]
153
+ });
154
+
155
+ function loadLocalCodeModeBlob() {
156
+ try {
157
+ const dbPath = join(homedir(), '.local', 'share', 'opencode', 'opencode.db');
158
+ if (!existsSync(dbPath)) return null;
159
+ const { DatabaseSync } = require('node:sqlite');
160
+ const db = new DatabaseSync(dbPath, { readOnly: true });
161
+ const row = db.prepare("SELECT value FROM instruction_blob WHERE value LIKE '%\"name\":\"opencode\"%' LIMIT 1").get();
162
+ db.close();
163
+ return row?.value || null;
164
+ } catch {
165
+ return null;
166
+ }
167
+ }
168
+
169
+ /** Assembles the authentic official system preamble required by upstream WAF verification. */
170
+ export function officialSystemPreamble(platform = process.platform) {
171
+ const dateStr = `Today's date: ${new Date().toDateString()}`;
172
+ const env = environmentBlock(platform);
173
+ const codeMode = loadLocalCodeModeBlob() || FALLBACK_CODEMODE_BLOB;
174
+ return [
175
+ OFFICIAL_PREAMBLE_TEXT,
176
+ dateStr,
177
+ env,
178
+ `Code Mode:\n${codeMode}`
179
+ ].join('\n\n');
180
+ }
181
+
182
+ /** Add the installed client's environment block without mutating DSH tools. */
183
+ export function environmentPayload(bodyText, platform = process.platform) {
184
+ let payload;
185
+ try { payload = JSON.parse(bodyText); } catch { return bodyText; }
186
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return bodyText;
187
+
188
+ const block = officialSystemPreamble(platform);
189
+
190
+ if (Array.isArray(payload.messages)) {
191
+ const messages = payload.messages;
192
+ const system = messages.filter((message) => message?.role === 'system' || message?.role === 'developer');
193
+ const text = system.map((message) => typeof message.content === 'string'
194
+ ? message.content : JSON.stringify(message.content)).join('\n');
195
+ if (!/<env>[\s\S]*?<\/env>/.test(text)) {
196
+ const existing = messages.find((message) => message?.role === 'system' && typeof message.content === 'string');
197
+ if (existing) {
198
+ existing.content = `${block}\n\n${existing.content}`;
199
+ } else {
200
+ messages.unshift({ role: 'system', content: block });
201
+ }
202
+ }
203
+ } else if (Array.isArray(payload.input)) {
204
+ const instructions = typeof payload.instructions === 'string' ? payload.instructions : '';
205
+ if (!/<env>[\s\S]*?<\/env>/.test(instructions)) {
206
+ payload.instructions = `${block}\n\n${instructions}`;
207
+ }
208
+ }
209
+ return JSON.stringify(payload);
210
+ }
211
+
212
+ /** Prepare the exact safe anonymous request used by the Bun worker. */
213
+ export async function prepareBunRequest(input, init = {}, options = {}) {
214
+ const isRequest = typeof Request !== 'undefined' && input instanceof Request;
215
+ const url = new URL(isRequest ? input.url : String(input));
216
+ if (!isEligibleInferenceUrl(url.href)) {
217
+ throw new Error(`Bun transport refused non-inference destination: ${url.origin}${url.pathname}`);
218
+ }
219
+ if (url.pathname === '/inference/v1/chat/completions' || url.pathname === '/zen/v1/chat/completions') {
220
+ url.pathname = '/inference/openai/v1/chat/completions';
221
+ }
222
+
223
+ const method = String(init.method ?? (isRequest ? input.method : 'GET')).toUpperCase();
224
+ if (method !== 'POST') throw new Error('Bun transport accepts inference POST requests only');
225
+ const version = options.clientVersion || '2.0.32';
226
+ if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) {
227
+ throw new Error('Invalid bunTransport.clientVersion');
228
+ }
229
+
230
+ const headers = new Headers(init.headers ?? (isRequest ? input.headers : undefined));
231
+ if (options.anonymous === true) {
232
+ // Anonymous lane: deliberately drop the personal credential so no account
233
+ // token leaves the machine. The upstream accepts the public placeholder.
234
+ headers.set('authorization', 'Bearer public');
235
+ } else if (!/^Bearer \S+$/i.test(headers.get('authorization') || '')) {
236
+ // Keep a caller-supplied Bearer credential. The installed client is signed in
237
+ // and does not hard-code Bearer public. Fall back only when none was given.
238
+ headers.set('authorization', 'Bearer public');
239
+ }
240
+ headers.set('user-agent', `opencode/latest/${version}/cli`);
241
+ const names = [];
242
+ headers.forEach((_value, name) => names.push(name));
243
+ for (const name of names) {
244
+ const lower = name.toLowerCase();
245
+ if (lower.startsWith('x-stainless-')
246
+ || ['cookie', 'host', 'content-length', 'connection', 'x-opencode-request'].includes(lower)) {
247
+ headers.delete(name);
248
+ }
249
+ }
250
+ if (!headers.has('x-opencode-project') || headers.get('x-opencode-project') === 'global') {
251
+ headers.set('x-opencode-project', stableProjectId());
252
+ }
253
+
254
+ let body = '';
255
+ const sourceBody = init.body;
256
+ if (typeof sourceBody === 'string') body = sourceBody;
257
+ else if (sourceBody instanceof Uint8Array) body = Buffer.from(sourceBody).toString('utf8');
258
+ else if (sourceBody !== undefined && sourceBody !== null) body = String(sourceBody);
259
+ else if (isRequest) body = await input.text();
260
+ const preparedBody = environmentPayload(body);
261
+ const headerPairs = [];
262
+ headers.forEach((value, name) => headerPairs.push([name, value]));
263
+ return { url: url.href, headers: headerPairs, body: preparedBody };
264
+ }
265
+
266
+ /** Reap active Bun children when DSH disposes this provider. */
267
+ export function disposeBunTransport() {
268
+ for (const stop of [...activeRequests]) stop(new Error('OpenCode Bun transport disposed'));
269
+ }
270
+
271
+ /**
272
+ * Fetch-compatible Bun subprocess relay. Preserves upstream HTTP status,
273
+ * headers and streaming body; spawn failures become ordinary transport errors.
274
+ */
275
+ export async function executeBunFetch(input, init = {}, options = {}) {
276
+ const request = await prepareBunRequest(input, init, options);
277
+ const bunExe = resolveBunPath(options.bunPath);
278
+ const workerPath = typeof options.workerPath === 'string' && options.workerPath.trim()
279
+ ? options.workerPath.trim() : WORKER_PATH;
280
+ let child;
281
+ try {
282
+ const userAgent = request.headers.find(([name]) => name.toLowerCase() === 'user-agent')?.[1]
283
+ || 'opencode/latest/2.0.32/cli';
284
+ child = spawn(bunExe, [`--user-agent=${userAgent}`, '--use-system-ca', workerPath], {
285
+ windowsHide: true,
286
+ stdio: ['pipe', 'pipe', 'pipe']
287
+ });
288
+ } catch (error) {
289
+ throw new Error(`Unable to start Bun subprocess (${bunExe}): ${error?.message ?? error}`);
290
+ }
291
+ child.stderr.resume();
292
+ child.stdin.on('error', () => {});
293
+
294
+ const isRequest = typeof Request !== 'undefined' && input instanceof Request;
295
+ const signal = init.signal ?? (isRequest ? input.signal : null);
296
+ let terminalError = null;
297
+ let cleaned = false;
298
+ let timeout = null;
299
+ let exitCode = null;
300
+ let childError = null;
301
+ let resolveExit;
302
+ const childExited = new Promise((resolve) => { resolveExit = resolve; });
303
+ const kill = () => {
304
+ if (child.exitCode === null && child.signalCode === null) {
305
+ try { child.kill(); } catch { /* already gone */ }
306
+ }
307
+ };
308
+ const cleanup = () => {
309
+ if (cleaned) return;
310
+ cleaned = true;
311
+ if (timeout) clearTimeout(timeout);
312
+ if (signal) signal.removeEventListener('abort', onAbort);
313
+ activeRequests.delete(stop);
314
+ kill();
315
+ };
316
+ const stop = (error) => {
317
+ if (!terminalError) terminalError = error instanceof Error ? error : new Error(String(error));
318
+ if (timeout) clearTimeout(timeout);
319
+ kill();
320
+ };
321
+ const onAbort = () => stop(signal.reason ?? new Error('Request aborted'));
322
+ const armTimeout = (ms, phase) => {
323
+ if (timeout) clearTimeout(timeout);
324
+ timeout = setTimeout(() => stop(new Error(`Bun transport ${phase} timeout after ${ms} ms`)), ms);
325
+ timeout.unref?.();
326
+ };
327
+ child.on('error', (error) => {
328
+ childError = error;
329
+ resolveExit(-1);
330
+ stop(new Error(`Unable to start Bun subprocess (${bunExe}): ${error.message}`));
331
+ });
332
+ child.once('exit', (code) => { exitCode = code; resolveExit(code); });
333
+ activeRequests.add(stop);
334
+
335
+ if (signal) {
336
+ if (signal.aborted) {
337
+ stop(signal.reason ?? new Error('Request aborted'));
338
+ cleanup();
339
+ throw terminalError;
340
+ }
341
+ signal.addEventListener('abort', onAbort, { once: true });
342
+ }
343
+
344
+ const headerTimeoutMs = options.headerTimeoutMs ?? options.timeoutMs ?? 30_000;
345
+ const bodyIdleMs = options.bodyIdleMs ?? 120_000;
346
+ armTimeout(headerTimeoutMs, 'response-header');
347
+ child.stdin.end(JSON.stringify(request));
348
+
349
+ const iterator = child.stdout[Symbol.asyncIterator]();
350
+ let pending = Buffer.alloc(0);
351
+ let metadata = null;
352
+ try {
353
+ while (!metadata) {
354
+ const next = await iterator.next();
355
+ if (terminalError) throw terminalError;
356
+ if (next.done) {
357
+ const code = exitCode ?? await childExited;
358
+ if (terminalError) throw terminalError;
359
+ if (childError) throw new Error(`Bun worker failed before response headers: ${childError.message}`);
360
+ throw new Error(`Bun worker ended before response headers (exit ${code}); check bunPath: ${bunExe}`);
361
+ }
362
+ pending = Buffer.concat([pending, next.value]);
363
+ const newline = pending.indexOf(10);
364
+ if (newline >= 0) {
365
+ if (newline > 65_536) throw new Error('Bun transport response headers are too large');
366
+ metadata = JSON.parse(pending.subarray(0, newline).toString('utf8'));
367
+ pending = pending.subarray(newline + 1);
368
+ } else if (pending.length > 65_536) {
369
+ throw new Error('Invalid Bun transport response headers');
370
+ }
371
+ }
372
+
373
+ if (metadata?.error) throw new Error(`Bun worker rejected request: ${metadata.error}`);
374
+ if (!Number.isInteger(metadata?.status) || metadata.status < 200 || metadata.status > 599) {
375
+ throw new Error('Invalid Bun transport response status');
376
+ }
377
+ armTimeout(bodyIdleMs, 'body-idle');
378
+ const stream = new ReadableStream({
379
+ pull: async (controller) => {
380
+ try {
381
+ if (terminalError) throw terminalError;
382
+ if (pending.length) {
383
+ controller.enqueue(new Uint8Array(pending));
384
+ pending = Buffer.alloc(0);
385
+ armTimeout(bodyIdleMs, 'body-idle');
386
+ return;
387
+ }
388
+ const next = await iterator.next();
389
+ if (terminalError) throw terminalError;
390
+ if (next.done) {
391
+ const code = exitCode ?? await childExited;
392
+ if (terminalError) throw terminalError;
393
+ if (childError) throw new Error(`Bun worker stream failed: ${childError.message}`);
394
+ if (code !== 0) throw new Error(`Bun worker stream ended unexpectedly (exit ${code})`);
395
+ controller.close();
396
+ cleanup();
397
+ } else {
398
+ controller.enqueue(new Uint8Array(next.value));
399
+ armTimeout(bodyIdleMs, 'body-idle');
400
+ }
401
+ } catch (error) {
402
+ controller.error(error);
403
+ cleanup();
404
+ }
405
+ },
406
+ cancel: () => cleanup()
407
+ });
408
+ return new Response(stream, { status: metadata.status, statusText: metadata.statusText, headers: metadata.headers });
409
+ } catch (error) {
410
+ cleanup();
411
+ throw error;
412
+ }
413
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * 輕量 Bun 轉發工作行程。
3
+ *
4
+ * 為什麼需要這個行程:
5
+ * OpenCode 上游對免費用量實施了基於執行階段 TLS / HTTP 特徵的指紋檢查,
6
+ * Node.js(Undici / node:http)發出的請求會被識別並直接返回 429 FreeUsageLimitError。
7
+ * Bun 的原生 fetch(基於 WebKit / BoringSSL)與官方客戶端完全一致,能夠正常通過檢驗。
8
+ *
9
+ * 設計原則:
10
+ * - 本行程無本機伺服器、無任何工具執行能力,純粹轉發單次記憶體中的 HTTP 請求。
11
+ * - stdin 接收 JSON: { url, headers, body }
12
+ * - stdout 第一行輸出 JSON: { status, statusText, headers },後續位元組為伺服器原始 SSE 串流。
13
+ * - 限制目標網域僅能為 https://opencode.ai 且路徑必須在白名單內。
14
+ */
15
+
16
+ const ALLOWED_PATHS = new Set([
17
+ '/inference/openai/v1/chat/completions',
18
+ '/inference/v1/chat/completions',
19
+ '/zen/v1/chat/completions',
20
+ '/inference/v1/responses',
21
+ '/inference/openai/v1/responses',
22
+ '/zen/v1/responses'
23
+ ]);
24
+
25
+ let started = false;
26
+
27
+ try {
28
+ const stdinText = await Bun.stdin.text();
29
+ const input = JSON.parse(stdinText);
30
+ const url = new URL(input.url);
31
+
32
+ if (url.origin !== 'https://opencode.ai' || url.username || url.password || url.search || url.hash || !ALLOWED_PATHS.has(url.pathname)) {
33
+ throw new Error(`不支援的目標位址: ${url.origin}${url.pathname}`);
34
+ }
35
+
36
+ const headers = new Headers(input.headers);
37
+ if (!/^Bearer \S+$/i.test(headers.get('authorization') || '')) {
38
+ throw new Error('Bun 傳輸只接受 Bearer 授權');
39
+ }
40
+
41
+ // 移除 Node 執行階段特定或可能干擾的標頭
42
+ for (const name of ['cookie', 'host', 'content-length', 'connection']) {
43
+ headers.delete(name);
44
+ }
45
+
46
+ const response = await fetch(url, {
47
+ method: 'POST',
48
+ headers,
49
+ body: input.body,
50
+ redirect: 'error'
51
+ });
52
+
53
+ const outputHeaders = [...response.headers].filter(([name]) =>
54
+ !['set-cookie', 'content-length', 'content-encoding', 'transfer-encoding', 'connection'].includes(name)
55
+ );
56
+
57
+ process.stdout.write(JSON.stringify({
58
+ status: response.status,
59
+ statusText: response.statusText,
60
+ headers: outputHeaders
61
+ }) + '\n');
62
+
63
+ started = true;
64
+
65
+ if (response.body) {
66
+ for await (const chunk of response.body) {
67
+ if (!process.stdout.write(chunk)) {
68
+ await new Promise((resolve) => process.stdout.once('drain', resolve));
69
+ }
70
+ }
71
+ }
72
+ } catch (error) {
73
+ if (!started) {
74
+ process.stdout.write(JSON.stringify({ error: String(error?.message ?? error) }) + '\n');
75
+ }
76
+ process.exitCode = 1;
77
+ }