@luchenglong/cli-bridge 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ // dynamic/opencode.host.template.mjs — opencode 动态沙箱宿主模板(cordis_define code.host 源)。
2
+ //
3
+ // 构建(node scripts/build.mjs --only=opencode)把 core/bridge-kit.mjs 与
4
+ // providers/opencode.mjs 分别内联进下方两个占位标记行(各占一行、行内仅此标记),
5
+ // 生成 dynamic/opencode.host.js。注意:标记字面量绝不能出现在本注释里 —— 构建做全局
6
+ // 替换,注释中出现同样会被替换成正文代码而炸掉语法。
7
+ // 沙箱纪律(旧仓 dynamic/host.js 头注 verbatim 精神):
8
+ // - 禁 import/require、无 TypeScript;无 AbortController/process 裸引用/Buffer/原生
9
+ // 定时器 —— process 只经 typeof 守卫探测;宿主能力全部来自注入的 harness.*/ctx。
10
+ // - 顶层 return { inject, apply } 为动态宿主约定形态(生成物是 .js/CJS 包装,顶层
11
+ // return 合法;本模板文件是 .mjs,不要直接 node --check 模板本身,只 check 生成物)。
12
+ // - 无 ctx.emit:状态经 ctx.get('cliBridgeCollector').mergeSnapshot('opencode', snap)
13
+ // 推给家级灯;动态形态不宣告 mode(旧语义:普通模式灯仅在调用时临时显示)。
14
+ /*__KIT__*/
15
+ /*__PROVIDER__*/
16
+ /*__SCHED__*/
17
+
18
+ return {
19
+ inject: ['tools', 'subprocess', 'systemPrompt', 'timer'],
20
+ apply(ctx) {
21
+ // 调度门禁(0.2.0):设置面板关掉 opencode → 本形态不注册工具/政策段;fail-open。
22
+ if (!isBridgeEnabled('opencode', SCHED_ALL_IDS)) return
23
+ const subprocess = ctx.subprocess
24
+ const sandboxPolicy = ctx.get('sandboxPolicy')
25
+ // 沙箱可能运行在无 process 的环境:typeof 守卫读 env(旧仓 dynamic 的等价面)。
26
+ const env = (typeof process !== 'undefined' && process.env) ? process.env : {}
27
+
28
+ const provider = defineProvider({ env })
29
+
30
+ function publish(snapshot) {
31
+ try {
32
+ const collector = ctx.get('cliBridgeCollector')
33
+ if (collector && typeof collector.mergeSnapshot === 'function') { collector.mergeSnapshot('opencode', snapshot); return }
34
+ } catch (e) { /* fall through to legacy alias */ }
35
+ try {
36
+ const legacy = ctx.get('opencodeCollector')
37
+ if (legacy && typeof legacy.mergeSnapshot === 'function') legacy.mergeSnapshot(snapshot)
38
+ } catch (e) { /* 灯数据尽力而为 */ }
39
+ }
40
+
41
+ // exe 优先级(与描述符同一套):env OPENCODE_BIN/OPENCODE_CLI > 桌面版 V2 探测
42
+ // > PATH 查找 opencode-cli(subprocess.resolveExecutable)。
43
+ // 二进制名 opencode-cli(V2 桌面版),不做 opencode.exe 兜底(V1/V2 不能并存)。
44
+ const exeCandidates = resolveExePrefix(env, '')
45
+ async function resolveExe(backend, signal) {
46
+ for (const c of exeCandidates) {
47
+ if (/\.(mjs|cjs|js)$/i.test(c) && typeof process !== 'undefined' && process.execPath) return [process.execPath, c]
48
+ return c
49
+ }
50
+ return await subprocess.resolveExecutable('opencode-cli', undefined, signal)
51
+ }
52
+
53
+ // cwd 兜底:OPENCODE_MCP_CWD > sandboxPolicy.workspaceRoot > process.cwd() > '.'。
54
+ function getCwdFallback() {
55
+ if (env.OPENCODE_MCP_CWD) return String(env.OPENCODE_MCP_CWD)
56
+ if (sandboxPolicy && typeof sandboxPolicy.workspaceRoot === 'string' && sandboxPolicy.workspaceRoot) return sandboxPolicy.workspaceRoot
57
+ if (typeof process !== 'undefined' && typeof process.cwd === 'function') { try { return process.cwd() } catch (e) {} }
58
+ return '.'
59
+ }
60
+
61
+ provider.attach({ ctx, subprocess, resolveExe, getCwdFallback, publish })
62
+
63
+ const OUTPUT_SCHEMA = { type: 'object', additionalProperties: true }
64
+
65
+ harness.registerTool(ctx, harness.defineTool({
66
+ name: provider.tools.run.name,
67
+ description: provider.tools.run.description,
68
+ parameters: provider.tools.run.inputSchema,
69
+ output: { schema: OUTPUT_SCHEMA, render: function (args, value) { return renderResult(value, provider) } },
70
+ execute: function (args, exec) { return provider.runToolLogic(args, exec) }
71
+ }))
72
+ harness.registerTool(ctx, harness.defineTool({
73
+ name: provider.tools.continue.name,
74
+ description: provider.tools.continue.description,
75
+ parameters: provider.tools.continue.inputSchema,
76
+ output: { schema: OUTPUT_SCHEMA, render: function (args, value) { return renderResult(value, provider) } },
77
+ execute: function (args, exec) { return provider.continueToolLogic(args, exec) }
78
+ }))
79
+ harness.registerTool(ctx, harness.defineTool({
80
+ name: provider.tools.status.name,
81
+ description: provider.tools.status.description,
82
+ parameters: provider.tools.status.inputSchema,
83
+ output: { schema: OUTPUT_SCHEMA, render: function (args, value) { return renderStatus(value, provider) } },
84
+ execute: function (args) { return provider.statusToolLogic(args) }
85
+ }))
86
+
87
+ // 浏览器指示灯轮询的 RPC 面(旧 dynamic/handle('<id>_status') verbatim 语义)。
88
+ harness.handle('opencode_status', function () { return provider.statusToolLogic({}) })
89
+
90
+ const policyText = [
91
+ 'opencode-first execution policy (local opencode CLI bridge).',
92
+ '',
93
+ 'Local agent CLI "opencode" handles coding tasks under full DSH control (permissions auto-approved, never blocks on a prompt). By default, opencode runs in the background and returns a jobId immediately; collect results via job_output and watch live progress via opencode_status anytime.',
94
+ '',
95
+ 'Decision table for tool selection:',
96
+ '- Single read/glob/grep or short (<30s) command -> Native tools.',
97
+ '- Implementing, editing, refactoring, debugging, builds, multi-file investigation -> opencode_run.',
98
+ '- Follow-ups on the same topic -> opencode_continue (with latest=true or sessionId; opencode preserves session context).',
99
+ '- Final build/test verification of opencode output -> Native tools.',
100
+ '',
101
+ 'Context protocol (one topic = one opencode session):',
102
+ '- First dispatch on a topic: provide the task with a compact CONTEXT preamble (point to paths, do not paste file contents):',
103
+ ' CONTEXT: 2-6 lines — goal; repo root; key paths; decisions/constraints; current state.',
104
+ ' TASK: the complete instruction.',
105
+ '- Follow-ups: call opencode_continue and state only what is new.',
106
+ '',
107
+ 'Execution & Fallback protocol:',
108
+ '- Dispatch defaults to background=true (set background=false only to block). Collect via job_output.',
109
+ '- On rate-limit or network failure, a confirmation dialog opens in BOTH foreground and background while in flight.',
110
+ '- If result has fallback=true (status FALLBACK_TO_DSH), the user chose DSH-local: finish with native tools and NEVER call opencode again for this task.',
111
+ '- Never loop opencode calls; never ask opencode to call back into DSH.',
112
+ '',
113
+ 'Model & credentials:',
114
+ '- Prefer a free model for routine work: pass a model id ending in -free (e.g. "opencode/nemotron-3-ultra-free") unless this task genuinely needs a frontier model.',
115
+ '- Omit the model unless you have a reason: opencode then uses its own configured default (or the one chosen in CLI Bridge settings). Pass model in provider/model form to override.',
116
+ '- Credentials are owned by opencode, not by this bridge: auth/API-key failures mean the user should run `opencode auth login`. Do not retry in a loop.'
117
+ ].join('\n')
118
+
119
+ ctx.systemPrompt.section({
120
+ name: 'opencode:policy',
121
+ order: (typeof ctx.systemPrompt.getSectionOrder === 'function' ? ctx.systemPrompt.getSectionOrder('TOOL_SUBAGENT') : 2800) + 10,
122
+ text: policyText
123
+ })
124
+ }
125
+ }
@@ -30,7 +30,17 @@ import { settingsView, parseSettingsBody, readSettingsFile, writeSettingsFile, S
30
30
  import { declareBridgePresets } from './preset-declarations.mjs'
31
31
 
32
32
  export const PRESET_TTL_MS = 75000
33
+ /** 运行中/仍在活动的项目的新鲜期(防抖:短暂停顿不该让灯闪)。 */
33
34
  export const PROJECT_TTL_MS = 10 * 60 * 1000
35
+ /**
36
+ * 已完成(running=0 且已有 lastStatus)项目的新鲜期。
37
+ *
38
+ * 0.2.1 用单一 10 分钟 TTL 修「一次失败后灯永久挂着」—— 但 10 分钟对于「刚跑完、
39
+ * 想看到灯灭」来说太长:任务结束后灯要挂满 10 分钟才消失,用户感知是「灯不灭」。
40
+ * 区分两态:运行中(含短暂间隔)保持长 TTL 防抖;已收口的项目走短 TTL 快速淡出。
41
+ * 淡出只影响 pill 渲染(stale 项目仍在弹窗里作历史),不丢数据。
42
+ */
43
+ export const PROJECT_DONE_TTL_MS = 60 * 1000
34
44
  export const MAX_PROJECTS = 24
35
45
  export const MAX_SESSIONS = 64
36
46
 
@@ -50,6 +60,11 @@ export function createIndicatorState(opts) {
50
60
  const now = typeof o.now === 'function' ? o.now : Date.now
51
61
  const ttlMs = o.ttlMs != null ? o.ttlMs : PRESET_TTL_MS
52
62
  const projectTtlMs = o.projectTtlMs != null ? o.projectTtlMs : PROJECT_TTL_MS
63
+ // doneTtlMs 缺省跟随 projectTtlMs(显式传 projectTtlMs 的测试/调用方同时支配两态,
64
+ // 否则「传短 TTL 却不生效」会静默坑人);只有走生产默认值时才取更短的
65
+ // PROJECT_DONE_TTL_MS(已完成项目快速淡出)。
66
+ const doneTtlMs = o.doneTtlMs != null ? o.doneTtlMs
67
+ : (o.projectTtlMs != null ? projectTtlMs : PROJECT_DONE_TTL_MS)
53
68
  const staleMs = o.staleMs != null ? o.staleMs : MCP_BRIDGE_STALE_MS
54
69
  const ids = Array.isArray(o.ids) && o.ids.length ? o.ids.slice() : PROVIDER_IDS.slice()
55
70
  const listPresetSessions = typeof o.listPresetSessions === 'function' ? o.listPresetSessions : null
@@ -183,7 +198,11 @@ export function createIndicatorState(opts) {
183
198
  const isStale = (p) => {
184
199
  if (p.running > 0) return false
185
200
  const at = Number(p.updatedAt) || Number(p.lastAt) || 0
186
- return !!at && (t - at) > projectTtlMs
201
+ if (!at) return false
202
+ // 已收口(有终态)的项目走短 TTL → 完成后快速淡出;
203
+ // 仍无终态的(长时间运行中的间隔、或从未跑完)保持长 TTL 防抖。
204
+ const ttl = p.lastStatus ? doneTtlMs : projectTtlMs
205
+ return (t - at) > ttl
187
206
  }
188
207
  // 顶层聚合只看新鲜(未 stale)项目:陈旧历史不再决定灯色(0.2.1 修复「指示灯长期
189
208
  // 存在」的服务端半边 —— 客户端半边在 pill 过滤;无新鲜项目时顶层回落 idle)。
@@ -25,7 +25,7 @@ export const PKG_NAME = '@luchenglong/cli-bridge'
25
25
 
26
26
  // preset 目录名映射(与 scripts/build.mjs 的 PRESET_DIRS 一致;目录名带 -first 后缀是
27
27
  // 三个旧包时代的遗留布局,provider id 不带 —— 这里不映射就永远找不到 plugin-list)。
28
- const PRESET_DIRS = { agy: 'agy-first', codebuddy: 'codebuddy-first', mimo: 'mimo-first' }
28
+ const PRESET_DIRS = { agy: 'agy-first', codebuddy: 'codebuddy-first', mimo: 'mimo-first', opencode: 'opencode-first' }
29
29
 
30
30
  const HERE = dirname(fileURLToPath(import.meta.url))
31
31
  const ROOT = join(HERE, '..', '..', '..')
@@ -28,12 +28,13 @@ import { resolveScheduling } from '../core/scheduling.mjs'
28
28
  import * as agyMcp from './providers/agy.mjs'
29
29
  import * as codebuddyMcp from './providers/codebuddy.mjs'
30
30
  import * as mimoMcp from './providers/mimo.mjs'
31
+ import * as opencodeMcp from './providers/opencode.mjs'
31
32
 
32
33
  const SERVER_NAME = 'cli-bridge-mcp'
33
- const SERVER_VERSION = '0.2.2'
34
+ const SERVER_VERSION = '0.2.4'
34
35
  const PROTOCOL = '2024-11-05'
35
36
 
36
- const PROVIDERS = [agyMcp, codebuddyMcp, mimoMcp]
37
+ const PROVIDERS = [agyMcp, codebuddyMcp, mimoMcp, opencodeMcp]
37
38
 
38
39
  function detectHomeDir() {
39
40
  if (process.env.DSH_HOME) return process.env.DSH_HOME
@@ -18,8 +18,9 @@ import { fileURLToPath } from 'node:url'
18
18
 
19
19
  import defineProvider from '../../providers/agy.mjs'
20
20
  import { createStatusEngine, createLineStream, buildMcpBridgePayload, isLimited, renderStatus } from '../../core/bridge-kit.mjs'
21
+ import { packageVersion } from '../version.mjs'
21
22
 
22
- export const meta = { id: 'agy', label: 'AGY', version: '0.2.2' }
23
+ export const meta = { id: 'agy', label: 'AGY', version: packageVersion() }
23
24
 
24
25
  const QUOTA_SCRIPT_DEFAULT = fileURLToPath(new URL('../../bin/agy-quota.mjs', import.meta.url))
25
26
 
@@ -24,8 +24,9 @@ import { resolve as resolvePath, join as nodePathJoin } from 'node:path'
24
24
 
25
25
  import defineProvider from '../../providers/codebuddy.mjs'
26
26
  import { createStatusEngine, createLineStream, buildMcpBridgePayload, mcpBridgeFileName } from '../../core/bridge-kit.mjs'
27
+ import { packageVersion } from '../version.mjs'
27
28
 
28
- export const meta = { id: 'codebuddy', label: 'CODEBUDDY', version: '0.2.2' }
29
+ export const meta = { id: 'codebuddy', label: 'CODEBUDDY', version: packageVersion() }
29
30
 
30
31
  const provider = defineProvider({
31
32
  env: process.env,
@@ -26,8 +26,9 @@ import {
26
26
  createStatusEngine, createLineStream, buildMcpBridgePayload,
27
27
  fallbackResult, shortLabel, renderStatus
28
28
  } from '../../core/bridge-kit.mjs'
29
+ import { packageVersion } from '../version.mjs'
29
30
 
30
- export const meta = { id: 'mimo', label: 'MIMO', version: '0.2.2' }
31
+ export const meta = { id: 'mimo', label: 'MIMO', version: packageVersion() }
31
32
 
32
33
  const BACKEND_DESKTOP = 'mimo-desktop'
33
34
  const SETTINGS_FILE_NAME = 'cli-bridge-settings.json'
@@ -0,0 +1,237 @@
1
+ // mcp/providers/opencode.mjs — opencode MCP 工具面(契约 §4)。
2
+ // framing/生命周期归 keystone 统一服务器 mcp/cli-bridge-mcp.mjs。
3
+ //
4
+ // 与 agy 面的结构同构(旧 MCP 语义保持):直接 spawn opencode(.exe)(win32 用
5
+ // opencode.exe;OPENCODE_BIN 覆盖;.js/.mjs 目标经 process.execPath 包装,供测试
6
+ // fixture 使用)。无 ctx.emit:状态走快照文件 {homeDir}/cli-bridge-mcp-opencode.json
7
+ // (bridge-kit buildMcpBridgePayload + 原子写 tmp→rename;写失败静默)。
8
+ //
9
+ // opencode 无 quota/额度门禁(凭据与额度由 opencode 自身与 provider 决定),
10
+ // 因此本面只有三件套。
11
+ import { spawn as nodeSpawn } from 'node:child_process'
12
+ import { resolve as resolvePath } from 'node:path'
13
+
14
+ import defineProvider, { resolveExePrefix } from '../../providers/opencode.mjs'
15
+ import { createStatusEngine, createLineStream, buildMcpBridgePayload, isLimited, renderStatus } from '../../core/bridge-kit.mjs'
16
+ import { packageVersion } from '../version.mjs'
17
+
18
+ export const meta = { id: 'opencode', label: 'OPENCODE', version: packageVersion() }
19
+
20
+ const provider = defineProvider({
21
+ env: process.env,
22
+ process,
23
+ nodeChild: { spawn: nodeSpawn }
24
+ })
25
+
26
+ let lastIo = null
27
+ function publishSnapshot(snapshot) {
28
+ const io = lastIo
29
+ if (!io) return
30
+ try {
31
+ const target = io.path.join(io.homeDir, 'cli-bridge-mcp-opencode.json')
32
+ const payload = buildMcpBridgePayload(snapshot, process.pid, Date.now())
33
+ const tmp = target + '.' + process.pid + '.tmp'
34
+ try { io.fs.mkdirSync(io.path.dirname(target), { recursive: true }) } catch (e) {}
35
+ io.fs.writeFileSync(tmp, JSON.stringify(payload), 'utf8')
36
+ io.fs.renameSync(tmp, target)
37
+ } catch (e) { /* 灯数据尽力而为,绝不影响工具调用 */ }
38
+ }
39
+ // provider.engine 在 attach 后才存在;MCP 形态不 attach,用本模块的 engine。
40
+ const engine = createStatusEngine({ provider, publish: publishSnapshot })
41
+ provider.engine = engine
42
+
43
+ // ── exe / cwd 解析 ────────────────────────────────────────────────────────────
44
+ // 与描述符同一套优先级(env > 桌面版探测 > PATH 名字);二进制名 opencode-cli.exe
45
+ // (V2 桌面版),不做 opencode.exe 兜底以免误命中不能并存的另一个版本。
46
+ function exePrefix() {
47
+ return resolveExePrefix(process.env, '')
48
+ }
49
+ function resolveCwd(a) {
50
+ if (a && a.cwd) return resolvePath(String(a.cwd))
51
+ return process.env.OPENCODE_MCP_CWD || process.cwd()
52
+ }
53
+
54
+ // ── spawn(实时折叠走 bridge-kit 行流)────────────────────────────────────────
55
+ function runOpencode(args) {
56
+ return new Promise((resolve) => {
57
+ const built = provider.buildArgv(exePrefix(), args, { planActive: false, defaultMode: 'auto' })
58
+ const cwd = resolveCwd(args)
59
+ let child
60
+ try {
61
+ child = nodeSpawn(built.argv[0], built.argv.slice(1), { cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true })
62
+ } catch (e) {
63
+ resolve({ ok: false, status: 'SPAWN_ERROR', response: '', sessionId: null, durationSeconds: null, numTurns: null, totalTokens: null, exitCode: null, mode: built.mode, backend: null, stderr: String(e && e.message || e) })
64
+ return
65
+ }
66
+ engine.begin(cwd)
67
+ let out = ''
68
+ let err = ''
69
+ let killed = false
70
+ const timer = setTimeout(() => { killed = true; try { child.kill() } catch (e) {} }, (built.timeoutSec + 60) * 1000)
71
+ const stream = createLineStream((ln) => {
72
+ const t = ln.trim()
73
+ if (!t.startsWith('{')) return
74
+ try { engine.foldEvent(JSON.parse(t), cwd) } catch (e) {}
75
+ })
76
+ child.stdout.on('data', (d) => {
77
+ out += d
78
+ if (out.length > 4000000) out = out.slice(-2000000)
79
+ stream.pushChunk(String(d))
80
+ })
81
+ child.stderr.on('data', (d) => { err += d; if (err.length > 1000000) err = err.slice(-500000) })
82
+ child.on('error', (e) => {
83
+ clearTimeout(timer)
84
+ stream.flush()
85
+ const res = { ok: false, status: 'OPENCODE_UNAVAILABLE', response: '', sessionId: null, durationSeconds: null, numTurns: null, totalTokens: null, exitCode: null, mode: built.mode, backend: null, stderr: 'opencode spawn failed: ' + String(e && e.message || e) }
86
+ engine.end(res, cwd)
87
+ resolve(res)
88
+ })
89
+ child.on('close', (code) => {
90
+ clearTimeout(timer)
91
+ stream.flush()
92
+ const outcome = { exitCode: killed ? 124 : code }
93
+ let res = provider.buildResult(provider.parseJson(out), outcome, built.mode, err, out, null)
94
+ if (killed && !res.ok) {
95
+ res.status = 'HUNG_TIMEOUT'
96
+ res.stderr = (res.stderr ? res.stderr + ' ' : '') + '[killed by DSH timeout guard after ' + built.timeoutSec + 's; if this was a long-running script (build/test) raise timeoutSec]'
97
+ }
98
+ engine.end(res, cwd)
99
+ resolve(res)
100
+ })
101
+ })
102
+ }
103
+
104
+ function textResult(res) {
105
+ if (res.fallback) {
106
+ return 'opencode unavailable (' + res.reason + '). Use native tools / the local model for this task; do not retry opencode.'
107
+ }
108
+ const limited = !res.ok && isLimited(res)
109
+ const head = 'opencode ' + (res.ok ? 'OK' : 'FAILED') + ' [status=' + res.status +
110
+ (res.sessionId ? ' session=' + res.sessionId : '') +
111
+ (res.durationSeconds != null ? ' ' + res.durationSeconds + 's' : '') + ']'
112
+ let note = ''
113
+ if (limited) note = '\n\n[Note: this looks like a rate-limit / network failure. Do NOT retry opencode in a loop; finish the task with your own tools, or ask the user.]'
114
+ const body = res.response || (res.stderr ? '[stderr] ' + res.stderr : (res.rawStdout ? '[raw] ' + res.rawStdout : ''))
115
+ return head + (body ? '\n\n' + body : '') + note
116
+ }
117
+
118
+ // ── 工具面 ────────────────────────────────────────────────────────────────────
119
+ const TOOLS = [
120
+ {
121
+ name: 'opencode_run',
122
+ description: 'Dispatch a coding/build/debug/investigation task to the local opencode agent CLI and return its final answer. opencode runs fully non-interactively (permissions auto-approved, never blocks on a prompt). Prefer it for implementation, multi-file edits, refactors and debugging; use your own tools for quick read-only lookups and final build/test verification. While it runs, call opencode_status to watch what opencode is doing live.',
123
+ inputSchema: {
124
+ type: 'object',
125
+ properties: {
126
+ 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).' },
127
+ model: { type: 'string', description: 'Optional model in provider/model form (e.g. "anthropic/claude-sonnet-4-20250514"). Omit to let opencode use its own configured default.' },
128
+ agent: { type: 'string', description: 'Optional opencode agent (subagent) name.' },
129
+ variant: { type: 'string', description: 'Optional provider-specific reasoning variant (e.g. high, max, minimal).' },
130
+ cwd: { type: 'string', description: 'Working directory for opencode (default: OPENCODE_MCP_CWD or the DSH workspace).' },
131
+ files: { type: 'array', items: { type: 'string' }, description: 'Optional file paths to attach to the message.' },
132
+ title: { type: 'string', description: 'Optional session title.' },
133
+ timeoutSec: { type: 'integer', description: '10-3600, default 600.' },
134
+ autoApprove: { type: 'boolean', description: 'Default true: pass --auto so opencode never blocks on a permission prompt. Set false to require explicit approval.' }
135
+ },
136
+ required: ['prompt']
137
+ }
138
+ },
139
+ {
140
+ name: 'opencode_continue',
141
+ 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 for the most recent session.',
142
+ inputSchema: {
143
+ type: 'object',
144
+ properties: {
145
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing opencode session. State only what is new; opencode preserves its session context.' },
146
+ sessionId: { type: 'string' },
147
+ latest: { type: 'boolean', description: 'Continue the most recent opencode session.' },
148
+ model: { type: 'string' },
149
+ agent: { type: 'string' },
150
+ variant: { type: 'string' },
151
+ cwd: { type: 'string' },
152
+ files: { type: 'array', items: { type: 'string' } },
153
+ timeoutSec: { type: 'integer', description: '10-3600, default 600.' },
154
+ autoApprove: { type: 'boolean' }
155
+ },
156
+ required: ['prompt']
157
+ }
158
+ },
159
+ {
160
+ name: 'opencode_status',
161
+ 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.',
162
+ inputSchema: { type: 'object', properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
163
+ },
164
+ {
165
+ name: 'opencode_models',
166
+ description: 'List the models available to the local opencode CLI (from `opencode models`). Use it 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 invents a model list.',
167
+ inputSchema: {
168
+ type: 'object',
169
+ properties: {
170
+ freeOnly: { type: 'boolean', description: 'Return only free models (id ends with -free).' },
171
+ provider: { type: 'string', description: 'Optional provider filter, e.g. "opencode" or "opencode-go".' }
172
+ }
173
+ }
174
+ }
175
+ ]
176
+
177
+ export function tools(env) {
178
+ return TOOLS.map((t) => Object.assign({}, t))
179
+ }
180
+
181
+ export async function call(name, args, io) {
182
+ if (io) lastIo = io
183
+ if (!lastIo) return 'opencode error: MCP io not initialized'
184
+ const a = args || {}
185
+ if (name === 'opencode_status') {
186
+ const snap = engine.statusSnapshot()
187
+ if (a.cwd) {
188
+ snap.projects = snap.projects.filter((p) => p.cwd === String(a.cwd))
189
+ const g = snap.projects[0]
190
+ if (g) Object.assign(snap, { state: g.state, running: g.running, current: g.current, trail: g.trail, lastStatus: g.lastStatus, lastAt: g.lastAt, lastSessionId: g.lastSessionId, lastBackend: g.lastBackend, fallbackActive: g.fallbackActive, updatedAt: g.updatedAt })
191
+ }
192
+ return renderStatus(snap, provider)[0].text
193
+ }
194
+ if (name === 'opencode_models') {
195
+ const res = await provider.listModels(a)
196
+ if (!res.ok) return 'opencode_models failed: ' + String(res.error || 'unknown')
197
+ const list = res.models || []
198
+ if (!list.length) return 'opencode_models: no models matched'
199
+ const lines = ['opencode models (' + list.length + '):']
200
+ for (const m of list.slice(0, 40)) lines.push(' ' + m.id + (m.free ? ' [free]' : ''))
201
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
202
+ const free = list.filter((m) => m.free).length
203
+ lines.push('free: ' + free + ' / ' + list.length)
204
+ if (a.freeOnly && !free) lines.push('(no free models under this filter)')
205
+ return lines.join('\n')
206
+ }
207
+ if (!a.prompt || !String(a.prompt).trim()) return 'opencode error: prompt is required'
208
+ const mapped = Object.assign({}, a)
209
+ if (name === 'opencode_continue') {
210
+ if (!mapped.sessionId && mapped.latest) mapped.continueLatest = true
211
+ }
212
+ const res = await runOpencode(mapped)
213
+ return textResult(res)
214
+ }
215
+
216
+ export function check(env) {
217
+ const ts = tools(env)
218
+ const names = ts.map((t) => t.name)
219
+ for (const req of ['opencode_run', 'opencode_continue', 'opencode_status', 'opencode_models']) {
220
+ if (!names.includes(req)) throw new Error('opencode mcp: missing tool ' + req)
221
+ }
222
+ for (const t of ts) {
223
+ if (!t.name || !t.description || !t.inputSchema || t.inputSchema.type !== 'object') throw new Error('opencode mcp: bad tool def ' + JSON.stringify(t && t.name))
224
+ }
225
+ // MCP 面必须覆盖 descriptor 三件套(名字一致,提示词连续性红线)。
226
+ for (const k of ['run', 'continue', 'status']) {
227
+ if (!names.includes(provider.tools[k].name)) throw new Error('opencode mcp: tools surface missing descriptor name ' + provider.tools[k].name)
228
+ }
229
+ // argv 契约漂移锁(实测 opencode 1.19.0 flag 集)。
230
+ const b = provider.buildArgv(['opencode'], { prompt: 'x' }, { planActive: false })
231
+ for (const f of ['run', 'x', '--format', 'json', '--auto']) {
232
+ if (!b.argv.includes(f)) throw new Error('opencode mcp: argv contract drift: ' + f)
233
+ }
234
+ const b2 = provider.buildArgv(['opencode'], { prompt: 'x', autoApprove: false }, { planActive: false })
235
+ if (b2.argv.includes('--auto')) throw new Error('opencode mcp: autoApprove=false must omit --auto')
236
+ return true
237
+ }
@@ -0,0 +1,26 @@
1
+ // mcp/version.mjs — MCP 工具面版本号单一来源。
2
+ //
3
+ // 历史问题:四个 provider 的 `meta.version` 与描述符的 `mcp.version` 各自硬编码
4
+ // 版本字面量(共 8 处),每次发布必须手工同步 —— 漏改一处就出现「统一 server 报
5
+ // 0.2.3、provider 面仍报 0.2.2」的自相矛盾输出(0.2.3 发布时即踩到)。
6
+ //
7
+ // 契约 §4 要求 provider version「独立跟随本包」—— 跟随 = 同源派生,不是各处抄写。
8
+ // 这里从包自身的 package.json 读一次,全包共用。失败时抛错而非静默回落:版本号
9
+ // 错误会误导排障,宁可大声失败(红线 7)。
10
+ import { readFileSync } from 'node:fs'
11
+ import { fileURLToPath } from 'node:url'
12
+
13
+ const pkgPath = fileURLToPath(new URL('../package.json', import.meta.url))
14
+ let cached = null
15
+
16
+ export function packageVersion() {
17
+ if (cached) return cached
18
+ let parsed
19
+ try { parsed = JSON.parse(readFileSync(pkgPath, 'utf8')) } catch (e) {
20
+ throw new Error('mcp/version: cannot read package.json (' + String(e && e.message || e) + ')')
21
+ }
22
+ const v = parsed && parsed.version
23
+ if (typeof v !== 'string' || !v) throw new Error('mcp/version: package.json has no version field')
24
+ cached = v
25
+ return v
26
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@luchenglong/cli-bridge",
3
- "version": "0.2.2",
4
- "description": "CLI Bridge for DeepSeek Harness (DSH): one package bridging three local coding-CLI agents — agy (Google Antigravity CLI), Tencent CodeBuddy Code, and Xiaomi MiMo (MiMoCode / MiMo Desktop). Each provider keeps its own agent preset (cordis-agy / codebuddy-first / cordis-mimo), tools (agy_run / codebuddy_run / mimo_run + continue + status), rate-limit/network fallback dialog, and zero-dependency MCP server, unified under a single home-level status light, one settings file, and one bundle patch. Merges agy-first-bridge, codebuddy-first-bridge and mimo-first-bridge.",
3
+ "version": "0.2.4",
4
+ "description": "CLI Bridge for DeepSeek Harness (DSH): one package bridging four local coding-CLI agents — agy (Google Antigravity CLI), Tencent CodeBuddy Code, Xiaomi MiMo (MiMoCode / MiMo Desktop), and OpenCode. Each provider keeps its own agent preset (cordis-agy / codebuddy-first / cordis-mimo / opencode-first), tools (agy_run / codebuddy_run / mimo_run / opencode_run + continue + status), rate-limit/network fallback dialog, and zero-dependency MCP server, unified under a single home-level status light, one settings file, and one bundle patch. Merges agy-first-bridge, codebuddy-first-bridge and mimo-first-bridge.",
5
5
  "license": "MIT",
6
6
  "publishConfig": {
7
7
  "access": "public"
@@ -19,9 +19,11 @@
19
19
  "./providers/agy": "./providers/agy.mjs",
20
20
  "./providers/codebuddy": "./providers/codebuddy.mjs",
21
21
  "./providers/mimo": "./providers/mimo.mjs",
22
+ "./providers/opencode": "./providers/opencode.mjs",
22
23
  "./preset-agy": "./preset/agy-first/cli-bridge.mjs",
23
24
  "./preset-codebuddy": "./preset/codebuddy-first/cli-bridge.mjs",
24
25
  "./preset-mimo": "./preset/mimo-first/cli-bridge.mjs",
26
+ "./preset-opencode": "./preset/opencode-first/cli-bridge.mjs",
25
27
  "./package.json": "./package.json"
26
28
  },
27
29
  "dsh": {
@@ -87,3 +89,4 @@
87
89
  "url": "https://github.com/new-256/cli-bridge/issues"
88
90
  }
89
91
  }
92
+