@luchenglong/cli-bridge 0.2.9 → 0.2.10

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,587 +1,553 @@
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
- }
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'(以及同目录的 opencode-exe.mjs 片文件,
16
+ // build 会把 providers/opencode-*.mjs 一并内联进同一沙箱作用域)。
17
+ // 契约 §3.2:设置面板**不自动探测**模型列表 —— settings.meta() 只读上次手动拉取的
18
+ // 缓存(缓存在 providers/opencode-exe.mjs),用户点「拉取可用模型」才走 refreshModels。
19
+ import { createStatusEngine, createRunner, clampInt, isLimited } from '../core/bridge-kit.mjs'
20
+ import {
21
+ candidateExePaths, resolveExePrefix, parseModelList,
22
+ sortModelsFreeFirst, fetchModelsDetailed, cachedModels, rememberModels
23
+ } from './opencode-exe.mjs'
24
+ export { candidateExePaths, resolveExePrefix, parseModelList }
25
+
26
+ function nowIso() { return new Date().toISOString() }
27
+
28
+ // 模型清单 → 下拉选项 / id→label 映射(免费模型带 [free] 后缀,与 opencode_models 展示一致)。
29
+ function modelLabel(m) { return String(m.id) + ((m && m.free) ? ' [free]' : '') }
30
+ function modelsToOptions(models) {
31
+ return (Array.isArray(models) ? models : []).map((m) => ({ value: String(m.id), label: modelLabel(m) }))
32
+ }
33
+
34
+ // 可执行文件探测 / 模型清单解析 / 手动拉取缓存全部在 providers/opencode-exe.mjs,
35
+ // 本文件只消费(契约 §3.2:settings.meta 只读缓存,绝不在面板渲染时 spawn)。
36
+ // 二进制名是 opencode-cli(V2 桌面版自带):V1/V2 不能并存安装(官方原话),
37
+ // 故不做 opencode.exe 兜底,以免误命中另一个版本。
38
+
39
+ // ── 三工具 schema ────────────────────────────────────────────────────────────
40
+ const RUN_PARAMS = {
41
+ type: 'object',
42
+ additionalProperties: false,
43
+ required: ['prompt'],
44
+ properties: {
45
+ 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).' },
46
+ 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.' },
47
+ agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
48
+ cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
49
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
50
+ title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
51
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
52
+ 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).' },
53
+ 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.' }
54
+ }
55
+ }
56
+ const CONTINUE_PARAMS = {
57
+ type: 'object',
58
+ additionalProperties: false,
59
+ required: ['prompt'],
60
+ properties: {
61
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
62
+ sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
63
+ latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
64
+ model: { type: 'string', description: 'Optional model in provider/model form.' },
65
+ agent: { type: 'string', description: 'Optional opencode agent name.' },
66
+ cwd: { type: 'string', description: 'Working directory for opencode.' },
67
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
68
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
69
+ autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
70
+ 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.' }
71
+ }
72
+ }
73
+ const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
74
+
75
+ // opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
76
+ const MODELS_PARAMS = {
77
+ type: 'object',
78
+ additionalProperties: false,
79
+ required: [],
80
+ properties: {
81
+ freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
82
+ provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
83
+ }
84
+ }
85
+ 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.'
86
+
87
+ function renderModels(value) {
88
+ const v = value || {}
89
+ if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
90
+ const list = Array.isArray(v.models) ? v.models : []
91
+ if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
92
+ const lines = ['opencode models (' + list.length + '):']
93
+ for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
94
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
95
+ const free = list.filter((m) => m.free).length
96
+ lines.push('free: ' + free + ' / ' + list.length)
97
+ return [{ type: 'text', text: lines.join('\n') }]
98
+ }
99
+
100
+ export default function defineProvider(deps = {}) {
101
+ const env = deps.env || {}
102
+ let host = null
103
+ let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
104
+
105
+ /**
106
+ * 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
107
+ * 面板改默认模型后无需重启即生效:
108
+ * 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
109
+ * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
110
+ * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
111
+ * 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
112
+ *
113
+ * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
114
+ * defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
115
+ * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
116
+ */
117
+ function currentSettings() {
118
+ const out = Object.assign({}, settingsRef)
119
+ try {
120
+ if (typeof deps.readSettings === 'function') {
121
+ const r = deps.readSettings()
122
+ if (r && typeof r === 'object') {
123
+ const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
124
+ if (part && typeof part === 'object') Object.assign(out, part)
125
+ }
126
+ }
127
+ } catch (e) { }
128
+ try {
129
+ if (host && typeof host.getSettings === 'function') {
130
+ const s = host.getSettings('opencode')
131
+ if (s && typeof s === 'object') Object.assign(out, s)
132
+ }
133
+ } catch (e) { }
134
+ return out
135
+ }
136
+
137
+ const descriptor = {
138
+ id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
139
+ exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
140
+
141
+ // 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
142
+ backends() { return null },
143
+ normalizeBackend() { return null },
144
+ resolveBackend(args, target, preferred) { return null },
145
+
146
+ // 实测 flag 集(V2.0.29)。
147
+ buildArgv(exePrefix, args, opts) {
148
+ const o = opts || {}
149
+ const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
150
+ argv.push('run', String(args.prompt), '--format', 'json')
151
+ if (args.autoApprove !== false) argv.push('--auto')
152
+ const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
153
+ // 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
154
+ // 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
155
+ const model = args.model || currentSettings().defaultModel || ''
156
+ if (model) argv.push('--model', String(model))
157
+ const agent = args.agent || currentSettings().defaultAgent || ''
158
+ if (agent) argv.push('--agent', String(agent))
159
+ if (args.title) argv.push('--title', String(args.title))
160
+ if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
161
+ if (args.sessionId) argv.push('--session', String(args.sessionId))
162
+ else if (args.continueLatest) argv.push('--continue')
163
+ return { argv, mode: 'auto', timeoutSec }
164
+ },
165
+
166
+ // JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
167
+ // step_start / text / reasoning / tool_use / step_finish / error。
168
+ // ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
169
+ // ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
170
+ // cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
171
+ // ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
172
+ // step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
173
+ // 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
174
+ // 是活的必经分支,不是死代码。
175
+ // 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
176
+ // 回填进 part.text,让 buildResult 统一从 part.text 读正文。
177
+ // 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
178
+ parseJson(stdoutText) {
179
+ const trimmed = String(stdoutText || '').trim()
180
+ if (!trimmed) return null
181
+ const lines = trimmed.split(/\r?\n/).filter(Boolean)
182
+ let lastText = null
183
+ let lastTextStr = ''
184
+ let terminal = null
185
+ let fallback = null
186
+ for (const raw of lines) {
187
+ const ln = raw.trim()
188
+ if (!ln.startsWith('{')) continue
189
+ let obj
190
+ try { obj = JSON.parse(ln) } catch (e) { continue }
191
+ if (!obj || typeof obj !== 'object') continue
192
+ const part = obj.part && typeof obj.part === 'object' ? obj.part : null
193
+ if (obj.type === 'text' && part && typeof part.text === 'string') {
194
+ lastText = obj
195
+ lastTextStr = part.text
196
+ } else if (obj.type === 'error') {
197
+ terminal = obj
198
+ } else if (obj.type === 'step_finish') {
199
+ if (!terminal || terminal.type !== 'error') terminal = obj
200
+ }
201
+ fallback = obj
202
+ }
203
+ if (terminal) {
204
+ const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
205
+ if (lastTextStr && !(part && typeof part.text === 'string')) {
206
+ terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
207
+ }
208
+ return terminal
209
+ }
210
+ return lastText || fallback
211
+ },
212
+
213
+ // 统一结果对象(契约 §1 buildResult 行)。
214
+ // 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
215
+ // 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
216
+ buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
217
+ const exitCode = outcome ? outcome.exitCode : null
218
+ const stderr = stderrText ? String(stderrText).slice(-2000) : ''
219
+ if (parsed && typeof parsed === 'object') {
220
+ const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
221
+ : (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
222
+ const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
223
+ const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
224
+ const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
225
+ const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
226
+ : (errObj && typeof errObj.message === 'string' ? errObj.message
227
+ : (typeof parsed.error === 'string' ? parsed.error : ''))
228
+ let response = ''
229
+ if (typeof part.text === 'string') response = part.text
230
+ else if (typeof parsed.response === 'string') response = parsed.response
231
+ const isErrorEvent = parsed.type === 'error'
232
+ let status
233
+ if (exitCode === 130) status = 'ABORTED'
234
+ else if (isErrorEvent) status = 'ERROR'
235
+ else if (typeof parsed.status === 'string') status = parsed.status
236
+ else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
237
+ const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
238
+ let totalTokens = null
239
+ if (tokens) {
240
+ if (typeof tokens.total === 'number') totalTokens = tokens.total
241
+ else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
242
+ else {
243
+ let sum = 0
244
+ let any = false
245
+ for (const k of Object.keys(tokens)) {
246
+ if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
247
+ }
248
+ if (any) totalTokens = sum
249
+ }
250
+ }
251
+ return {
252
+ ok: exitCode === 0 && !isErrorEvent,
253
+ status,
254
+ response,
255
+ sessionId,
256
+ durationSeconds: null,
257
+ numTurns: null,
258
+ totalTokens,
259
+ exitCode, mode, backend: backend || null,
260
+ stderr: (stderr ? stderr + ' ' : '') + errMsg,
261
+ cost: typeof part.cost === 'number' ? part.cost : null
262
+ }
263
+ }
264
+ const text = String(stdoutText || '').trim()
265
+ return {
266
+ ok: exitCode === 0,
267
+ status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
268
+ response: text,
269
+ sessionId: null,
270
+ durationSeconds: null, numTurns: null, totalTokens: null,
271
+ exitCode, mode, backend: backend || null, stderr,
272
+ rawStdout: text.slice(-2000)
273
+ }
274
+ },
275
+
276
+ // 实时步骤折叠(写 project.current/trail)。
277
+ // tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
278
+ // text.part = { text:"…", time:{start,end} }
279
+ foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
280
+ if (!ev || typeof ev !== 'object') return
281
+ const type = ev.type
282
+ if (!type) return
283
+ const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
284
+ p.updatedAt = Date.now()
285
+ if (type === 'tool_use') {
286
+ const tool = part.tool || part.name || 'tool'
287
+ const st = part.state && typeof part.state === 'object' ? part.state : {}
288
+ const args = summarizeArgs(st.input || part.input)
289
+ const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
290
+ const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
291
+ p.trail.push(entry)
292
+ const cap = maxTrail || 12
293
+ if (p.trail.length > cap) p.trail.shift()
294
+ if (p.current) p.current = null
295
+ } else if (type === 'text' || type === 'reasoning') {
296
+ const delta = typeof part.text === 'string' ? part.text : ''
297
+ if (!delta) return
298
+ const capLen = maxArgLen || 120
299
+ p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
300
+ } else if (type === 'step_finish') {
301
+ if (p.current) p.current = null
302
+ }
303
+ },
304
+
305
+ isTransientCliError(res) {
306
+ if (!res || res.ok) return false
307
+ if (isLimited(res)) return false
308
+ return res.status === 'ERROR_DURING_EXECUTION'
309
+ },
310
+
311
+ failureHint(res) {
312
+ if (!res || res.ok) return ''
313
+ const st = String(res.status || '')
314
+ if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
315
+ const hay = String(res.stderr || '') + ' ' + String(res.response || '')
316
+ if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
317
+ return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
318
+ }
319
+ if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
320
+ return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
321
+ }
322
+ if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
323
+ return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
324
+ }
325
+ return ''
326
+ },
327
+
328
+ isSuccessStatus(st) { return st === 'SUCCESS' },
329
+
330
+ tools: {
331
+ 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 },
332
+ 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 },
333
+ 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 }
334
+ },
335
+
336
+ // opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
337
+ // deps.nodeChild;dynamic 沙箱形态省略)。
338
+ extraTools: (deps.process || deps.nodeChild) ? [{
339
+ name: 'opencode_models',
340
+ description: MODELS_DESCRIPTION,
341
+ inputSchema: MODELS_PARAMS,
342
+ render: renderModels,
343
+ async logic(args) {
344
+ return await descriptor.listModels(args || {})
345
+ }
346
+ }] : [],
347
+
348
+ /**
349
+ * 列出可用模型(三形态共用)。真实执行 `opencode models`;
350
+ * CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
351
+ */
352
+ async listModels(args) {
353
+ const a = args || {}
354
+ const child = deps.nodeChild
355
+ if (!child || typeof child.spawn !== 'function') {
356
+ // preset 形态:宿主 subprocess(attach 后可用)。
357
+ if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
358
+ }
359
+ const prefix = resolveExePrefix(env, currentSettings().binPath)
360
+ const argv = prefix.slice(1).concat(['models'])
361
+ const run = child && typeof child.spawn === 'function'
362
+ ? spawnModelsNode(child, prefix[0], argv)
363
+ : spawnModelsHost(argv)
364
+ let res
365
+ try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
366
+ if (!res.ok) return res
367
+ let list = res.models
368
+ if (a.provider) {
369
+ const pv = String(a.provider).toLowerCase()
370
+ list = list.filter((m) => String(m.provider).toLowerCase() === pv)
371
+ }
372
+ if (a.freeOnly) list = list.filter((m) => m.free)
373
+ // 免费模型优先展示(用户要求:优先用免费模型),与设置面板拉取列表同一排序。
374
+ list = sortModelsFreeFirst(list)
375
+ return { ok: true, models: list, count: list.length }
376
+ },
377
+
378
+ // 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
379
+ settings: {
380
+ keys: ['binPath', 'defaultModel', 'defaultAgent'],
381
+ defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
382
+ normalize: (raw) => {
383
+ const r = raw && typeof raw === 'object' ? raw : {}
384
+ const out = { binPath: '', defaultModel: '', defaultAgent: '' }
385
+ for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
386
+ if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
387
+ }
388
+ return out
389
+ },
390
+ meta: (env2) => {
391
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
392
+ const s = currentSettings()
393
+ // 契约 §3.2:面板渲染**只读缓存**(命中就填 options,没命中留空),绝不 spawn。
394
+ // 探测改由用户点「拉取可用模型」显式触发(settings.refreshModels)。
395
+ const options = modelsToOptions(cachedModels())
396
+ // 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
397
+ const exeCandidates = []
398
+ if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
399
+ for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
400
+ return {
401
+ titleSuffix: 'OpenCode',
402
+ fields: [
403
+ {
404
+ key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
405
+ options: exeCandidates.map((p) => ({ value: p, label: p })),
406
+ placeholder: '留空 = 自动探测桌面版 / PATH',
407
+ note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
408
+ },
409
+ {
410
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
411
+ options: options,
412
+ refresh: { label: '拉取可用模型' },
413
+ placeholder: '留空 = 由 opencode 自身配置决定',
414
+ note: options.length
415
+ ? '共 ' + options.length + ' 个可用模型(上次手动拉取的结果,免费模型已排在前面)。点「拉取可用模型」可重新拉取;调用时传 model 可覆盖本项。'
416
+ : '还没拉取过可用模型清单 —— 点右侧「拉取可用模型」按钮拉取(面板不再自动探测,避免拖慢首屏)。拉取失败会显示具体原因(CLI 未安装 / 未登录 / 超时)。仍可手动输入 provider/model。'
417
+ },
418
+ {
419
+ key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
420
+ options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
421
+ placeholder: '留空 = opencode 默认 agent',
422
+ note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
423
+ }
424
+ ]
425
+ }
426
+ },
427
+ /**
428
+ * 契约 §3.2:手动拉取可用模型(面板按钮 → POST /cli-bridge/settings/models)。
429
+ * 复用 opencode-exe.mjs 的同步探测(包一层 async 即可 —— 该端点本身就是串行
430
+ * 请求,为它再写一套异步 spawn 只会多一份要维护的探测代码)。
431
+ * 成功写回缓存让随后的 meta() 命中;失败**必须** ok:false + 可操作原因,
432
+ * 绝不返回 { ok:true, ids:[] },也绝不硬编码模型名冒充清单。
433
+ */
434
+ async refreshModels(settings, envArg) {
435
+ const s = settings && typeof settings === 'object' ? settings : {}
436
+ const e = envArg && typeof envArg === 'object' ? envArg : env
437
+ const binPath = (typeof s.binPath === 'string' && s.binPath.trim()) ? s.binPath.trim() : (currentSettings().binPath || '')
438
+ const r = fetchModelsDetailed(e, binPath, 15000)
439
+ const source = 'opencode-models'
440
+ if (!r.ok) return { ok: false, ids: [], source: source, error: r.error }
441
+ const models = sortModelsFreeFirst(r.models)
442
+ rememberModels(models)
443
+ const labels = Object.create(null)
444
+ for (const m of models) labels[m.id] = modelLabel(m)
445
+ return { ok: true, ids: models.map((m) => String(m.id)), labels: labels, source: source }
446
+ },
447
+ diagnose: (settings, env2) => {
448
+ const s = settings && typeof settings === 'object' ? settings : {}
449
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
450
+ const bits = []
451
+ const found = candidateExePaths(e)
452
+ if (s.binPath) bits.push('bin=设置:' + s.binPath)
453
+ else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
454
+ else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
455
+ else bits.push('bin=PATH:opencode-cli')
456
+ bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
457
+ if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
458
+ return bits.join(' · ')
459
+ }
460
+ },
461
+
462
+ mcp: { version: '0.2.2' }
463
+ }
464
+
465
+ // MCP/测试形态:真 child_process。
466
+ function spawnModelsNode(child, exe, argv) {
467
+ return new Promise((resolve) => {
468
+ let c
469
+ try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
470
+ catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
471
+ let out = ''
472
+ let err = ''
473
+ const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
474
+ c.stdout.on('data', (d) => { out += d })
475
+ c.stderr.on('data', (d) => { err += d })
476
+ c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
477
+ c.on('close', (code) => {
478
+ clearTimeout(timer)
479
+ if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
480
+ const list = parseModelList(out)
481
+ if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
482
+ resolve({ ok: true, models: list })
483
+ })
484
+ })
485
+ }
486
+
487
+ // preset 形态:DSH subprocess。
488
+ async function spawnModelsHost(argv) {
489
+ try {
490
+ const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
491
+ if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
492
+ const handle = host.subprocess.spawn(spec)
493
+ const outcome = await handle.done
494
+ const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
495
+ const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
496
+ if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
497
+ const list = parseModelList(stdoutText)
498
+ if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
499
+ return { ok: true, models: list }
500
+ } catch (e) { return { ok: false, error: String(e && e.message || e) } }
501
+ }
502
+
503
+ descriptor.runToolLogic = async function (args, exec) {
504
+ const a = args || {}
505
+ const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
506
+ return this.runner.coreExecute(normalized, exec)
507
+ }
508
+ descriptor.continueToolLogic = async function (args, exec) {
509
+ const a = args || {}
510
+ const mapped = {
511
+ prompt: a.prompt, model: a.model, agent: a.agent,
512
+ cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
513
+ background: a.background === undefined ? true : a.background
514
+ }
515
+ const sid = a.sessionId || null
516
+ if (sid) mapped.sessionId = sid
517
+ else if (a.latest) mapped.continueLatest = true
518
+ return this.runner.coreExecute(mapped, exec)
519
+ }
520
+ descriptor.statusToolLogic = function (args) {
521
+ const a = args || {}
522
+ const snap = this.engine.statusSnapshot()
523
+ if (a.cwd) {
524
+ const key = String(a.cwd)
525
+ snap.projects = snap.projects.filter((p) => p.cwd === key)
526
+ const g = snap.projects[0]
527
+ if (g) {
528
+ Object.assign(snap, {
529
+ state: g.state, running: g.running, current: g.current, trail: g.trail,
530
+ lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
531
+ lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
532
+ })
533
+ }
534
+ }
535
+ return snap
536
+ }
537
+
538
+ descriptor.attach = function (hostOpts) {
539
+ host = hostOpts || {}
540
+ // 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
541
+ try {
542
+ if (typeof host.getSettings === 'function') {
543
+ const s = host.getSettings('opencode')
544
+ if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
545
+ }
546
+ } catch (e) { }
547
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
548
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
549
+ this.runner = runner
550
+ return runner
551
+ }
552
+ return descriptor
553
+ }