one-model-router 0.0.10 → 0.0.12

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 (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
@@ -1,226 +1,226 @@
1
- /**
2
- * OpenCode 免密车道的 Bun 传输层。
3
- *
4
- * ## 为什么推理必须走 Bun
5
- *
6
- * 两个独立事实,都实测于本机(2026-11-11):
7
- *
8
- * 1. **网络层:SNI 阻断**。本机网络对 `opencode.ai` 只拦 TLS 明文 SNI——
9
- * TCP 443 可通、Node fetch / curl 的握手超时;Bun(BoringSSL,带 ECH)
10
- * 直连同地址 200(1.4s)。桌面端插件能正常对话正是同因:它的推理走 Bun worker。
11
- * 2. **应用层:客户端指纹**。上游对免费道 POST 的 TLS/HTTP 客户端指纹敏感,
12
- * 即使字节全对,非官方栈也可能回 `429 FreeUsageLimitError`(报文与
13
- * 「IP 配额烧尽」无法区分,2026-10-31 实测:同字节 Go 200、
14
- * curl/python 429)。自 2026-10-28 起 `opencode.ai/inference/*`
15
- * 的 POST 推理强制走 Bun worker。
16
- *
17
- * 本实现的取舍:**GET 清单也优先走 Bun**——本机网络下 GET 走
18
- * Node 必超时(SNI 阻断);
19
- * Bun 缺失时 GET 回落 Node(老行为),POST 直接报配置错误(双语,内联修复指引)。
20
- *
21
- * ## 机制
22
- *
23
- * worker 源码内联,首用时写进 `{DATA_DIR}/run/`(缺失自动重建,防临时目录清扫);
24
- * 请求元数据与 body 走 stdin(body base64),stdout 先回一行 JSON 元数据
25
- * (status/statusText/headers,已剔除编码与长度头)再回传原始响应字节。
26
- * 凭据与请求体不进命令行参数、不进错误信息;无隐式重试;stderr 永不外显。
27
- * `options.proxy` 仅经 stdin 传给 Bun 的 fetch(每请求代理;省略则继承
28
- * Bun 对 HTTP_PROXY/HTTPS_PROXY/NO_PROXY 的原生处理)。
29
- *
30
- * @module src/providers/opencode/bun-fetch
31
- */
32
-
33
- import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, statSync, writeFileSync } from 'node:fs'
34
- import { homedir, tmpdir } from 'node:os'
35
- import { delimiter, join, resolve } from 'node:path'
36
- import { spawn } from 'node:child_process'
37
- import { PassThrough, Readable } from 'node:stream'
38
- import { DATA_DIR } from '../../store.js'
39
-
40
- const WORKER_SOURCE = `import { Readable } from 'node:stream';
41
- import { pipeline } from 'node:stream/promises';
42
- try {
43
- const chunks = [];
44
- for await (const chunk of process.stdin) chunks.push(chunk);
45
- const request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
46
- const init = { method: request.method, headers: request.headers, redirect: request.redirect ?? 'error' };
47
- if (request.body !== null) init.body = Buffer.from(request.body, 'base64');
48
- if (request.proxy !== undefined) init.proxy = request.proxy;
49
- const response = await fetch(request.url, init);
50
- const headers = [...response.headers].filter(([key]) => ![
51
- 'content-encoding', 'content-length', 'transfer-encoding', 'connection',
52
- 'keep-alive', 'trailer', 'upgrade',
53
- ].includes(key.toLowerCase()));
54
- const metadata = Buffer.from(JSON.stringify({ status: response.status, statusText: response.statusText, headers }) + '\\n');
55
- await pipeline(Readable.from((async function* () {
56
- yield metadata;
57
- if (response.body) for await (const chunk of response.body) yield chunk;
58
- })()), process.stdout);
59
- } catch (error) {
60
- const code = error?.cause?.code ?? error?.code;
61
- if (typeof code === 'string' && code !== '') process.stderr.write(code.slice(0, 64) + '\\n');
62
- process.exitCode = 1;
63
- }
64
- `
65
-
66
- /** 网络错误码 → 可行动提示(只匹配错误码,stderr 原文永不外显)。 */
67
- function networkHint(code) {
68
- switch (code) {
69
- case 'ECONNRESET': return '连接被重置:本机直连上游被网络阻断,需要代理/VPN 出口'
70
- case 'ECONNREFUSED': return '代理不可达:代理进程未运行或端口不对'
71
- case 'ENOTFOUND':
72
- case 'EAI_AGAIN': return 'DNS 解析失败'
73
- case 'ETIMEDOUT': return '连接超时'
74
- default: return ''
75
- }
76
- }
77
-
78
- /** worker 未完成响应的失败:拿到网络错误码时给出可行动文案,否则保持原笼统报错。 */
79
- function workerFailureError(stderrText) {
80
- const match = /\b(ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT)\b/.exec(stderrText)
81
- const hint = match ? networkHint(match[1]) : ''
82
- if (hint === '') return new Error('Bun worker failed before completing the response.')
83
- return new Error(`Bun worker 网络失败(${match[1]}):${hint}。启动代理/VPN 后,在 OpenCode 卡片填「车道代理」(如 http://127.0.0.1:7890),或以 HTTPS_PROXY 环境变量启动本服务`)
84
- }
85
-
86
- let workerPath = undefined
87
-
88
- /** 物化内联 worker;每次调用都复查存在性(外部清扫删掉后自愈)。 */
89
- export function bunWorkerPath() {
90
- if (workerPath !== undefined && existsSync(workerPath)) return workerPath
91
- try {
92
- const dir = join(DATA_DIR, 'run')
93
- mkdirSync(dir, { recursive: true })
94
- const file = join(dir, 'opencode-bun-worker.mjs')
95
- writeFileSync(file, WORKER_SOURCE, { mode: 0o600 })
96
- workerPath = file
97
- } catch {
98
- // 数据目录只读时退回系统临时目录(车道降级为可用但不持久)
99
- const dir = mkdtempSync(join(tmpdir(), 'omr-bun-worker-'))
100
- workerPath = join(dir, 'opencode-bun-worker.mjs')
101
- writeFileSync(workerPath, WORKER_SOURCE, { mode: 0o600 })
102
- }
103
- return workerPath
104
- }
105
-
106
- /** 定位原生 Bun 可执行文件(永不执行 .cmd/.ps1 壳)。不安装、不下载。 */
107
- export function findBunExecutable() {
108
- const name = process.platform === 'win32' ? 'bun.exe' : 'bun'
109
- const candidates = [
110
- process.env.OMR_OPENCODE_BUN,
111
- process.env.OUR_FREE_MODEL_BUN,
112
- process.env.BUN_INSTALL && join(process.env.BUN_INSTALL, 'bin', name),
113
- join(homedir(), '.bun', 'bin', name),
114
- ...(process.env.PATH || '').split(delimiter).filter(Boolean).map(p => join(p.replace(/^"|"$/g, ''), name)),
115
- process.env.APPDATA && join(process.env.APPDATA, 'npm', 'node_modules', 'bun', 'bin', name),
116
- ]
117
- for (const candidate of candidates.filter(Boolean)) {
118
- try {
119
- const path = resolve(candidate)
120
- if (process.platform === 'win32' && !path.toLowerCase().endsWith('.exe')) continue
121
- if (!statSync(path).isFile()) continue
122
- accessSync(path, constants.X_OK)
123
- return path
124
- } catch { /* 试下一个候选 */ }
125
- }
126
- return undefined
127
- }
128
-
129
- /**
130
- * 经 Bun worker 发一次请求。`init.body` 只接受 string/Uint8Array;
131
- * `init.signal` 控制整个响应生命周期;重定向默认 error;无重试。
132
- * 返回标准 `Response`(body 为 Web 流,可直接 getReader())。
133
- */
134
- export async function bunFetch(url, init = {}, options = {}) {
135
- const { signal } = init
136
- signal?.throwIfAborted()
137
- const executable = options.executable || findBunExecutable()
138
- if (!executable) throw new Error('Bun executable not found; set OMR_OPENCODE_BUN to a native executable.')
139
- if (init.body != null && typeof init.body !== 'string' && !(init.body instanceof Uint8Array)) {
140
- throw new TypeError('bunFetch body must be a string or Uint8Array.')
141
- }
142
- let payload
143
- try {
144
- payload = JSON.stringify({
145
- url: String(url),
146
- method: init.method || 'GET',
147
- headers: [...new Headers(init.headers)],
148
- body: init.body == null ? null : Buffer.from(init.body).toString('base64'),
149
- proxy: options.proxy,
150
- redirect: init.redirect ?? 'error',
151
- })
152
- } catch { throw new TypeError('Invalid bunFetch request.') }
153
- return new Promise((resolveResponse, reject) => {
154
- let child
155
- let body
156
- let header = Buffer.alloc(0)
157
- let receivedHeaders = false
158
- let stderrText = ''
159
- let stopped = false
160
- const stop = () => { if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') }
161
- const fail = error => {
162
- if (stopped) return
163
- stopped = true
164
- reject(error)
165
- body?.destroy(error)
166
- stop()
167
- }
168
- const onAbort = () => fail(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'))
169
- try { child = spawn(executable, [bunWorkerPath()], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) } catch {
170
- reject(new Error('Bun worker failed to start.'))
171
- return
172
- }
173
- signal?.addEventListener('abort', onAbort, { once: true })
174
- child.on('error', () => fail(new Error('Bun worker failed to start.')))
175
- child.stdin.on('error', () => fail(new Error('Bun worker input failed.')))
176
- // 只收集错误码供失败归因(worker 最多写一行 code),stderr 原文永不外显
177
- child.stderr.on('data', chunk => { if (stderrText.length < 4096) stderrText += chunk.toString('utf8') })
178
- child.stdout.on('error', () => fail(new Error('Bun worker output failed.')))
179
- child.on('close', code => {
180
- signal?.removeEventListener('abort', onAbort)
181
- if (!stopped) {
182
- if (code !== 0 || !receivedHeaders) fail(workerFailureError(stderrText))
183
- else { stopped = true; body?.end() }
184
- }
185
- })
186
- const onData = chunk => {
187
- if (stopped) return
188
- header = Buffer.concat([header, chunk])
189
- const newline = header.indexOf(10)
190
- if (newline > 1024 * 1024 || (newline < 0 && header.length > 1024 * 1024)) {
191
- fail(new Error('Invalid Bun worker response headers.'))
192
- return
193
- }
194
- if (newline < 0) return
195
- child.stdout.pause()
196
- child.stdout.removeListener('data', onData)
197
- try {
198
- const meta = JSON.parse(header.subarray(0, newline).toString('utf8'))
199
- if (!Number.isInteger(meta.status) || meta.status < 200 || meta.status > 599 || !Array.isArray(meta.headers)) throw new Error()
200
- const headers = new Headers(meta.headers)
201
- for (const key of ['content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', 'trailer', 'upgrade']) headers.delete(key)
202
- const empty = init.method?.toUpperCase() === 'HEAD' || [204, 205, 304].includes(meta.status)
203
- const rest = header.subarray(newline + 1)
204
- header = null
205
- if (!empty) {
206
- body = new PassThrough()
207
- // toWeb 把 cancel() 传导到 destroy();destroy 会终止 worker
208
- body.on('close', () => { if (!stopped) { stopped = true; stop() } })
209
- const webBody = Readable.toWeb(body, { strategy: { highWaterMark: 64 * 1024, size: chunk => chunk.byteLength } })
210
- const response = new Response(webBody, { status: meta.status, statusText: meta.statusText, headers })
211
- receivedHeaders = true
212
- if (rest.length) child.stdout.unshift(rest)
213
- child.stdout.pipe(body, { end: false })
214
- resolveResponse(response)
215
- } else {
216
- receivedHeaders = true
217
- resolveResponse(new Response(null, { status: meta.status, statusText: meta.statusText, headers }))
218
- child.stdout.resume()
219
- }
220
- } catch { fail(new Error('Invalid Bun worker response headers.')) }
221
- }
222
- child.stdout.on('data', onData)
223
- if (signal?.aborted) onAbort()
224
- if (!stopped) child.stdin.end(payload)
225
- })
226
- }
1
+ /**
2
+ * OpenCode 免密车道的 Bun 传输层。
3
+ *
4
+ * ## 为什么推理必须走 Bun
5
+ *
6
+ * 两个独立事实,都实测于本机(2026-11-11):
7
+ *
8
+ * 1. **网络层:SNI 阻断**。本机网络对 `opencode.ai` 只拦 TLS 明文 SNI——
9
+ * TCP 443 可通、Node fetch / curl 的握手超时;Bun(BoringSSL,带 ECH)
10
+ * 直连同地址 200(1.4s)。桌面端插件能正常对话正是同因:它的推理走 Bun worker。
11
+ * 2. **应用层:客户端指纹**。上游对免费道 POST 的 TLS/HTTP 客户端指纹敏感,
12
+ * 即使字节全对,非官方栈也可能回 `429 FreeUsageLimitError`(报文与
13
+ * 「IP 配额烧尽」无法区分,2026-10-31 实测:同字节 Go 200、
14
+ * curl/python 429)。自 2026-10-28 起 `opencode.ai/inference/*`
15
+ * 的 POST 推理强制走 Bun worker。
16
+ *
17
+ * 本实现的取舍:**GET 清单也优先走 Bun**——本机网络下 GET 走
18
+ * Node 必超时(SNI 阻断);
19
+ * Bun 缺失时 GET 回落 Node(老行为),POST 直接报配置错误(双语,内联修复指引)。
20
+ *
21
+ * ## 机制
22
+ *
23
+ * worker 源码内联,首用时写进 `{DATA_DIR}/run/`(缺失自动重建,防临时目录清扫);
24
+ * 请求元数据与 body 走 stdin(body base64),stdout 先回一行 JSON 元数据
25
+ * (status/statusText/headers,已剔除编码与长度头)再回传原始响应字节。
26
+ * 凭据与请求体不进命令行参数、不进错误信息;无隐式重试;stderr 永不外显。
27
+ * `options.proxy` 仅经 stdin 传给 Bun 的 fetch(每请求代理;省略则继承
28
+ * Bun 对 HTTP_PROXY/HTTPS_PROXY/NO_PROXY 的原生处理)。
29
+ *
30
+ * @module src/providers/opencode/bun-fetch
31
+ */
32
+
33
+ import { accessSync, constants, existsSync, mkdirSync, mkdtempSync, statSync, writeFileSync } from 'node:fs'
34
+ import { homedir, tmpdir } from 'node:os'
35
+ import { delimiter, join, resolve } from 'node:path'
36
+ import { spawn } from 'node:child_process'
37
+ import { PassThrough, Readable } from 'node:stream'
38
+ import { DATA_DIR } from '../../store.js'
39
+
40
+ const WORKER_SOURCE = `import { Readable } from 'node:stream';
41
+ import { pipeline } from 'node:stream/promises';
42
+ try {
43
+ const chunks = [];
44
+ for await (const chunk of process.stdin) chunks.push(chunk);
45
+ const request = JSON.parse(Buffer.concat(chunks).toString('utf8'));
46
+ const init = { method: request.method, headers: request.headers, redirect: request.redirect ?? 'error' };
47
+ if (request.body !== null) init.body = Buffer.from(request.body, 'base64');
48
+ if (request.proxy !== undefined) init.proxy = request.proxy;
49
+ const response = await fetch(request.url, init);
50
+ const headers = [...response.headers].filter(([key]) => ![
51
+ 'content-encoding', 'content-length', 'transfer-encoding', 'connection',
52
+ 'keep-alive', 'trailer', 'upgrade',
53
+ ].includes(key.toLowerCase()));
54
+ const metadata = Buffer.from(JSON.stringify({ status: response.status, statusText: response.statusText, headers }) + '\\n');
55
+ await pipeline(Readable.from((async function* () {
56
+ yield metadata;
57
+ if (response.body) for await (const chunk of response.body) yield chunk;
58
+ })()), process.stdout);
59
+ } catch (error) {
60
+ const code = error?.cause?.code ?? error?.code;
61
+ if (typeof code === 'string' && code !== '') process.stderr.write(code.slice(0, 64) + '\\n');
62
+ process.exitCode = 1;
63
+ }
64
+ `
65
+
66
+ /** 网络错误码 → 可行动提示(只匹配错误码,stderr 原文永不外显)。 */
67
+ function networkHint(code) {
68
+ switch (code) {
69
+ case 'ECONNRESET': return '连接被重置:本机直连上游被网络阻断,需要代理/VPN 出口'
70
+ case 'ECONNREFUSED': return '代理不可达:代理进程未运行或端口不对'
71
+ case 'ENOTFOUND':
72
+ case 'EAI_AGAIN': return 'DNS 解析失败'
73
+ case 'ETIMEDOUT': return '连接超时'
74
+ default: return ''
75
+ }
76
+ }
77
+
78
+ /** worker 未完成响应的失败:拿到网络错误码时给出可行动文案,否则保持原笼统报错。 */
79
+ function workerFailureError(stderrText) {
80
+ const match = /\b(ECONNRESET|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|ETIMEDOUT)\b/.exec(stderrText)
81
+ const hint = match ? networkHint(match[1]) : ''
82
+ if (hint === '') return new Error('Bun worker failed before completing the response.')
83
+ return new Error(`Bun worker 网络失败(${match[1]}):${hint}。启动代理/VPN 后,在 OpenCode 卡片填「车道代理」(如 http://127.0.0.1:7890),或以 HTTPS_PROXY 环境变量启动本服务`)
84
+ }
85
+
86
+ let workerPath = undefined
87
+
88
+ /** 物化内联 worker;每次调用都复查存在性(外部清扫删掉后自愈)。 */
89
+ export function bunWorkerPath() {
90
+ if (workerPath !== undefined && existsSync(workerPath)) return workerPath
91
+ try {
92
+ const dir = join(DATA_DIR, 'run')
93
+ mkdirSync(dir, { recursive: true })
94
+ const file = join(dir, 'opencode-bun-worker.mjs')
95
+ writeFileSync(file, WORKER_SOURCE, { mode: 0o600 })
96
+ workerPath = file
97
+ } catch {
98
+ // 数据目录只读时退回系统临时目录(车道降级为可用但不持久)
99
+ const dir = mkdtempSync(join(tmpdir(), 'omr-bun-worker-'))
100
+ workerPath = join(dir, 'opencode-bun-worker.mjs')
101
+ writeFileSync(workerPath, WORKER_SOURCE, { mode: 0o600 })
102
+ }
103
+ return workerPath
104
+ }
105
+
106
+ /** 定位原生 Bun 可执行文件(永不执行 .cmd/.ps1 壳)。不安装、不下载。 */
107
+ export function findBunExecutable() {
108
+ const name = process.platform === 'win32' ? 'bun.exe' : 'bun'
109
+ const candidates = [
110
+ process.env.OMR_OPENCODE_BUN,
111
+ process.env.OUR_FREE_MODEL_BUN,
112
+ process.env.BUN_INSTALL && join(process.env.BUN_INSTALL, 'bin', name),
113
+ join(homedir(), '.bun', 'bin', name),
114
+ ...(process.env.PATH || '').split(delimiter).filter(Boolean).map(p => join(p.replace(/^"|"$/g, ''), name)),
115
+ process.env.APPDATA && join(process.env.APPDATA, 'npm', 'node_modules', 'bun', 'bin', name),
116
+ ]
117
+ for (const candidate of candidates.filter(Boolean)) {
118
+ try {
119
+ const path = resolve(candidate)
120
+ if (process.platform === 'win32' && !path.toLowerCase().endsWith('.exe')) continue
121
+ if (!statSync(path).isFile()) continue
122
+ accessSync(path, constants.X_OK)
123
+ return path
124
+ } catch { /* 试下一个候选 */ }
125
+ }
126
+ return undefined
127
+ }
128
+
129
+ /**
130
+ * 经 Bun worker 发一次请求。`init.body` 只接受 string/Uint8Array;
131
+ * `init.signal` 控制整个响应生命周期;重定向默认 error;无重试。
132
+ * 返回标准 `Response`(body 为 Web 流,可直接 getReader())。
133
+ */
134
+ export async function bunFetch(url, init = {}, options = {}) {
135
+ const { signal } = init
136
+ signal?.throwIfAborted()
137
+ const executable = options.executable || findBunExecutable()
138
+ if (!executable) throw new Error('Bun executable not found; set OMR_OPENCODE_BUN to a native executable.')
139
+ if (init.body != null && typeof init.body !== 'string' && !(init.body instanceof Uint8Array)) {
140
+ throw new TypeError('bunFetch body must be a string or Uint8Array.')
141
+ }
142
+ let payload
143
+ try {
144
+ payload = JSON.stringify({
145
+ url: String(url),
146
+ method: init.method || 'GET',
147
+ headers: [...new Headers(init.headers)],
148
+ body: init.body == null ? null : Buffer.from(init.body).toString('base64'),
149
+ proxy: options.proxy,
150
+ redirect: init.redirect ?? 'error',
151
+ })
152
+ } catch { throw new TypeError('Invalid bunFetch request.') }
153
+ return new Promise((resolveResponse, reject) => {
154
+ let child
155
+ let body
156
+ let header = Buffer.alloc(0)
157
+ let receivedHeaders = false
158
+ let stderrText = ''
159
+ let stopped = false
160
+ const stop = () => { if (child && child.exitCode === null && child.signalCode === null) child.kill('SIGKILL') }
161
+ const fail = error => {
162
+ if (stopped) return
163
+ stopped = true
164
+ reject(error)
165
+ body?.destroy(error)
166
+ stop()
167
+ }
168
+ const onAbort = () => fail(signal.reason ?? new DOMException('The operation was aborted.', 'AbortError'))
169
+ try { child = spawn(executable, [bunWorkerPath()], { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true }) } catch {
170
+ reject(new Error('Bun worker failed to start.'))
171
+ return
172
+ }
173
+ signal?.addEventListener('abort', onAbort, { once: true })
174
+ child.on('error', () => fail(new Error('Bun worker failed to start.')))
175
+ child.stdin.on('error', () => fail(new Error('Bun worker input failed.')))
176
+ // 只收集错误码供失败归因(worker 最多写一行 code),stderr 原文永不外显
177
+ child.stderr.on('data', chunk => { if (stderrText.length < 4096) stderrText += chunk.toString('utf8') })
178
+ child.stdout.on('error', () => fail(new Error('Bun worker output failed.')))
179
+ child.on('close', code => {
180
+ signal?.removeEventListener('abort', onAbort)
181
+ if (!stopped) {
182
+ if (code !== 0 || !receivedHeaders) fail(workerFailureError(stderrText))
183
+ else { stopped = true; body?.end() }
184
+ }
185
+ })
186
+ const onData = chunk => {
187
+ if (stopped) return
188
+ header = Buffer.concat([header, chunk])
189
+ const newline = header.indexOf(10)
190
+ if (newline > 1024 * 1024 || (newline < 0 && header.length > 1024 * 1024)) {
191
+ fail(new Error('Invalid Bun worker response headers.'))
192
+ return
193
+ }
194
+ if (newline < 0) return
195
+ child.stdout.pause()
196
+ child.stdout.removeListener('data', onData)
197
+ try {
198
+ const meta = JSON.parse(header.subarray(0, newline).toString('utf8'))
199
+ if (!Number.isInteger(meta.status) || meta.status < 200 || meta.status > 599 || !Array.isArray(meta.headers)) throw new Error()
200
+ const headers = new Headers(meta.headers)
201
+ for (const key of ['content-encoding', 'content-length', 'transfer-encoding', 'connection', 'keep-alive', 'trailer', 'upgrade']) headers.delete(key)
202
+ const empty = init.method?.toUpperCase() === 'HEAD' || [204, 205, 304].includes(meta.status)
203
+ const rest = header.subarray(newline + 1)
204
+ header = null
205
+ if (!empty) {
206
+ body = new PassThrough()
207
+ // toWeb 把 cancel() 传导到 destroy();destroy 会终止 worker
208
+ body.on('close', () => { if (!stopped) { stopped = true; stop() } })
209
+ const webBody = Readable.toWeb(body, { strategy: { highWaterMark: 64 * 1024, size: chunk => chunk.byteLength } })
210
+ const response = new Response(webBody, { status: meta.status, statusText: meta.statusText, headers })
211
+ receivedHeaders = true
212
+ if (rest.length) child.stdout.unshift(rest)
213
+ child.stdout.pipe(body, { end: false })
214
+ resolveResponse(response)
215
+ } else {
216
+ receivedHeaders = true
217
+ resolveResponse(new Response(null, { status: meta.status, statusText: meta.statusText, headers }))
218
+ child.stdout.resume()
219
+ }
220
+ } catch { fail(new Error('Invalid Bun worker response headers.')) }
221
+ }
222
+ child.stdout.on('data', onData)
223
+ if (signal?.aborted) onAbort()
224
+ if (!stopped) child.stdin.end(payload)
225
+ })
226
+ }