@luchenglong/cli-bridge 0.2.9 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +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
-
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,254 @@
1
+ // providers/codebuddy-models-source.mjs — codebuddy 的「模型清单探测 + 缓存」(第二片).
2
+ //
3
+ // 从 codebuddy-catalog.mjs 抽出:探测要走子进程(同步/异步两条路),与纯解析逻辑内聚度低,
4
+ // 分开后两个文件都在 600 行红线内(规则 §26)。scripts/build.mjs 会把 providers/codebuddy-*.mjs
5
+ // 全部按字典序内联进 dynamic 沙箱同一作用域,所以这里仍可引用 catalog 的函数;ESM 形态走 import。
6
+ // 注意:注释里绝不写出口令标记字面量(build 全局替换会把注释劈开导致生成物语法崩)。
7
+
8
+ import { cbCatalogEnv, cbCatalogRead, cbCatalogPathJoin, parseAccountModels } from './codebuddy-catalog.mjs'
9
+
10
+ // ── 实时模型清单(CLI 是一手权威来源,对齐 workbuddy-auth 的「权威白名单」思路)──
11
+ //
12
+ // 为什么不再以静态表/磁盘描述文件为主:实测本机 codebuddy CLI --
13
+ // • 账号实时清单(用无效模型触发 400 报文)= 19 项
14
+ // • CLI `--help` 声明的 roster = 19 项,与账号清单完全一致
15
+ // • 我们原先读的 product.ioa.json 静态表 = 16 项,且 2 个 id 已过时
16
+ // (minimax-m3 → minimax-m3-pay、kimi-k3-1 → kimi-k3-2),另缺 4 个新模型。
17
+ // 静态表是「随包冻结」的,必然落后于 CLI,故只保留作倍率元数据与最后兜底。
18
+ //
19
+ // 两级实时来源(都不静默冒充权威数据,各带 source 标签):
20
+ // A. account-live —— 起 CLI 用无效模型探测「该账号当前支持」的清单(需该面已登录,
21
+ // 一次网络往返;对照 workbuddy-auth 的 agents[cli].models 白名单语义)。
22
+ // B. cli-help —— 解析 `--help` 的 "Currently supported: (...)"(零网络、随 CLI
23
+ // 版本自动更新;产品面级 roster)。
24
+ // 静态表仅作 credit 元数据与 descriptor-static 兜底标签,绝不冒充实时。
25
+
26
+ /** 解析 CLI `--help` 里声明的模型 roster。空/畸形输入返回 []。
27
+ * ⚠️ 名册很长时 yargs 会在任意列**折行**(实测把 `minimax-m3-pay` 从中间断成
28
+ * `minimax-` + `m3-pay`),若按行/按逗号直接切会丢项或产生残片(同一命令两次运行
29
+ * 给出 18/19 两种结果)。故先去掉括号内所有空白再按逗号切:逗号是唯一分隔符,
30
+ * 折行插入的空白一律视为噪声。 */
31
+ export function parseHelpModels(helpText) {
32
+ const m = /Currently supported:\s*\(([^)]+)\)/.exec(String(helpText || ''))
33
+ if (!m) return []
34
+ const out = []
35
+ for (const raw of m[1].replace(/\s+/g, '').split(',')) {
36
+ const id = raw.trim()
37
+ if (id && /^[A-Za-z0-9_.\-]+$/.test(id) && out.indexOf(id) < 0) out.push(id)
38
+ }
39
+ return out
40
+ }
41
+
42
+ /** 解析 codebuddy CLI 的可执行候选(env > npm 全局 shim > PATH 名)。 */
43
+ export function cbCatalogCliCandidates(env) {
44
+ const e = env || cbCatalogEnv || {}
45
+ const out = []
46
+ const push = (p) => { if (p && out.indexOf(p) < 0) out.push(p) }
47
+ if (e.CODEBUDDY_BIN) push(String(e.CODEBUDDY_BIN))
48
+ const joinP = (a, b) => cbCatalogPathJoin(a, b)
49
+ if (e.APPDATA) push(joinP(joinP(e.APPDATA, 'npm'), 'codebuddy.cmd'))
50
+ if (e.APPDATA) push(joinP(joinP(e.APPDATA, 'npm'), 'codebuddy'))
51
+ push('codebuddy')
52
+ return out
53
+ }
54
+
55
+ const CLI_MODEL_CACHE = new Map() // backend → { at, mode, ids }
56
+ const CLI_MODEL_TTL_MS = 5 * 60 * 1000
57
+
58
+ // Windows .cmd/.bat 需要经 shell(Node 安全限制),但 `shell:true` + args 数组会触发
59
+ // DEP0190(参数不转义)。这里统一做法:把命令与参数拼成【一个】字符串交给 shell,
60
+ // 参数各自按 Windows 规则加引号 —— 既避开 DEP0190,又保证含空格参数不被拆开。
61
+ function quoteWinArg(a) {
62
+ const s = String(a)
63
+ if (s === '') return '""'
64
+ if (!/[\s"&|<>^]/.test(s)) return s
65
+ return '"' + s.replace(/"/g, '\\"') + '"'
66
+ }
67
+ function cliCommandLine(exe, args) {
68
+ return [exe].concat(args || []).map(quoteWinArg).join(' ')
69
+ }
70
+
71
+ /** 把候选拆成 { cmd, prefixArgs }:.mjs/.js/.cjs 目标经 node 包装(测试夹具与自定义
72
+ * 入口都靠这条),其余原样。 */
73
+ function splitExeSpec(exe) {
74
+ if (/\.(mjs|cjs|js)$/i.test(String(exe))) {
75
+ const proc = globalThis.process
76
+ return { cmd: (proc && proc.execPath) ? proc.execPath : 'node', prefixArgs: [String(exe)] }
77
+ }
78
+ return { cmd: String(exe), prefixArgs: [] }
79
+ }
80
+
81
+ function cliSpawnSync(exe, args, opts) {
82
+ const proc = globalThis.process
83
+ const child = (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule('node:child_process') : null
84
+ if (!child || typeof child.spawnSync !== 'function') return null
85
+ const base = Object.assign({
86
+ encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe']
87
+ }, opts || {})
88
+ const spec = splitExeSpec(exe)
89
+ const argv = spec.prefixArgs.concat(args || [])
90
+ const isCmd = /\.(cmd|bat)$/i.test(spec.cmd)
91
+ if (isCmd) base.shell = true
92
+ try {
93
+ // shell 形态不带 args 数组(否则 DEP0190);非 shell 形态正常传数组。
94
+ return isCmd
95
+ ? child.spawnSync(cliCommandLine(spec.cmd, argv), base)
96
+ : child.spawnSync(spec.cmd, argv, base)
97
+ } catch (e) { return null }
98
+ }
99
+
100
+ /**
101
+ * 同步取「CLI 声明的 roster」(零网络,随 CLI 版本走)。
102
+ * @returns {{ok:boolean, ids:string[], mode:string, error?:string}}
103
+ */
104
+ export function fetchHelpModelsSync(env, opts) {
105
+ const o = opts || {}
106
+ const cands = cbCatalogCliCandidates(env)
107
+ let lastErr = null
108
+ for (const exe of cands) {
109
+ const r = cliSpawnSync(exe, ['--help'], { timeout: Math.max(1000, Math.min(o.timeoutMs || 12000, 30000)) })
110
+ if (!r || r.error) { lastErr = 'spawn failed: ' + String((r && r.error && r.error.message) || 'unavailable'); continue }
111
+ const text = String(r.stdout || '') + String(r.stderr || '')
112
+ const ids = parseHelpModels(text)
113
+ if (ids.length) return { ok: true, ids, mode: 'cli-help', exe }
114
+ lastErr = 'no roster in --help output'
115
+ }
116
+ return { ok: false, ids: [], mode: 'cli-help', error: lastErr || 'codebuddy CLI not found (set CODEBUDDY_BIN)' }
117
+ }
118
+
119
+ /**
120
+ * 同步版的账号探测(供设置面板用 —— 面板必须同步返回)。
121
+ * 走 spawnSync + 超时;结果进 5 分钟缓存,避免每次渲染都打一次网络。
122
+ *
123
+ * ⚠️ 为什么面板不能用 `--help` 名册顶替:实测本机 CLI 2.167.0 的 help 文本**本身
124
+ * 就是过时的** —— 它列 18 项且含已不存在的 `minimax-m3` / `kimi-k3-1`,缺真实的
125
+ * `glm-5.3-flashx` / `minimax-m3-pay` / `kimi-k3-2`;而账号探测给出 19 项且全部有效。
126
+ * 也就是说「CLI 声明」≠「服务端实际可用」,拿它当兜底会直接把错误清单展示给用户。
127
+ * 故这里宁可空列表 + 明确提示,也不展示已知错误的 roster。
128
+ * @returns {{ok:boolean, ids:string[], mode:string, error?:string}}
129
+ */
130
+ export function probeAccountModelsSync(env, opts) {
131
+ const o = opts || {}
132
+ const cands = cbCatalogCliCandidates(env)
133
+ const extraEnv = o.envExtra || {}
134
+ const reasons = []
135
+ const timeout = Math.max(3000, Math.min(o.timeoutMs || 12000, 30000))
136
+ for (const exe of cands) {
137
+ const r = cliSpawnSync(exe, ['-p', 'hi', '--model', '__clb_probe_invalid__', '--output-format', 'text'], {
138
+ timeout,
139
+ env: Object.assign({}, (globalThis.process && globalThis.process.env) || {}, env || {}, extraEnv)
140
+ })
141
+ if (!r || r.error) { reasons.push(exe + ': ' + String((r && r.error && (r.error.code || r.error.message)) || 'spawn failed')); continue }
142
+ const out = String(r.stdout || '') + String(r.stderr || '')
143
+ const ids = parseAccountModels(out)
144
+ if (ids && ids.length) return { ok: true, ids, mode: 'account-live', exe }
145
+ const head = String(out).replace(/\s+/g, ' ').trim().slice(0, 140)
146
+ reasons.push(exe + ': exit ' + r.status + ', no account roster' + (head ? ' — ' + head : ''))
147
+ }
148
+ return { ok: false, ids: [], mode: 'account-live', error: reasons.join('; ') || 'no CLI candidate to probe' }
149
+ }
150
+
151
+ /**
152
+ * 异步探测「该账号当前支持」的清单:用无效模型触发 CLI 的 400 报文。
153
+ * 对齐 workbuddy-auth 的权威白名单语义(服务器告诉我们这个账号能用什么)。
154
+ * @returns {Promise<{ok:boolean, ids:string[], mode:string, error?:string}>}
155
+ */
156
+ export function probeAccountModels(env, opts) {
157
+ const o = opts || {}
158
+ const cands = cbCatalogCliCandidates(env)
159
+ const proc = globalThis.process
160
+ const child = (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule('node:child_process') : null
161
+ if (!child || typeof child.spawn !== 'function') {
162
+ return Promise.resolve({ ok: false, ids: [], mode: 'account-live', error: 'no spawn capability in this host form' })
163
+ }
164
+ const extraEnv = o.envExtra || {}
165
+ return new Promise((resolve) => {
166
+ let idx = 0
167
+ // 记录每个候选的真实结局:区分「压根没找到 CLI」与「CLI 跑了但没吐账号名录」
168
+ // (后者通常是该面未登录 / 端点拒了)—— 报错文案必须能指导下一步,不能一律
169
+ // 说 "CLI not found"(本轮就踩到:codebuddy-en 无 token 时被误报成找不到 CLI)。
170
+ const reasons = []
171
+ const attempt = () => {
172
+ if (idx >= cands.length) {
173
+ resolve({
174
+ ok: false, ids: [], mode: 'account-live',
175
+ error: reasons.length ? reasons.join('; ') : 'no CLI candidate to probe',
176
+ notFound: reasons.every((r) => /not found|ENOENT|spawn/i.test(r))
177
+ })
178
+ return
179
+ }
180
+ const exe = cands[idx++]
181
+ let c
182
+ try {
183
+ // .cmd/.bat 需经 shell(Windows 安全限制);.mjs/.js 经 node 包装。
184
+ // 与 cliSpawnSync 同一规则:shell 形态把命令拼成单字符串(避免 DEP0190)。
185
+ const spec = splitExeSpec(exe)
186
+ const isCmd = /\.(cmd|bat)$/i.test(spec.cmd)
187
+ const probeArgs = spec.prefixArgs.concat(['-p', 'hi', '--model', '__clb_probe_invalid__', '--output-format', 'text'])
188
+ const opts = {
189
+ stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
190
+ env: Object.assign({}, proc.env, env || {}, extraEnv)
191
+ }
192
+ c = isCmd
193
+ ? child.spawn(cliCommandLine(spec.cmd, probeArgs), Object.assign({ shell: true }, opts))
194
+ : child.spawn(spec.cmd, probeArgs, opts)
195
+ } catch (e) { reasons.push(exe + ': spawn threw ' + String(e && e.message || e)); attempt(); return }
196
+ let out = ''
197
+ const timer = setTimeout(() => { try { c.kill() } catch (e) { } }, Math.max(5000, Math.min(o.timeoutMs || 30000, 90000)))
198
+ const onData = (d) => { out += d; if (out.length > 400000) out = out.slice(-200000) }
199
+ c.stdout.on('data', onData)
200
+ c.stderr.on('data', onData)
201
+ c.on('error', (e) => {
202
+ clearTimeout(timer)
203
+ reasons.push(exe + ': ' + String((e && e.code) || (e && e.message) || 'spawn error'))
204
+ attempt()
205
+ })
206
+ c.on('close', (code) => {
207
+ clearTimeout(timer)
208
+ const ids = parseAccountModels(out)
209
+ if (ids && ids.length) { resolve({ ok: true, ids, mode: 'account-live', exe }); return }
210
+ const head = String(out).replace(/\s+/g, ' ').trim().slice(0, 160)
211
+ reasons.push(exe + ': exit ' + code + ', no account roster' + (head ? ' — ' + head : ''))
212
+ attempt()
213
+ })
214
+ }
215
+ attempt()
216
+ })
217
+ }
218
+
219
+ /** 缓存读写(面板每次渲染都会取,避免反复起进程)。 */
220
+ export function cachedCliModels(backend, load, nowMs) {
221
+ const at = Number(nowMs) || Date.now()
222
+ const hit = CLI_MODEL_CACHE.get(backend)
223
+ if (hit && at - hit.at < CLI_MODEL_TTL_MS) return hit
224
+ // 不传 load = 纯只读缓存(未命中返回 undefined)。设置面板靠这条避免每次渲染都 spawn。
225
+ if (typeof load !== 'function') return undefined
226
+ const v = load()
227
+ if (v && v.ok && v.ids && v.ids.length) CLI_MODEL_CACHE.set(backend, { at, mode: v.mode, ids: v.ids.slice() })
228
+ return v
229
+ }
230
+
231
+ /**
232
+ * 手动拉取成功后回填缓存(契约 §3.2 的 refreshModels 用),让随后的 meta() 能直接命中。
233
+ * 只接受非空 ids —— 空结果绝不入缓存,否则下次渲染会显示"有缓存但没内容"。
234
+ */
235
+ export function rememberCliModels(backend, ids, mode, nowMs) {
236
+ if (!Array.isArray(ids) || !ids.length) return false
237
+ CLI_MODEL_CACHE.set(backend, { at: Number(nowMs) || Date.now(), mode: mode || 'account-live', ids: ids.slice() })
238
+ return true
239
+ }
240
+
241
+ /** 读统一设置文件里 codebuddy 分区的 preferredBackend(meta 需要它才知道列哪个面)。 */
242
+ export function currentPreferredBackend() {
243
+ try {
244
+ const e = cbCatalogEnv || {}
245
+ const p = cbCatalogRead(e.CLI_BRIDGE_SETTINGS_FILE || cbCatalogPathJoin(
246
+ e.DSH_HOME || (e.APPDATA ? cbCatalogPathJoin(e.APPDATA, 'DSH Desktop', 'dsh-home') : ''), 'cli-bridge-settings.json'))
247
+ if (!p) return null
248
+ const all = JSON.parse(p)
249
+ const v = all && all.codebuddy && all.codebuddy.preferredBackend
250
+ return typeof v === 'string' && v ? v : null
251
+ } catch (err) { return null }
252
+ }
253
+
254
+ // CLI 报错里解析「该账号当前支持的模型」(旧 core parseAccountModels verbatim)。