@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.
@@ -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
+
@@ -37,10 +37,9 @@ export function codebuddyModelsTool(ctx) {
37
37
  lines.push(' ' + m.id + (m.creditLabel ? ' ' + m.creditLabel : '') + (flags.length ? ' [' + flags.join(',') + ']' : ''))
38
38
  }
39
39
  if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
40
- const srcLabel = v.source === 'account-live'
41
- ? 'account-live (authoritative for this account)'
42
- : 'cli-help (installed CLI roster, not the licensed subset)'
43
- lines.push('source: ' + srcLabel)
40
+ // 只有一种来源:账号实时(服务端裁决)。不再有 cli-help 兜底分支,
41
+ // 因为 CLI 的 --help 名册实测会滞后服务端并含已废弃 id。
42
+ lines.push('source: account-live (authoritative for this account)')
44
43
  if (v.note) lines.push('note: ' + v.note)
45
44
  return [{ type: 'text', text: lines.join('\n') }]
46
45
  },
@@ -54,30 +53,31 @@ export function codebuddyModelsTool(ctx) {
54
53
  // 绝不把静态表冒充成账号可用清单。
55
54
  const extraEnv = (c.faceEnv && c.faceEnv(backend)) || {}
56
55
  const probe = await probeAccountModels(env, { envExtra: extraEnv, timeoutMs: a.timeoutMs })
57
- let ids = null
58
- let source = null
59
- let note = ''
60
- if (probe.ok && probe.ids.length) {
61
- ids = probe.ids
62
- source = 'account-live'
63
- } else {
64
- // ② CLI 声明的 roster(零网络,随 CLI 版本更新)。
65
- const help = fetchHelpModelsSync(env, { timeoutMs: a.timeoutMs })
66
- if (help.ok && help.ids.length) {
67
- ids = help.ids
68
- source = 'cli-help'
69
- note = 'account probe unavailable (' + String(probe.error || 'not logged in for this face') +
70
- '); showing the roster the installed CLI declares. It reflects the CLI version, not the licensed subset of this account.'
71
- }
72
- }
73
- if (!ids || !ids.length) {
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) { }
74
72
  return {
75
73
  ok: false, backend,
76
- error: 'no live model roster could be read for backend "' + backend + '". ' +
77
- 'Account probe: ' + String(probe.error || 'failed') + '. ' +
78
- 'Install/fix the codebuddy CLI (CODEBUDDY_BIN) and make sure this face is logged in, then retry.'
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
79
77
  }
80
78
  }
79
+ const ids = probe.ids
80
+ const source = 'account-live'
81
81
 
82
82
  // ③ 倍率/授权元数据(来自描述文件;仅作标注,不参与「是否可用」判定)。
83
83
  let detail = []
@@ -97,7 +97,7 @@ export function codebuddyModelsTool(ctx) {
97
97
  if (a.freeOnly) list = list.filter((m) => m.credits === 0)
98
98
  return {
99
99
  ok: true, backend, models: list, count: list.length,
100
- source, note: note || undefined,
100
+ source, note: (typeof note !== 'undefined' ? note : undefined),
101
101
  probedAt: Date.now()
102
102
  }
103
103
  }
@@ -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).' } } }
@@ -1,87 +1,18 @@
1
- // providers/codebuddy.mjs — codebuddy provider descriptor(真移植,替换 Lead 冒烟占位)。
1
+ // providers/codebuddy.mjs — codebuddy provider descriptor。
2
2
  //
3
- // 移植基线:codebuddy-first-bridge v1.6.x core/codebuddy-core.mjs 的纯逻辑
4
- // (后端注册表/端点对齐/凭据链/模型目录/buildArgv/parseCodebuddyJson/buildResult/
5
- // foldEvent/settings 清洗/三工具 schema)与 preset/codebuddy-first 内联语义,
6
- // 逐字保持(PROVIDER-CONTRACT.md §8 红线:工具入参语义与 schema 不许漂移)。
7
- // 与 provider 无关的骨架(状态引擎/行流/回退弹窗/展示层)在 core/bridge-kit.mjs。
3
+ // 移植基线:codebuddy-first-bridge v1.6.x 的纯逻辑与 preset/codebuddy-first 内联语义,
4
+ // 逐字保持(契约 §8:工具入参语义与 schema 不许漂移)。provider 无关骨架在 bridge-kit。
5
+ // 纯逻辑片:codebuddy-catalog.mjs(模型目录/凭据/探测)、codebuddy-schemas.mjs(三 schema)、
6
+ // codebuddy-models-tool.mjs(codebuddy_models 工具)。build 会把 codebuddy-*.mjs 全部
7
+ // 内联进沙箱同一作用域。
8
8
  //
9
- // TODO(Lead 定案,0.1.0 不做):旧包 credits/促销面板的 modelPromotions /
10
- // isPromotionActive / activePromotionFor(约 200 行)不进统一设置面板;本版
11
- // modelCatalogDetailed 只给「倍率 + 授权」两标(无促销角标),行为差异在设置面板
12
- // 单列,运行面(buildArgv/CLI 选择)不受影响。
13
- //
14
- // 红线(PROVIDER-CONTRACT.md §8):
15
- // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现元环境字面量;
16
- // process/env/fs 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 attach(hostOpts)。
17
- // - 只允许 import '../core/bridge-kit.mjs' 一行。
18
- // - isLimited 用本文件自定义的中文限流表(旧 core verbatim),不用 kit 通用表。
9
+ // 红线:本文件会被内联进 dynamic 沙箱 —— 绝不出现元环境字面量;process/env/fs 只经
10
+ // deps 注入或 typeof 守卫读取;宿主能力全部走 attach(hostOpts)。isLimited 用本文件
11
+ // 自定义的中文限流表(旧 core verbatim),不用 kit 通用表。
19
12
  import { createStatusEngine, createRunner, clampInt } from '../core/bridge-kit.mjs'
20
13
 
21
14
  // ── 提示词策略段(旧 preset POLICY_TEXT verbatim;systemPrompt order 5)────────
22
- const POLICY_TEXT = [
23
- 'codebuddy-first execution policy (local codebuddy CLI bridge, with fallback + live indicator + live status tool).',
24
- '',
25
- '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).',
26
- '',
27
- 'Priority rule for EVERY mode (normal, plan, accept-edits, subagent/workflow/ralph delegation, and goal rounds):',
28
- '- 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.',
29
- '- Use native read/write/shell tools mainly for quick read-only lookups and for the final build/test verification of what codebuddy produced.',
30
- '- In plan mode, call codebuddy_run with mode=auto (or mode=plan); in accept-edits/normal mode codebuddy_run applies edits directly.',
31
- '- When you delegate to a DSH subagent or workflow, instruct that delegate to also prefer codebuddy_run.',
32
- '- For long-running tasks, call codebuddy_run with background=true and collect the result with job_output; use codebuddy_status to watch progress.',
33
- '',
34
- '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.',
35
- '',
36
- '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).',
37
- '',
38
- '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.'
39
- ].join('\n')
40
-
41
- // ── 限流/网络/认证失败判定(旧 core verbatim)。仅匹配 stderr + status;数字码
42
- // 加词边界(避免 "1500" 命中 500、"4013" 命中 401)。中文码(流量/受限/金额/
43
- // 余额/额度/认证/连接/断开 等)为 codebuddy 面专属,必须逐字保留。
44
- // 命名纪律(mimo 同款):本文件顶层名绝不与 core/bridge-kit.mjs 顶层导出同名 ——
45
- // dynamic 形态把 kit 与 provider 内联进同一脚本作用域,同名 const 直接炸语法
46
15
  // (LIMIT_RE 在 kit L33 已有,故此处带 CODEBUDDY_ 前缀)。
47
- 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
48
-
49
- // ── 后端注册表(旧 core verbatim:端点按登录域自动对齐)───────────────────────
50
- const BACKENDS = ['codebuddy', 'codebuddy-intl', 'codebuddy-en', 'workbuddy']
51
-
52
- const BACKEND_ENDPOINTS = {
53
- 'codebuddy': 'https://www.codebuddy.ai/v2',
54
- 'codebuddy-intl': 'https://www.codebuddy.ai/v2',
55
- 'codebuddy-en': 'https://www.workbuddy.ai/v2',
56
- 'workbuddy': 'https://copilot.tencent.com/v2'
57
- }
58
-
59
- const AUTH_DOMAIN_ENDPOINTS = {
60
- 'www.codebuddy.cn': 'https://www.codebuddy.cn/v2',
61
- 'www.codebuddy.ai': 'https://www.codebuddy.ai/v2',
62
- 'www.workbuddy.ai': 'https://www.workbuddy.ai/v2',
63
- 'copilot.tencent.com': 'https://copilot.tencent.com/v2'
64
- }
65
-
66
- const BACKEND_LABELS = {
67
- 'codebuddy': 'CodeBuddy 国内版(npm CLI)',
68
- 'codebuddy-intl': 'CodeBuddy 国际版(npm CLI · 国际面)',
69
- 'codebuddy-en': 'WorkBuddy 国际版(WorkBuddyAI 桌面 CLI)',
70
- 'workbuddy': 'WorkBuddy 国内版(桌面 CLI)'
71
- }
72
-
73
- const BACKEND_ALIASES = {
74
- 'workbuddy-en': 'codebuddy-en',
75
- 'workbuddy-ai': 'codebuddy-en',
76
- 'codebuddy-ioa': 'codebuddy-intl',
77
- 'codebuddy-international': 'codebuddy-intl',
78
- 'codebuddy-oversea': 'codebuddy-intl'
79
- }
80
-
81
- const DEFAULT_BACKEND = 'codebuddy'
82
-
83
- const SETTINGS_KEYS = ['preferredBackend', 'defaultModel', 'codebuddyEnToken', 'endpointOverride']
84
-
85
16
  // codebuddy-en 凭据的第三条通道:DSH 凭据库里可能已有的 workbuddy key(旧 core verbatim)。
86
17
 
87
18
  // 离线/读不到描述文件时的回退静态表(真机按账号实测快照,2026-09)。
@@ -100,11 +31,12 @@ import {
100
31
  modelCatalogDetailed, formatModelCatalogText, cbCatalogSetHost,
101
32
  BACKEND_AUTH_IDS, CREDENTIAL_KEYS, readBackendAuthDomain,
102
33
  readDshWorkbuddyToken, resolveEnToken,
103
- fetchHelpModelsSync, cachedCliModels, currentPreferredBackend, parseHelpModels,
104
- RUN_PARAMS, CONTINUE_PARAMS, STATUS_PARAMS
34
+ fetchHelpModelsSync, cachedCliModels, currentPreferredBackend, parseHelpModels, probeAccountModelsSync,
35
+
105
36
  } from './codebuddy-catalog.mjs'
106
37
  import { codebuddyModelsTool } from './codebuddy-models-tool.mjs'
107
-
38
+ import { POLICY_TEXT, CODEBUDDY_LIMIT_RE, BACKENDS, BACKEND_ENDPOINTS, AUTH_DOMAIN_ENDPOINTS, BACKEND_LABELS, BACKEND_ALIASES, DEFAULT_BACKEND, SETTINGS_KEYS } from './codebuddy-consts.mjs'
39
+ import { RUN_PARAMS, CONTINUE_PARAMS, STATUS_PARAMS } from './codebuddy-schemas.mjs'
108
40
 
109
41
  export default function defineProvider(deps = {}) {
110
42
  const env = deps.env || {}
@@ -519,16 +451,25 @@ export default function defineProvider(deps = {}) {
519
451
  defaults: () => normalizeSettings(null),
520
452
  normalize: (raw) => normalizeSettings(raw),
521
453
  meta() {
522
- // defaultModel 下拉 = **实时**取自 CLI(parseHelpModels 解析 `--help` 的
523
- // "Currently supported: (...)")。此前读磁盘 product.ioa.json 静态表,实测
524
- // 落后于 CLI(16 项 vs CLI 19 项,且 2 个 id 已改名),是「列表不对」的根因。
525
- // 面板必须同步返回,故用零网络的 cli-help roster;账号级权威清单由
526
- // codebuddy_models 工具(异步探测)提供。
527
- // 面跟随 preferredBackend(旧实现硬编码 codebuddy 面,无视用户设置)。
454
+ // defaultModel 下拉 = 账号级实时清单(服务端裁决)。走过的弯路留档:
455
+ // ① 随包冻结的 product.ioa.json → 16 项、2 个 id 已改名(错)
456
+ // ② CLI `--help` 的 "Currently supported:" → 18 项,但那是 CLI 构建期烙进去的,
457
+ // 实测同样滞后(含已废弃的 minimax-m3/kimi-k3-1,缺 glm-5.3-flashx 等)
458
+ // ③ 现在:用无效模型探测让服务端回「该账号当前支持」的 19 项 —— 唯一权威源。
459
+ // 面板同步回调故用 spawnSync 探测并缓存 5 分钟;失败则下拉留空 + 明确提示,
460
+ // 绝不展示已知错误的 roster。面跟随 preferredBackend(旧实现硬编码 codebuddy 面)。
528
461
  const face = (currentPreferredBackend() && normalizeBackend(currentPreferredBackend())) || DEFAULT_BACKEND
529
- const live = cachedCliModels(face, () => fetchHelpModelsSync(env))
462
+ const faceEnv = (() => {
463
+ try {
464
+ const s = deps.settings || {}
465
+ const authDomain = readBackendAuthDomain(face, { env })
466
+ const tok = resolveEnToken(face === 'codebuddy-en' ? s.codebuddyEnToken : null, { env })
467
+ return endpointEnv(face, s.endpointOverride, authDomain, tok.token) || {}
468
+ } catch (e) { return {} }
469
+ })()
470
+ const live = cachedCliModels(face, () => probeAccountModelsSync(env, { envExtra: faceEnv, timeoutMs: 12000 }))
530
471
  let options = []
531
- let note = '账号实际可用性以服务端实时裁决;日常任务优先免费(x0.00)。'
472
+ let note = ''
532
473
  if (live && live.ok && live.ids.length) {
533
474
  const detail = modelCatalogDetailed(face, { env, accountModels: live.ids })
534
475
  const byId = new Map(detail.map((x) => [x.id, x]))
@@ -536,9 +477,10 @@ export default function defineProvider(deps = {}) {
536
477
  const d = byId.get(id)
537
478
  return { value: id, label: (d && d.label) || id }
538
479
  })
539
- note = '实时来自本机 codebuddy CLI 的声明名册(' + live.ids.length + ' 项,随 CLI 版本更新);当前面:' + face + '。账号级权威清单见 codebuddy_models。'
480
+ note = '账号实时清单(' + live.ids.length + ' 项,服务端裁决);当前面:' + face + '。日常任务优先免费(x0.00)。'
540
481
  } else {
541
- note = '未能从 CLI 读取模型名册(' + String((live && live.error) || 'unknown') + ')—— 下拉为空,可手动输入模型 id。'
482
+ note = '未能读取该账号的模型清单(' + String((live && live.error) || 'unknown') +
483
+ ')。请确认该产品面已登录(在 codebuddy CLI 里完成登录),或手动输入模型 id。'
542
484
  }
543
485
  return {
544
486
  titleSuffix: 'CodeBuddy',
@@ -0,0 +1,111 @@
1
+ // providers/mimo-pure.mjs — mimo 的纯解析/结果构造(无宿主依赖)。
2
+ //
3
+ // 从 providers/mimo.mjs 拆出,让两个文件都留在 600 行红线内(规则 §26)。
4
+ // build 会把 providers/mimo-*.mjs 全部内联进 dynamic 沙箱同一作用域,故主文件
5
+ // 仍可直接调用这些函数;ESM 形态走本文件的 import。
6
+ // 注意:注释里绝不写出口令标记字面量(build 全局替换会把注释劈开)。
7
+
8
+ import { shortLabel, summarizeArgs } from '../core/bridge-kit.mjs'
9
+
10
+ export function parseMimoJson(stdoutText) {
11
+ const trimmed = String(stdoutText || '').trim()
12
+ if (!trimmed) return null
13
+ const events = []
14
+ const lines = trimmed.split(/\r?\n/)
15
+ for (const raw of lines) {
16
+ const ln = raw.trim()
17
+ if (!ln.startsWith('{')) continue
18
+ try {
19
+ const obj = JSON.parse(ln)
20
+ if (obj && typeof obj === 'object') events.push(obj)
21
+ } catch (e) { /* tolerate log lines */ }
22
+ }
23
+ if (!events.length) {
24
+ try {
25
+ const obj = JSON.parse(trimmed)
26
+ if (obj && typeof obj === 'object') events.push(obj)
27
+ } catch (e) {
28
+ return { events: [], text: trimmed, sessionId: null, error: null, steps: [] }
29
+ }
30
+ }
31
+ let sessionId = null
32
+ let text = ''
33
+ let errorMessage = null
34
+ let errorName = null
35
+ let numTurns = 0
36
+ let totalTokens = null
37
+ const steps = []
38
+ const textParts = []
39
+ for (const ev of events) {
40
+ if (ev.sessionID && typeof ev.sessionID === 'string') sessionId = ev.sessionID
41
+ if (ev.sessionId && typeof ev.sessionId === 'string') sessionId = ev.sessionId
42
+ if (ev.session && typeof ev.session === 'object' && ev.session.id) sessionId = ev.session.id
43
+ if (ev.type === 'session' && ev.properties && ev.properties.id) sessionId = ev.properties.id
44
+ const t = ev.type
45
+ const p = ev.properties || ev
46
+ if (t === 'error') {
47
+ const err = ev.error || p
48
+ errorMessage = (err.data && err.data.message) || err.message || err.name || 'error'
49
+ errorName = err.name || 'Error'
50
+ } else if (t === 'text' || t === 'message' || t === 'assistant' || t === 'output') {
51
+ const chunk = p.text || p.content || p.message || p.output || (typeof ev.text === 'string' ? ev.text : '')
52
+ if (typeof chunk === 'string' && chunk) {
53
+ textParts.push(chunk)
54
+ steps.push({ at: Date.now(), kind: 'text', label: shortLabel(chunk) })
55
+ }
56
+ } else if (t === 'step-start' || t === 'step-finish' || t === 'step_update') {
57
+ numTurns += 1
58
+ if (p.tokens && typeof p.tokens === 'object') {
59
+ const tt = p.tokens.total ?? p.tokens.input ?? p.tokens.output
60
+ if (typeof tt === 'number') totalTokens = (totalTokens || 0) + tt
61
+ }
62
+ if (t === 'step_update') {
63
+ const name = p.tool_name || p.tool || p.name
64
+ if (name) steps.push({ at: Date.now(), kind: 'tool', label: shortLabel(name + ' ' + JSON.stringify(summarizeArgs(p.arguments || p.args || p.input) || {})) })
65
+ }
66
+ } else if (t === 'tool' || t === 'tool-call' || t === 'tool_use') {
67
+ const name = p.tool || p.name || p.tool_name || 'tool'
68
+ steps.push({ at: Date.now(), kind: 'tool', label: shortLabel(name + ' ' + JSON.stringify(summarizeArgs(p.arguments || p.args || p.input) || {})) })
69
+ }
70
+ }
71
+ if (textParts.length) text = textParts.join('\n')
72
+ else {
73
+ const last = events[events.length - 1] || {}
74
+ const r = last.result || last
75
+ if (typeof r.response === 'string') text = r.response
76
+ else if (typeof r.text === 'string') text = r.text
77
+ }
78
+ return { events, text, sessionId, error: errorMessage, errorName, numTurns, totalTokens, steps }
79
+ }
80
+
81
+ export function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
82
+ const MAX_TRAIL = 12
83
+ const exitCode = outcome ? outcome.exitCode : null
84
+ const errText = (parsed && parsed.error) ? String(parsed.error) : ''
85
+ const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
86
+ const text = parsed && typeof parsed.text === 'string' ? parsed.text : ''
87
+ const failed = exitCode !== 0 || !!(parsed && parsed.error)
88
+ const be = (parsed && parsed.backend) || (outcome && outcome.backend) || backend || null
89
+ if (parsed) {
90
+ return {
91
+ ok: !failed && (!!text || parsed.accepted === true),
92
+ status: failed ? (parsed.errorName || 'ERROR') : (parsed.accepted && !text ? 'ACCEPTED' : (text ? 'SUCCESS' : 'EMPTY')),
93
+ response: text,
94
+ sessionId: parsed.sessionId || null,
95
+ durationSeconds: null,
96
+ numTurns: parsed.numTurns || null,
97
+ totalTokens: parsed.totalTokens || null,
98
+ exitCode, mode, backend: be,
99
+ stderr,
100
+ errorMessage: parsed.error || '',
101
+ accepted: parsed.accepted === true,
102
+ steps: Array.isArray(parsed.steps) ? parsed.steps.slice(-MAX_TRAIL) : []
103
+ }
104
+ }
105
+ return {
106
+ ok: false, status: 'PARSE_ERROR', response: '', sessionId: null,
107
+ durationSeconds: null, numTurns: null, totalTokens: null,
108
+ exitCode, mode, backend: be, stderr, errorMessage: '',
109
+ rawStdout: String(stdoutText || '').slice(-2000)
110
+ }
111
+ }