@luchenglong/cli-bridge 0.2.6 → 0.2.8

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.
@@ -1,629 +1,587 @@
1
- // providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
2
- //
3
- // 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
4
- // 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
5
- // • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
6
- // `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
7
- // • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
8
- // • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
9
- // • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
10
- // step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
11
- //
12
- // 红线(PROVIDER-CONTRACT.md §8 + §1):
13
- // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
14
- // process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
15
- // - 只允许 import '../core/bridge-kit.mjs'。
16
- import { createStatusEngine, createRunner, clampInt, isLimited } from '../core/bridge-kit.mjs'
17
-
18
- function nowIso() { return new Date().toISOString() }
19
-
20
- // ── 可执行文件解析(env > 桌面版已知路径 > PATH)───────────────────────────────
21
- // 二进制名是 opencode-cli.exe(不是 opencode.exe):V2 桌面版自带,且 V1/V2 不能并存
22
- // 安装(官方原话),故不做「opencode.exe 兜底」以免误命中另一个版本。
23
- const EXE_BASENAMES = ['opencode-cli', 'opencode']
24
- // 桌面版各版本目录形如 ...\ai.opencode.desktop\cli\<ver>-<arch>\opencode-cli.exe。
25
- // 沙箱内可能没有 fs —— 全部读取走 typeof 守卫,读不到就返回空数组(退回 PATH 查找)。
26
- const DESKTOP_CLI_REL = ['ai.opencode.desktop', 'cli']
27
-
28
- function schedBuiltin(name) {
29
- try {
30
- const proc = globalThis.process
31
- return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
32
- } catch (e) { return null }
33
- }
34
-
35
- /**
36
- * 探测本机 opencode 可执行文件候选路径(优先桌面版 V2)。
37
- * 纯函数、零副作用;无 fs 能力时返回空数组 —— 由调用方退回 PATH 查找。
38
- * @param {object} env 环境变量(读 APPDATA / LOCALAPPDATA / PROGRAMFILES / HOME)
39
- */
40
- export function candidateExePaths(env) {
41
- const e = env || {}
42
- const out = []
43
- const fs = schedBuiltin('node:fs')
44
- const path = schedBuiltin('node:path')
45
- if (!fs || typeof fs.readdirSync !== 'function' || !path || typeof path.join !== 'function') return out
46
- const roots = []
47
- for (const k of ['APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES']) if (e[k]) roots.push(String(e[k]))
48
- const home = e.HOME || e.USERPROFILE
49
- if (home && !roots.length) roots.push(String(home))
50
- for (const root of roots) {
51
- const cliDir = path.join.apply(path, [root].concat(DESKTOP_CLI_REL))
52
- let versions = []
53
- try { versions = fs.readdirSync(cliDir, { withFileTypes: true }) } catch (err) { continue }
54
- // 版本目录按 semver 降序(新版本优先);解析失败的排末尾。
55
- const dirs = versions.filter((d) => d && d.isDirectory && d.isDirectory()).map((d) => d.name)
56
- const key = (n) => {
57
- const m = String(n).match(/(\d+)\.(\d+)\.(\d+)/)
58
- return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [-1, -1, -1]
59
- }
60
- dirs.sort((a, b) => {
61
- const ka = key(a), kb = key(b)
62
- for (let i = 0; i < 3; i++) if (ka[i] !== kb[i]) return kb[i] - ka[i]
63
- return 0
64
- })
65
- for (const d of dirs) {
66
- for (const base of EXE_BASENAMES) {
67
- const exe = path.join(cliDir, d, base + (String(e.OS || '').toLowerCase().startsWith('win') || e.APPDATA ? '.exe' : ''))
68
- try { if (fs.existsSync(exe)) out.push(exe) } catch (err) { }
69
- }
70
- }
71
- }
72
- return out
73
- }
74
-
75
- /**
76
- * 解析本次调用使用的 exe 前缀(数组或字符串)。
77
- * 优先级:binPath 设置 > env OPENCODE_BIN/OPENCODE_CLI > 桌面版探测 > PATH 名字。
78
- * @param {object} env
79
- * @param {string} [binPath] 设置面板里的显式路径(可空)
80
- */
81
- export function resolveExePrefix(env, binPath) {
82
- const e = env || {}
83
- const bin = binPath || e.OPENCODE_BIN || e.OPENCODE_CLI || ''
84
- if (bin) {
85
- if (/\.(mjs|cjs|js)$/i.test(bin)) {
86
- const proc = globalThis.process
87
- const node = (proc && proc.execPath) ? proc.execPath : 'node'
88
- return [node, bin]
89
- }
90
- return [String(bin)]
91
- }
92
- const found = candidateExePaths(e)
93
- if (found.length) return [found[0]]
94
- return [EXE_BASENAMES[0]]
95
- }
96
-
97
- // ── 模型列表(`opencode models`;纯文本每行 provider/model)─────────────────────
98
- // 同步版给 settings.meta(面板下拉);异步版给 MCP 工具。解析宽容:只认
99
- // provider/model 形态的行,其余(表头/说明/空行)一律丢弃。
100
- const MODEL_LINE_RE = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.#@+-]+)$/
101
-
102
- export function parseModelList(text) {
103
- const out = []
104
- const seen = Object.create(null)
105
- for (const raw of String(text || '').split(/\r?\n/)) {
106
- const ln = raw.trim()
107
- if (!ln) continue
108
- const m = ln.match(MODEL_LINE_RE)
109
- if (!m) continue
110
- const id = m[1] + '/' + m[2]
111
- if (seen[id]) continue
112
- seen[id] = true
113
- out.push({ id: id, provider: m[1], name: m[2], free: /(-free$|free)/i.test(m[2]) })
114
- }
115
- return out
116
- }
117
-
118
- /**
119
- * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
120
- * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
121
- */
122
- export function fetchModelsSync(env, binPath, timeoutMs) {
123
- try {
124
- const child = schedBuiltin('node:child_process')
125
- if (!child || typeof child.spawnSync !== 'function') return []
126
- const prefix = resolveExePrefix(env, binPath)
127
- const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), {
128
- encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000),
129
- windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
130
- })
131
- if (!r || r.error || r.status !== 0) return []
132
- return parseModelList(String(r.stdout || ''))
133
- } catch (e) { return [] }
134
- }
135
-
136
- // ── 三工具 schema ────────────────────────────────────────────────────────────
137
- const RUN_PARAMS = {
138
- type: 'object',
139
- additionalProperties: false,
140
- required: ['prompt'],
141
- properties: {
142
- prompt: { type: 'string', description: 'The task instruction for opencode. On first dispatch for a topic, include a compact CONTEXT preamble (goal, repo root, key paths, decisions/constraints; point at paths, do not paste file contents — opencode reads the repo itself). For follow-ups on the same topic, use opencode_continue with latest=true or sessionId (opencode keeps session context; state only what is new).' },
143
- model: { type: 'string', description: 'Optional model in provider/model form (e.g. "opencode/big-pickle"). Prefer a -free model when the task does not need a frontier model. Omit to use the model chosen in the CLI Bridge settings panel, or (if unset there) opencode\'s own default.' },
144
- agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
145
- cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
146
- files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
147
- title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
148
- timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
149
- autoApprove: { type: 'boolean', description: 'Default true: pass --auto so opencode auto-approves permissions and never blocks on a prompt. Set false to require explicit approval (opencode may then block and hit the timeout).' },
150
- background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
151
- }
152
- }
153
- const CONTINUE_PARAMS = {
154
- type: 'object',
155
- additionalProperties: false,
156
- required: ['prompt'],
157
- properties: {
158
- prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
159
- sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
160
- latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
161
- model: { type: 'string', description: 'Optional model in provider/model form.' },
162
- agent: { type: 'string', description: 'Optional opencode agent name.' },
163
- cwd: { type: 'string', description: 'Working directory for opencode.' },
164
- files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
165
- timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
166
- autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
167
- background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
168
- }
169
- }
170
- const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
171
-
172
- // opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
173
- const MODELS_PARAMS = {
174
- type: 'object',
175
- additionalProperties: false,
176
- required: [],
177
- properties: {
178
- freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
179
- provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
180
- }
181
- }
182
- const MODELS_DESCRIPTION = 'List the models available to the local opencode CLI (from `opencode models`). Returns { ok, models: [{id, provider, name, free}], count }. Use this to pick a model before opencode_run, or to check which models are free. Prefer a -free model for routine work and reserve paid/frontier models for tasks that genuinely need them. If the CLI is missing or not logged in, this returns ok:false with an actionable error — it never silently invents a model list.'
183
-
184
- function renderModels(value) {
185
- const v = value || {}
186
- if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
187
- const list = Array.isArray(v.models) ? v.models : []
188
- if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
189
- const lines = ['opencode models (' + list.length + '):']
190
- for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
191
- if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
192
- const free = list.filter((m) => m.free).length
193
- lines.push('free: ' + free + ' / ' + list.length)
194
- return [{ type: 'text', text: lines.join('\n') }]
195
- }
196
-
197
- export default function defineProvider(deps = {}) {
198
- const env = deps.env || {}
199
- let host = null
200
- let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
201
-
202
- /**
203
- * 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
204
- * 面板改默认模型后无需重启即生效:
205
- * 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
206
- * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
207
- * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
208
- * 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
209
- *
210
- * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
211
- * defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
212
- * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
213
- */
214
- function currentSettings() {
215
- const out = Object.assign({}, settingsRef)
216
- try {
217
- if (typeof deps.readSettings === 'function') {
218
- const r = deps.readSettings()
219
- if (r && typeof r === 'object') {
220
- const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
221
- if (part && typeof part === 'object') Object.assign(out, part)
222
- }
223
- }
224
- } catch (e) { }
225
- try {
226
- if (host && typeof host.getSettings === 'function') {
227
- const s = host.getSettings('opencode')
228
- if (s && typeof s === 'object') Object.assign(out, s)
229
- }
230
- } catch (e) { }
231
- return out
232
- }
233
-
234
- const descriptor = {
235
- id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
236
- exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
237
-
238
- // 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
239
- backends() { return null },
240
- normalizeBackend() { return null },
241
- resolveBackend(args, target, preferred) { return null },
242
-
243
- // 实测 flag 集(V2.0.29)。
244
- buildArgv(exePrefix, args, opts) {
245
- const o = opts || {}
246
- const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
247
- argv.push('run', String(args.prompt), '--format', 'json')
248
- if (args.autoApprove !== false) argv.push('--auto')
249
- const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
250
- // 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
251
- // 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
252
- const model = args.model || currentSettings().defaultModel || ''
253
- if (model) argv.push('--model', String(model))
254
- const agent = args.agent || currentSettings().defaultAgent || ''
255
- if (agent) argv.push('--agent', String(agent))
256
- if (args.title) argv.push('--title', String(args.title))
257
- if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
258
- if (args.sessionId) argv.push('--session', String(args.sessionId))
259
- else if (args.continueLatest) argv.push('--continue')
260
- return { argv, mode: 'auto', timeoutSec }
261
- },
262
-
263
- // JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
264
- // step_start / text / reasoning / tool_use / step_finish / error。
265
- // ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
266
- // ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
267
- // cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
268
- // ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
269
- // step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
270
- // 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
271
- // 是活的必经分支,不是死代码。
272
- // 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
273
- // 回填进 part.text,让 buildResult 统一从 part.text 读正文。
274
- // 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
275
- parseJson(stdoutText) {
276
- const trimmed = String(stdoutText || '').trim()
277
- if (!trimmed) return null
278
- const lines = trimmed.split(/\r?\n/).filter(Boolean)
279
- let lastText = null
280
- let lastTextStr = ''
281
- let terminal = null
282
- let fallback = null
283
- for (const raw of lines) {
284
- const ln = raw.trim()
285
- if (!ln.startsWith('{')) continue
286
- let obj
287
- try { obj = JSON.parse(ln) } catch (e) { continue }
288
- if (!obj || typeof obj !== 'object') continue
289
- const part = obj.part && typeof obj.part === 'object' ? obj.part : null
290
- if (obj.type === 'text' && part && typeof part.text === 'string') {
291
- lastText = obj
292
- lastTextStr = part.text
293
- } else if (obj.type === 'error') {
294
- terminal = obj
295
- } else if (obj.type === 'step_finish') {
296
- if (!terminal || terminal.type !== 'error') terminal = obj
297
- }
298
- fallback = obj
299
- }
300
- if (terminal) {
301
- const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
302
- if (lastTextStr && !(part && typeof part.text === 'string')) {
303
- terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
304
- }
305
- return terminal
306
- }
307
- return lastText || fallback
308
- },
309
-
310
- // 统一结果对象(契约 §1 buildResult 行)。
311
- // 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
312
- // 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
313
- buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
314
- const exitCode = outcome ? outcome.exitCode : null
315
- const stderr = stderrText ? String(stderrText).slice(-2000) : ''
316
- if (parsed && typeof parsed === 'object') {
317
- const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
318
- : (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
319
- const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
320
- const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
321
- const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
322
- const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
323
- : (errObj && typeof errObj.message === 'string' ? errObj.message
324
- : (typeof parsed.error === 'string' ? parsed.error : ''))
325
- let response = ''
326
- if (typeof part.text === 'string') response = part.text
327
- else if (typeof parsed.response === 'string') response = parsed.response
328
- const isErrorEvent = parsed.type === 'error'
329
- let status
330
- if (exitCode === 130) status = 'ABORTED'
331
- else if (isErrorEvent) status = 'ERROR'
332
- else if (typeof parsed.status === 'string') status = parsed.status
333
- else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
334
- const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
335
- let totalTokens = null
336
- if (tokens) {
337
- if (typeof tokens.total === 'number') totalTokens = tokens.total
338
- else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
339
- else {
340
- let sum = 0
341
- let any = false
342
- for (const k of Object.keys(tokens)) {
343
- if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
344
- }
345
- if (any) totalTokens = sum
346
- }
347
- }
348
- return {
349
- ok: exitCode === 0 && !isErrorEvent,
350
- status,
351
- response,
352
- sessionId,
353
- durationSeconds: null,
354
- numTurns: null,
355
- totalTokens,
356
- exitCode, mode, backend: backend || null,
357
- stderr: (stderr ? stderr + ' ' : '') + errMsg,
358
- cost: typeof part.cost === 'number' ? part.cost : null
359
- }
360
- }
361
- const text = String(stdoutText || '').trim()
362
- return {
363
- ok: exitCode === 0,
364
- status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
365
- response: text,
366
- sessionId: null,
367
- durationSeconds: null, numTurns: null, totalTokens: null,
368
- exitCode, mode, backend: backend || null, stderr,
369
- rawStdout: text.slice(-2000)
370
- }
371
- },
372
-
373
- // 实时步骤折叠(写 project.current/trail)。
374
- // tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
375
- // text.part = { text:"…", time:{start,end} }
376
- foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
377
- if (!ev || typeof ev !== 'object') return
378
- const type = ev.type
379
- if (!type) return
380
- const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
381
- p.updatedAt = Date.now()
382
- if (type === 'tool_use') {
383
- const tool = part.tool || part.name || 'tool'
384
- const st = part.state && typeof part.state === 'object' ? part.state : {}
385
- const args = summarizeArgs(st.input || part.input)
386
- const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
387
- const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
388
- p.trail.push(entry)
389
- const cap = maxTrail || 12
390
- if (p.trail.length > cap) p.trail.shift()
391
- if (p.current) p.current = null
392
- } else if (type === 'text' || type === 'reasoning') {
393
- const delta = typeof part.text === 'string' ? part.text : ''
394
- if (!delta) return
395
- const capLen = maxArgLen || 120
396
- p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
397
- } else if (type === 'step_finish') {
398
- if (p.current) p.current = null
399
- }
400
- },
401
-
402
- isTransientCliError(res) {
403
- if (!res || res.ok) return false
404
- if (isLimited(res)) return false
405
- return res.status === 'ERROR_DURING_EXECUTION'
406
- },
407
-
408
- failureHint(res) {
409
- if (!res || res.ok) return ''
410
- const st = String(res.status || '')
411
- if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
412
- const hay = String(res.stderr || '') + ' ' + String(res.response || '')
413
- if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
414
- return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
415
- }
416
- if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
417
- return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
418
- }
419
- if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
420
- return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
421
- }
422
- return ''
423
- },
424
-
425
- isSuccessStatus(st) { return st === 'SUCCESS' },
426
-
427
- tools: {
428
- run: { name: 'opencode_run', description: 'Dispatch a coding/build/debug/investigation task to the local opencode agent CLI and return its final answer. Prefer this for implementation, edits, refactors, multi-file investigation and debugging in every mode. DSH fully controls opencode: it always runs non-interactively with permissions auto-approved (opencode never blocks on a prompt). Use read-only native tools only for quick lookups and for final build/test verification. Runs in the background by default (returns a jobId immediately; collect with job_output); set background=false to block for the final answer.', inputSchema: RUN_PARAMS },
429
- continue: { name: 'opencode_continue', description: 'Continue an existing opencode session with a follow-up prompt, reusing opencode context. Pass sessionId from a prior opencode_run result, or set latest=true to continue the most recent opencode session. Same DSH-controlled, no-prompt execution as opencode_run.', inputSchema: CONTINUE_PARAMS },
430
- status: { name: 'opencode_status', description: 'Read a live snapshot of what the local opencode agent is currently doing. Returns one section per project (working directory): running count, the current step (tool name + arguments being executed, or agent_response thinking/typing), the recent step trail (tools executed, done/error), and the last completed run status + session id. Optional cwd filters to a single project. Call this to check on an in-flight opencode_run/opencode_continue without waiting for it to finish.', inputSchema: STATUS_PARAMS }
431
- },
432
-
433
- // opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
434
- // deps.nodeChild;dynamic 沙箱形态省略)。
435
- extraTools: (deps.process || deps.nodeChild) ? [{
436
- name: 'opencode_models',
437
- description: MODELS_DESCRIPTION,
438
- inputSchema: MODELS_PARAMS,
439
- render: renderModels,
440
- async logic(args) {
441
- return await descriptor.listModels(args || {})
442
- }
443
- }] : [],
444
-
445
- /**
446
- * 列出可用模型(三形态共用)。真实执行 `opencode models`;
447
- * CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
448
- */
449
- async listModels(args) {
450
- const a = args || {}
451
- const child = deps.nodeChild
452
- if (!child || typeof child.spawn !== 'function') {
453
- // preset 形态:宿主 subprocess(attach 后可用)。
454
- if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
455
- }
456
- const prefix = resolveExePrefix(env, currentSettings().binPath)
457
- const argv = prefix.slice(1).concat(['models'])
458
- const run = child && typeof child.spawn === 'function'
459
- ? spawnModelsNode(child, prefix[0], argv)
460
- : spawnModelsHost(argv)
461
- let res
462
- try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
463
- if (!res.ok) return res
464
- let list = res.models
465
- if (a.provider) {
466
- const pv = String(a.provider).toLowerCase()
467
- list = list.filter((m) => String(m.provider).toLowerCase() === pv)
468
- }
469
- if (a.freeOnly) list = list.filter((m) => m.free)
470
- // 免费模型优先展示(用户要求:优先用性能较好的免费模型),其次按字母序。
471
- list.sort((x, y) => (x.free === y.free ? String(x.id).localeCompare(String(y.id)) : (x.free ? -1 : 1)))
472
- return { ok: true, models: list, count: list.length }
473
- },
474
-
475
- // 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
476
- settings: {
477
- keys: ['binPath', 'defaultModel', 'defaultAgent'],
478
- defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
479
- normalize: (raw) => {
480
- const r = raw && typeof raw === 'object' ? raw : {}
481
- const out = { binPath: '', defaultModel: '', defaultAgent: '' }
482
- for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
483
- if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
484
- }
485
- return out
486
- },
487
- meta: (env2) => {
488
- const e = env2 && typeof env2 === 'object' ? env2 : {}
489
- const s = currentSettings()
490
- // 下拉选项:实时 `opencode models`(失败则退化为空 → 面板仍可自由输入)。
491
- const models = fetchModelsSync(e, s.binPath, 8000)
492
- const options = models.map((m) => ({ value: m.id, label: m.id + (m.free ? ' [free]' : '') }))
493
- // 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
494
- const exeCandidates = []
495
- if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
496
- for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
497
- return {
498
- titleSuffix: 'OpenCode',
499
- fields: [
500
- {
501
- key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
502
- options: exeCandidates.map((p) => ({ value: p, label: p })),
503
- placeholder: '留空 = 自动探测桌面版 / PATH',
504
- note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
505
- },
506
- {
507
- key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
508
- options: options,
509
- placeholder: '留空 = 由 opencode 自身配置决定',
510
- note: options.length
511
- ? '共 ' + options.length + ' 个可用模型,免费模型已排在前面([free])。调用时传 model 可覆盖本项。'
512
- : '未能读取模型列表(CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model。'
513
- },
514
- {
515
- key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
516
- options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
517
- placeholder: '留空 = opencode 默认 agent',
518
- note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
519
- }
520
- ]
521
- }
522
- },
523
- diagnose: (settings, env2) => {
524
- const s = settings && typeof settings === 'object' ? settings : {}
525
- const e = env2 && typeof env2 === 'object' ? env2 : {}
526
- const bits = []
527
- const found = candidateExePaths(e)
528
- if (s.binPath) bits.push('bin=设置:' + s.binPath)
529
- else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
530
- else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
531
- else bits.push('bin=PATH:opencode-cli')
532
- bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
533
- if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
534
- return bits.join(' · ')
535
- }
536
- },
537
-
538
- mcp: { version: '0.2.2' }
539
- }
540
-
541
- // MCP/测试形态:真 child_process。
542
- function spawnModelsNode(child, exe, argv) {
543
- return new Promise((resolve) => {
544
- let c
545
- try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
546
- catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
547
- let out = ''
548
- let err = ''
549
- const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
550
- c.stdout.on('data', (d) => { out += d })
551
- c.stderr.on('data', (d) => { err += d })
552
- c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
553
- c.on('close', (code) => {
554
- clearTimeout(timer)
555
- if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
556
- const list = parseModelList(out)
557
- if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
558
- resolve({ ok: true, models: list })
559
- })
560
- })
561
- }
562
-
563
- // preset 形态:DSH subprocess。
564
- async function spawnModelsHost(argv) {
565
- try {
566
- const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
567
- if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
568
- const handle = host.subprocess.spawn(spec)
569
- const outcome = await handle.done
570
- const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
571
- const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
572
- if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
573
- const list = parseModelList(stdoutText)
574
- if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
575
- return { ok: true, models: list }
576
- } catch (e) { return { ok: false, error: String(e && e.message || e) } }
577
- }
578
-
579
- descriptor.runToolLogic = async function (args, exec) {
580
- const a = args || {}
581
- const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
582
- return this.runner.coreExecute(normalized, exec)
583
- }
584
- descriptor.continueToolLogic = async function (args, exec) {
585
- const a = args || {}
586
- const mapped = {
587
- prompt: a.prompt, model: a.model, agent: a.agent,
588
- cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
589
- background: a.background === undefined ? true : a.background
590
- }
591
- const sid = a.sessionId || null
592
- if (sid) mapped.sessionId = sid
593
- else if (a.latest) mapped.continueLatest = true
594
- return this.runner.coreExecute(mapped, exec)
595
- }
596
- descriptor.statusToolLogic = function (args) {
597
- const a = args || {}
598
- const snap = this.engine.statusSnapshot()
599
- if (a.cwd) {
600
- const key = String(a.cwd)
601
- snap.projects = snap.projects.filter((p) => p.cwd === key)
602
- const g = snap.projects[0]
603
- if (g) {
604
- Object.assign(snap, {
605
- state: g.state, running: g.running, current: g.current, trail: g.trail,
606
- lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
607
- lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
608
- })
609
- }
610
- }
611
- return snap
612
- }
613
-
614
- descriptor.attach = function (hostOpts) {
615
- host = hostOpts || {}
616
- // 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
617
- try {
618
- if (typeof host.getSettings === 'function') {
619
- const s = host.getSettings('opencode')
620
- if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
621
- }
622
- } catch (e) { }
623
- this.engine = createStatusEngine({ provider: this, publish: host.publish })
624
- const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
625
- this.runner = runner
626
- return runner
627
- }
628
- return descriptor
629
- }
1
+ // providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
2
+ //
3
+ // 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
4
+ // 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
5
+ // • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
6
+ // `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
7
+ // • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
8
+ // • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
9
+ // • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
10
+ // step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
11
+ //
12
+ // 红线(PROVIDER-CONTRACT.md §8 + §1):
13
+ // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
14
+ // process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
15
+ // - 只允许 import '../core/bridge-kit.mjs'。
16
+ import { createStatusEngine, createRunner, clampInt, isLimited } from '../core/bridge-kit.mjs'
17
+ import { candidateExePaths, EXE_BASENAMES } from './opencode-exe.mjs'
18
+ export { candidateExePaths }
19
+
20
+ function nowIso() { return new Date().toISOString() }
21
+
22
+ // ── 可执行文件解析(env > 桌面版已知路径 > PATH)───────────────────────────────
23
+ // 二进制名是 opencode-cli.exe(不是 opencode.exe):V2 桌面版自带,且 V1/V2 不能并存
24
+ // 安装(官方原话),故不做「opencode.exe 兜底」以免误命中另一个版本。
25
+ // 桌面版各版本目录形如 ...\ai.opencode.desktop\cli\<ver>-<arch>\opencode-cli.exe。
26
+
27
+ function schedBuiltin(name) {
28
+ try {
29
+ const proc = globalThis.process
30
+ return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
31
+ } catch (e) { return null }
32
+ }
33
+
34
+ /**
35
+ * 探测本机 opencode 可执行文件候选路径(优先桌面版 V2)。
36
+ * 纯函数、零副作用;无 fs 能力时返回空数组 —— 由调用方退回 PATH 查找。
37
+ * @param {object} env 环境变量(读 APPDATA / LOCALAPPDATA / PROGRAMFILES / HOME)
38
+ */
39
+ export function resolveExePrefix(env, binPath) {
40
+ const e = env || {}
41
+ const bin = binPath || e.OPENCODE_BIN || e.OPENCODE_CLI || ''
42
+ if (bin) {
43
+ if (/\.(mjs|cjs|js)$/i.test(bin)) {
44
+ const proc = globalThis.process
45
+ const node = (proc && proc.execPath) ? proc.execPath : 'node'
46
+ return [node, bin]
47
+ }
48
+ return [String(bin)]
49
+ }
50
+ const found = candidateExePaths(e)
51
+ if (found.length) return [found[0]]
52
+ return [EXE_BASENAMES[0]]
53
+ }
54
+
55
+ // ── 模型列表(`opencode models`;纯文本每行 provider/model)─────────────────────
56
+ // 同步版给 settings.meta(面板下拉);异步版给 MCP 工具。解析宽容:只认
57
+ // provider/model 形态的行,其余(表头/说明/空行)一律丢弃。
58
+ const MODEL_LINE_RE = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.#@+-]+)$/
59
+
60
+ export function parseModelList(text) {
61
+ const out = []
62
+ const seen = Object.create(null)
63
+ for (const raw of String(text || '').split(/\r?\n/)) {
64
+ const ln = raw.trim()
65
+ if (!ln) continue
66
+ const m = ln.match(MODEL_LINE_RE)
67
+ if (!m) continue
68
+ const id = m[1] + '/' + m[2]
69
+ if (seen[id]) continue
70
+ seen[id] = true
71
+ out.push({ id: id, provider: m[1], name: m[2], free: /(-free$|free)/i.test(m[2]) })
72
+ }
73
+ return out
74
+ }
75
+
76
+ /**
77
+ * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
78
+ * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
79
+ */
80
+ export function fetchModelsSync(env, binPath, timeoutMs) {
81
+ try {
82
+ const child = schedBuiltin('node:child_process')
83
+ if (!child || typeof child.spawnSync !== 'function') return []
84
+ const prefix = resolveExePrefix(env, binPath)
85
+ const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), {
86
+ encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000),
87
+ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
88
+ })
89
+ if (!r || r.error || r.status !== 0) return []
90
+ return parseModelList(String(r.stdout || ''))
91
+ } catch (e) { return [] }
92
+ }
93
+
94
+ // ── 三工具 schema ────────────────────────────────────────────────────────────
95
+ const RUN_PARAMS = {
96
+ type: 'object',
97
+ additionalProperties: false,
98
+ required: ['prompt'],
99
+ properties: {
100
+ prompt: { type: 'string', description: 'The task instruction for opencode. On first dispatch for a topic, include a compact CONTEXT preamble (goal, repo root, key paths, decisions/constraints; point at paths, do not paste file contents — opencode reads the repo itself). For follow-ups on the same topic, use opencode_continue with latest=true or sessionId (opencode keeps session context; state only what is new).' },
101
+ model: { type: 'string', description: 'Optional model in provider/model form (e.g. "opencode/big-pickle"). Prefer a -free model when the task does not need a frontier model. Omit to use the model chosen in the CLI Bridge settings panel, or (if unset there) opencode\'s own default.' },
102
+ agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
103
+ cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
104
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
105
+ title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
106
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
107
+ autoApprove: { type: 'boolean', description: 'Default true: pass --auto so opencode auto-approves permissions and never blocks on a prompt. Set false to require explicit approval (opencode may then block and hit the timeout).' },
108
+ background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
109
+ }
110
+ }
111
+ const CONTINUE_PARAMS = {
112
+ type: 'object',
113
+ additionalProperties: false,
114
+ required: ['prompt'],
115
+ properties: {
116
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
117
+ sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
118
+ latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
119
+ model: { type: 'string', description: 'Optional model in provider/model form.' },
120
+ agent: { type: 'string', description: 'Optional opencode agent name.' },
121
+ cwd: { type: 'string', description: 'Working directory for opencode.' },
122
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
123
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
124
+ autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
125
+ background: { type: 'boolean', description: 'Defaults to true: dispatch returns a jobId immediately; collect with job_output, watch progress with opencode_status. Set false to block for the final answer.' }
126
+ }
127
+ }
128
+ const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
129
+
130
+ // opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
131
+ const MODELS_PARAMS = {
132
+ type: 'object',
133
+ additionalProperties: false,
134
+ required: [],
135
+ properties: {
136
+ freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
137
+ provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
138
+ }
139
+ }
140
+ const MODELS_DESCRIPTION = 'List the models available to the local opencode CLI (from `opencode models`). Returns { ok, models: [{id, provider, name, free}], count }. Use this to pick a model before opencode_run, or to check which models are free. Prefer a -free model for routine work and reserve paid/frontier models for tasks that genuinely need them. If the CLI is missing or not logged in, this returns ok:false with an actionable error — it never silently invents a model list.'
141
+
142
+ function renderModels(value) {
143
+ const v = value || {}
144
+ if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
145
+ const list = Array.isArray(v.models) ? v.models : []
146
+ if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
147
+ const lines = ['opencode models (' + list.length + '):']
148
+ for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
149
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
150
+ const free = list.filter((m) => m.free).length
151
+ lines.push('free: ' + free + ' / ' + list.length)
152
+ return [{ type: 'text', text: lines.join('\n') }]
153
+ }
154
+
155
+ export default function defineProvider(deps = {}) {
156
+ const env = deps.env || {}
157
+ let host = null
158
+ let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
159
+
160
+ /**
161
+ * 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
162
+ * 面板改默认模型后无需重启即生效:
163
+ * 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
164
+ * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
165
+ * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
166
+ * 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
167
+ *
168
+ * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
169
+ * defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
170
+ * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
171
+ */
172
+ function currentSettings() {
173
+ const out = Object.assign({}, settingsRef)
174
+ try {
175
+ if (typeof deps.readSettings === 'function') {
176
+ const r = deps.readSettings()
177
+ if (r && typeof r === 'object') {
178
+ const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
179
+ if (part && typeof part === 'object') Object.assign(out, part)
180
+ }
181
+ }
182
+ } catch (e) { }
183
+ try {
184
+ if (host && typeof host.getSettings === 'function') {
185
+ const s = host.getSettings('opencode')
186
+ if (s && typeof s === 'object') Object.assign(out, s)
187
+ }
188
+ } catch (e) { }
189
+ return out
190
+ }
191
+
192
+ const descriptor = {
193
+ id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
194
+ exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
195
+
196
+ // 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
197
+ backends() { return null },
198
+ normalizeBackend() { return null },
199
+ resolveBackend(args, target, preferred) { return null },
200
+
201
+ // 实测 flag 集(V2.0.29)。
202
+ buildArgv(exePrefix, args, opts) {
203
+ const o = opts || {}
204
+ const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
205
+ argv.push('run', String(args.prompt), '--format', 'json')
206
+ if (args.autoApprove !== false) argv.push('--auto')
207
+ const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
208
+ // 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
209
+ // 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
210
+ const model = args.model || currentSettings().defaultModel || ''
211
+ if (model) argv.push('--model', String(model))
212
+ const agent = args.agent || currentSettings().defaultAgent || ''
213
+ if (agent) argv.push('--agent', String(agent))
214
+ if (args.title) argv.push('--title', String(args.title))
215
+ if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
216
+ if (args.sessionId) argv.push('--session', String(args.sessionId))
217
+ else if (args.continueLatest) argv.push('--continue')
218
+ return { argv, mode: 'auto', timeoutSec }
219
+ },
220
+
221
+ // JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
222
+ // step_start / text / reasoning / tool_use / step_finish / error。
223
+ // ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
224
+ // ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
225
+ // cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
226
+ // ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
227
+ // step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
228
+ // 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
229
+ // 是活的必经分支,不是死代码。
230
+ // 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
231
+ // 回填进 part.text,让 buildResult 统一从 part.text 读正文。
232
+ // 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
233
+ parseJson(stdoutText) {
234
+ const trimmed = String(stdoutText || '').trim()
235
+ if (!trimmed) return null
236
+ const lines = trimmed.split(/\r?\n/).filter(Boolean)
237
+ let lastText = null
238
+ let lastTextStr = ''
239
+ let terminal = null
240
+ let fallback = null
241
+ for (const raw of lines) {
242
+ const ln = raw.trim()
243
+ if (!ln.startsWith('{')) continue
244
+ let obj
245
+ try { obj = JSON.parse(ln) } catch (e) { continue }
246
+ if (!obj || typeof obj !== 'object') continue
247
+ const part = obj.part && typeof obj.part === 'object' ? obj.part : null
248
+ if (obj.type === 'text' && part && typeof part.text === 'string') {
249
+ lastText = obj
250
+ lastTextStr = part.text
251
+ } else if (obj.type === 'error') {
252
+ terminal = obj
253
+ } else if (obj.type === 'step_finish') {
254
+ if (!terminal || terminal.type !== 'error') terminal = obj
255
+ }
256
+ fallback = obj
257
+ }
258
+ if (terminal) {
259
+ const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
260
+ if (lastTextStr && !(part && typeof part.text === 'string')) {
261
+ terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
262
+ }
263
+ return terminal
264
+ }
265
+ return lastText || fallback
266
+ },
267
+
268
+ // 统一结果对象(契约 §1 buildResult 行)。
269
+ // 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
270
+ // 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
271
+ buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
272
+ const exitCode = outcome ? outcome.exitCode : null
273
+ const stderr = stderrText ? String(stderrText).slice(-2000) : ''
274
+ if (parsed && typeof parsed === 'object') {
275
+ const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
276
+ : (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
277
+ const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
278
+ const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
279
+ const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
280
+ const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
281
+ : (errObj && typeof errObj.message === 'string' ? errObj.message
282
+ : (typeof parsed.error === 'string' ? parsed.error : ''))
283
+ let response = ''
284
+ if (typeof part.text === 'string') response = part.text
285
+ else if (typeof parsed.response === 'string') response = parsed.response
286
+ const isErrorEvent = parsed.type === 'error'
287
+ let status
288
+ if (exitCode === 130) status = 'ABORTED'
289
+ else if (isErrorEvent) status = 'ERROR'
290
+ else if (typeof parsed.status === 'string') status = parsed.status
291
+ else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
292
+ const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
293
+ let totalTokens = null
294
+ if (tokens) {
295
+ if (typeof tokens.total === 'number') totalTokens = tokens.total
296
+ else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
297
+ else {
298
+ let sum = 0
299
+ let any = false
300
+ for (const k of Object.keys(tokens)) {
301
+ if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
302
+ }
303
+ if (any) totalTokens = sum
304
+ }
305
+ }
306
+ return {
307
+ ok: exitCode === 0 && !isErrorEvent,
308
+ status,
309
+ response,
310
+ sessionId,
311
+ durationSeconds: null,
312
+ numTurns: null,
313
+ totalTokens,
314
+ exitCode, mode, backend: backend || null,
315
+ stderr: (stderr ? stderr + ' ' : '') + errMsg,
316
+ cost: typeof part.cost === 'number' ? part.cost : null
317
+ }
318
+ }
319
+ const text = String(stdoutText || '').trim()
320
+ return {
321
+ ok: exitCode === 0,
322
+ status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
323
+ response: text,
324
+ sessionId: null,
325
+ durationSeconds: null, numTurns: null, totalTokens: null,
326
+ exitCode, mode, backend: backend || null, stderr,
327
+ rawStdout: text.slice(-2000)
328
+ }
329
+ },
330
+
331
+ // 实时步骤折叠(写 project.current/trail)。
332
+ // tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
333
+ // text.part = { text:"…", time:{start,end} }
334
+ foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
335
+ if (!ev || typeof ev !== 'object') return
336
+ const type = ev.type
337
+ if (!type) return
338
+ const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
339
+ p.updatedAt = Date.now()
340
+ if (type === 'tool_use') {
341
+ const tool = part.tool || part.name || 'tool'
342
+ const st = part.state && typeof part.state === 'object' ? part.state : {}
343
+ const args = summarizeArgs(st.input || part.input)
344
+ const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
345
+ const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
346
+ p.trail.push(entry)
347
+ const cap = maxTrail || 12
348
+ if (p.trail.length > cap) p.trail.shift()
349
+ if (p.current) p.current = null
350
+ } else if (type === 'text' || type === 'reasoning') {
351
+ const delta = typeof part.text === 'string' ? part.text : ''
352
+ if (!delta) return
353
+ const capLen = maxArgLen || 120
354
+ p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
355
+ } else if (type === 'step_finish') {
356
+ if (p.current) p.current = null
357
+ }
358
+ },
359
+
360
+ isTransientCliError(res) {
361
+ if (!res || res.ok) return false
362
+ if (isLimited(res)) return false
363
+ return res.status === 'ERROR_DURING_EXECUTION'
364
+ },
365
+
366
+ failureHint(res) {
367
+ if (!res || res.ok) return ''
368
+ const st = String(res.status || '')
369
+ if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
370
+ const hay = String(res.stderr || '') + ' ' + String(res.response || '')
371
+ if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
372
+ return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
373
+ }
374
+ if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
375
+ return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
376
+ }
377
+ if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
378
+ return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
379
+ }
380
+ return ''
381
+ },
382
+
383
+ isSuccessStatus(st) { return st === 'SUCCESS' },
384
+
385
+ tools: {
386
+ run: { name: 'opencode_run', description: 'Dispatch a coding/build/debug/investigation task to the local opencode agent CLI and return its final answer. Prefer this for implementation, edits, refactors, multi-file investigation and debugging in every mode. DSH fully controls opencode: it always runs non-interactively with permissions auto-approved (opencode never blocks on a prompt). Use read-only native tools only for quick lookups and for final build/test verification. Runs in the background by default (returns a jobId immediately; collect with job_output); set background=false to block for the final answer.', inputSchema: RUN_PARAMS },
387
+ continue: { name: 'opencode_continue', description: 'Continue an existing opencode session with a follow-up prompt, reusing opencode context. Pass sessionId from a prior opencode_run result, or set latest=true to continue the most recent opencode session. Same DSH-controlled, no-prompt execution as opencode_run.', inputSchema: CONTINUE_PARAMS },
388
+ status: { name: 'opencode_status', description: 'Read a live snapshot of what the local opencode agent is currently doing. Returns one section per project (working directory): running count, the current step (tool name + arguments being executed, or agent_response thinking/typing), the recent step trail (tools executed, done/error), and the last completed run status + session id. Optional cwd filters to a single project. Call this to check on an in-flight opencode_run/opencode_continue without waiting for it to finish.', inputSchema: STATUS_PARAMS }
389
+ },
390
+
391
+ // opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
392
+ // deps.nodeChild;dynamic 沙箱形态省略)。
393
+ extraTools: (deps.process || deps.nodeChild) ? [{
394
+ name: 'opencode_models',
395
+ description: MODELS_DESCRIPTION,
396
+ inputSchema: MODELS_PARAMS,
397
+ render: renderModels,
398
+ async logic(args) {
399
+ return await descriptor.listModels(args || {})
400
+ }
401
+ }] : [],
402
+
403
+ /**
404
+ * 列出可用模型(三形态共用)。真实执行 `opencode models`;
405
+ * CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
406
+ */
407
+ async listModels(args) {
408
+ const a = args || {}
409
+ const child = deps.nodeChild
410
+ if (!child || typeof child.spawn !== 'function') {
411
+ // preset 形态:宿主 subprocess(attach 后可用)。
412
+ if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
413
+ }
414
+ const prefix = resolveExePrefix(env, currentSettings().binPath)
415
+ const argv = prefix.slice(1).concat(['models'])
416
+ const run = child && typeof child.spawn === 'function'
417
+ ? spawnModelsNode(child, prefix[0], argv)
418
+ : spawnModelsHost(argv)
419
+ let res
420
+ try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
421
+ if (!res.ok) return res
422
+ let list = res.models
423
+ if (a.provider) {
424
+ const pv = String(a.provider).toLowerCase()
425
+ list = list.filter((m) => String(m.provider).toLowerCase() === pv)
426
+ }
427
+ if (a.freeOnly) list = list.filter((m) => m.free)
428
+ // 免费模型优先展示(用户要求:优先用性能较好的免费模型),其次按字母序。
429
+ list.sort((x, y) => (x.free === y.free ? String(x.id).localeCompare(String(y.id)) : (x.free ? -1 : 1)))
430
+ return { ok: true, models: list, count: list.length }
431
+ },
432
+
433
+ // 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
434
+ settings: {
435
+ keys: ['binPath', 'defaultModel', 'defaultAgent'],
436
+ defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
437
+ normalize: (raw) => {
438
+ const r = raw && typeof raw === 'object' ? raw : {}
439
+ const out = { binPath: '', defaultModel: '', defaultAgent: '' }
440
+ for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
441
+ if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
442
+ }
443
+ return out
444
+ },
445
+ meta: (env2) => {
446
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
447
+ const s = currentSettings()
448
+ // 下拉选项:实时 `opencode models`(失败则退化为空 → 面板仍可自由输入)。
449
+ const models = fetchModelsSync(e, s.binPath, 8000)
450
+ const options = models.map((m) => ({ value: m.id, label: m.id + (m.free ? ' [free]' : '') }))
451
+ // 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
452
+ const exeCandidates = []
453
+ if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
454
+ for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
455
+ return {
456
+ titleSuffix: 'OpenCode',
457
+ fields: [
458
+ {
459
+ key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
460
+ options: exeCandidates.map((p) => ({ value: p, label: p })),
461
+ placeholder: '留空 = 自动探测桌面版 / PATH',
462
+ note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
463
+ },
464
+ {
465
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
466
+ options: options,
467
+ placeholder: '留空 = 由 opencode 自身配置决定',
468
+ note: options.length
469
+ ? '共 ' + options.length + ' 个可用模型,免费模型已排在前面([free])。调用时传 model 可覆盖本项。'
470
+ : '未能读取模型列表(CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model。'
471
+ },
472
+ {
473
+ key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
474
+ options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
475
+ placeholder: '留空 = opencode 默认 agent',
476
+ note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
477
+ }
478
+ ]
479
+ }
480
+ },
481
+ diagnose: (settings, env2) => {
482
+ const s = settings && typeof settings === 'object' ? settings : {}
483
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
484
+ const bits = []
485
+ const found = candidateExePaths(e)
486
+ if (s.binPath) bits.push('bin=设置:' + s.binPath)
487
+ else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
488
+ else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
489
+ else bits.push('bin=PATH:opencode-cli')
490
+ bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
491
+ if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
492
+ return bits.join(' · ')
493
+ }
494
+ },
495
+
496
+ mcp: { version: '0.2.2' }
497
+ }
498
+
499
+ // MCP/测试形态:真 child_process。
500
+ function spawnModelsNode(child, exe, argv) {
501
+ return new Promise((resolve) => {
502
+ let c
503
+ try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
504
+ catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
505
+ let out = ''
506
+ let err = ''
507
+ const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
508
+ c.stdout.on('data', (d) => { out += d })
509
+ c.stderr.on('data', (d) => { err += d })
510
+ c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
511
+ c.on('close', (code) => {
512
+ clearTimeout(timer)
513
+ if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
514
+ const list = parseModelList(out)
515
+ if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
516
+ resolve({ ok: true, models: list })
517
+ })
518
+ })
519
+ }
520
+
521
+ // preset 形态:DSH subprocess。
522
+ async function spawnModelsHost(argv) {
523
+ try {
524
+ const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
525
+ if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
526
+ const handle = host.subprocess.spawn(spec)
527
+ const outcome = await handle.done
528
+ const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
529
+ const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
530
+ if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
531
+ const list = parseModelList(stdoutText)
532
+ if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
533
+ return { ok: true, models: list }
534
+ } catch (e) { return { ok: false, error: String(e && e.message || e) } }
535
+ }
536
+
537
+ descriptor.runToolLogic = async function (args, exec) {
538
+ const a = args || {}
539
+ const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
540
+ return this.runner.coreExecute(normalized, exec)
541
+ }
542
+ descriptor.continueToolLogic = async function (args, exec) {
543
+ const a = args || {}
544
+ const mapped = {
545
+ prompt: a.prompt, model: a.model, agent: a.agent,
546
+ cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
547
+ background: a.background === undefined ? true : a.background
548
+ }
549
+ const sid = a.sessionId || null
550
+ if (sid) mapped.sessionId = sid
551
+ else if (a.latest) mapped.continueLatest = true
552
+ return this.runner.coreExecute(mapped, exec)
553
+ }
554
+ descriptor.statusToolLogic = function (args) {
555
+ const a = args || {}
556
+ const snap = this.engine.statusSnapshot()
557
+ if (a.cwd) {
558
+ const key = String(a.cwd)
559
+ snap.projects = snap.projects.filter((p) => p.cwd === key)
560
+ const g = snap.projects[0]
561
+ if (g) {
562
+ Object.assign(snap, {
563
+ state: g.state, running: g.running, current: g.current, trail: g.trail,
564
+ lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
565
+ lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
566
+ })
567
+ }
568
+ }
569
+ return snap
570
+ }
571
+
572
+ descriptor.attach = function (hostOpts) {
573
+ host = hostOpts || {}
574
+ // 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
575
+ try {
576
+ if (typeof host.getSettings === 'function') {
577
+ const s = host.getSettings('opencode')
578
+ if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
579
+ }
580
+ } catch (e) { }
581
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
582
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
583
+ this.runner = runner
584
+ return runner
585
+ }
586
+ return descriptor
587
+ }