@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.
@@ -561,634 +561,590 @@ function createRunner(o) {
561
561
  return { coreExecute, runSync, askFallback }
562
562
  }
563
563
 
564
- // providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
565
- //
566
- // 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
567
- // 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
568
- // • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
569
- // `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
570
- // • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
571
- // • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
572
- // • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
573
- // step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
574
- //
575
- // 红线(PROVIDER-CONTRACT.md §8 + §1):
576
- // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
577
- // process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
578
- // - 只允许 import '../core/bridge-kit.mjs'。
579
- // import { createStatusEngine, createRunner, clampInt, isLimited } from '../core/bridge-kit.mjs'
580
- function nowIso() { return new Date().toISOString() }
581
-
582
- // ── 可执行文件解析(env > 桌面版已知路径 > PATH)───────────────────────────────
583
- // 二进制名是 opencode-cli.exe(不是 opencode.exe):V2 桌面版自带,且 V1/V2 不能并存
584
- // 安装(官方原话),故不做「opencode.exe 兜底」以免误命中另一个版本。
585
- const EXE_BASENAMES = ['opencode-cli', 'opencode']
586
- // 桌面版各版本目录形如 ...\ai.opencode.desktop\cli\<ver>-<arch>\opencode-cli.exe。
587
- // 沙箱内可能没有 fs —— 全部读取走 typeof 守卫,读不到就返回空数组(退回 PATH 查找)。
588
- const DESKTOP_CLI_REL = ['ai.opencode.desktop', 'cli']
589
-
590
- function schedBuiltin(name) {
591
- try {
592
- const proc = globalThis.process
593
- return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
594
- } catch (e) { return null }
595
- }
596
-
597
- /**
598
- * 探测本机 opencode 可执行文件候选路径(优先桌面版 V2)。
599
- * 纯函数、零副作用;无 fs 能力时返回空数组 —— 由调用方退回 PATH 查找。
600
- * @param {object} env 环境变量(读 APPDATA / LOCALAPPDATA / PROGRAMFILES / HOME)
601
- */
602
- function candidateExePaths(env) {
603
- const e = env || {}
604
- const out = []
605
- const fs = schedBuiltin('node:fs')
606
- const path = schedBuiltin('node:path')
607
- if (!fs || typeof fs.readdirSync !== 'function' || !path || typeof path.join !== 'function') return out
608
- const roots = []
609
- for (const k of ['APPDATA', 'LOCALAPPDATA', 'PROGRAMFILES']) if (e[k]) roots.push(String(e[k]))
610
- const home = e.HOME || e.USERPROFILE
611
- if (home && !roots.length) roots.push(String(home))
612
- for (const root of roots) {
613
- const cliDir = path.join.apply(path, [root].concat(DESKTOP_CLI_REL))
614
- let versions = []
615
- try { versions = fs.readdirSync(cliDir, { withFileTypes: true }) } catch (err) { continue }
616
- // 版本目录按 semver 降序(新版本优先);解析失败的排末尾。
617
- const dirs = versions.filter((d) => d && d.isDirectory && d.isDirectory()).map((d) => d.name)
618
- const key = (n) => {
619
- const m = String(n).match(/(\d+)\.(\d+)\.(\d+)/)
620
- return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : [-1, -1, -1]
621
- }
622
- dirs.sort((a, b) => {
623
- const ka = key(a), kb = key(b)
624
- for (let i = 0; i < 3; i++) if (ka[i] !== kb[i]) return kb[i] - ka[i]
625
- return 0
626
- })
627
- for (const d of dirs) {
628
- for (const base of EXE_BASENAMES) {
629
- const exe = path.join(cliDir, d, base + (String(e.OS || '').toLowerCase().startsWith('win') || e.APPDATA ? '.exe' : ''))
630
- try { if (fs.existsSync(exe)) out.push(exe) } catch (err) { }
631
- }
632
- }
633
- }
634
- return out
635
- }
636
-
637
- /**
638
- * 解析本次调用使用的 exe 前缀(数组或字符串)。
639
- * 优先级:binPath 设置 > env OPENCODE_BIN/OPENCODE_CLI > 桌面版探测 > PATH 名字。
640
- * @param {object} env
641
- * @param {string} [binPath] 设置面板里的显式路径(可空)
642
- */
643
- function resolveExePrefix(env, binPath) {
644
- const e = env || {}
645
- const bin = binPath || e.OPENCODE_BIN || e.OPENCODE_CLI || ''
646
- if (bin) {
647
- if (/\.(mjs|cjs|js)$/i.test(bin)) {
648
- const proc = globalThis.process
649
- const node = (proc && proc.execPath) ? proc.execPath : 'node'
650
- return [node, bin]
651
- }
652
- return [String(bin)]
653
- }
654
- const found = candidateExePaths(e)
655
- if (found.length) return [found[0]]
656
- return [EXE_BASENAMES[0]]
657
- }
658
-
659
- // ── 模型列表(`opencode models`;纯文本每行 provider/model)─────────────────────
660
- // 同步版给 settings.meta(面板下拉);异步版给 MCP 工具。解析宽容:只认
661
- // provider/model 形态的行,其余(表头/说明/空行)一律丢弃。
662
- const MODEL_LINE_RE = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.#@+-]+)$/
663
-
664
- function parseModelList(text) {
665
- const out = []
666
- const seen = Object.create(null)
667
- for (const raw of String(text || '').split(/\r?\n/)) {
668
- const ln = raw.trim()
669
- if (!ln) continue
670
- const m = ln.match(MODEL_LINE_RE)
671
- if (!m) continue
672
- const id = m[1] + '/' + m[2]
673
- if (seen[id]) continue
674
- seen[id] = true
675
- out.push({ id: id, provider: m[1], name: m[2], free: /(-free$|free)/i.test(m[2]) })
676
- }
677
- return out
678
- }
679
-
680
- /**
681
- * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
682
- * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
683
- */
684
- function fetchModelsSync(env, binPath, timeoutMs) {
685
- try {
686
- const child = schedBuiltin('node:child_process')
687
- if (!child || typeof child.spawnSync !== 'function') return []
688
- const prefix = resolveExePrefix(env, binPath)
689
- const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), {
690
- encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000),
691
- windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
692
- })
693
- if (!r || r.error || r.status !== 0) return []
694
- return parseModelList(String(r.stdout || ''))
695
- } catch (e) { return [] }
696
- }
697
-
698
- // ── 三工具 schema ────────────────────────────────────────────────────────────
699
- const RUN_PARAMS = {
700
- type: 'object',
701
- additionalProperties: false,
702
- required: ['prompt'],
703
- properties: {
704
- 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).' },
705
- 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.' },
706
- agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
707
- cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
708
- files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
709
- title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
710
- timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
711
- 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).' },
712
- 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.' }
713
- }
714
- }
715
- const CONTINUE_PARAMS = {
716
- type: 'object',
717
- additionalProperties: false,
718
- required: ['prompt'],
719
- properties: {
720
- prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
721
- sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
722
- latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
723
- model: { type: 'string', description: 'Optional model in provider/model form.' },
724
- agent: { type: 'string', description: 'Optional opencode agent name.' },
725
- cwd: { type: 'string', description: 'Working directory for opencode.' },
726
- files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
727
- timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
728
- autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
729
- 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.' }
730
- }
731
- }
732
- const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
733
-
734
- // opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
735
- const MODELS_PARAMS = {
736
- type: 'object',
737
- additionalProperties: false,
738
- required: [],
739
- properties: {
740
- freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
741
- provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
742
- }
743
- }
744
- 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.'
745
-
746
- function renderModels(value) {
747
- const v = value || {}
748
- if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
749
- const list = Array.isArray(v.models) ? v.models : []
750
- if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
751
- const lines = ['opencode models (' + list.length + '):']
752
- for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
753
- if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
754
- const free = list.filter((m) => m.free).length
755
- lines.push('free: ' + free + ' / ' + list.length)
756
- return [{ type: 'text', text: lines.join('\n') }]
757
- }
758
-
759
- function defineProvider (deps = {}) {
760
- const env = deps.env || {}
761
- let host = null
762
- let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
763
-
764
- /**
765
- * 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
766
- * 面板改默认模型后无需重启即生效:
767
- * 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
768
- * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
769
- * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
770
- * 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
771
- *
772
- * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
773
- * defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
774
- * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
775
- */
776
- function currentSettings() {
777
- const out = Object.assign({}, settingsRef)
778
- try {
779
- if (typeof deps.readSettings === 'function') {
780
- const r = deps.readSettings()
781
- if (r && typeof r === 'object') {
782
- const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
783
- if (part && typeof part === 'object') Object.assign(out, part)
784
- }
785
- }
786
- } catch (e) { }
787
- try {
788
- if (host && typeof host.getSettings === 'function') {
789
- const s = host.getSettings('opencode')
790
- if (s && typeof s === 'object') Object.assign(out, s)
791
- }
792
- } catch (e) { }
793
- return out
794
- }
795
-
796
- const descriptor = {
797
- id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
798
- exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
799
-
800
- // 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
801
- backends() { return null },
802
- normalizeBackend() { return null },
803
- resolveBackend(args, target, preferred) { return null },
804
-
805
- // 实测 flag 集(V2.0.29)。
806
- buildArgv(exePrefix, args, opts) {
807
- const o = opts || {}
808
- const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
809
- argv.push('run', String(args.prompt), '--format', 'json')
810
- if (args.autoApprove !== false) argv.push('--auto')
811
- const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
812
- // 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
813
- // 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
814
- const model = args.model || currentSettings().defaultModel || ''
815
- if (model) argv.push('--model', String(model))
816
- const agent = args.agent || currentSettings().defaultAgent || ''
817
- if (agent) argv.push('--agent', String(agent))
818
- if (args.title) argv.push('--title', String(args.title))
819
- if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
820
- if (args.sessionId) argv.push('--session', String(args.sessionId))
821
- else if (args.continueLatest) argv.push('--continue')
822
- return { argv, mode: 'auto', timeoutSec }
823
- },
824
-
825
- // JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
826
- // step_start / text / reasoning / tool_use / step_finish / error。
827
- // ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
828
- // ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
829
- // cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
830
- // ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
831
- // step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
832
- // 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
833
- // 是活的必经分支,不是死代码。
834
- // 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
835
- // 回填进 part.text,让 buildResult 统一从 part.text 读正文。
836
- // 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
837
- parseJson(stdoutText) {
838
- const trimmed = String(stdoutText || '').trim()
839
- if (!trimmed) return null
840
- const lines = trimmed.split(/\r?\n/).filter(Boolean)
841
- let lastText = null
842
- let lastTextStr = ''
843
- let terminal = null
844
- let fallback = null
845
- for (const raw of lines) {
846
- const ln = raw.trim()
847
- if (!ln.startsWith('{')) continue
848
- let obj
849
- try { obj = JSON.parse(ln) } catch (e) { continue }
850
- if (!obj || typeof obj !== 'object') continue
851
- const part = obj.part && typeof obj.part === 'object' ? obj.part : null
852
- if (obj.type === 'text' && part && typeof part.text === 'string') {
853
- lastText = obj
854
- lastTextStr = part.text
855
- } else if (obj.type === 'error') {
856
- terminal = obj
857
- } else if (obj.type === 'step_finish') {
858
- if (!terminal || terminal.type !== 'error') terminal = obj
859
- }
860
- fallback = obj
861
- }
862
- if (terminal) {
863
- const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
864
- if (lastTextStr && !(part && typeof part.text === 'string')) {
865
- terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
866
- }
867
- return terminal
868
- }
869
- return lastText || fallback
870
- },
871
-
872
- // 统一结果对象(契约 §1 buildResult 行)。
873
- // 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
874
- // 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
875
- buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
876
- const exitCode = outcome ? outcome.exitCode : null
877
- const stderr = stderrText ? String(stderrText).slice(-2000) : ''
878
- if (parsed && typeof parsed === 'object') {
879
- const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
880
- : (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
881
- const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
882
- const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
883
- const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
884
- const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
885
- : (errObj && typeof errObj.message === 'string' ? errObj.message
886
- : (typeof parsed.error === 'string' ? parsed.error : ''))
887
- let response = ''
888
- if (typeof part.text === 'string') response = part.text
889
- else if (typeof parsed.response === 'string') response = parsed.response
890
- const isErrorEvent = parsed.type === 'error'
891
- let status
892
- if (exitCode === 130) status = 'ABORTED'
893
- else if (isErrorEvent) status = 'ERROR'
894
- else if (typeof parsed.status === 'string') status = parsed.status
895
- else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
896
- const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
897
- let totalTokens = null
898
- if (tokens) {
899
- if (typeof tokens.total === 'number') totalTokens = tokens.total
900
- else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
901
- else {
902
- let sum = 0
903
- let any = false
904
- for (const k of Object.keys(tokens)) {
905
- if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
906
- }
907
- if (any) totalTokens = sum
908
- }
909
- }
910
- return {
911
- ok: exitCode === 0 && !isErrorEvent,
912
- status,
913
- response,
914
- sessionId,
915
- durationSeconds: null,
916
- numTurns: null,
917
- totalTokens,
918
- exitCode, mode, backend: backend || null,
919
- stderr: (stderr ? stderr + ' ' : '') + errMsg,
920
- cost: typeof part.cost === 'number' ? part.cost : null
921
- }
922
- }
923
- const text = String(stdoutText || '').trim()
924
- return {
925
- ok: exitCode === 0,
926
- status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
927
- response: text,
928
- sessionId: null,
929
- durationSeconds: null, numTurns: null, totalTokens: null,
930
- exitCode, mode, backend: backend || null, stderr,
931
- rawStdout: text.slice(-2000)
932
- }
933
- },
934
-
935
- // 实时步骤折叠(写 project.current/trail)。
936
- // tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
937
- // text.part = { text:"…", time:{start,end} }
938
- foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
939
- if (!ev || typeof ev !== 'object') return
940
- const type = ev.type
941
- if (!type) return
942
- const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
943
- p.updatedAt = Date.now()
944
- if (type === 'tool_use') {
945
- const tool = part.tool || part.name || 'tool'
946
- const st = part.state && typeof part.state === 'object' ? part.state : {}
947
- const args = summarizeArgs(st.input || part.input)
948
- const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
949
- const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
950
- p.trail.push(entry)
951
- const cap = maxTrail || 12
952
- if (p.trail.length > cap) p.trail.shift()
953
- if (p.current) p.current = null
954
- } else if (type === 'text' || type === 'reasoning') {
955
- const delta = typeof part.text === 'string' ? part.text : ''
956
- if (!delta) return
957
- const capLen = maxArgLen || 120
958
- p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
959
- } else if (type === 'step_finish') {
960
- if (p.current) p.current = null
961
- }
962
- },
963
-
964
- isTransientCliError(res) {
965
- if (!res || res.ok) return false
966
- if (isLimited(res)) return false
967
- return res.status === 'ERROR_DURING_EXECUTION'
968
- },
969
-
970
- failureHint(res) {
971
- if (!res || res.ok) return ''
972
- const st = String(res.status || '')
973
- if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
974
- const hay = String(res.stderr || '') + ' ' + String(res.response || '')
975
- if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
976
- return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
977
- }
978
- if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
979
- return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
980
- }
981
- if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
982
- return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
983
- }
984
- return ''
985
- },
986
-
987
- isSuccessStatus(st) { return st === 'SUCCESS' },
988
-
989
- tools: {
990
- 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 },
991
- 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 },
992
- 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 }
993
- },
994
-
995
- // opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
996
- // deps.nodeChild;dynamic 沙箱形态省略)。
997
- extraTools: (deps.process || deps.nodeChild) ? [{
998
- name: 'opencode_models',
999
- description: MODELS_DESCRIPTION,
1000
- inputSchema: MODELS_PARAMS,
1001
- render: renderModels,
1002
- async logic(args) {
1003
- return await descriptor.listModels(args || {})
1004
- }
1005
- }] : [],
1006
-
1007
- /**
1008
- * 列出可用模型(三形态共用)。真实执行 `opencode models`;
1009
- * CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
1010
- */
1011
- async listModels(args) {
1012
- const a = args || {}
1013
- const child = deps.nodeChild
1014
- if (!child || typeof child.spawn !== 'function') {
1015
- // preset 形态:宿主 subprocess(attach 后可用)。
1016
- if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
1017
- }
1018
- const prefix = resolveExePrefix(env, currentSettings().binPath)
1019
- const argv = prefix.slice(1).concat(['models'])
1020
- const run = child && typeof child.spawn === 'function'
1021
- ? spawnModelsNode(child, prefix[0], argv)
1022
- : spawnModelsHost(argv)
1023
- let res
1024
- try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
1025
- if (!res.ok) return res
1026
- let list = res.models
1027
- if (a.provider) {
1028
- const pv = String(a.provider).toLowerCase()
1029
- list = list.filter((m) => String(m.provider).toLowerCase() === pv)
1030
- }
1031
- if (a.freeOnly) list = list.filter((m) => m.free)
1032
- // 免费模型优先展示(用户要求:优先用性能较好的免费模型),其次按字母序。
1033
- list.sort((x, y) => (x.free === y.free ? String(x.id).localeCompare(String(y.id)) : (x.free ? -1 : 1)))
1034
- return { ok: true, models: list, count: list.length }
1035
- },
1036
-
1037
- // 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
1038
- settings: {
1039
- keys: ['binPath', 'defaultModel', 'defaultAgent'],
1040
- defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
1041
- normalize: (raw) => {
1042
- const r = raw && typeof raw === 'object' ? raw : {}
1043
- const out = { binPath: '', defaultModel: '', defaultAgent: '' }
1044
- for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
1045
- if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
1046
- }
1047
- return out
1048
- },
1049
- meta: (env2) => {
1050
- const e = env2 && typeof env2 === 'object' ? env2 : {}
1051
- const s = currentSettings()
1052
- // 下拉选项:实时 `opencode models`(失败则退化为空 → 面板仍可自由输入)。
1053
- const models = fetchModelsSync(e, s.binPath, 8000)
1054
- const options = models.map((m) => ({ value: m.id, label: m.id + (m.free ? ' [free]' : '') }))
1055
- // 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
1056
- const exeCandidates = []
1057
- if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
1058
- for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
1059
- return {
1060
- titleSuffix: 'OpenCode',
1061
- fields: [
1062
- {
1063
- key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
1064
- options: exeCandidates.map((p) => ({ value: p, label: p })),
1065
- placeholder: '留空 = 自动探测桌面版 / PATH',
1066
- note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
1067
- },
1068
- {
1069
- key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
1070
- options: options,
1071
- placeholder: '留空 = 由 opencode 自身配置决定',
1072
- note: options.length
1073
- ? '共 ' + options.length + ' 个可用模型,免费模型已排在前面([free])。调用时传 model 可覆盖本项。'
1074
- : '未能读取模型列表(CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model。'
1075
- },
1076
- {
1077
- key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
1078
- options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
1079
- placeholder: '留空 = opencode 默认 agent',
1080
- note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
1081
- }
1082
- ]
1083
- }
1084
- },
1085
- diagnose: (settings, env2) => {
1086
- const s = settings && typeof settings === 'object' ? settings : {}
1087
- const e = env2 && typeof env2 === 'object' ? env2 : {}
1088
- const bits = []
1089
- const found = candidateExePaths(e)
1090
- if (s.binPath) bits.push('bin=设置:' + s.binPath)
1091
- else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
1092
- else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
1093
- else bits.push('bin=PATH:opencode-cli')
1094
- bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
1095
- if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
1096
- return bits.join(' · ')
1097
- }
1098
- },
1099
-
1100
- mcp: { version: '0.2.2' }
1101
- }
1102
-
1103
- // MCP/测试形态:真 child_process。
1104
- function spawnModelsNode(child, exe, argv) {
1105
- return new Promise((resolve) => {
1106
- let c
1107
- try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
1108
- catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
1109
- let out = ''
1110
- let err = ''
1111
- const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
1112
- c.stdout.on('data', (d) => { out += d })
1113
- c.stderr.on('data', (d) => { err += d })
1114
- c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
1115
- c.on('close', (code) => {
1116
- clearTimeout(timer)
1117
- if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
1118
- const list = parseModelList(out)
1119
- if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
1120
- resolve({ ok: true, models: list })
1121
- })
1122
- })
1123
- }
1124
-
1125
- // preset 形态:DSH subprocess。
1126
- async function spawnModelsHost(argv) {
1127
- try {
1128
- const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
1129
- if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
1130
- const handle = host.subprocess.spawn(spec)
1131
- const outcome = await handle.done
1132
- const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
1133
- const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
1134
- if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
1135
- const list = parseModelList(stdoutText)
1136
- if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
1137
- return { ok: true, models: list }
1138
- } catch (e) { return { ok: false, error: String(e && e.message || e) } }
1139
- }
1140
-
1141
- descriptor.runToolLogic = async function (args, exec) {
1142
- const a = args || {}
1143
- const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
1144
- return this.runner.coreExecute(normalized, exec)
1145
- }
1146
- descriptor.continueToolLogic = async function (args, exec) {
1147
- const a = args || {}
1148
- const mapped = {
1149
- prompt: a.prompt, model: a.model, agent: a.agent,
1150
- cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
1151
- background: a.background === undefined ? true : a.background
1152
- }
1153
- const sid = a.sessionId || null
1154
- if (sid) mapped.sessionId = sid
1155
- else if (a.latest) mapped.continueLatest = true
1156
- return this.runner.coreExecute(mapped, exec)
1157
- }
1158
- descriptor.statusToolLogic = function (args) {
1159
- const a = args || {}
1160
- const snap = this.engine.statusSnapshot()
1161
- if (a.cwd) {
1162
- const key = String(a.cwd)
1163
- snap.projects = snap.projects.filter((p) => p.cwd === key)
1164
- const g = snap.projects[0]
1165
- if (g) {
1166
- Object.assign(snap, {
1167
- state: g.state, running: g.running, current: g.current, trail: g.trail,
1168
- lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
1169
- lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
1170
- })
1171
- }
1172
- }
1173
- return snap
1174
- }
1175
-
1176
- descriptor.attach = function (hostOpts) {
1177
- host = hostOpts || {}
1178
- // 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
1179
- try {
1180
- if (typeof host.getSettings === 'function') {
1181
- const s = host.getSettings('opencode')
1182
- if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
1183
- }
1184
- } catch (e) { }
1185
- this.engine = createStatusEngine({ provider: this, publish: host.publish })
1186
- const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
1187
- this.runner = runner
1188
- return runner
1189
- }
1190
- return descriptor
1191
- }
564
+ // providers/opencode.mjs — opencode provider descriptor(第四家 CLI,无旧包可迁)。
565
+ //
566
+ // 基线 = 本机实测 OpenCode V2 CLI v2.0.29(桌面版自带 opencode-cli.exe)+ 源码 emit 全集。
567
+ // 完整 CLI 事实表见 docs/HANDOVER.md §13;这里只留写代码时最容易踩的几条:
568
+ // • 非交互 = `opencode run "<prompt>"`,prompt 是【位置参数】(run 子命令无 --prompt;
569
+ // `-p` 是 --password)。`--format json` → NDJSON。`--auto` = 自动批准权限。
570
+ // • ⚠️ V2 无 --dir(cwd 靠 spawn)、无 --variant(并入 --model#variant)。
571
+ // • 退出码才是成败判据:0 成功 / 1 错误 / 130 SIGINT。
572
+ // • ⚠️ 无 result/complete/init 事件;type 全集 = step_start/text/reasoning/tool_use/
573
+ // step_finish/error。文本在 part.text,统计在 step_finish.part —— 两者是不同事件。
574
+ //
575
+ // 红线(PROVIDER-CONTRACT.md §8 + §1):
576
+ // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现 import.meta 字面量;
577
+ // process 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 deps/attach(hostOpts)。
578
+ // - 只允许 import '../core/bridge-kit.mjs'。
579
+
580
+ function nowIso() { return new Date().toISOString() }
581
+
582
+ // ── 可执行文件解析(env > 桌面版已知路径 > PATH)───────────────────────────────
583
+ // 二进制名是 opencode-cli.exe(不是 opencode.exe):V2 桌面版自带,且 V1/V2 不能并存
584
+ // 安装(官方原话),故不做「opencode.exe 兜底」以免误命中另一个版本。
585
+ // 桌面版各版本目录形如 ...\ai.opencode.desktop\cli\<ver>-<arch>\opencode-cli.exe。
586
+
587
+ function schedBuiltin(name) {
588
+ try {
589
+ const proc = globalThis.process
590
+ return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
591
+ } catch (e) { return null }
592
+ }
593
+
594
+ /**
595
+ * 探测本机 opencode 可执行文件候选路径(优先桌面版 V2)。
596
+ * 纯函数、零副作用;无 fs 能力时返回空数组 —— 由调用方退回 PATH 查找。
597
+ * @param {object} env 环境变量(读 APPDATA / LOCALAPPDATA / PROGRAMFILES / HOME)
598
+ */
599
+ function resolveExePrefix(env, binPath) {
600
+ const e = env || {}
601
+ const bin = binPath || e.OPENCODE_BIN || e.OPENCODE_CLI || ''
602
+ if (bin) {
603
+ if (/\.(mjs|cjs|js)$/i.test(bin)) {
604
+ const proc = globalThis.process
605
+ const node = (proc && proc.execPath) ? proc.execPath : 'node'
606
+ return [node, bin]
607
+ }
608
+ return [String(bin)]
609
+ }
610
+ const found = candidateExePaths(e)
611
+ if (found.length) return [found[0]]
612
+ return [EXE_BASENAMES[0]]
613
+ }
614
+
615
+ // ── 模型列表(`opencode models`;纯文本每行 provider/model)─────────────────────
616
+ // 同步版给 settings.meta(面板下拉);异步版给 MCP 工具。解析宽容:只认
617
+ // provider/model 形态的行,其余(表头/说明/空行)一律丢弃。
618
+ const MODEL_LINE_RE = /^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.#@+-]+)$/
619
+
620
+ function parseModelList(text) {
621
+ const out = []
622
+ const seen = Object.create(null)
623
+ for (const raw of String(text || '').split(/\r?\n/)) {
624
+ const ln = raw.trim()
625
+ if (!ln) continue
626
+ const m = ln.match(MODEL_LINE_RE)
627
+ if (!m) continue
628
+ const id = m[1] + '/' + m[2]
629
+ if (seen[id]) continue
630
+ seen[id] = true
631
+ out.push({ id: id, provider: m[1], name: m[2], free: /(-free$|free)/i.test(m[2]) })
632
+ }
633
+ return out
634
+ }
635
+
636
+ /**
637
+ * 同步抓取模型列表(供设置面板下拉)。失败返回空数组 —— 下拉退化为自由输入,
638
+ * 绝不因探测失败影响面板渲染。仅 spawnSync 可用时生效(宿主形态)。
639
+ */
640
+ function fetchModelsSync(env, binPath, timeoutMs) {
641
+ try {
642
+ const child = schedBuiltin('node:child_process')
643
+ if (!child || typeof child.spawnSync !== 'function') return []
644
+ const prefix = resolveExePrefix(env, binPath)
645
+ const r = child.spawnSync(prefix[0], prefix.slice(1).concat(['models']), {
646
+ encoding: 'utf8', timeout: clampInt(timeoutMs, 8000, 1000, 30000),
647
+ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
648
+ })
649
+ if (!r || r.error || r.status !== 0) return []
650
+ return parseModelList(String(r.stdout || ''))
651
+ } catch (e) { return [] }
652
+ }
653
+
654
+ // ── 三工具 schema ────────────────────────────────────────────────────────────
655
+ const RUN_PARAMS = {
656
+ type: 'object',
657
+ additionalProperties: false,
658
+ required: ['prompt'],
659
+ properties: {
660
+ 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).' },
661
+ 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.' },
662
+ agent: { type: 'string', description: 'Optional opencode agent name (primary agents only; subagent names are rejected by opencode itself).' },
663
+ cwd: { type: 'string', description: 'Working directory for opencode. Defaults to the DSH workspace root.' },
664
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
665
+ title: { type: 'string', description: 'Optional session title (opencode truncates the prompt when omitted).' },
666
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
667
+ 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).' },
668
+ 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.' }
669
+ }
670
+ }
671
+ const CONTINUE_PARAMS = {
672
+ type: 'object',
673
+ additionalProperties: false,
674
+ required: ['prompt'],
675
+ properties: {
676
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
677
+ sessionId: { type: 'string', description: 'opencode session id to continue (from a prior opencode_run result).' },
678
+ latest: { type: 'boolean', description: 'Continue the most recent opencode session instead of a specific id.' },
679
+ model: { type: 'string', description: 'Optional model in provider/model form.' },
680
+ agent: { type: 'string', description: 'Optional opencode agent name.' },
681
+ cwd: { type: 'string', description: 'Working directory for opencode.' },
682
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach.' },
683
+ timeoutSec: { type: 'integer', description: 'Execution timeout seconds (10-3600, default 600).' },
684
+ autoApprove: { type: 'boolean', description: 'Default true: pass --auto. Set false to require explicit approval.' },
685
+ 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.' }
686
+ }
687
+ }
688
+ const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
689
+
690
+ // opencode_models(附加工具):列出本机 opencode 可用模型(免费模型优先展示)。
691
+ const MODELS_PARAMS = {
692
+ type: 'object',
693
+ additionalProperties: false,
694
+ required: [],
695
+ properties: {
696
+ freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free). Default false = all.' },
697
+ provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
698
+ }
699
+ }
700
+ 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.'
701
+
702
+ function renderModels(value) {
703
+ const v = value || {}
704
+ if (!v.ok) return [{ type: 'text', text: 'opencode_models failed: ' + String(v.error || 'unknown') }]
705
+ const list = Array.isArray(v.models) ? v.models : []
706
+ if (!list.length) return [{ type: 'text', text: 'opencode_models: no models returned' }]
707
+ const lines = ['opencode models (' + list.length + '):']
708
+ for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
709
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
710
+ const free = list.filter((m) => m.free).length
711
+ lines.push('free: ' + free + ' / ' + list.length)
712
+ return [{ type: 'text', text: lines.join('\n') }]
713
+ }
714
+
715
+ function defineProvider (deps = {}) {
716
+ const env = deps.env || {}
717
+ let host = null
718
+ let settingsRef = { binPath: '', defaultModel: '', defaultAgent: '' }
719
+
720
+ /**
721
+ * 取当前生效的偏好设置。三条来源按优先级合并,每次 buildArgv 都重新读 ——
722
+ * 面板改默认模型后无需重启即生效:
723
+ * 1) `host.getSettings('opencode')` —— preset/dynamic 形态(attach 时由宿主注入);
724
+ * 2) `deps.readSettings()` —— MCP 形态(真 Node 进程,每次现读设置文件);
725
+ * 3) `settingsRef` —— attach 时固化的一次性快照 / 缺省值。
726
+ * 三条都拿不到 → 缺省空值(= 不传 --model,交给 opencode 自身配置决定)。
727
+ *
728
+ * 历史坑:MCP 形态不 attach(自建 engine),只认 host.getSettings 会让面板设置的
729
+ * defaultModel 在 MCP 面对 opencode_run 完全失效 —— 只有 args.model 才落地。
730
+ * 三个形态行为不一致是缺陷,故此处统一把 readSettings 纳入(与 mimo 同构)。
731
+ */
732
+ function currentSettings() {
733
+ const out = Object.assign({}, settingsRef)
734
+ try {
735
+ if (typeof deps.readSettings === 'function') {
736
+ const r = deps.readSettings()
737
+ if (r && typeof r === 'object') {
738
+ const part = ('partition' in r || 'path' in r || 'home' in r) ? r.partition : r
739
+ if (part && typeof part === 'object') Object.assign(out, part)
740
+ }
741
+ }
742
+ } catch (e) { }
743
+ try {
744
+ if (host && typeof host.getSettings === 'function') {
745
+ const s = host.getSettings('opencode')
746
+ if (s && typeof s === 'object') Object.assign(out, s)
747
+ }
748
+ } catch (e) { }
749
+ return out
750
+ }
751
+
752
+ const descriptor = {
753
+ id: 'opencode', label: 'OPENCODE', presetId: 'opencode-first', defaultBackend: null, defaultMode: 'auto',
754
+ exeName: 'opencode-cli', binEnvVars: ['OPENCODE_BIN', 'OPENCODE_CLI'], unavailableStatus: 'OPENCODE_UNAVAILABLE',
755
+
756
+ // 单后端:opencode 自身选择 provider/model,桥不引入第二后端概念。
757
+ backends() { return null },
758
+ normalizeBackend() { return null },
759
+ resolveBackend(args, target, preferred) { return null },
760
+
761
+ // 实测 flag 集(V2.0.29)。
762
+ buildArgv(exePrefix, args, opts) {
763
+ const o = opts || {}
764
+ const argv = Array.isArray(exePrefix) ? exePrefix.slice() : [String(exePrefix)]
765
+ argv.push('run', String(args.prompt), '--format', 'json')
766
+ if (args.autoApprove !== false) argv.push('--auto')
767
+ const timeoutSec = clampInt(args.timeoutSec, 600, 10, 3600)
768
+ // 模型优先级:调用参数 > 设置面板 defaultModel > 不传(交给 opencode 自身默认)。
769
+ // 用户要求「不设默认 → 由 opencode 自决」,故 settingsRef.defaultModel 为空时不落地 --model。
770
+ const model = args.model || currentSettings().defaultModel || ''
771
+ if (model) argv.push('--model', String(model))
772
+ const agent = args.agent || currentSettings().defaultAgent || ''
773
+ if (agent) argv.push('--agent', String(agent))
774
+ if (args.title) argv.push('--title', String(args.title))
775
+ if (Array.isArray(args.files)) for (const f of args.files) { if (f) argv.push('--file', String(f)) }
776
+ if (args.sessionId) argv.push('--session', String(args.sessionId))
777
+ else if (args.continueLatest) argv.push('--continue')
778
+ return { argv, mode: 'auto', timeoutSec }
779
+ },
780
+
781
+ // JSONL(每行一个 JSON 对象)。事件 type 取自 CLI 源码 emit 全集(实测一致):
782
+ // step_start / text / reasoning / tool_use / step_finish / error。
783
+ // ⚠️ 不存在 result/complete/init 事件 —— 终止判据是「进程退出码」,不是某个终态事件。
784
+ // ⚠️ 文本与统计在【不同】事件里:text.part.text 是回复正文,step_finish.part 只有
785
+ // cost/tokens。若直接取 step_finish 会得到「成功但正文为空」的结果。
786
+ // ⚠️ 因此必须【正向】扫完整个流再决策:倒序会在读到 text 之前就命中末尾的
787
+ // step_finish 并返回,回填永远为空(第一版实现的真实 bug)。
788
+ // 实测一次真实调用只产生 step_start + text(无 step_finish)—— 末段 text 兜底
789
+ // 是活的必经分支,不是死代码。
790
+ // 决策优先级:error > step_finish > 末段 text > 末条事件;命中前两者时把末段文本
791
+ // 回填进 part.text,让 buildResult 统一从 part.text 读正文。
792
+ // 无 JSON 时返回 null,由 buildResult 走纯文本兜底(绝不假造 status)。
793
+ parseJson(stdoutText) {
794
+ const trimmed = String(stdoutText || '').trim()
795
+ if (!trimmed) return null
796
+ const lines = trimmed.split(/\r?\n/).filter(Boolean)
797
+ let lastText = null
798
+ let lastTextStr = ''
799
+ let terminal = null
800
+ let fallback = null
801
+ for (const raw of lines) {
802
+ const ln = raw.trim()
803
+ if (!ln.startsWith('{')) continue
804
+ let obj
805
+ try { obj = JSON.parse(ln) } catch (e) { continue }
806
+ if (!obj || typeof obj !== 'object') continue
807
+ const part = obj.part && typeof obj.part === 'object' ? obj.part : null
808
+ if (obj.type === 'text' && part && typeof part.text === 'string') {
809
+ lastText = obj
810
+ lastTextStr = part.text
811
+ } else if (obj.type === 'error') {
812
+ terminal = obj
813
+ } else if (obj.type === 'step_finish') {
814
+ if (!terminal || terminal.type !== 'error') terminal = obj
815
+ }
816
+ fallback = obj
817
+ }
818
+ if (terminal) {
819
+ const part = terminal.part && typeof terminal.part === 'object' ? terminal.part : null
820
+ if (lastTextStr && !(part && typeof part.text === 'string')) {
821
+ terminal.part = Object.assign({}, part || {}, { text: lastTextStr })
822
+ }
823
+ return terminal
824
+ }
825
+ return lastText || fallback
826
+ },
827
+
828
+ // 统一结果对象(契约 §1 buildResult 行)。
829
+ // 事件负载一律在 part 里(CLI emit: {type,timestamp,sessionID,...data},data = {part})。
830
+ // 终止判据 = exit code(0 成功 / 1 错误 / 130 SIGINT),不存在 result 事件可依赖。
831
+ buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
832
+ const exitCode = outcome ? outcome.exitCode : null
833
+ const stderr = stderrText ? String(stderrText).slice(-2000) : ''
834
+ if (parsed && typeof parsed === 'object') {
835
+ const sessionId = typeof parsed.sessionID === 'string' ? parsed.sessionID
836
+ : (typeof parsed.sessionId === 'string' ? parsed.sessionId : null)
837
+ const part = parsed.part && typeof parsed.part === 'object' ? parsed.part : {}
838
+ const errObj = parsed.error && typeof parsed.error === 'object' ? parsed.error : null
839
+ const dataObj = errObj && errObj.data && typeof errObj.data === 'object' ? errObj.data : null
840
+ const errMsg = dataObj && typeof dataObj.message === 'string' ? dataObj.message
841
+ : (errObj && typeof errObj.message === 'string' ? errObj.message
842
+ : (typeof parsed.error === 'string' ? parsed.error : ''))
843
+ let response = ''
844
+ if (typeof part.text === 'string') response = part.text
845
+ else if (typeof parsed.response === 'string') response = parsed.response
846
+ const isErrorEvent = parsed.type === 'error'
847
+ let status
848
+ if (exitCode === 130) status = 'ABORTED'
849
+ else if (isErrorEvent) status = 'ERROR'
850
+ else if (typeof parsed.status === 'string') status = parsed.status
851
+ else status = exitCode === 0 ? 'SUCCESS' : 'ERROR'
852
+ const tokens = part.tokens && typeof part.tokens === 'object' ? part.tokens : null
853
+ let totalTokens = null
854
+ if (tokens) {
855
+ if (typeof tokens.total === 'number') totalTokens = tokens.total
856
+ else if (typeof tokens.totalTokens === 'number') totalTokens = tokens.totalTokens
857
+ else {
858
+ let sum = 0
859
+ let any = false
860
+ for (const k of Object.keys(tokens)) {
861
+ if (typeof tokens[k] === 'number') { sum += tokens[k]; any = true }
862
+ }
863
+ if (any) totalTokens = sum
864
+ }
865
+ }
866
+ return {
867
+ ok: exitCode === 0 && !isErrorEvent,
868
+ status,
869
+ response,
870
+ sessionId,
871
+ durationSeconds: null,
872
+ numTurns: null,
873
+ totalTokens,
874
+ exitCode, mode, backend: backend || null,
875
+ stderr: (stderr ? stderr + ' ' : '') + errMsg,
876
+ cost: typeof part.cost === 'number' ? part.cost : null
877
+ }
878
+ }
879
+ const text = String(stdoutText || '').trim()
880
+ return {
881
+ ok: exitCode === 0,
882
+ status: exitCode === 0 ? 'SUCCESS' : 'ERROR',
883
+ response: text,
884
+ sessionId: null,
885
+ durationSeconds: null, numTurns: null, totalTokens: null,
886
+ exitCode, mode, backend: backend || null, stderr,
887
+ rawStdout: text.slice(-2000)
888
+ }
889
+ },
890
+
891
+ // 实时步骤折叠(写 project.current/trail)。
892
+ // tool_use.part = { tool:"bash", state:{status,input,output,title,time}, … }
893
+ // text.part = { text:"…", time:{start,end} }
894
+ foldStreamEvent(ev, p, summarizeArgs, maxArgLen, maxTrail) {
895
+ if (!ev || typeof ev !== 'object') return
896
+ const type = ev.type
897
+ if (!type) return
898
+ const part = ev.part && typeof ev.part === 'object' ? ev.part : {}
899
+ p.updatedAt = Date.now()
900
+ if (type === 'tool_use') {
901
+ const tool = part.tool || part.name || 'tool'
902
+ const st = part.state && typeof part.state === 'object' ? part.state : {}
903
+ const args = summarizeArgs(st.input || part.input)
904
+ const state = st.status === 'completed' ? 'DONE' : (st.status === 'failed' ? 'ERROR' : 'ACTIVE')
905
+ const entry = { stepIndex: p.trail.length, state: state, tool: tool, args: args || null, at: nowIso() }
906
+ p.trail.push(entry)
907
+ const cap = maxTrail || 12
908
+ if (p.trail.length > cap) p.trail.shift()
909
+ if (p.current) p.current = null
910
+ } else if (type === 'text' || type === 'reasoning') {
911
+ const delta = typeof part.text === 'string' ? part.text : ''
912
+ if (!delta) return
913
+ const capLen = maxArgLen || 120
914
+ p.current = { tool: type === 'reasoning' ? 'reasoning' : 'agent_response', args: { text_delta: String(delta).slice(0, capLen) }, stepIndex: p.trail.length, since: nowIso() }
915
+ } else if (type === 'step_finish') {
916
+ if (p.current) p.current = null
917
+ }
918
+ },
919
+
920
+ isTransientCliError(res) {
921
+ if (!res || res.ok) return false
922
+ if (isLimited(res)) return false
923
+ return res.status === 'ERROR_DURING_EXECUTION'
924
+ },
925
+
926
+ failureHint(res) {
927
+ if (!res || res.ok) return ''
928
+ const st = String(res.status || '')
929
+ if (st === 'OPENCODE_UNAVAILABLE') return '[诊断] 未找到 opencode 可执行文件:请安装 OpenCode(桌面版自带 CLI),或在 CLI Bridge 设置面板填写 opencode 可执行文件路径。'
930
+ const hay = String(res.stderr || '') + ' ' + String(res.response || '')
931
+ if (/Incorrect API key|invalid_api_key|401|unauthorized|not logged|login/i.test(hay) && !/rate.?limit|quota|限流|额度/i.test(hay)) {
932
+ return '[诊断] opencode 凭据问题(未登录 / API key 无效):请让用户执行 `opencode auth login` 登录 provider。这不是限流。'
933
+ }
934
+ if (/No models available|no models|model not found|Unknown provider|not found.*model/i.test(hay)) {
935
+ return '[诊断] opencode 没有可用模型或模型名无效:先用 opencode_models(或 `opencode models`)列出可用模型,再传 model。'
936
+ }
937
+ if (/quota|额度|exhausted|insufficient|credit|balance/i.test(hay)) {
938
+ return '[诊断] opencode 额度可能耗尽:换一个(优先 -free)模型,或改用原生工具完成本任务。'
939
+ }
940
+ return ''
941
+ },
942
+
943
+ isSuccessStatus(st) { return st === 'SUCCESS' },
944
+
945
+ tools: {
946
+ 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 },
947
+ 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 },
948
+ 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 }
949
+ },
950
+
951
+ // opencode_models:宿主有 spawn 能力时注册(preset 注入 deps.process / MCP 注入
952
+ // deps.nodeChild;dynamic 沙箱形态省略)。
953
+ extraTools: (deps.process || deps.nodeChild) ? [{
954
+ name: 'opencode_models',
955
+ description: MODELS_DESCRIPTION,
956
+ inputSchema: MODELS_PARAMS,
957
+ render: renderModels,
958
+ async logic(args) {
959
+ return await descriptor.listModels(args || {})
960
+ }
961
+ }] : [],
962
+
963
+ /**
964
+ * 列出可用模型(三形态共用)。真实执行 `opencode models`;
965
+ * CLI 缺失/未登录 → { ok:false, error }(绝不凭空造列表)。
966
+ */
967
+ async listModels(args) {
968
+ const a = args || {}
969
+ const child = deps.nodeChild
970
+ if (!child || typeof child.spawn !== 'function') {
971
+ // preset 形态:宿主 subprocess(attach 后可用)。
972
+ if (!(host && host.subprocess)) return { ok: false, error: 'no spawn capability in this host form' }
973
+ }
974
+ const prefix = resolveExePrefix(env, currentSettings().binPath)
975
+ const argv = prefix.slice(1).concat(['models'])
976
+ const run = child && typeof child.spawn === 'function'
977
+ ? spawnModelsNode(child, prefix[0], argv)
978
+ : spawnModelsHost(argv)
979
+ let res
980
+ try { res = await run } catch (e) { return { ok: false, error: String(e && e.message || e) } }
981
+ if (!res.ok) return res
982
+ let list = res.models
983
+ if (a.provider) {
984
+ const pv = String(a.provider).toLowerCase()
985
+ list = list.filter((m) => String(m.provider).toLowerCase() === pv)
986
+ }
987
+ if (a.freeOnly) list = list.filter((m) => m.free)
988
+ // 免费模型优先展示(用户要求:优先用性能较好的免费模型),其次按字母序。
989
+ list.sort((x, y) => (x.free === y.free ? String(x.id).localeCompare(String(y.id)) : (x.free ? -1 : 1)))
990
+ return { ok: true, models: list, count: list.length }
991
+ },
992
+
993
+ // 设置分区:用户可选「用哪个 opencode(exe 路径)」+「默认模型」+「默认 agent」。
994
+ settings: {
995
+ keys: ['binPath', 'defaultModel', 'defaultAgent'],
996
+ defaults: () => ({ binPath: '', defaultModel: '', defaultAgent: '' }),
997
+ normalize: (raw) => {
998
+ const r = raw && typeof raw === 'object' ? raw : {}
999
+ const out = { binPath: '', defaultModel: '', defaultAgent: '' }
1000
+ for (const k of ['binPath', 'defaultModel', 'defaultAgent']) {
1001
+ if (typeof r[k] === 'string') out[k] = String(r[k]).trim()
1002
+ }
1003
+ return out
1004
+ },
1005
+ meta: (env2) => {
1006
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
1007
+ const s = currentSettings()
1008
+ // 下拉选项:实时 `opencode models`(失败则退化为空 → 面板仍可自由输入)。
1009
+ const models = fetchModelsSync(e, s.binPath, 8000)
1010
+ const options = models.map((m) => ({ value: m.id, label: m.id + (m.free ? ' [free]' : '') }))
1011
+ // 默认给「可用 exe 路径」的下拉候选(env 覆盖 > 桌面版探测)。
1012
+ const exeCandidates = []
1013
+ if (e.OPENCODE_BIN || e.OPENCODE_CLI) exeCandidates.push(String(e.OPENCODE_BIN || e.OPENCODE_CLI))
1014
+ for (const p of candidateExePaths(e)) if (exeCandidates.indexOf(p) < 0) exeCandidates.push(p)
1015
+ return {
1016
+ titleSuffix: 'OpenCode',
1017
+ fields: [
1018
+ {
1019
+ key: 'binPath', label: 'opencode 可执行文件路径', type: 'select', allowCustom: true,
1020
+ options: exeCandidates.map((p) => ({ value: p, label: p })),
1021
+ placeholder: '留空 = 自动探测桌面版 / PATH',
1022
+ note: '检测到 ' + exeCandidates.length + ' 个候选;也可手动粘贴任意路径(含 .mjs 会经 node 启动)。'
1023
+ },
1024
+ {
1025
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true,
1026
+ options: options,
1027
+ placeholder: '留空 = 由 opencode 自身配置决定',
1028
+ note: options.length
1029
+ ? '共 ' + options.length + ' 个可用模型,免费模型已排在前面([free])。调用时传 model 可覆盖本项。'
1030
+ : '未能读取模型列表(CLI 未安装/未登录/超时)—— 仍可手动输入 provider/model。'
1031
+ },
1032
+ {
1033
+ key: 'defaultAgent', label: '默认 agent', type: 'select', allowCustom: true,
1034
+ options: [{ value: 'build', label: 'build(默认,全权限)' }, { value: 'plan', label: 'plan(只读)' }],
1035
+ placeholder: '留空 = opencode 默认 agent',
1036
+ note: 'opencode 只接受 primary agent;subagent 名会被 opencode 自身拒绝并回退。'
1037
+ }
1038
+ ]
1039
+ }
1040
+ },
1041
+ diagnose: (settings, env2) => {
1042
+ const s = settings && typeof settings === 'object' ? settings : {}
1043
+ const e = env2 && typeof env2 === 'object' ? env2 : {}
1044
+ const bits = []
1045
+ const found = candidateExePaths(e)
1046
+ if (s.binPath) bits.push('bin=设置:' + s.binPath)
1047
+ else if (e.OPENCODE_BIN || e.OPENCODE_CLI) bits.push('bin=env:' + (e.OPENCODE_BIN || e.OPENCODE_CLI))
1048
+ else if (found.length) bits.push('bin=桌面版:' + found[0].split(/[\\/]/).slice(-3).join('/'))
1049
+ else bits.push('bin=PATH:opencode-cli')
1050
+ bits.push(s.defaultModel ? 'model=' + s.defaultModel : 'model=(opencode 自决)')
1051
+ if (s.defaultAgent) bits.push('agent=' + s.defaultAgent)
1052
+ return bits.join(' · ')
1053
+ }
1054
+ },
1055
+
1056
+ mcp: { version: '0.2.2' }
1057
+ }
1058
+
1059
+ // MCP/测试形态:真 child_process。
1060
+ function spawnModelsNode(child, exe, argv) {
1061
+ return new Promise((resolve) => {
1062
+ let c
1063
+ try { c = child.spawn(exe, argv, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true }) }
1064
+ catch (e) { resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }); return }
1065
+ let out = ''
1066
+ let err = ''
1067
+ const timer = setTimeout(() => { try { c.kill() } catch (e) {} }, 15000)
1068
+ c.stdout.on('data', (d) => { out += d })
1069
+ c.stderr.on('data', (d) => { err += d })
1070
+ c.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: 'spawn: ' + String(e && e.message || e) }) })
1071
+ c.on('close', (code) => {
1072
+ clearTimeout(timer)
1073
+ if (code !== 0) { resolve({ ok: false, error: '`opencode models` exited ' + code + ': ' + String(err || out).slice(0, 300) }); return }
1074
+ const list = parseModelList(out)
1075
+ if (!list.length) { resolve({ ok: false, error: 'no models parsed from output: ' + String(out).slice(0, 200) }); return }
1076
+ resolve({ ok: true, models: list })
1077
+ })
1078
+ })
1079
+ }
1080
+
1081
+ // preset 形态:DSH subprocess。
1082
+ async function spawnModelsHost(argv) {
1083
+ try {
1084
+ const spec = { argv: [resolveExePrefix(env, currentSettings().binPath)[0]].concat(argv), stdio: { stdin: 'ignore', stdout: { maxBytes: 1000000 }, stderr: { maxBytes: 200000 } }, graceMs: 5000 }
1085
+ if (deps.process && typeof deps.process.cwd === 'function') spec.cwd = deps.process.cwd()
1086
+ const handle = host.subprocess.spawn(spec)
1087
+ const outcome = await handle.done
1088
+ const stdoutText = handle.collected && handle.collected.stdout ? handle.collected.stdout.readFrom(0).text : ''
1089
+ const stderrText = handle.collected && handle.collected.stderr ? handle.collected.stderr.readFrom(0).text : ''
1090
+ if (!outcome || outcome.exitCode !== 0) return { ok: false, error: '`opencode models` exited ' + (outcome && outcome.exitCode) + ': ' + String(stderrText || stdoutText).slice(0, 300) }
1091
+ const list = parseModelList(stdoutText)
1092
+ if (!list.length) return { ok: false, error: 'no models parsed from output: ' + String(stdoutText).slice(0, 200) }
1093
+ return { ok: true, models: list }
1094
+ } catch (e) { return { ok: false, error: String(e && e.message || e) } }
1095
+ }
1096
+
1097
+ descriptor.runToolLogic = async function (args, exec) {
1098
+ const a = args || {}
1099
+ const normalized = a.background === undefined ? Object.assign({}, a, { background: true }) : a
1100
+ return this.runner.coreExecute(normalized, exec)
1101
+ }
1102
+ descriptor.continueToolLogic = async function (args, exec) {
1103
+ const a = args || {}
1104
+ const mapped = {
1105
+ prompt: a.prompt, model: a.model, agent: a.agent,
1106
+ cwd: a.cwd, files: a.files, timeoutSec: a.timeoutSec, autoApprove: a.autoApprove,
1107
+ background: a.background === undefined ? true : a.background
1108
+ }
1109
+ const sid = a.sessionId || null
1110
+ if (sid) mapped.sessionId = sid
1111
+ else if (a.latest) mapped.continueLatest = true
1112
+ return this.runner.coreExecute(mapped, exec)
1113
+ }
1114
+ descriptor.statusToolLogic = function (args) {
1115
+ const a = args || {}
1116
+ const snap = this.engine.statusSnapshot()
1117
+ if (a.cwd) {
1118
+ const key = String(a.cwd)
1119
+ snap.projects = snap.projects.filter((p) => p.cwd === key)
1120
+ const g = snap.projects[0]
1121
+ if (g) {
1122
+ Object.assign(snap, {
1123
+ state: g.state, running: g.running, current: g.current, trail: g.trail,
1124
+ lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId,
1125
+ lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt
1126
+ })
1127
+ }
1128
+ }
1129
+ return snap
1130
+ }
1131
+
1132
+ descriptor.attach = function (hostOpts) {
1133
+ host = hostOpts || {}
1134
+ // 宿主注入 getSettings 时才能把面板偏好带进 buildArgv(preset/dynamic 形态)。
1135
+ try {
1136
+ if (typeof host.getSettings === 'function') {
1137
+ const s = host.getSettings('opencode')
1138
+ if (s && typeof s === 'object') settingsRef = descriptor.settings.normalize(s)
1139
+ }
1140
+ } catch (e) { }
1141
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
1142
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
1143
+ this.runner = runner
1144
+ return runner
1145
+ }
1146
+ return descriptor
1147
+ }
1192
1148
 
1193
1149
  // core/scheduling.mjs — CLI 调度(启用集合 + 调用优先级)单源纯逻辑。
1194
1150
  //