@luchenglong/cli-bridge 0.2.5 → 0.2.7

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.
@@ -31,7 +31,7 @@ import * as mimoMcp from './providers/mimo.mjs'
31
31
  import * as opencodeMcp from './providers/opencode.mjs'
32
32
 
33
33
  const SERVER_NAME = 'cli-bridge-mcp'
34
- const SERVER_VERSION = '0.2.5'
34
+ const SERVER_VERSION = '0.2.7'
35
35
  const PROTOCOL = '2024-11-05'
36
36
 
37
37
  const PROVIDERS = [agyMcp, codebuddyMcp, mimoMcp, opencodeMcp]
@@ -183,3 +183,4 @@ process.stdin.on('data', (d) => {
183
183
  process.stdin.on('end', () => { stdinClosed = true; maybeExit() })
184
184
  process.on('SIGINT', () => process.exit(0))
185
185
  process.on('SIGTERM', () => process.exit(0))
186
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luchenglong/cli-bridge",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
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": {
@@ -91,3 +91,5 @@
91
91
  }
92
92
 
93
93
 
94
+
95
+
@@ -230,6 +230,238 @@ export const BACKEND_ENUM = ['codebuddy', 'codebuddy-intl', 'codebuddy-ioa', 'co
230
230
  return v && v.length ? v.slice() : null
231
231
  }
232
232
 
233
+ // ── 实时模型清单(CLI 是一手权威来源,对齐 workbuddy-auth 的「权威白名单」思路)──
234
+ //
235
+ // 为什么不再以静态表/磁盘描述文件为主:实测本机 codebuddy CLI --
236
+ // • 账号实时清单(用无效模型触发 400 报文)= 19 项
237
+ // • CLI `--help` 声明的 roster = 19 项,与账号清单完全一致
238
+ // • 我们原先读的 product.ioa.json 静态表 = 16 项,且 2 个 id 已过时
239
+ // (minimax-m3 → minimax-m3-pay、kimi-k3-1 → kimi-k3-2),另缺 4 个新模型。
240
+ // 静态表是「随包冻结」的,必然落后于 CLI,故只保留作倍率元数据与最后兜底。
241
+ //
242
+ // 两级实时来源(都不静默冒充权威数据,各带 source 标签):
243
+ // A. account-live —— 起 CLI 用无效模型探测「该账号当前支持」的清单(需该面已登录,
244
+ // 一次网络往返;对照 workbuddy-auth 的 agents[cli].models 白名单语义)。
245
+ // B. cli-help —— 解析 `--help` 的 "Currently supported: (...)"(零网络、随 CLI
246
+ // 版本自动更新;产品面级 roster)。
247
+ // 静态表仅作 credit 元数据与 descriptor-static 兜底标签,绝不冒充实时。
248
+
249
+ /** 解析 CLI `--help` 里声明的模型 roster。空/畸形输入返回 []。
250
+ * ⚠️ 名册很长时 yargs 会在任意列**折行**(实测把 `minimax-m3-pay` 从中间断成
251
+ * `minimax-` + `m3-pay`),若按行/按逗号直接切会丢项或产生残片(同一命令两次运行
252
+ * 给出 18/19 两种结果)。故先去掉括号内所有空白再按逗号切:逗号是唯一分隔符,
253
+ * 折行插入的空白一律视为噪声。 */
254
+ export function parseHelpModels(helpText) {
255
+ const m = /Currently supported:\s*\(([^)]+)\)/.exec(String(helpText || ''))
256
+ if (!m) return []
257
+ const out = []
258
+ for (const raw of m[1].replace(/\s+/g, '').split(',')) {
259
+ const id = raw.trim()
260
+ if (id && /^[A-Za-z0-9_.\-]+$/.test(id) && out.indexOf(id) < 0) out.push(id)
261
+ }
262
+ return out
263
+ }
264
+
265
+ /** 解析 codebuddy CLI 的可执行候选(env > npm 全局 shim > PATH 名)。 */
266
+ export function cbCatalogCliCandidates(env) {
267
+ const e = env || cbCatalogEnv || {}
268
+ const out = []
269
+ const push = (p) => { if (p && out.indexOf(p) < 0) out.push(p) }
270
+ if (e.CODEBUDDY_BIN) push(String(e.CODEBUDDY_BIN))
271
+ const joinP = (a, b) => cbCatalogPathJoin(a, b)
272
+ if (e.APPDATA) push(joinP(joinP(e.APPDATA, 'npm'), 'codebuddy.cmd'))
273
+ if (e.APPDATA) push(joinP(joinP(e.APPDATA, 'npm'), 'codebuddy'))
274
+ push('codebuddy')
275
+ return out
276
+ }
277
+
278
+ const CLI_MODEL_CACHE = new Map() // backend → { at, mode, ids }
279
+ const CLI_MODEL_TTL_MS = 5 * 60 * 1000
280
+
281
+ // Windows .cmd/.bat 需要经 shell(Node 安全限制),但 `shell:true` + args 数组会触发
282
+ // DEP0190(参数不转义)。这里统一做法:把命令与参数拼成【一个】字符串交给 shell,
283
+ // 参数各自按 Windows 规则加引号 —— 既避开 DEP0190,又保证含空格参数不被拆开。
284
+ function quoteWinArg(a) {
285
+ const s = String(a)
286
+ if (s === '') return '""'
287
+ if (!/[\s"&|<>^]/.test(s)) return s
288
+ return '"' + s.replace(/"/g, '\\"') + '"'
289
+ }
290
+ function cliCommandLine(exe, args) {
291
+ return [exe].concat(args || []).map(quoteWinArg).join(' ')
292
+ }
293
+
294
+ /** 把候选拆成 { cmd, prefixArgs }:.mjs/.js/.cjs 目标经 node 包装(测试夹具与自定义
295
+ * 入口都靠这条),其余原样。 */
296
+ function splitExeSpec(exe) {
297
+ if (/\.(mjs|cjs|js)$/i.test(String(exe))) {
298
+ const proc = globalThis.process
299
+ return { cmd: (proc && proc.execPath) ? proc.execPath : 'node', prefixArgs: [String(exe)] }
300
+ }
301
+ return { cmd: String(exe), prefixArgs: [] }
302
+ }
303
+
304
+ function cliSpawnSync(exe, args, opts) {
305
+ const proc = globalThis.process
306
+ const child = (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule('node:child_process') : null
307
+ if (!child || typeof child.spawnSync !== 'function') return null
308
+ const base = Object.assign({
309
+ encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
310
+ }, opts || {})
311
+ const spec = splitExeSpec(exe)
312
+ const argv = spec.prefixArgs.concat(args || [])
313
+ const isCmd = /\.(cmd|bat)$/i.test(spec.cmd)
314
+ if (isCmd) base.shell = true
315
+ try {
316
+ // shell 形态不带 args 数组(否则 DEP0190);非 shell 形态正常传数组。
317
+ return isCmd
318
+ ? child.spawnSync(cliCommandLine(spec.cmd, argv), base)
319
+ : child.spawnSync(spec.cmd, argv, base)
320
+ } catch (e) { return null }
321
+ }
322
+
323
+ /**
324
+ * 同步取「CLI 声明的 roster」(零网络,随 CLI 版本走)。
325
+ * @returns {{ok:boolean, ids:string[], mode:string, error?:string}}
326
+ */
327
+ export function fetchHelpModelsSync(env, opts) {
328
+ const o = opts || {}
329
+ const cands = cbCatalogCliCandidates(env)
330
+ let lastErr = null
331
+ for (const exe of cands) {
332
+ const r = cliSpawnSync(exe, ['--help'], { timeout: Math.max(1000, Math.min(o.timeoutMs || 12000, 30000)) })
333
+ if (!r || r.error) { lastErr = 'spawn failed: ' + String((r && r.error && r.error.message) || 'unavailable'); continue }
334
+ const text = String(r.stdout || '') + String(r.stderr || '')
335
+ const ids = parseHelpModels(text)
336
+ if (ids.length) return { ok: true, ids, mode: 'cli-help', exe }
337
+ lastErr = 'no roster in --help output'
338
+ }
339
+ return { ok: false, ids: [], mode: 'cli-help', error: lastErr || 'codebuddy CLI not found (set CODEBUDDY_BIN)' }
340
+ }
341
+
342
+ /**
343
+ * 同步版的账号探测(供设置面板用 —— 面板必须同步返回)。
344
+ * 走 spawnSync + 超时;结果进 5 分钟缓存,避免每次渲染都打一次网络。
345
+ *
346
+ * ⚠️ 为什么面板不能用 `--help` 名册顶替:实测本机 CLI 2.167.0 的 help 文本**本身
347
+ * 就是过时的** —— 它列 18 项且含已不存在的 `minimax-m3` / `kimi-k3-1`,缺真实的
348
+ * `glm-5.3-flashx` / `minimax-m3-pay` / `kimi-k3-2`;而账号探测给出 19 项且全部有效。
349
+ * 也就是说「CLI 声明」≠「服务端实际可用」,拿它当兜底会直接把错误清单展示给用户。
350
+ * 故这里宁可空列表 + 明确提示,也不展示已知错误的 roster。
351
+ * @returns {{ok:boolean, ids:string[], mode:string, error?:string}}
352
+ */
353
+ export function probeAccountModelsSync(env, opts) {
354
+ const o = opts || {}
355
+ const cands = cbCatalogCliCandidates(env)
356
+ const extraEnv = o.envExtra || {}
357
+ const reasons = []
358
+ const timeout = Math.max(3000, Math.min(o.timeoutMs || 12000, 30000))
359
+ for (const exe of cands) {
360
+ const r = cliSpawnSync(exe, ['-p', 'hi', '--model', '__clb_probe_invalid__', '--output-format', 'text'], {
361
+ timeout,
362
+ env: Object.assign({}, (globalThis.process && globalThis.process.env) || {}, extraEnv)
363
+ })
364
+ if (!r || r.error) { reasons.push(exe + ': ' + String((r && r.error && (r.error.code || r.error.message)) || 'spawn failed')); continue }
365
+ const out = String(r.stdout || '') + String(r.stderr || '')
366
+ const ids = parseAccountModels(out)
367
+ if (ids && ids.length) return { ok: true, ids, mode: 'account-live', exe }
368
+ const head = String(out).replace(/\s+/g, ' ').trim().slice(0, 140)
369
+ reasons.push(exe + ': exit ' + r.status + ', no account roster' + (head ? ' — ' + head : ''))
370
+ }
371
+ return { ok: false, ids: [], mode: 'account-live', error: reasons.join('; ') || 'no CLI candidate to probe' }
372
+ }
373
+
374
+ /**
375
+ * 异步探测「该账号当前支持」的清单:用无效模型触发 CLI 的 400 报文。
376
+ * 对齐 workbuddy-auth 的权威白名单语义(服务器告诉我们这个账号能用什么)。
377
+ * @returns {Promise<{ok:boolean, ids:string[], mode:string, error?:string}>}
378
+ */
379
+ export function probeAccountModels(env, opts) {
380
+ const o = opts || {}
381
+ const cands = cbCatalogCliCandidates(env)
382
+ const proc = globalThis.process
383
+ const child = (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule('node:child_process') : null
384
+ if (!child || typeof child.spawn !== 'function') {
385
+ return Promise.resolve({ ok: false, ids: [], mode: 'account-live', error: 'no spawn capability in this host form' })
386
+ }
387
+ const extraEnv = o.envExtra || {}
388
+ return new Promise((resolve) => {
389
+ let idx = 0
390
+ // 记录每个候选的真实结局:区分「压根没找到 CLI」与「CLI 跑了但没吐账号名录」
391
+ // (后者通常是该面未登录 / 端点拒了)—— 报错文案必须能指导下一步,不能一律
392
+ // 说 "CLI not found"(本轮就踩到:codebuddy-en 无 token 时被误报成找不到 CLI)。
393
+ const reasons = []
394
+ const attempt = () => {
395
+ if (idx >= cands.length) {
396
+ resolve({
397
+ ok: false, ids: [], mode: 'account-live',
398
+ error: reasons.length ? reasons.join('; ') : 'no CLI candidate to probe',
399
+ notFound: reasons.every((r) => /not found|ENOENT|spawn/i.test(r))
400
+ })
401
+ return
402
+ }
403
+ const exe = cands[idx++]
404
+ let c
405
+ try {
406
+ // .cmd/.bat 需经 shell(Windows 安全限制);.mjs/.js 经 node 包装。
407
+ // 与 cliSpawnSync 同一规则:shell 形态把命令拼成单字符串(避免 DEP0190)。
408
+ const spec = splitExeSpec(exe)
409
+ const isCmd = /\.(cmd|bat)$/i.test(spec.cmd)
410
+ const probeArgs = spec.prefixArgs.concat(['-p', 'hi', '--model', '__clb_probe_invalid__', '--output-format', 'text'])
411
+ const opts = {
412
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
413
+ env: Object.assign({}, proc.env, extraEnv)
414
+ }
415
+ c = isCmd
416
+ ? child.spawn(cliCommandLine(spec.cmd, probeArgs), Object.assign({ shell: true }, opts))
417
+ : child.spawn(spec.cmd, probeArgs, opts)
418
+ } catch (e) { reasons.push(exe + ': spawn threw ' + String(e && e.message || e)); attempt(); return }
419
+ let out = ''
420
+ const timer = setTimeout(() => { try { c.kill() } catch (e) { } }, Math.max(5000, Math.min(o.timeoutMs || 30000, 90000)))
421
+ const onData = (d) => { out += d; if (out.length > 400000) out = out.slice(-200000) }
422
+ c.stdout.on('data', onData)
423
+ c.stderr.on('data', onData)
424
+ c.on('error', (e) => {
425
+ clearTimeout(timer)
426
+ reasons.push(exe + ': ' + String((e && e.code) || (e && e.message) || 'spawn error'))
427
+ attempt()
428
+ })
429
+ c.on('close', (code) => {
430
+ clearTimeout(timer)
431
+ const ids = parseAccountModels(out)
432
+ if (ids && ids.length) { resolve({ ok: true, ids, mode: 'account-live', exe }); return }
433
+ const head = String(out).replace(/\s+/g, ' ').trim().slice(0, 160)
434
+ reasons.push(exe + ': exit ' + code + ', no account roster' + (head ? ' — ' + head : ''))
435
+ attempt()
436
+ })
437
+ }
438
+ attempt()
439
+ })
440
+ }
441
+
442
+ /** 缓存读写(面板每次渲染都会取,避免反复起进程)。 */
443
+ export function cachedCliModels(backend, load, nowMs) {
444
+ const at = Number(nowMs) || Date.now()
445
+ const hit = CLI_MODEL_CACHE.get(backend)
446
+ if (hit && at - hit.at < CLI_MODEL_TTL_MS) return hit
447
+ const v = typeof load === 'function' ? load() : load
448
+ if (v && v.ok && v.ids && v.ids.length) CLI_MODEL_CACHE.set(backend, { at, mode: v.mode, ids: v.ids.slice() })
449
+ return v
450
+ }
451
+
452
+ /** 读统一设置文件里 codebuddy 分区的 preferredBackend(meta 需要它才知道列哪个面)。 */
453
+ export function currentPreferredBackend() {
454
+ try {
455
+ const e = cbCatalogEnv || {}
456
+ const p = cbCatalogRead(e.CLI_BRIDGE_SETTINGS_FILE || cbCatalogPathJoin(
457
+ e.DSH_HOME || (e.APPDATA ? cbCatalogPathJoin(e.APPDATA, 'DSH Desktop', 'dsh-home') : ''), 'cli-bridge-settings.json'))
458
+ if (!p) return null
459
+ const all = JSON.parse(p)
460
+ const v = all && all.codebuddy && all.codebuddy.preferredBackend
461
+ return typeof v === 'string' && v ? v : null
462
+ } catch (err) { return null }
463
+ }
464
+
233
465
  // CLI 报错里解析「该账号当前支持的模型」(旧 core parseAccountModels verbatim)。
234
466
  export function parseAccountModels(text) {
235
467
  const s = String(text || '')
@@ -365,68 +597,3 @@ export const CREDENTIAL_KEYS = ['WORKBUDDY_TOKEN', 'WORKBUDDY_AI_TOKEN', 'CODEBU
365
597
  return { token: null, source: null }
366
598
  }
367
599
 
368
- // ── codebuddy_models 工具定义(搬自主文件;纯逻辑,依赖经 ctx 注入)────────────
369
- // ctx = { env, deps, resolveBackend, modelCatalogDetailed, getAccountCatalog }
370
- export function codebuddyModelsTool(ctx) {
371
- const c = ctx || {}
372
- const deps = c.deps || {}
373
- const env = c.env || {}
374
- return {
375
- name: 'codebuddy_models',
376
- description: 'List the models available to the local codebuddy CLI for a given backend. Merges three layers: the built-in product descriptor id table, any descriptor file on disk, and the account catalogue harvested from a previous CLI run (authorized ids first). Each item carries its credit multiplier (x0.00 = free). Use it to pick a model before codebuddy_run, or to see which ids are free. Returns ok:false with an actionable error when no catalogue can be read — it never invents a model list.',
377
- inputSchema: {
378
- type: 'object', additionalProperties: false, required: [],
379
- properties: {
380
- backend: { type: 'string', enum: c.BACKEND_ENUM, description: 'Which product face to list (default: the preferred backend).' },
381
- freeOnly: { type: 'boolean', description: 'Return only x0.00 (free) models.' },
382
- authorizedOnly: { type: 'boolean', description: 'Return only ids the current account is licensed for (harvested from a prior run).' }
383
- }
384
- },
385
- render: (args, value) => {
386
- const v = value || {}
387
- if (!v.ok) return [{ type: 'text', text: 'codebuddy_models failed: ' + String(v.error || 'unknown') }]
388
- const list = Array.isArray(v.models) ? v.models : []
389
- if (!list.length) return [{ type: 'text', text: 'codebuddy_models: no models matched (backend=' + (v.backend || '?') + ')' }]
390
- const lines = ['codebuddy models [' + v.backend + '] (' + list.length + '):']
391
- for (const m of list.slice(0, 40)) {
392
- const flags = []
393
- if (m.authorized) flags.push('authorized')
394
- if (m.credits === 0) flags.push('free')
395
- lines.push(' ' + m.id + (m.creditLabel ? ' ' + m.creditLabel : '') + (flags.length ? ' [' + flags.join(',') + ']' : ''))
396
- }
397
- if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
398
- lines.push('source: ' + (v.source || 'unknown') + (v.accountCatalogue ? ' · account catalogue available' : ' · no account catalogue yet (run once to harvest)'))
399
- return [{ type: 'text', text: lines.join('\n') }]
400
- },
401
- async logic(args) {
402
- const a = args || {}
403
- const preferred = (deps.settings && deps.settings.preferredBackend) || null
404
- const backend = c.normalizeBackend(a.backend) || c.resolveBackend({}, null, preferred)
405
- let items = []
406
- try {
407
- items = c.modelCatalogDetailed(backend, { env }) || []
408
- } catch (e) {
409
- return { ok: false, backend, error: 'catalogue read failed: ' + String(e && e.message || e) }
410
- }
411
- if (!Array.isArray(items) || !items.length) {
412
- return {
413
- ok: false, backend,
414
- error: 'no model catalogue could be read for backend "' + backend + '". Check that the codebuddy CLI is installed (CODEBUDDY_BIN) and that its product descriptor exists, or run the CLI once so the account catalogue can be harvested.'
415
- }
416
- }
417
- const acctIds = c.getAccountCatalog(backend)
418
- const accountCatalogue = !!(acctIds && acctIds.length)
419
- let list = items.map((x) => ({
420
- id: x.id, authorized: !!x.authorized, credits: typeof x.credits === 'number' ? x.credits : null,
421
- creditLabel: x.creditLabel || x.label || '', label: x.label || x.id
422
- }))
423
- if (a.authorizedOnly) list = list.filter((m) => m.authorized)
424
- if (a.freeOnly) list = list.filter((m) => m.credits === 0)
425
- return {
426
- ok: true, backend, models: list, count: list.length,
427
- source: accountCatalogue ? 'account+descriptor' : 'descriptor',
428
- accountCatalogue
429
- }
430
- }
431
- }
432
- }
@@ -0,0 +1,72 @@
1
+ // providers/codebuddy-consts.mjs — codebuddy 的提示词策略与后端注册表常量(纯数据)。
2
+ //
3
+ // 从 providers/codebuddy.mjs 拆出,让主描述符留在 600 行红线内(规则 §26)。
4
+ // build 会把 providers/codebuddy-*.mjs 全部内联进 dynamic 沙箱同一作用域。
5
+ // 命名纪律:顶层名绝不与 core/bridge-kit.mjs 同名(同作用域重复声明 = 语法错)。
6
+ // ⚠️ 注释里绝不写出口令标记字面量(build 全局替换会把注释劈开)。
7
+
8
+ // ── 提示词策略段(旧 preset POLICY_TEXT verbatim;systemPrompt order 5)────────
9
+ export const POLICY_TEXT = [
10
+ 'codebuddy-first execution policy (local codebuddy CLI bridge, with fallback + live indicator + live status tool).',
11
+ '',
12
+ 'A local sub-agent CLI named "codebuddy" (Tencent CodeBuddy Code) is available through the codebuddy_run and codebuddy_continue tools. DSH fully controls codebuddy: every invocation runs non-interactively with permissions auto-approved (--permission-mode bypassPermissions), so codebuddy never prompts and DSH decides all of its work. A header status light shows when codebuddy is working — one light per project (working directory), so parallel runs in different projects are tracked separately; call codebuddy_status any time to see what codebuddy is doing right now (per project: current tool/step, recent trail, and cumulative usage).',
13
+ '',
14
+ 'Priority rule for EVERY mode (normal, plan, accept-edits, subagent/workflow/ralph delegation, and goal rounds):',
15
+ '- For any real work — implementing features, editing/refactoring code, debugging, running builds, or multi-file investigation — prefer dispatching the task to codebuddy_run FIRST with a complete, self-contained prompt.',
16
+ '- Use native read/write/shell tools mainly for quick read-only lookups and for the final build/test verification of what codebuddy produced.',
17
+ '- In plan mode, call codebuddy_run with mode=auto (or mode=plan); in accept-edits/normal mode codebuddy_run applies edits directly.',
18
+ '- When you delegate to a DSH subagent or workflow, instruct that delegate to also prefer codebuddy_run.',
19
+ '- For long-running tasks, call codebuddy_run with background=true and collect the result with job_output; use codebuddy_status to watch progress.',
20
+ '',
21
+ 'Fallback protocol: when codebuddy is rate-limited or the network is down, codebuddy_run/codebuddy_continue automatically pop a confirmation dialog asking the user whether to use the DSH local API config. If the returned result has fallback=true (status FALLBACK_TO_DSH), the user chose to fall back: complete the task with native DSH tools / the local model and DO NOT call codebuddy again for this task. If ok=false without fallback, report the codebuddy error. Never loop codebuddy calls; never ask codebuddy to call back into DSH.',
22
+ '',
23
+ 'Model selection: codebuddy_run takes an optional model. When unspecified, the CLI default applies unless the user set a preferred default model in the plugin settings (then that is injected automatically per call). Which models ACTUALLY WORK depends on the ACCOUNT, and the authoritative live list comes from the server: running the CLI with a nonexistent model returns 400 followed by "Currently supported models for your account:" and one "- <id>" per line (core exposes parseAccountModels for this; the plugin caches the result automatically and the settings panel shows exactly those ids, with the credit multiplier of each). Do NOT trust the bundled product descriptor as a menu of usable models: it lists ids with an "-ioa" suffix (glm-5.3-ioa) and expensive flagships (claude-opus-4.8, gpt-5.4, gpt-6-astra) that are present in the catalogue but NOT licensed for this account, and picking one fails with 400 "only available for authorized users". The four backends are also not one pool: "codebuddy" and "codebuddy-intl" are the npm CLI and offer its catalogue - including the free tier (hy3 and deepseek-v4.1-flash cost x0.00 credits; hy4-preview costs x0.29 but is frequently free on promotional accounts); "codebuddy-en" (WorkBuddyAI) has its OWN catalogue which does NOT contain hy4-preview or deepseek-v4.1-flash - it offers hy3 (free), gpt-5.1-codex-mini, gemini-3.1-flash-lite, gemini-2.5-flash, minimax-m3, gemini-3.0-flash, deepseek-v3-2-volc, kimi-k2.5/2.6, glm-5.0/5.2/5.3, gpt-5.3-codex, gpt-5.4/5.5, gpt-5.6-sol/terra/luna and the role aliases (fast/balanced/primary/deep-model); "workbuddy" (domestic desktop) has a further catalogue (auto, hy4-preview, hy3, deepseek-v4.1-flash, glm-5.x, kimi-k2.6/2.7/2.8-preview/k3-1, minimax-m3/m2.7, deepseek-v4-pro). Within a face availability is still gated per ACCOUNT: an id outside the account catalogue fails with "400 model [...] service info not found", and one inside it but unlicensed fails with "400 model [...] is only available for authorized users". International ids (claude-sonnet-5, claude-opus-5, gemini-3.1-pro, ...) are per-account gated and return the latter for a domestic account. COST: every id carries a credit multiplier in the credits field of its descriptor (x0.00 means free, x3.31 means 3.31x the base rate); the settings panel shows each candidate with its multiplier and reads it live from the CLI descriptor, so it stays in sync when the CLI is upgraded. Measured free (x0.00) models for this account: hy3 and deepseek-v4.1-flash (both npm faces) and hy3 for WorkBuddyAI; hy4-preview is x0.29 on npm faces. Prefer the cheapest model that can do the job and use a free one for routine work; do not silently upgrade to an expensive id when the task is simple. To get the exact live list for a CLI, run it with a deliberately invalid model id - the reply prints "Currently supported models for your account:" followed by one "- <id>" per line (core exposes parseAccountModels for this). Pass a model only when the task clearly benefits from a specific one; the default is usually right. Optional effort: minimal/low/medium/high/xhigh/max. Optional maxTurns caps agentic turns (default unlimited).',
24
+ '',
25
+ 'Backends: codebuddy_run/codebuddy_continue take an optional backend parameter choosing which CLI face of the same engine (Tencent CodeBuddy Code) runs the task. "codebuddy" is the domestic CodeBuddy (npm CLI @tencent-ai/codebuddy-code, product endpoint www.codebuddy.ai) — default for coding work. "codebuddy-intl" is the INTERNATIONAL face of that SAME npm CLI (product.ioa.json catalogue: claude-sonnet-5, claude-opus-5, gemini-3.1-pro, gpt-6-astra, hy3-ioa …); use it when the account is an international CodeBuddy account. Its aliases "codebuddy-ioa" and "codebuddy-international" are accepted and normalized to codebuddy-intl. "codebuddy-en" is the WorkBuddy INTERNATIONAL edition — the CLI bundled with the WorkBuddyAI desktop app (C:\\Program Files\\WorkBuddyAI, product endpoint www.workbuddy.ai); the aliases "workbuddy-en" and "workbuddy-ai" are also accepted and normalized to codebuddy-en. "workbuddy" is the CLI bundled with the domestic WorkBuddy desktop app (product endpoint copilot.tencent.com, zero config) — the office-scenario face: documents, slides, spreadsheets, knowledge-base lookups, image/video generation, WeChat/WeCom replies. When the user asks for office/document/IM work, dispatch with backend="workbuddy"; for international accounts use "codebuddy-intl" (CodeBuddy 国际版) or "codebuddy-en" (WorkBuddy 国际版 / WorkBuddyAI). Sessions are kept per backend (login domains are exclusive), and continuing a session automatically routes back to the backend that owns it (explicit backend wins). A user-preferred default backend (plugin settings) applies when a call is new (no session) and no explicit backend is given.'
26
+ ].join('\n')
27
+
28
+ // ── 限流/网络/认证失败判定(旧 core verbatim)。仅匹配 stderr + status;数字码
29
+ // 加词边界(避免 "1500" 命中 500、"4013" 命中 401)。中文码(流量/受限/金额/
30
+ // 余额/额度/认证/连接/断开 等)为 codebuddy 面专属,必须逐字保留。
31
+ // 命名纪律(mimo 同款):本文件顶层名绝不与 core/bridge-kit.mjs 顶层导出同名 ——
32
+ // dynamic 形态把 kit 与 provider 内联进同一脚本作用域,同名 const 直接炸语法
33
+
34
+ // ── 后端注册表(旧 core verbatim:端点按登录域自动对齐)───────────────────────
35
+ export const CODEBUDDY_LIMIT_RE = /rate.?limit|ratelimit|\b429\b|too many|quota|insufficient|credit|balance|exhausted|exceed|\bnetwork\b|offline|ENETUNREACH|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|\btimeouts?\b|timed out|unavailable|\b50[023]\b|\b40[13]\b|unauthorized|invalid api|api key|proxy|socket|tls|ssl|\bdns\b|网络|超时|限流|流量|受限|配额|金额|余额|额度|认证|连接|断开/i
36
+
37
+ // ── 后端注册表(旧 core verbatim:端点按登录域自动对齐)───────────────────────
38
+ export const BACKENDS = ['codebuddy', 'codebuddy-intl', 'codebuddy-en', 'workbuddy']
39
+
40
+ export const BACKEND_ENDPOINTS = {
41
+ 'codebuddy': 'https://www.codebuddy.ai/v2',
42
+ 'codebuddy-intl': 'https://www.codebuddy.ai/v2',
43
+ 'codebuddy-en': 'https://www.workbuddy.ai/v2',
44
+ 'workbuddy': 'https://copilot.tencent.com/v2'
45
+ }
46
+
47
+ export const AUTH_DOMAIN_ENDPOINTS = {
48
+ 'www.codebuddy.cn': 'https://www.codebuddy.cn/v2',
49
+ 'www.codebuddy.ai': 'https://www.codebuddy.ai/v2',
50
+ 'www.workbuddy.ai': 'https://www.workbuddy.ai/v2',
51
+ 'copilot.tencent.com': 'https://copilot.tencent.com/v2'
52
+ }
53
+
54
+ export const BACKEND_LABELS = {
55
+ 'codebuddy': 'CodeBuddy 国内版(npm CLI)',
56
+ 'codebuddy-intl': 'CodeBuddy 国际版(npm CLI · 国际面)',
57
+ 'codebuddy-en': 'WorkBuddy 国际版(WorkBuddyAI 桌面 CLI)',
58
+ 'workbuddy': 'WorkBuddy 国内版(桌面 CLI)'
59
+ }
60
+
61
+ export const BACKEND_ALIASES = {
62
+ 'workbuddy-en': 'codebuddy-en',
63
+ 'workbuddy-ai': 'codebuddy-en',
64
+ 'codebuddy-ioa': 'codebuddy-intl',
65
+ 'codebuddy-international': 'codebuddy-intl',
66
+ 'codebuddy-oversea': 'codebuddy-intl'
67
+ }
68
+
69
+ export const DEFAULT_BACKEND = 'codebuddy'
70
+
71
+ export const SETTINGS_KEYS = ['preferredBackend', 'defaultModel', 'codebuddyEnToken', 'endpointOverride']
72
+
@@ -0,0 +1,106 @@
1
+ // providers/codebuddy-models-tool.mjs — codebuddy_models 工具定义(纯逻辑)。
2
+ //
3
+ // 从 codebuddy-catalog.mjs 再拆出:两个文件都要留在 600 行红线内(规则 §26)。
4
+ // scripts/build.mjs 会把 providers/codebuddy-*.mjs 全部内联进 dynamic 沙箱的同一个
5
+ // 作用域,所以这里仍可引用 catalog 的函数(沙箱内天然可见);ESM 形态走本文件的 import。
6
+ // ⚠️ 注释里绝不写出口令标记字面量(build 全局替换会劈开注释 → 生成物语法崩)。
7
+
8
+ import { currentPreferredBackend, probeAccountModels, fetchHelpModelsSync } from './codebuddy-catalog.mjs'
9
+
10
+ // ── codebuddy_models 工具定义(搬自主文件;纯逻辑,依赖经 ctx 注入)────────────
11
+ // ctx = { env, deps, resolveBackend, modelCatalogDetailed, getAccountCatalog }
12
+ export function codebuddyModelsTool(ctx) {
13
+ const c = ctx || {}
14
+ const deps = c.deps || {}
15
+ const env = c.env || {}
16
+ return {
17
+ name: 'codebuddy_models',
18
+ description: 'List the models the local codebuddy CLI can use for a given backend, read LIVE from the CLI. Primary source: an account probe (runs the CLI with a deliberately invalid model id, which makes the server print "Currently supported models for your account") — this is the authoritative licensed list for THIS account. If that face is not logged in, it falls back to the roster the installed CLI declares in --help and says so in the source field. Credit multipliers (x0.00 = free) come from the product descriptor as metadata. Returns ok:false with an actionable error when no live roster can be read — it never presents a frozen static table as if it were live.',
19
+ inputSchema: {
20
+ type: 'object', additionalProperties: false, required: [],
21
+ properties: {
22
+ backend: { type: 'string', enum: c.BACKEND_ENUM, description: 'Which product face to list (default: the preferred backend).' },
23
+ freeOnly: { type: 'boolean', description: 'Return only x0.00 (free) models.' },
24
+ authorizedOnly: { type: 'boolean', description: 'Return only ids the current account is licensed for (harvested from a prior run).' }
25
+ }
26
+ },
27
+ render: (args, value) => {
28
+ const v = value || {}
29
+ if (!v.ok) return [{ type: 'text', text: 'codebuddy_models failed: ' + String(v.error || 'unknown') }]
30
+ const list = Array.isArray(v.models) ? v.models : []
31
+ if (!list.length) return [{ type: 'text', text: 'codebuddy_models: no models matched (backend=' + (v.backend || '?') + ')' }]
32
+ const lines = ['codebuddy models [' + v.backend + '] (' + list.length + '):']
33
+ for (const m of list.slice(0, 40)) {
34
+ const flags = []
35
+ if (m.authorized) flags.push('authorized')
36
+ if (m.credits === 0) flags.push('free')
37
+ lines.push(' ' + m.id + (m.creditLabel ? ' ' + m.creditLabel : '') + (flags.length ? ' [' + flags.join(',') + ']' : ''))
38
+ }
39
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
40
+ // 只有一种来源:账号实时(服务端裁决)。不再有 cli-help 兜底分支,
41
+ // 因为 CLI 的 --help 名册实测会滞后服务端并含已废弃 id。
42
+ lines.push('source: account-live (authoritative for this account)')
43
+ if (v.note) lines.push('note: ' + v.note)
44
+ return [{ type: 'text', text: lines.join('\n') }]
45
+ },
46
+ async logic(args) {
47
+ const a = args || {}
48
+ const preferred = currentPreferredBackend() || (deps.settings && deps.settings.preferredBackend) || null
49
+ const backend = c.normalizeBackend(a.backend) || c.resolveBackend({}, null, preferred)
50
+
51
+ // ① 账号实时(最权威,对照 workbuddy-auth 的 agents[cli] 白名单语义)。
52
+ // 该面未登录/无 token 时探测会失败 —— 失败就**明确降级到 CLI 名册并标注**,
53
+ // 绝不把静态表冒充成账号可用清单。
54
+ const extraEnv = (c.faceEnv && c.faceEnv(backend)) || {}
55
+ const probe = await probeAccountModels(env, { envExtra: extraEnv, timeoutMs: a.timeoutMs })
56
+
57
+ // 唯一权威源 = 账号探测(服务端裁决)。**不再回落 CLI `--help` 名册**:
58
+ // 实测 CLI 2.167.0 的 help 文本本身就过时(18 项、含已废弃的 minimax-m3 /
59
+ // kimi-k3-1、缺 3 个真实模型),拿它兜底等于把错误清单当结果交付。
60
+ // 探测失败就明确失败,并附上「CLI 声明了 N 项」作为诊断线索(只作提示,不展示
61
+ // 那些 id),符合红线:开发期禁止静默降级。
62
+ if (!probe.ok || !probe.ids || !probe.ids.length) {
63
+ let hint = ''
64
+ try {
65
+ const help = fetchHelpModelsSync(env, { timeoutMs: a.timeoutMs })
66
+ if (help.ok && help.ids.length) {
67
+ hint = ' The installed CLI declares ' + help.ids.length + ' models via --help, but that roster is a static ' +
68
+ 'build-time list and has been observed to lag the server (it can contain retired ids). It is NOT shown here ' +
69
+ 'because it is not authoritative for this account.'
70
+ }
71
+ } catch (e) { }
72
+ return {
73
+ ok: false, backend,
74
+ error: 'no account model roster for backend "' + backend + '": ' + String(probe.error || 'probe failed') +
75
+ '. Make sure this product face is logged in (run the codebuddy CLI and complete login), or set CODEBUDDY_BIN ' +
76
+ 'to the right executable, then retry.' + hint
77
+ }
78
+ }
79
+ const ids = probe.ids
80
+ const source = 'account-live'
81
+
82
+ // ③ 倍率/授权元数据(来自描述文件;仅作标注,不参与「是否可用」判定)。
83
+ let detail = []
84
+ try { detail = c.modelCatalogDetailed(backend, { env, accountModels: ids }) || [] } catch (e) { detail = [] }
85
+ const byId = new Map(detail.map((x) => [x.id, x]))
86
+ let list = ids.map((id) => {
87
+ const d = byId.get(id)
88
+ return {
89
+ id,
90
+ authorized: d ? !!d.authorized : (source === 'account-live'),
91
+ credits: d && typeof d.credits === 'number' ? d.credits : null,
92
+ creditLabel: (d && (d.creditLabel || d.label)) || '',
93
+ label: (d && d.label) || id
94
+ }
95
+ })
96
+ if (a.authorizedOnly) list = list.filter((m) => m.authorized)
97
+ if (a.freeOnly) list = list.filter((m) => m.credits === 0)
98
+ return {
99
+ ok: true, backend, models: list, count: list.length,
100
+ source, note: (typeof note !== 'undefined' ? note : undefined),
101
+ probedAt: Date.now()
102
+ }
103
+ }
104
+ }
105
+ }
106
+
@@ -0,0 +1,46 @@
1
+ // providers/codebuddy-schemas.mjs — 三工具 JSON Schema(纯数据,零依赖)。
2
+ //
3
+ // 旧 preset/codebuddy-first verbatim(契约 §8 红线):字段名/枚举/描述一字不改。
4
+ // 放这里是为了让 catalog 与主描述符都留在 600 行红线内(规则 §26)。
5
+ // ⚠️ 注释里绝不写出口令标记字面量(build 全局替换会把注释劈开)。
6
+
7
+ import { BACKEND_ENUM, MODEL_DESCRIPTION } from './codebuddy-catalog.mjs'
8
+
9
+ // ── 三工具 schema(旧 preset/codebuddy-first verbatim;契约 §8 红线)────────────
10
+ // 纯数据,无依赖 —— 放这里是为了让主描述符留在 600 行红线内(规则 §26)。
11
+ export const RUN_PARAMS = {
12
+ type: 'object',
13
+ additionalProperties: false,
14
+ required: ['prompt'],
15
+ properties: {
16
+ prompt: { type: 'string', description: 'The full task/instruction for codebuddy. Be complete and self-contained.' },
17
+ backend: { type: 'string', enum: BACKEND_ENUM, description: 'Which CLI face to dispatch to. codebuddy (default; domestic CodeBuddy npm CLI, product endpoint www.codebuddy.ai) for coding work; codebuddy-intl = CodeBuddy INTERNATIONAL face of the same npm CLI (product.ioa.json catalogue: claude-sonnet-5 / claude-opus-5 / gemini-3.1-pro / gpt-6-astra / hy3-ioa ...; aliases codebuddy-ioa / codebuddy-international) when the account is an international CodeBuddy account; codebuddy-en = WorkBuddy international edition (the WorkBuddyAI desktop bundled CLI at C:\\Program Files\\WorkBuddyAI, product endpoint www.workbuddy.ai; needs codebuddyEnToken unless DSH already holds a workbuddy key) — aliases workbuddy-en / workbuddy-ai also accepted; workbuddy = WorkBuddy domestic desktop CLI (product endpoint copilot.tencent.com, zero config), the office-scenario face: documents/slides/spreadsheets, knowledge-base lookups, image/video generation, WeChat/WeCom replies. New calls without a backend follow the user-preferred default backend (plugin settings). Continuing a session routes back to its owning backend automatically.' },
18
+ mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'auto follows DSH plan state; plan = no writes; accept-edits = allow edits. Default auto.' },
19
+ model: { type: 'string', description: MODEL_DESCRIPTION },
20
+ effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
21
+ maxTurns: { type: 'integer', description: 'Optional max agentic turns (1-500, default unlimited).' },
22
+ cwd: { type: 'string', description: 'Working directory for codebuddy. Defaults to the DSH workspace root.' },
23
+ addDirs: { type: 'array', items: { type: 'string' }, description: 'Extra directories to add to codebuddy workspace.' },
24
+ timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
25
+ background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
26
+ }
27
+ }
28
+ export const CONTINUE_PARAMS = {
29
+ type: 'object',
30
+ additionalProperties: false,
31
+ required: ['prompt'],
32
+ properties: {
33
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing codebuddy conversation.' },
34
+ sessionId: { type: 'string', description: 'codebuddy session id to resume (from a prior codebuddy_run result).' },
35
+ latest: { type: 'boolean', description: 'Continue the most recent codebuddy conversation instead of a specific id.' },
36
+ backend: { type: 'string', enum: BACKEND_ENUM, description: 'Which CLI face to resume on. codebuddy-en = WorkBuddy international (WorkBuddyAI desktop CLI; aliases workbuddy-en / workbuddy-ai accepted), workbuddy = WorkBuddy domestic desktop CLI. When omitted, the backend that owns the sessionId is used automatically; brand-new conversations follow the user-preferred default backend (plugin settings).' },
37
+ mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'Execution mode; default auto.' },
38
+ model: { type: 'string', description: 'Optional model id (two layers: product face carries it, account licenses it; the credit multiplier of each id comes from the CLI descriptor — see codebuddy_run).' },
39
+ effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
40
+ maxTurns: { type: 'integer', description: 'Optional max agentic turns.' },
41
+ cwd: { type: 'string', description: "Working directory for codebuddy; when resuming, defaults to the resumed session's project directory." },
42
+ timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
43
+ background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
44
+ }
45
+ }
46
+ export const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }