@luchenglong/cli-bridge 0.2.4 → 0.2.6

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,926 +1,636 @@
1
- // providers/codebuddy.mjs — codebuddy provider descriptor(真移植,替换 Lead 冒烟占位)。
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。
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 通用表。
19
- import { createStatusEngine, createRunner, clampInt } from '../core/bridge-kit.mjs'
20
-
21
- // ── 提示词策略段(旧 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
- // (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_AUTH_IDS = {
67
- 'codebuddy': 'Tencent-Cloud.coding-copilot',
68
- 'codebuddy-intl': 'Tencent-Cloud.coding-copilot',
69
- 'codebuddy-en': 'workbuddy-desktop-ai',
70
- 'workbuddy': 'workbuddy-desktop'
71
- }
72
-
73
- const BACKEND_LABELS = {
74
- 'codebuddy': 'CodeBuddy 国内版(npm CLI)',
75
- 'codebuddy-intl': 'CodeBuddy 国际版(npm CLI · 国际面)',
76
- 'codebuddy-en': 'WorkBuddy 国际版(WorkBuddyAI 桌面 CLI)',
77
- 'workbuddy': 'WorkBuddy 国内版(桌面 CLI)'
78
- }
79
-
80
- const BACKEND_ALIASES = {
81
- 'workbuddy-en': 'codebuddy-en',
82
- 'workbuddy-ai': 'codebuddy-en',
83
- 'codebuddy-ioa': 'codebuddy-intl',
84
- 'codebuddy-international': 'codebuddy-intl',
85
- 'codebuddy-oversea': 'codebuddy-intl'
86
- }
87
-
88
- const DEFAULT_BACKEND = 'codebuddy'
89
-
90
- const SETTINGS_KEYS = ['preferredBackend', 'defaultModel', 'codebuddyEnToken', 'endpointOverride']
91
-
92
- // codebuddy-en 凭据的第三条通道:DSH 凭据库里可能已有的 workbuddy key(旧 core verbatim)。
93
- const CREDENTIAL_KEYS = ['WORKBUDDY_TOKEN', 'WORKBUDDY_AI_TOKEN', 'CODEBUDDY_EN_TOKEN']
94
-
95
- // 离线/读不到描述文件时的回退静态表(真机按账号实测快照,2026-09)。
96
- const BACKEND_MODEL_IDS = {
97
- 'codebuddy': ['hy4-preview', 'hy3', 'hy3-x', 'deepseek-v4.1-flash', 'glm-5.3', 'glm-5.3-flash', 'glm-5.2', 'glm-5.1', 'glm-5v-turbo', 'minimax-m3', 'minimax-m2.7', 'kimi-k3-1', 'kimi-k2.8-preview', 'kimi-k2.7', 'kimi-k2.6', 'deepseek-v4-pro'],
98
- 'codebuddy-intl': ['claude-sonnet-5', 'claude-sonnet-5-1m', 'claude-opus-5', 'claude-opus-4.8', 'claude-opus-4.8-1m', 'gemini-3.1-pro', 'gemini-3.5-flash', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5', 'gpt-5.4', 'glm-5.3-ioa', 'glm-5.3-flash-ioa', 'glm-5.2-ioa', 'kimi-k3-ioa', 'kimi-k2.8-preview', 'kimi-k2.6-ioa', 'minimax-m3-ioa', 'minimax-m2.7-ioa', 'deepseek-v4.1-flash', 'deepseek-v4-pro-ioa'],
99
- // WorkBuddyAI 自制目录(product.json 顶层 37 项,按其 credits 排序:免费的在前)
100
- 'codebuddy-en': ['hy3', 'gpt-5.1-codex-mini', 'gemini-3.1-flash-lite', 'gemini-2.5-flash', 'minimax-m3', 'gemini-3.0-flash', 'fast-model', 'deepseek-v3-2-volc', 'balanced-model', 'kimi-k2.5', 'kimi-k2.6', 'default-model-lite', 'glm-5.3', 'glm-5.2', 'glm-5.0', 'gpt-5.1-codex', 'gemini-2.5-pro', 'gemini-3.5-flash', 'gpt-5.3-codex', 'gemini-3.1-pro', 'gpt-5.6-terra', 'kimi-k3', 'gpt-5.4', 'primary-model', 'default-model', 'deep-model', 'gpt-5.5', 'gpt-5.6-sol', 'gpt-5.6-luna'],
101
- // WorkBuddy 国内桌面自制目录(product.json:applicationName=WorkBuddy)
102
- 'workbuddy': ['auto', 'hy4-preview', 'hy3', 'hy3-x', 'deepseek-v4.1-flash', 'glm-5.3', 'glm-5.3-flash', 'glm-5.2', 'glm-5.1', 'glm-5v-turbo', 'minimax-m3', 'minimax-m2.7', 'kimi-k3-1', 'kimi-k2.8-preview', 'kimi-k2.7', 'kimi-k2.6', 'deepseek-v4-pro']
103
- }
104
-
105
- // 各后端真正生效的 product 描述文件位置(旧 core v1.6.1 verbatim)。
106
- const PRODUCT_DESCRIPTOR_ENV = {
107
- 'codebuddy': { env: 'CODEBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
108
- 'codebuddy-intl': { env: 'CODEBUDDY_INTL_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
109
- 'codebuddy-en': { env: 'CODEBUDDY_EN_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy-ai' },
110
- 'workbuddy': { env: 'WORKBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy' }
111
- }
112
-
113
- // 倍率跨命名匹配(账号清单 id → 描述文件 id,旧 core verbatim)。
114
- const CREDIT_ID_ALIASES = {
115
- 'kimi-k3-1': ['kimi-k3', 'kimi-k3-ioa'],
116
- 'hy3-x': ['hy3', 'hy3-ioa'],
117
- 'default': ['codewise-default-model-v2'],
118
- 'auto': ['hy3', 'hy3-ioa']
119
- }
120
-
121
- const MODEL_DESCRIPTION = 'Optional model id. When unspecified, the user-preferred default model (plugin settings) is used if set, else the CLI default. Two layers decide: the PRODUCT FACE decides whether the id exists in its catalogue, then the ACCOUNT decides whether it is licensed. The free tier (hy3, deepseek-v4.1-flash at x0.00 credits; hy4-preview at x0.29) belongs to the npm CLI faces codebuddy/codebuddy-intl: hy4-preview, hy3, hy3-x, deepseek-v4.1-flash, glm-5.3, glm-5.3-flash, glm-5.2, glm-5.1, glm-5v-turbo, minimax-m3, minimax-m2.7, kimi-k3-1, kimi-k2.8-preview, kimi-k2.7, kimi-k2.6, deepseek-v4-pro. codebuddy-en (WorkBuddyAI) carries NO hy4-preview and NO deepseek-v4.1-flash; its only free model is hy3. International ids (claude-sonnet-5, gemini-3.1-pro, ...) are account-gated. Availability is per ACCOUNT: the CLI rejects an id outside the account catalogue with "400 service info not found" and one inside it but unlicensed with "400 only available for authorized users" (many catalogue flagships such as claude-opus-4.8, gpt-5.4 and gpt-6-astra are in this second group for a domestic account). Run the CLI with a deliberately invalid model id to print "Currently supported models for your account:" and get the authoritative list; the plugin caches that result and the settings panel lists exactly those ids with their credit multiplier (x0.00 = free), read live from the CLI descriptor so it stays in sync with CLI upgrades. Prefer the cheapest model that can do the job, and prefer a free (x0.00) one for routine work. Pass a model only when the task clearly benefits from a specific one.'
122
-
123
- const BACKEND_ENUM = ['codebuddy', 'codebuddy-intl', 'codebuddy-ioa', 'codebuddy-international', 'codebuddy-en', 'workbuddy-en', 'workbuddy-ai', 'workbuddy']
124
-
125
- // ── 三工具 schema(旧 preset/codebuddy-first verbatim;契约 §8)────────────────
126
- const RUN_PARAMS = {
127
- type: 'object',
128
- additionalProperties: false,
129
- required: ['prompt'],
130
- properties: {
131
- prompt: { type: 'string', description: 'The full task/instruction for codebuddy. Be complete and self-contained.' },
132
- 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.' },
133
- mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'auto follows DSH plan state; plan = no writes; accept-edits = allow edits. Default auto.' },
134
- model: { type: 'string', description: MODEL_DESCRIPTION },
135
- effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
136
- maxTurns: { type: 'integer', description: 'Optional max agentic turns (1-500, default unlimited).' },
137
- cwd: { type: 'string', description: 'Working directory for codebuddy. Defaults to the DSH workspace root.' },
138
- addDirs: { type: 'array', items: { type: 'string' }, description: 'Extra directories to add to codebuddy workspace.' },
139
- timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
140
- background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
141
- }
142
- }
143
- const CONTINUE_PARAMS = {
144
- type: 'object',
145
- additionalProperties: false,
146
- required: ['prompt'],
147
- properties: {
148
- prompt: { type: 'string', description: 'Follow-up instruction for the ongoing codebuddy conversation.' },
149
- sessionId: { type: 'string', description: 'codebuddy session id to resume (from a prior codebuddy_run result).' },
150
- latest: { type: 'boolean', description: 'Continue the most recent codebuddy conversation instead of a specific id.' },
151
- 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).' },
152
- mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'Execution mode; default auto.' },
153
- 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).' },
154
- effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
155
- maxTurns: { type: 'integer', description: 'Optional max agentic turns.' },
156
- cwd: { type: 'string', description: "Working directory for codebuddy; when resuming, defaults to the resumed session's project directory." },
157
- timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
158
- background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
159
- }
160
- }
161
- const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
162
-
163
- export default function defineProvider(deps = {}) {
164
- const env = deps.env || {}
165
- let host = null // attach 后保存 hostOpts(preset/dynamic/MCP 形态宿主能力)
166
-
167
- // 宿主 fs/path 访问的统一入口:deps 注入优先;dynamic 内联体(无 import,运行在
168
- // 后端 Node 上下文)回退到 getBuiltinModule —— 与旧 core builtinModule() 的
169
- // typeof 守卫模式一致(这是旧 dynamic 端点修复生效的同一条通道,缺了它默认
170
- // 后端会回到 401 老病)。两者皆不可用时自然降级:读不到文件 = 静态表兜底。
171
- function builtinModule(name) {
172
- try {
173
- const proc = globalThis.process
174
- return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
175
- } catch (e) { return null }
176
- }
177
- function fsRead(p) {
178
- const nf = deps.nodeFs || builtinModule('node:fs')
179
- if (!nf || typeof nf.readFileSync !== 'function') return null
180
- try { return nf.readFileSync(p, 'utf8') } catch (e) { return null }
181
- }
182
- function pathJoin(...parts) {
183
- const np = deps.nodePath || builtinModule('node:path')
184
- if (np && typeof np.join === 'function') return np.join(...parts)
185
- return parts.join('/')
186
- }
187
- const pathSep = (deps.nodePath && deps.nodePath.sep) || (/[A-Za-z]:[\\/]/.test(env.USERPROFILE || env.APPDATA || '') ? '\\' : '/')
188
-
189
- // ── 端点/登录域(旧 core endpointHost verbatim:非法 URL 容错)───────────────
190
- function endpointHost(url) {
191
- const s = String(url || '').trim()
192
- if (!s) return ''
193
- try { return new URL(s).hostname.toLowerCase() } catch (e) { }
194
- const m = /^[a-z]+:\/\/([^/?#]+)/i.exec(s)
195
- return m ? m[1].toLowerCase() : ''
196
- }
197
-
198
- function resolveEndpoint(explicitBaseUrl, authDomain) {
199
- const explicit = String(explicitBaseUrl || '').trim()
200
- if (explicit) return explicit
201
- const d = String(authDomain || '').trim().toLowerCase()
202
- if (d && AUTH_DOMAIN_ENDPOINTS[d]) return AUTH_DOMAIN_ENDPOINTS[d]
203
- return null
204
- }
205
-
206
- function isBackend(v) { return BACKENDS.indexOf(v) >= 0 }
207
-
208
- // 后端名规范化(v1.3.3 verbatim):别名 + 大小写不敏感;非后端名原样返回。
209
- function normalizeBackend(v) {
210
- if (typeof v !== 'string') return v
211
- const lower = v.trim().toLowerCase()
212
- const aliased = BACKEND_ALIASES[lower] || lower
213
- return BACKENDS.indexOf(aliased) >= 0 ? aliased : v
214
- }
215
-
216
- // 后端解析优先级(旧 core verbatim):显式 > 会话归属 > 用户偏好 > 默认。
217
- function resolveBackend(args, target, preferredBackend) {
218
- if (args && isBackend(normalizeBackend(args.backend))) return normalizeBackend(args.backend)
219
- if (target && target.backend && isBackend(normalizeBackend(target.backend))) return normalizeBackend(target.backend)
220
- if (preferredBackend && isBackend(normalizeBackend(preferredBackend))) return normalizeBackend(preferredBackend)
221
- return DEFAULT_BACKEND
222
- }
223
-
224
- // 本次调用的端点/凭据 env 注入(旧 core endpointEnv verbatim 三规则)。
225
- function endpointEnv(backend, explicitBaseUrl, authDomain, authToken) {
226
- const out = {}
227
- const endpoint = resolveEndpoint(explicitBaseUrl, authDomain)
228
- const product = BACKEND_ENDPOINTS[backend]
229
- if (endpoint && endpointHost(endpoint) !== endpointHost(product)) {
230
- out.CODEBUDDY_BASE_URL = endpoint
231
- }
232
- if (backend === 'codebuddy-en') {
233
- const tok = String(authToken || '').trim()
234
- if (tok) out.CODEBUDDY_AUTH_TOKEN = tok
235
- }
236
- return Object.keys(out).length ? out : null
237
- }
238
-
239
- // 可操作提示(旧 core endpointMismatchHint 三分支 verbatim)。
240
- function endpointMismatchHint(backend, authDomain, hasToken) {
241
- if (backend === 'codebuddy-en' && !hasToken) {
242
- return 'codebuddy-en(WorkBuddy 国际版)没有可用凭据。国际版的登录 token 被桌面 App 的 protector key 封装,该密钥不落盘、headless CLI 无法自行读取(CLI 自身报 category:"missing-key")。桥接会依次尝试:插件设置 codebuddyEnToken → 环境变量 CODEBUDDY_AUTH_TOKEN → DSH 凭据库(.credentials.yaml / .env 里的 WORKBUDDY_TOKEN)——三者皆空。请在 DSH 里配好 workbuddy provider 的 key,或把国际版 token 填入插件设置;也可直接用 backend="workbuddy"(国内版桌面 CLI,免配置)。'
243
- }
244
- if (backend === 'codebuddy-intl') {
245
- return 'codebuddy-intl(CodeBuddy 国际版)使用同一个 npm CLI,但国际面模型由服务端按账号授权放行:未授权时 CLI 返回 400「model [...] is only available for authorized users」。若你用的是国内账号,请改用 backend="codebuddy"(国内面模型清单)或 backend="codebuddy-en"(WorkBuddy 国际版)。'
246
- }
247
- const d = String(authDomain || '').trim().toLowerCase()
248
- if (d && endpointHost(resolveEndpoint(null, d)) !== endpointHost(BACKEND_ENDPOINTS[backend])) {
249
- return backend + ' 的登录域是 ' + d + ',与产品端点 ' + BACKEND_ENDPOINTS[backend] + ' 不一致;桥接层已自动注入 CODEBUDDY_BASE_URL=' + AUTH_DOMAIN_ENDPOINTS[d] + '。若仍 401,请重新登录对应客户端。'
250
- }
251
- return null
252
- }
253
-
254
- // 从 auth 库读某后端登录域(旧 core readBackendAuthDomain verbatim 语义;fs 经
255
- // deps 注入。io 可覆盖 readFileSync/dir/env,供测试夹具与 MCP 面注入真实 fs)。
256
- function readBackendAuthDomain(backend, io) {
257
- const o = io || {}
258
- const id = BACKEND_AUTH_IDS[backend]
259
- if (!id) return null
260
- try {
261
- const read = o.readFileSync || fsRead
262
- if (typeof read !== 'function') return null
263
- const e = o.env || env
264
- let dir = o.dir
265
- if (!dir) {
266
- dir = e.CODEBUDDY_AUTH_DIR ||
267
- pathJoin(e.LOCALAPPDATA || 'C:\\Users\\lcl\\AppData\\Local', 'CodeBuddyExtension', 'Data', 'Public', 'auth')
268
- }
269
- const sep = String(dir).indexOf('\\') >= 0 ? '\\' : '/'
270
- const txt = read(dir + sep + id + '.info', 'utf8')
271
- if (txt == null) return null
272
- const raw = JSON.parse(txt)
273
- const d = raw && raw.auth && raw.auth.domain
274
- return typeof d === 'string' && d.trim() ? d.trim() : null
275
- } catch (e) { return null }
276
- }
277
-
278
- // DSH 凭据库第三通道(旧 core readDshWorkbuddyToken verbatim 语义;CODEBUDDY_
279
- // CREDENTIALS_DIR 覆盖测试夹具;fs 经 deps 注入)。
280
- function readDshWorkbuddyToken() {
281
- const overrideDir = env.CODEBUDDY_CREDENTIALS_DIR || null
282
- const home = overrideDir || env.DSH_HOME || null
283
- if (!home) return null
284
- const files = [home + '\\.credentials.yaml', home + '\\.env', home + '/.credentials.yaml', home + '/.env']
285
- for (const f of files) {
286
- const text = fsRead(f)
287
- if (!text) continue
288
- for (const key of CREDENTIAL_KEYS) {
289
- const m = text.match(new RegExp('^[ \\t]*' + key + '[ \\t]*[:=][ \\t]*(.+)$', 'm'))
290
- if (!m) continue
291
- const v = m[1].trim().replace(/\s+#.*$/, '').replace(/^['"]|['"]$/g, '').trim()
292
- // 只接受看起来是真实 token 的值(避免把 $VAR 引用或占位符当凭据)。
293
- if (v.length >= 40 && !v.startsWith('$') && !/^<.*>$/.test(v)) return v
294
- }
295
- }
296
- return null
297
- }
298
-
299
- // codebuddy-en 凭据链(旧 core verbatim):设置面板 > CODEBUDDY_AUTH_TOKEN >
300
- // DSH 凭据库。dynamic 沙箱无 fs → 第三通道自然缺席(旧 dynamic 本也有限)。
301
- function resolveEnToken(settingToken) {
302
- const s = String(settingToken || '').trim()
303
- if (s) return { token: s, source: 'setting' }
304
- const envTok = env.CODEBUDDY_AUTH_TOKEN || ''
305
- if (String(envTok).trim()) return { token: String(envTok).trim(), source: 'env' }
306
- const fromStore = readDshWorkbuddyToken()
307
- if (fromStore) return { token: fromStore, source: 'dsh-store' }
308
- return { token: null, source: null }
309
- }
310
-
311
- // ── 模型目录(面板/诊断用;无促销角标版,见头注 TODO)───────────────────────
312
- function accountConfigCandidates(backend) {
313
- const spec = PRODUCT_DESCRIPTOR_ENV[backend]
314
- if (!spec || !spec.accountDir) return []
315
- const home = env.USERPROFILE || env.HOME
316
- if (!home) return []
317
- const base = pathJoin(home, spec.accountDir.split('/').join(pathSep))
318
- return [
319
- pathJoin(base, 'cache', 'acc-product-config-v3.json'),
320
- pathJoin(base, 'local_storage', 'entry_d43e96994f944cfb77961c2ea7d04605.info'),
321
- pathJoin(base, 'local_storage', 'wb_entry_d43e96994f944cfb77961c2ea7d04605.info')
322
- ]
323
- }
324
-
325
- function productDescriptorCandidates(backend) {
326
- const spec = PRODUCT_DESCRIPTOR_ENV[backend]
327
- if (!spec) return []
328
- const out = []
329
- for (const p of accountConfigCandidates(backend)) out.push(p)
330
- if (env[spec.env]) out.push(env[spec.env])
331
- const rels = spec.fallbackRel ? [spec.rel, spec.fallbackRel] : [spec.rel]
332
- const push = (root) => { if (root) for (const r of rels) out.push(pathJoin(root, ...r.split('/'))) }
333
- if (backend === 'codebuddy' || backend === 'codebuddy-intl') {
334
- push(env.APPDATA ? pathJoin(env.APPDATA, 'npm', 'node_modules', '@tencent-ai', 'codebuddy-code') : null)
335
- } else if (backend === 'codebuddy-en') {
336
- push('C:\\Program Files\\WorkBuddyAI\\resources\\app.asar.unpacked\\cli')
337
- } else if (backend === 'workbuddy') {
338
- push('C:\\Program Files\\WorkBuddy\\resources\\app.asar.unpacked\\cli')
339
- }
340
- return out
341
- }
342
-
343
- function normalizeProductConfig(raw) {
344
- try {
345
- const obj = typeof raw === 'string' ? JSON.parse(raw) : raw
346
- if (!obj) return null
347
- if (Array.isArray(obj)) {
348
- // 数组形态:从后往前找第一个带 data 的条目(末尾最新)。
349
- for (let i = obj.length - 1; i >= 0; i--) {
350
- const e = obj[i]
351
- if (e && typeof e === 'object' && e.data && typeof e.data === 'object') return e.data
352
- }
353
- return null
354
- }
355
- if (typeof obj !== 'object') return null
356
- if (obj.data && typeof obj.data === 'object' && !Array.isArray(obj.models) && !Array.isArray(obj.agents)) return obj.data
357
- return obj
358
- } catch (e) { return null }
359
- }
360
-
361
- function extractModelIds(productJson) {
362
- try {
363
- const obj = normalizeProductConfig(productJson)
364
- if (!obj || typeof obj !== 'object') return null
365
- const pick = (arr) => {
366
- if (!Array.isArray(arr) || !arr.length) return null
367
- const ids = arr.map((m) => (typeof m === 'string' ? m : m && m.id)).filter((s) => typeof s === 'string' && s.trim())
368
- return ids.length ? [...new Set(ids)] : null
369
- }
370
- const agents = Array.isArray(obj.agents) ? obj.agents : []
371
- const cli = agents.find((a) => a && a.name === 'cli')
372
- const fromCli = cli ? pick(cli.models) : null
373
- const fromTop = pick(obj.models)
374
- if (fromCli && fromTop) return fromTop.length > fromCli.length ? fromTop : fromCli
375
- return fromCli || fromTop || null
376
- } catch (e) { return null }
377
- }
378
-
379
- function parseCreditValue(raw) {
380
- if (typeof raw !== 'string') return null
381
- const s = raw.trim()
382
- let m = s.match(/^[xX×]\s*([0-9]+(?:\.[0-9]+)?)/)
383
- if (!m) m = s.match(/^([0-9]+(?:\.[0-9]+)?)\s*[xX×]/)
384
- if (!m) return null
385
- const n = Number(m[1])
386
- return Number.isFinite(n) ? n : null
387
- }
388
-
389
- function formatCreditLabel(credits) {
390
- if (typeof credits !== 'number' || !Number.isFinite(credits)) return ''
391
- if (credits === 0) return '免费'
392
- return `x${credits.toFixed(2)}`
393
- }
394
-
395
- function extractModelCredits(productJson) {
396
- try {
397
- const obj = normalizeProductConfig(productJson)
398
- if (!obj || typeof obj !== 'object' || !Array.isArray(obj.models)) return null
399
- const map = new Map()
400
- for (const m of obj.models) {
401
- if (!m || typeof m !== 'object') continue
402
- const id = typeof m.id === 'string' ? m.id.trim() : ''
403
- if (!id) continue
404
- const n = parseCreditValue(m.credits)
405
- if (n !== null) map.set(id, n)
406
- }
407
- return map.size ? map : null
408
- } catch (e) { return null }
409
- }
410
-
411
- function lookupModelCredits(creditsMap, id) {
412
- if (!creditsMap || typeof id !== 'string') return null
413
- const norm = id.trim()
414
- const cands = [norm]
415
- if (norm.endsWith('-ioa')) cands.push(norm.slice(0, -4))
416
- else cands.push(norm + '-ioa')
417
- if (CREDIT_ID_ALIASES[norm]) cands.push(...CREDIT_ID_ALIASES[norm])
418
- for (const c of cands) {
419
- if (creditsMap.has(c)) {
420
- const v = creditsMap.get(c)
421
- if (typeof v === 'number') return v
422
- }
423
- }
424
- return null
425
- }
426
-
427
- function backendModelCatalog(backend, io) {
428
- const known = BACKEND_MODEL_IDS[backend] || []
429
- const read = (io && io.readFileSync) || fsRead
430
- let fromFile = null
431
- let fromFileRich = null
432
- // 旧 v1.6.1 语义:第一份有内容的 + 第一份带促销的,优先后者。
433
- for (const p of productDescriptorCandidates(backend)) {
434
- let txt = null
435
- try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
436
- if (txt == null) continue
437
- const ids = extractModelIds(txt)
438
- if (ids && ids.length) {
439
- if (!fromFile) fromFile = ids
440
- const obj = normalizeProductConfig(txt)
441
- if (!fromFileRich && obj && Array.isArray(obj.modelPromotions)) fromFileRich = ids
442
- }
443
- if (fromFileRich) break
444
- }
445
- if (!fromFile) return known
446
- return fromFileRich || fromFile
447
- }
448
-
449
- // 服务端回吐的账号清单缓存(进程内,旧 core verbatim)。
450
- const ACCOUNT_CATALOG_CACHE = new Map()
451
- function rememberAccountCatalog(backend, ids) {
452
- if (Array.isArray(ids) && ids.length) ACCOUNT_CATALOG_CACHE.set(backend, ids.slice())
453
- }
454
- function getAccountCatalog(backend) {
455
- const v = ACCOUNT_CATALOG_CACHE.get(backend)
456
- return v && v.length ? v.slice() : null
457
- }
458
-
459
- // CLI 报错里解析「该账号当前支持的模型」(旧 core parseAccountModels verbatim)。
460
- function parseAccountModels(text) {
461
- const s = String(text || '')
462
- const anchor = s.indexOf('Currently supported models for your account')
463
- if (anchor < 0) return null
464
- const tail = s.slice(anchor)
465
- const ids = []
466
- for (const line of tail.split(/\r?\n/)) {
467
- const m = /^\s*[-*]\s+(\S+)\s*$/.exec(line)
468
- if (!m) {
469
- if (ids.length) break
470
- continue
471
- }
472
- if (!ids.includes(m[1])) ids.push(m[1])
473
- }
474
- return ids.length ? ids : null
475
- }
476
-
477
- // 带倍率/授权的详细清单(无促销角标,旧 v1.6.1 的 0.1.0 子集;排序规则 verbatim:
478
- // 已授权在前 → 有倍率升序 → 无倍率殿后)。
479
- function modelCatalogDetailed(backend, io) {
480
- const o = io || {}
481
- const fromFile = backendModelCatalog(backend, o)
482
- const acct = (Array.isArray(o.accountModels) && o.accountModels.length) ? o.accountModels : getAccountCatalog(backend)
483
- const ids = []
484
- const authorized = new Set()
485
- if (acct) for (const id of acct) { if (!ids.includes(id)) ids.push(id); authorized.add(id) }
486
- for (const id of fromFile) if (!ids.includes(id)) ids.push(id)
487
- const read = o.readFileSync || fsRead
488
- let creditsMap = null
489
- for (const p of productDescriptorCandidates(backend)) {
490
- let txt = null
491
- try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
492
- if (txt == null) continue
493
- const map = extractModelCredits(txt)
494
- if (map) { creditsMap = map; break }
495
- }
496
- const items = ids.map((id) => {
497
- const base = lookupModelCredits(creditsMap, id)
498
- const credits = base
499
- const hasCredits = typeof credits === 'number'
500
- const suffix = formatCreditLabel(credits)
501
- const marks = []
502
- if (suffix) marks.push(suffix)
503
- if (acct && !authorized.has(id)) marks.push('未授权')
504
- return {
505
- id,
506
- credits,
507
- baseCredits: base,
508
- free: hasCredits && credits === 0,
509
- hasCredits,
510
- authorized: acct ? authorized.has(id) : null,
511
- promotion: null,
512
- label: marks.length ? `${id} · ${marks.join(' · ')}` : id
513
- }
514
- })
515
- const rank = (x) => (x.authorized === false ? 1 : 0)
516
- const withC = items.filter((x) => x.hasCredits).sort((a, b) => rank(a) - rank(b) || a.credits - b.credits)
517
- const withoutC = items.filter((x) => !x.hasCredits).sort((a, b) => rank(a) - rank(b))
518
- return [...withC, ...withoutC]
519
- }
520
-
521
- function formatModelCatalogText(backend, io) {
522
- return modelCatalogDetailed(backend, io).map((x) => x.label).join(', ')
523
- }
524
-
525
- // ── 设置清洗(旧 normalizeBridgeSettings verbatim;updatedAt 透传)───────────
526
- function normalizeSettings(raw) {
527
- const snap = { preferredBackend: DEFAULT_BACKEND, defaultModel: '', codebuddyEnToken: '', endpointOverride: '' }
528
- if (!raw || typeof raw !== 'object') return snap
529
- if (typeof raw.preferredBackend === 'string') {
530
- const nb = normalizeBackend(raw.preferredBackend)
531
- if (typeof nb === 'string' && BACKENDS.indexOf(nb) >= 0) snap.preferredBackend = nb
532
- }
533
- if (typeof raw.defaultModel === 'string') snap.defaultModel = raw.defaultModel.trim()
534
- if (typeof raw.codebuddyEnToken === 'string') snap.codebuddyEnToken = raw.codebuddyEnToken.trim()
535
- if (typeof raw.endpointOverride === 'string') snap.endpointOverride = raw.endpointOverride.trim()
536
- if (typeof raw.updatedAt === 'number' && raw.updatedAt > 0) snap.updatedAt = raw.updatedAt
537
- return snap
538
- }
539
-
540
- // 诊断(旧 diagnoseBackend verbatim;fs/env 走 deps)。
541
- function diagnoseBackend(backend, settings, io) {
542
- const o = io || {}
543
- const e = o.env || env
544
- const s = settings || normalizeSettings(null)
545
- const authDomain = readBackendAuthDomain(backend, Object.assign({ env: e }, o))
546
- const override = String(s.endpointOverride || '').trim()
547
- const byDomain = resolveEndpoint(null, authDomain)
548
- const endpoint = override || byDomain || BACKEND_ENDPOINTS[backend] || null
549
- const endpointSource = override ? 'override' : (byDomain ? 'auth-domain' : 'product')
550
- const tok = resolveEnToken(backend === 'codebuddy-en' ? s.codebuddyEnToken : null)
551
- return {
552
- backend: backend,
553
- authDomain: authDomain,
554
- endpoint: endpoint,
555
- endpointSource: endpointSource,
556
- tokenSource: backend === 'codebuddy-en' ? tok.source : 'not-needed',
557
- tokenHint: tok.source === 'setting' ? '来自设置面板'
558
- : tok.source === 'env' ? '来自环境变量 CODEBUDDY_AUTH_TOKEN'
559
- : tok.source === 'dsh-store' ? '来自 DSH 凭据库(自动复用 WORKBUDDY_TOKEN)'
560
- : backend === 'codebuddy-en' ? '缺失:国际版 token 不落盘,需在设置面板填写或先在 DSH 配 workbuddy provider'
561
- : '无需填写(国内版由 CLI 自行登录)',
562
- mismatch: endpointMismatchHint(backend, authDomain, !!tok.token) !== null,
563
- hint: endpointMismatchHint(backend, authDomain, !!tok.token) || null,
564
- defaultModel: String(s.defaultModel || '').trim() || '(CLI 默认)'
565
- }
566
- }
567
-
568
- // ── 结果判定(旧 isLimited/isTransientCliError/failureHint verbatim)─────────
569
- function isLimitedCodebuddy(res) {
570
- if (!res || res.ok) return false
571
- // 前置凭据缺失:配置问题,不是限流(弹窗重试不会让 token 出现)。
572
- if (res.status === 'AUTH_REQUIRED') return false
573
- if (res.status === 'SPAWN_ERROR' || res.status === 'CODEBUDDY_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
574
- const hay = String(res.stderr || '') + ' ' + String(res.status || '')
575
- // 401/端点域不匹配:需要用户换登录域,不归限流类(旧 v1.3.0 verbatim)。
576
- if (/401 authentication failed|differs from the current product endpoint/i.test(hay)) return false
577
- return CODEBUDDY_LIMIT_RE.test(hay)
578
- }
579
-
580
- function isTransientCliError(res) {
581
- if (!res || res.ok) return false
582
- if (isLimitedCodebuddy(res)) return false
583
- return res.status === 'ERROR_DURING_EXECUTION'
584
- }
585
-
586
- function failureHint(res) {
587
- if (!res || res.ok) return ''
588
- // AUTH_REQUIRED:stderr 已带完整指引,透传(旧 v1.3.1 verbatim)。
589
- if (res.status === 'AUTH_REQUIRED') return '[诊断] ' + String(res.stderr || '')
590
- if (isTransientCliError(res)) {
591
- return res.retried
592
- ? '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因),已自动重试 1 次仍失败。可换 model 再试一次;若仍失败请改用原生工具完成,或告知用户。'
593
- : '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因)。直接重试同一请求通常即可通过;也可显式指定 model。不要据此认为任务本身有问题。'
594
- }
595
- if (res.status === 'PARSE_ERROR') {
596
- return '[诊断] 未能从 codebuddy 输出解析出 result 事件(进程可能被中断或输出被截断)。可重试;持续出现请检查 codebuddy CLI 版本。'
597
- }
598
- if (/401 authentication failed|differs from the current product endpoint/i.test(String(res.stderr || ''))) {
599
- return '[诊断] 认证失败(401):请求被送到的端点与当前 CLI 登录域不匹配(国际/国内登录互斥)。请让用户在对应产品域完成 `codebuddy` CLI 登录后重试;这不是限流,重试与回退都无效。'
600
- }
601
- return ''
602
- }
603
-
604
- // stream-json 解析(旧 parseCodebuddyJson verbatim)。
605
- function parseCodebuddyJson(stdoutText) {
606
- const trimmed = String(stdoutText || '').trim()
607
- if (!trimmed) return null
608
- const lines = trimmed.split(/\r?\n/).filter(Boolean)
609
- for (let i = lines.length - 1; i >= 0; i--) {
610
- const ln = lines[i].trim()
611
- if (!ln.startsWith('{')) continue
612
- try {
613
- const obj = JSON.parse(ln)
614
- if (obj && obj.type === 'result') return obj
615
- } catch (e) {}
616
- }
617
- try { return JSON.parse(trimmed) } catch (e) {}
618
- return null
619
- }
620
-
621
- // result 事件 → 统一结果对象(旧 buildResult verbatim,含账号清单收割)。
622
- function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
623
- const bk = backend || 'codebuddy'
624
- const exitCode = outcome ? outcome.exitCode : null
625
- const errText = parsed && typeof parsed.error === 'string' && parsed.error ? parsed.error : ''
626
- const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
627
- // v1.6.0:顺手收割服务端回吐的「本账号可用模型」清单(失败静默)。
628
- try {
629
- const harvest = parseAccountModels(stderr) || parseAccountModels(String(stdoutText || ''))
630
- if (harvest && harvest.length) rememberAccountCatalog(bk, harvest)
631
- } catch (e) { /* 收割失败不影响主流程 */ }
632
- if (parsed && parsed.type === 'result') {
633
- const isOk = exitCode === 0 && parsed.is_error === false && parsed.subtype === 'success'
634
- let modelUsed = null
635
- try {
636
- if (parsed.modelUsage && typeof parsed.modelUsage === 'object') {
637
- const names = Object.keys(parsed.modelUsage)
638
- if (names.length) modelUsed = names.join('+')
639
- }
640
- } catch (e) { }
641
- return {
642
- ok: isOk,
643
- status: String(parsed.subtype || (isOk ? 'SUCCESS' : 'ERROR')).toUpperCase(),
644
- response: typeof parsed.result === 'string' ? parsed.result : '',
645
- sessionId: typeof parsed.session_id === 'string' ? parsed.session_id : null,
646
- durationSeconds: typeof parsed.duration_ms === 'number' ? parsed.duration_ms / 1000 : null,
647
- numTurns: typeof parsed.num_turns === 'number' ? parsed.num_turns : null,
648
- totalTokens: (parsed.usage && typeof parsed.usage.input_tokens === 'number' && typeof parsed.usage.output_tokens === 'number')
649
- ? (parsed.usage.input_tokens + parsed.usage.output_tokens) : null,
650
- exitCode: exitCode,
651
- mode: mode,
652
- backend: bk,
653
- modelUsed: modelUsed,
654
- stderr: stderr
655
- }
656
- }
657
- return {
658
- ok: false,
659
- status: 'PARSE_ERROR',
660
- response: '',
661
- sessionId: null,
662
- durationSeconds: null,
663
- numTurns: null,
664
- totalTokens: null,
665
- exitCode: exitCode,
666
- mode: mode,
667
- backend: bk,
668
- stderr: stderr,
669
- rawStdout: String(stdoutText || '').slice(-2000)
670
- }
671
- }
672
-
673
- // 统一 argv 构造(旧 buildArgv verbatim;env 端点/凭据注入在本 provider 内完成,
674
- // 因为 kit 只透传 opts,宿主三形态都从本函数的返回值取 built.env 下发 spawn)。
675
- function buildArgvCodebuddy(prefix, args, opts) {
676
- const o = opts || {}
677
- const argv = [prefix[0], ...prefix.slice(1), '-p', String(args.prompt), '--output-format', 'stream-json']
678
- let mode = args.mode || o.defaultMode || 'auto'
679
- if (mode === 'auto') mode = o.planActive ? 'plan' : 'bypassPermissions'
680
- if (mode === 'plan') {
681
- argv.push('--permission-mode', 'plan')
682
- argv.push('--allowedTools', 'Bash')
683
- } else {
684
- mode = 'bypassPermissions'
685
- argv.push('--permission-mode', 'bypassPermissions')
686
- }
687
- // 模型优先级:显式 args.model > 用户偏好 defaultModel > CLI 默认。
688
- const model = args.model || o.defaultModel
689
- if (model) argv.push('--model', String(model))
690
- if (args.effort) argv.push('--effort', String(args.effort))
691
- if (args.maxTurns !== undefined && args.maxTurns !== null) argv.push('--max-turns', String(clampInt(args.maxTurns, 50, 1, 500)))
692
- if (Array.isArray(args.addDirs)) for (const d of args.addDirs) { if (d) argv.push('--add-dir', String(d)) }
693
- if (args.sessionId) argv.push('--resume', String(args.sessionId))
694
- else if (args.continueLatest) argv.push('--continue')
695
- const timeoutSec = clampInt(args.timeoutSec, 300, 10, 3600)
696
- // 端点/凭据注入(旧 preset/dynamic/MCP 三形态一致语义,宿主不必自算):
697
- // authDomain 只在有 fs 能力的宿主读得到;dynamic 沙箱 → 沿用 CLI 自身端点。
698
- const bk = o.backend || DEFAULT_BACKEND
699
- const settings = o.settings || null
700
- const authDomain = readBackendAuthDomain(bk, {})
701
- const tok = resolveEnToken(bk === 'codebuddy-en' && settings ? settings.codebuddyEnToken : null)
702
- const inject = endpointEnv(bk, settings ? settings.endpointOverride : null, authDomain, tok.token)
703
- return { argv: argv, timeoutSec: timeoutSec, mode: mode, env: o.env || inject }
704
- }
705
-
706
- // 流事件折叠(旧 foldEvent 主体 verbatim;project 状态由 kit engine 持有)。
707
- function foldStreamEvent(ev, p, summarizeArgs, MAX_ARG_LEN, MAX_TRAIL) {
708
- if (!ev || !ev.type) return
709
- if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {
710
- for (const block of ev.message.content) {
711
- if (block.type === 'tool_use') {
712
- p._stepCounter = (p._stepCounter || 0) + 1
713
- const stepIndex = p._stepCounter
714
- if (!p._toolMap) p._toolMap = {}
715
- p._toolMap[block.id] = { stepIndex: stepIndex, name: block.name }
716
- const args = summarizeArgs(block.input)
717
- p.trail.push({ stepIndex: stepIndex, state: 'ACTIVE', tool: block.name, args: args, at: new Date().toISOString() })
718
- if (p.trail.length > MAX_TRAIL) p.trail.shift()
719
- p.current = { tool: block.name, args: args, stepIndex: stepIndex, since: new Date().toISOString() }
720
- } else if (block.type === 'thinking') {
721
- p.current = { tool: 'thinking', args: { text: String(block.thinking || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
722
- } else if (block.type === 'text') {
723
- p.current = { tool: 'typing', args: { text: String(block.text || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
724
- }
725
- }
726
- } else if (ev.type === 'user' && ev.message && Array.isArray(ev.message.content)) {
727
- for (const block of ev.message.content) {
728
- if (block.type === 'tool_result' && p._toolMap && p._toolMap[block.tool_use_id]) {
729
- const rec = p._toolMap[block.tool_use_id]
730
- p.trail.push({ stepIndex: rec.stepIndex, state: block.is_error ? 'ERROR' : 'DONE', tool: rec.name, args: null, at: new Date().toISOString() })
731
- if (p.trail.length > MAX_TRAIL) p.trail.shift()
732
- if (p.current && p.current.stepIndex === rec.stepIndex) p.current = null
733
- }
734
- }
735
- }
736
- }
737
-
738
- const descriptor = {
739
- id: 'codebuddy',
740
- label: 'CB',
741
- presetId: 'codebuddy-first',
742
- defaultBackend: DEFAULT_BACKEND,
743
- defaultMode: 'auto',
744
- exeName: 'codebuddy',
745
- binEnvVars: ['CODEBUDDY_BIN', 'CODEBUDDY_EN_BIN', 'WORKBUDDY_BIN'],
746
- unavailableStatus: 'CODEBUDDY_UNAVAILABLE',
747
- // 旧 renderResult verbatim 语义:标头用具体 backend('workbuddy OK'),仅当结果
748
- // 无 backend 字段时回落 'codebuddy'(= provider.id)。agy/mimo 旧包标头硬编码
749
- // provider 名,不设此旗。
750
- backendLabel: true,
751
-
752
- backends: () => BACKENDS.slice(),
753
- normalizeBackend,
754
- resolveBackend,
755
-
756
- buildArgv: buildArgvCodebuddy,
757
- parseJson: parseCodebuddyJson,
758
- buildResult,
759
- foldStreamEvent,
760
- isLimited: isLimitedCodebuddy,
761
- isTransientCliError,
762
- failureHint,
763
-
764
- // codebuddy-en 无凭据的确定性前置(v1.3.1 语义,经 kit preflight 钩子实现):
765
- // 三通道皆空 → 直接 AUTH_REQUIRED(可操作指引进 stderr),不白跑一次 spawn。
766
- // 其它后端一律放行。dynamic 沙箱无 fs → dsh-store 通道缺席,abort 提示即可。
767
- preflight({ args, backend, engine, o }) {
768
- if (backend !== 'codebuddy-en') return null
769
- const settings = (o && o.getSettings && o.getSettings()) || null
770
- const tok = resolveEnToken(settings ? settings.codebuddyEnToken : null)
771
- if (tok.token) return null
772
- const authDomain = readBackendAuthDomain('codebuddy-en', {})
773
- const hint = endpointMismatchHint('codebuddy-en', authDomain, false)
774
- return {
775
- abort: {
776
- ok: false,
777
- status: 'AUTH_REQUIRED',
778
- response: '',
779
- sessionId: null,
780
- durationSeconds: null,
781
- numTurns: null,
782
- totalTokens: null,
783
- exitCode: null,
784
- mode: (args && args.mode) || descriptor.defaultMode || 'auto',
785
- backend: 'codebuddy-en',
786
- stderr: hint
787
- }
788
- }
789
- },
790
-
791
- tools: {
792
- run: {
793
- name: 'codebuddy_run',
794
- description: 'Dispatch a coding/build/debug/investigation task to the local codebuddy agent CLI and return its final answer. Prefer this for implementation, edits, refactors, multi-file investigation and debugging in every mode. DSH fully controls codebuddy: it always runs non-interactively with permissions auto-approved (codebuddy never prompts). Use read-only native tools only for quick lookups and for final build/test verification. In mode=auto the DSH plan state decides plan vs bypassPermissions. Set background=true for long tasks and collect the result via job_output.',
795
- inputSchema: RUN_PARAMS
796
- },
797
- continue: {
798
- name: 'codebuddy_continue',
799
- description: 'Continue an existing codebuddy conversation with a follow-up prompt, reusing codebuddy context. Pass sessionId from a prior codebuddy_run result, or set latest=true to continue the most recent codebuddy conversation. Same DSH-controlled, no-prompt execution as codebuddy_run.',
800
- inputSchema: CONTINUE_PARAMS
801
- },
802
- status: {
803
- name: 'codebuddy_status',
804
- description: 'Read a live snapshot of what the local codebuddy agent is currently doing. Returns one section per project (working directory): running count, the current step (tool name + arguments being executed, or agent_response thinking/typing), the recent step trail (tools executed, done/error), the last completed run status + session id, and per-project cumulative usage (runs + total tokens, since codebuddy exposes no quota API). Optional cwd filters to a single project. Call this to check on an in-flight codebuddy_run/codebuddy_continue without waiting for it to finish.',
805
- inputSchema: STATUS_PARAMS
806
- }
807
- },
808
-
809
- extraTools: [],
810
-
811
- // 设置分区(契约 §3):keystone 统一文件 {codebuddy:{...}};旧扁平文件的字段
812
- // 级迁移由 keystone LEGACY_SOURCES 承担(字段名逐字相同)。
813
- settings: {
814
- keys: SETTINGS_KEYS,
815
- secretKeys: ['codebuddyEnToken'],
816
- defaults: () => normalizeSettings(null),
817
- normalize: (raw) => normalizeSettings(raw),
818
- meta() {
819
- // defaultModel 下拉 = 默认后端(codebuddy 面)的带倍率目录(升级 CLI 后
820
- // 自动同步);其余三面目录不同,字段允许自定义输入即可覆盖。促销角标为
821
- // 0.1.0 有意省略(见头注 TODO)。
822
- const options = modelCatalogDetailed(DEFAULT_BACKEND, {}).map((x) => ({ value: x.id, label: x.label }))
823
- return {
824
- titleSuffix: 'CodeBuddy',
825
- fields: [
826
- {
827
- key: 'preferredBackend', label: '默认后端', type: 'select',
828
- options: BACKENDS.map((b) => ({ value: b, label: BACKEND_LABELS[b] })),
829
- note: '新会话未显式指定 backend 时用这里选的后端;单次调用可覆盖。codebuddy-en 需要 codebuddyEnToken 或 DSH 已配 workbuddy key。'
830
- },
831
- {
832
- key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true, placeholder: '(CLI 默认)',
833
- options,
834
- note: '账号实际可用性以服务端实时裁决(400 报文回吐权威清单,桥接自动缓存)。优先选能完成任务里最便宜的,日常任务优先免费(x0.00)。'
835
- },
836
- { key: 'codebuddyEnToken', label: 'WorkBuddy 国际版 Token', type: 'secret', note: '仅 backend="codebuddy-en" 需要。国际版登录 token 被 protector key 封装不落盘,只能手工提供;留空则自动尝试 DSH 凭据库的 WORKBUDDY_TOKEN。' },
837
- { key: 'endpointOverride', label: '端点覆盖', type: 'text', placeholder: 'https://…/v2', note: '一般留空:端点按登录域自动对齐(www.codebuddy.cn 等)。仅在需要强制指定 API 端点时填写,且必须自带 /v2。' }
838
- ]
839
- }
840
- },
841
- diagnose(snap) {
842
- const s = normalizeSettings(snap)
843
- const lines = []
844
- const seen = new Set()
845
- // 默认后端一行;codebuddy-en 是 4 面里唯一需要凭据的,恒附一行状态。
846
- for (const b of [s.preferredBackend, 'codebuddy-en']) {
847
- if (seen.has(b)) continue
848
- seen.add(b)
849
- const d = diagnoseBackend(b, s, {})
850
- lines.push(b + ': ' + (d.endpoint || '?') + '(登录域 ' + (d.authDomain || '未读到') + ',' + d.tokenHint + ')')
851
- if (d.hint) lines.push(' ⚠ ' + d.hint)
852
- }
853
- return lines.join('\n')
854
- }
855
- },
856
-
857
- mcp: { version: '0.2.2' }
858
- }
859
-
860
- // 三形态共用的工具逻辑(签名保持 keystone/队友接线契约不变)。
861
- descriptor.runToolLogic = async function (args, exec) {
862
- return this.runner.coreExecute(args, exec)
863
- }
864
- // 旧 preset continueTool.execute verbatim 映射(sessionId 优先,否则 latest)。
865
- descriptor.continueToolLogic = async function (args, exec) {
866
- const a = args || {}
867
- const mapped = { prompt: a.prompt, backend: a.backend, mode: a.mode, model: a.model, effort: a.effort, maxTurns: a.maxTurns, cwd: a.cwd, timeoutSec: a.timeoutSec, background: a.background }
868
- if (a.sessionId) mapped.sessionId = a.sessionId
869
- else if (a.latest) mapped.continueLatest = true
870
- return this.runner.coreExecute(mapped, exec)
871
- }
872
- // 旧 statusTool.execute verbatim:cwd 过滤 + 单项目聚合覆写(含 runs/totalTokens)。
873
- descriptor.statusToolLogic = function (args) {
874
- const a = args || {}
875
- const snap = this.engine.statusSnapshot()
876
- if (a.cwd) {
877
- const key = String(a.cwd)
878
- snap.projects = snap.projects.filter((p) => p.cwd === key)
879
- const g = snap.projects[0]
880
- if (g) { snap.state = g.state; snap.running = g.running; snap.current = g.current; snap.trail = g.trail; snap.lastStatus = g.lastStatus; snap.lastAt = g.lastAt; snap.lastSessionId = g.lastSessionId; snap.lastBackend = g.lastBackend; snap.fallbackActive = g.fallbackActive; snap.runs = g.runs; snap.totalTokens = g.totalTokens; snap.updatedAt = g.updatedAt }
881
- }
882
- return snap
883
- }
884
-
885
- // 供 preset/dynamic/MCP/测试形态复用的领域函数(不 import home-plugin,全部经
886
- // 描述符暴露;MCP 面据 buildArgv/parseJson/buildResult/isLimited/failureHint 组
887
- // 装真实 spawn 执行,语义与旧 mcp/codebuddy-mcp-server.mjs 一致)。
888
- descriptor.policyText = POLICY_TEXT
889
- descriptor.limits = { LIMIT_RE: CODEBUDDY_LIMIT_RE }
890
- descriptor.backendLabels = BACKEND_LABELS
891
- descriptor.backendEndpoints = BACKEND_ENDPOINTS
892
- descriptor.authDomainEndpoints = AUTH_DOMAIN_ENDPOINTS
893
- descriptor.backendAuthIds = BACKEND_AUTH_IDS
894
- descriptor.staticModelIds = BACKEND_MODEL_IDS
895
- descriptor.endpointHost = endpointHost
896
- descriptor.resolveEndpoint = resolveEndpoint
897
- descriptor.endpointEnv = endpointEnv
898
- descriptor.endpointMismatchHint = endpointMismatchHint
899
- descriptor.resolveEnToken = resolveEnToken
900
- descriptor.readDshWorkbuddyToken = readDshWorkbuddyToken
901
- descriptor.readBackendAuthDomain = readBackendAuthDomain
902
- descriptor.diagnoseBackend = diagnoseBackend
903
- descriptor.backendModelCatalog = backendModelCatalog
904
- descriptor.modelCatalogDetailed = modelCatalogDetailed
905
- descriptor.formatModelCatalogText = formatModelCatalogText
906
- descriptor.parseAccountModels = parseAccountModels
907
- descriptor.rememberAccountCatalog = rememberAccountCatalog
908
- descriptor.getAccountCatalog = getAccountCatalog
909
- descriptor.normalizeProductConfig = normalizeProductConfig
910
- descriptor.extractModelIds = extractModelIds
911
- descriptor.extractModelCredits = extractModelCredits
912
- descriptor.parseCreditValue = parseCreditValue
913
- descriptor.formatCreditLabel = formatCreditLabel
914
- descriptor.lookupModelCredits = lookupModelCredits
915
- descriptor.normalizeSettings = normalizeSettings
916
-
917
- descriptor.attach = function (hostOpts) {
918
- host = hostOpts || {}
919
- this.engine = createStatusEngine({ provider: this, publish: host.publish })
920
- const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
921
- this.runner = runner
922
- return runner
923
- }
924
- descriptor.hostOptions = () => host
925
- return descriptor
926
- }
1
+ // providers/codebuddy.mjs — codebuddy provider descriptor(真移植,替换 Lead 冒烟占位)。
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。
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 通用表。
19
+ import { createStatusEngine, createRunner, clampInt } from '../core/bridge-kit.mjs'
20
+
21
+ // ── 提示词策略段(旧 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
+ // (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
+ // codebuddy-en 凭据的第三条通道:DSH 凭据库里可能已有的 workbuddy key(旧 core verbatim)。
86
+
87
+ // 离线/读不到描述文件时的回退静态表(真机按账号实测快照,2026-09)。
88
+ // 模型目录相关常量与纯逻辑已拆到 ./codebuddy-catalog.mjs —— 主文件原 864 行远超
89
+ // 600 行红线(规则 §26)。
90
+ // • ESM 形态(preset / MCP / 测试):直接 import。
91
+ // • dynamic 沙箱形态:scripts/build.mjs 把该文件内联进同一作用域(模板顶部的
92
+ // 第三个占位标记),import 行被 stripModuleSyntax 剥掉,同名标识符天然可见。
93
+ // ⚠️ 本注释里绝不写出那个标记的字面量:build 做全局文本替换,注释中出现同样
94
+ // 会被替换成正文代码,把注释劈开 → 生成物语法崩。
95
+ import {
96
+ BACKEND_MODEL_IDS, PRODUCT_DESCRIPTOR_ENV, CREDIT_ID_ALIASES, MODEL_DESCRIPTION, BACKEND_ENUM,
97
+ accountConfigCandidates, productDescriptorCandidates, normalizeProductConfig,
98
+ extractModelIds, parseCreditValue, formatCreditLabel, extractModelCredits, lookupModelCredits,
99
+ backendModelCatalog, rememberAccountCatalog, getAccountCatalog, parseAccountModels,
100
+ modelCatalogDetailed, formatModelCatalogText, cbCatalogSetHost,
101
+ BACKEND_AUTH_IDS, CREDENTIAL_KEYS, readBackendAuthDomain,
102
+ readDshWorkbuddyToken, resolveEnToken,
103
+ fetchHelpModelsSync, cachedCliModels, currentPreferredBackend, parseHelpModels,
104
+ RUN_PARAMS, CONTINUE_PARAMS, STATUS_PARAMS
105
+ } from './codebuddy-catalog.mjs'
106
+ import { codebuddyModelsTool } from './codebuddy-models-tool.mjs'
107
+
108
+
109
+ export default function defineProvider(deps = {}) {
110
+ const env = deps.env || {}
111
+ let host = null // attach 后保存 hostOpts(preset/dynamic/MCP 形态宿主能力)
112
+
113
+ // 宿主 fs/path 访问的统一入口:deps 注入优先;dynamic 内联体(无 import,运行在
114
+ // 后端 Node 上下文)回退到 getBuiltinModule —— 与旧 core builtinModule() 的
115
+ // typeof 守卫模式一致(这是旧 dynamic 端点修复生效的同一条通道,缺了它默认
116
+ // 后端会回到 401 老病)。两者皆不可用时自然降级:读不到文件 = 静态表兜底。
117
+ function builtinModule(name) {
118
+ try {
119
+ const proc = globalThis.process
120
+ return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
121
+ } catch (e) { return null }
122
+ }
123
+ function fsRead(p) {
124
+ const nf = deps.nodeFs || builtinModule('node:fs')
125
+ if (!nf || typeof nf.readFileSync !== 'function') return null
126
+ try { return nf.readFileSync(p, 'utf8') } catch (e) { return null }
127
+ }
128
+ function pathJoin(...parts) {
129
+ const np = deps.nodePath || builtinModule('node:path')
130
+ if (np && typeof np.join === 'function') return np.join(...parts)
131
+ return parts.join('/')
132
+ }
133
+ const pathSep = (deps.nodePath && deps.nodePath.sep) || (/[A-Za-z]:[\\/]/.test(env.USERPROFILE || env.APPDATA || '') ? '\\' : '/')
134
+
135
+ // 把宿主真实能力注入 catalog 模块:它从本闭包搬出后拿不到 env / fsRead / pathJoin /
136
+ // pathSep。未注入时 catalog 退到 getBuiltinModule 守卫(绝不抛)。内联到 dynamic
137
+ // 沙箱时 cbCatalogSetHost 同作用域可见,行为一致。
138
+ try {
139
+ cbCatalogSetHost(env, deps.nodePath || builtinModule('node:path'), deps.nodeFs || builtinModule('node:fs'))
140
+ } catch (e) { }
141
+
142
+ // ── 端点/登录域(旧 core endpointHost verbatim:非法 URL 容错)───────────────
143
+ function endpointHost(url) {
144
+ const s = String(url || '').trim()
145
+ if (!s) return ''
146
+ try { return new URL(s).hostname.toLowerCase() } catch (e) { }
147
+ const m = /^[a-z]+:\/\/([^/?#]+)/i.exec(s)
148
+ return m ? m[1].toLowerCase() : ''
149
+ }
150
+
151
+ function resolveEndpoint(explicitBaseUrl, authDomain) {
152
+ const explicit = String(explicitBaseUrl || '').trim()
153
+ if (explicit) return explicit
154
+ const d = String(authDomain || '').trim().toLowerCase()
155
+ if (d && AUTH_DOMAIN_ENDPOINTS[d]) return AUTH_DOMAIN_ENDPOINTS[d]
156
+ return null
157
+ }
158
+
159
+ function isBackend(v) { return BACKENDS.indexOf(v) >= 0 }
160
+
161
+ // 后端名规范化(v1.3.3 verbatim):别名 + 大小写不敏感;非后端名原样返回。
162
+ function normalizeBackend(v) {
163
+ if (typeof v !== 'string') return v
164
+ const lower = v.trim().toLowerCase()
165
+ const aliased = BACKEND_ALIASES[lower] || lower
166
+ return BACKENDS.indexOf(aliased) >= 0 ? aliased : v
167
+ }
168
+
169
+ // 后端解析优先级(旧 core verbatim):显式 > 会话归属 > 用户偏好 > 默认。
170
+ function resolveBackend(args, target, preferredBackend) {
171
+ if (args && isBackend(normalizeBackend(args.backend))) return normalizeBackend(args.backend)
172
+ if (target && target.backend && isBackend(normalizeBackend(target.backend))) return normalizeBackend(target.backend)
173
+ if (preferredBackend && isBackend(normalizeBackend(preferredBackend))) return normalizeBackend(preferredBackend)
174
+ return DEFAULT_BACKEND
175
+ }
176
+
177
+ // 本次调用的端点/凭据 env 注入(旧 core endpointEnv verbatim 三规则)。
178
+ function endpointEnv(backend, explicitBaseUrl, authDomain, authToken) {
179
+ const out = {}
180
+ const endpoint = resolveEndpoint(explicitBaseUrl, authDomain)
181
+ const product = BACKEND_ENDPOINTS[backend]
182
+ if (endpoint && endpointHost(endpoint) !== endpointHost(product)) {
183
+ out.CODEBUDDY_BASE_URL = endpoint
184
+ }
185
+ if (backend === 'codebuddy-en') {
186
+ const tok = String(authToken || '').trim()
187
+ if (tok) out.CODEBUDDY_AUTH_TOKEN = tok
188
+ }
189
+ return Object.keys(out).length ? out : null
190
+ }
191
+
192
+ // 可操作提示(旧 core endpointMismatchHint 三分支 verbatim)。
193
+ function endpointMismatchHint(backend, authDomain, hasToken) {
194
+ if (backend === 'codebuddy-en' && !hasToken) {
195
+ return 'codebuddy-en(WorkBuddy 国际版)没有可用凭据。国际版的登录 token 被桌面 App 的 protector key 封装,该密钥不落盘、headless CLI 无法自行读取(CLI 自身报 category:"missing-key")。桥接会依次尝试:插件设置 codebuddyEnToken → 环境变量 CODEBUDDY_AUTH_TOKEN → DSH 凭据库(.credentials.yaml / .env 里的 WORKBUDDY_TOKEN)——三者皆空。请在 DSH 里配好 workbuddy provider 的 key,或把国际版 token 填入插件设置;也可直接用 backend="workbuddy"(国内版桌面 CLI,免配置)。'
196
+ }
197
+ if (backend === 'codebuddy-intl') {
198
+ return 'codebuddy-intl(CodeBuddy 国际版)使用同一个 npm CLI,但国际面模型由服务端按账号授权放行:未授权时 CLI 返回 400「model [...] is only available for authorized users」。若你用的是国内账号,请改用 backend="codebuddy"(国内面模型清单)或 backend="codebuddy-en"(WorkBuddy 国际版)。'
199
+ }
200
+ const d = String(authDomain || '').trim().toLowerCase()
201
+ if (d && endpointHost(resolveEndpoint(null, d)) !== endpointHost(BACKEND_ENDPOINTS[backend])) {
202
+ return backend + ' 的登录域是 ' + d + ',与产品端点 ' + BACKEND_ENDPOINTS[backend] + ' 不一致;桥接层已自动注入 CODEBUDDY_BASE_URL=' + AUTH_DOMAIN_ENDPOINTS[d] + '。若仍 401,请重新登录对应客户端。'
203
+ }
204
+ return null
205
+ }
206
+
207
+ // 从 auth 库读某后端登录域(旧 core readBackendAuthDomain verbatim 语义;fs 经
208
+ // deps 注入。io 可覆盖 readFileSync/dir/env,供测试夹具与 MCP 面注入真实 fs)。
209
+
210
+ // ── 模型目录(面板/诊断用;无促销角标版,见头注 TODO)───────────────────────
211
+ // ── 设置清洗(旧 normalizeBridgeSettings verbatim;updatedAt 透传)───────────
212
+ function normalizeSettings(raw) {
213
+ const snap = { preferredBackend: DEFAULT_BACKEND, defaultModel: '', codebuddyEnToken: '', endpointOverride: '' }
214
+ if (!raw || typeof raw !== 'object') return snap
215
+ if (typeof raw.preferredBackend === 'string') {
216
+ const nb = normalizeBackend(raw.preferredBackend)
217
+ if (typeof nb === 'string' && BACKENDS.indexOf(nb) >= 0) snap.preferredBackend = nb
218
+ }
219
+ if (typeof raw.defaultModel === 'string') snap.defaultModel = raw.defaultModel.trim()
220
+ if (typeof raw.codebuddyEnToken === 'string') snap.codebuddyEnToken = raw.codebuddyEnToken.trim()
221
+ if (typeof raw.endpointOverride === 'string') snap.endpointOverride = raw.endpointOverride.trim()
222
+ if (typeof raw.updatedAt === 'number' && raw.updatedAt > 0) snap.updatedAt = raw.updatedAt
223
+ return snap
224
+ }
225
+
226
+ // 诊断(旧 diagnoseBackend verbatim;fs/env 走 deps)。
227
+ function diagnoseBackend(backend, settings, io) {
228
+ const o = io || {}
229
+ const e = o.env || env
230
+ const s = settings || normalizeSettings(null)
231
+ const authDomain = readBackendAuthDomain(backend, Object.assign({ env: e }, o))
232
+ const override = String(s.endpointOverride || '').trim()
233
+ const byDomain = resolveEndpoint(null, authDomain)
234
+ const endpoint = override || byDomain || BACKEND_ENDPOINTS[backend] || null
235
+ const endpointSource = override ? 'override' : (byDomain ? 'auth-domain' : 'product')
236
+ const tok = resolveEnToken(backend === 'codebuddy-en' ? s.codebuddyEnToken : null, { env })
237
+ return {
238
+ backend: backend,
239
+ authDomain: authDomain,
240
+ endpoint: endpoint,
241
+ endpointSource: endpointSource,
242
+ tokenSource: backend === 'codebuddy-en' ? tok.source : 'not-needed',
243
+ tokenHint: tok.source === 'setting' ? '来自设置面板'
244
+ : tok.source === 'env' ? '来自环境变量 CODEBUDDY_AUTH_TOKEN'
245
+ : tok.source === 'dsh-store' ? '来自 DSH 凭据库(自动复用 WORKBUDDY_TOKEN)'
246
+ : backend === 'codebuddy-en' ? '缺失:国际版 token 不落盘,需在设置面板填写或先在 DSH 配 workbuddy provider'
247
+ : '无需填写(国内版由 CLI 自行登录)',
248
+ mismatch: endpointMismatchHint(backend, authDomain, !!tok.token) !== null,
249
+ hint: endpointMismatchHint(backend, authDomain, !!tok.token) || null,
250
+ defaultModel: String(s.defaultModel || '').trim() || '(CLI 默认)'
251
+ }
252
+ }
253
+
254
+ // ── 结果判定(旧 isLimited/isTransientCliError/failureHint verbatim)─────────
255
+ function isLimitedCodebuddy(res) {
256
+ if (!res || res.ok) return false
257
+ // 前置凭据缺失:配置问题,不是限流(弹窗重试不会让 token 出现)。
258
+ if (res.status === 'AUTH_REQUIRED') return false
259
+ if (res.status === 'SPAWN_ERROR' || res.status === 'CODEBUDDY_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
260
+ const hay = String(res.stderr || '') + ' ' + String(res.status || '')
261
+ // 401/端点域不匹配:需要用户换登录域,不归限流类(旧 v1.3.0 verbatim)。
262
+ if (/401 authentication failed|differs from the current product endpoint/i.test(hay)) return false
263
+ return CODEBUDDY_LIMIT_RE.test(hay)
264
+ }
265
+
266
+ function isTransientCliError(res) {
267
+ if (!res || res.ok) return false
268
+ if (isLimitedCodebuddy(res)) return false
269
+ return res.status === 'ERROR_DURING_EXECUTION'
270
+ }
271
+
272
+ function failureHint(res) {
273
+ if (!res || res.ok) return ''
274
+ // AUTH_REQUIRED:stderr 已带完整指引,透传(旧 v1.3.1 verbatim)。
275
+ if (res.status === 'AUTH_REQUIRED') return '[诊断] ' + String(res.stderr || '')
276
+ if (isTransientCliError(res)) {
277
+ return res.retried
278
+ ? '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因),已自动重试 1 次仍失败。可换 model 再试一次;若仍失败请改用原生工具完成,或告知用户。'
279
+ : '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因)。直接重试同一请求通常即可通过;也可显式指定 model。不要据此认为任务本身有问题。'
280
+ }
281
+ if (res.status === 'PARSE_ERROR') {
282
+ return '[诊断] 未能从 codebuddy 输出解析出 result 事件(进程可能被中断或输出被截断)。可重试;持续出现请检查 codebuddy CLI 版本。'
283
+ }
284
+ if (/401 authentication failed|differs from the current product endpoint/i.test(String(res.stderr || ''))) {
285
+ return '[诊断] 认证失败(401):请求被送到的端点与当前 CLI 登录域不匹配(国际/国内登录互斥)。请让用户在对应产品域完成 `codebuddy` CLI 登录后重试;这不是限流,重试与回退都无效。'
286
+ }
287
+ return ''
288
+ }
289
+
290
+ // stream-json 解析(旧 parseCodebuddyJson verbatim)。
291
+ function parseCodebuddyJson(stdoutText) {
292
+ const trimmed = String(stdoutText || '').trim()
293
+ if (!trimmed) return null
294
+ const lines = trimmed.split(/\r?\n/).filter(Boolean)
295
+ for (let i = lines.length - 1; i >= 0; i--) {
296
+ const ln = lines[i].trim()
297
+ if (!ln.startsWith('{')) continue
298
+ try {
299
+ const obj = JSON.parse(ln)
300
+ if (obj && obj.type === 'result') return obj
301
+ } catch (e) {}
302
+ }
303
+ try { return JSON.parse(trimmed) } catch (e) {}
304
+ return null
305
+ }
306
+
307
+ // result 事件 → 统一结果对象(旧 buildResult verbatim,含账号清单收割)。
308
+ function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
309
+ const bk = backend || 'codebuddy'
310
+ const exitCode = outcome ? outcome.exitCode : null
311
+ const errText = parsed && typeof parsed.error === 'string' && parsed.error ? parsed.error : ''
312
+ const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
313
+ // v1.6.0:顺手收割服务端回吐的「本账号可用模型」清单(失败静默)。
314
+ try {
315
+ const harvest = parseAccountModels(stderr) || parseAccountModels(String(stdoutText || ''))
316
+ if (harvest && harvest.length) rememberAccountCatalog(bk, harvest)
317
+ } catch (e) { /* 收割失败不影响主流程 */ }
318
+ if (parsed && parsed.type === 'result') {
319
+ const isOk = exitCode === 0 && parsed.is_error === false && parsed.subtype === 'success'
320
+ let modelUsed = null
321
+ try {
322
+ if (parsed.modelUsage && typeof parsed.modelUsage === 'object') {
323
+ const names = Object.keys(parsed.modelUsage)
324
+ if (names.length) modelUsed = names.join('+')
325
+ }
326
+ } catch (e) { }
327
+ return {
328
+ ok: isOk,
329
+ status: String(parsed.subtype || (isOk ? 'SUCCESS' : 'ERROR')).toUpperCase(),
330
+ response: typeof parsed.result === 'string' ? parsed.result : '',
331
+ sessionId: typeof parsed.session_id === 'string' ? parsed.session_id : null,
332
+ durationSeconds: typeof parsed.duration_ms === 'number' ? parsed.duration_ms / 1000 : null,
333
+ numTurns: typeof parsed.num_turns === 'number' ? parsed.num_turns : null,
334
+ totalTokens: (parsed.usage && typeof parsed.usage.input_tokens === 'number' && typeof parsed.usage.output_tokens === 'number')
335
+ ? (parsed.usage.input_tokens + parsed.usage.output_tokens) : null,
336
+ exitCode: exitCode,
337
+ mode: mode,
338
+ backend: bk,
339
+ modelUsed: modelUsed,
340
+ stderr: stderr
341
+ }
342
+ }
343
+ return {
344
+ ok: false,
345
+ status: 'PARSE_ERROR',
346
+ response: '',
347
+ sessionId: null,
348
+ durationSeconds: null,
349
+ numTurns: null,
350
+ totalTokens: null,
351
+ exitCode: exitCode,
352
+ mode: mode,
353
+ backend: bk,
354
+ stderr: stderr,
355
+ rawStdout: String(stdoutText || '').slice(-2000)
356
+ }
357
+ }
358
+
359
+ // 统一 argv 构造(旧 buildArgv verbatim;env 端点/凭据注入在本 provider 内完成,
360
+ // 因为 kit 只透传 opts,宿主三形态都从本函数的返回值取 built.env 下发 spawn)。
361
+ function buildArgvCodebuddy(prefix, args, opts) {
362
+ const o = opts || {}
363
+ const argv = [prefix[0], ...prefix.slice(1), '-p', String(args.prompt), '--output-format', 'stream-json']
364
+ let mode = args.mode || o.defaultMode || 'auto'
365
+ if (mode === 'auto') mode = o.planActive ? 'plan' : 'bypassPermissions'
366
+ if (mode === 'plan') {
367
+ argv.push('--permission-mode', 'plan')
368
+ argv.push('--allowedTools', 'Bash')
369
+ } else {
370
+ mode = 'bypassPermissions'
371
+ argv.push('--permission-mode', 'bypassPermissions')
372
+ }
373
+ // 模型优先级:显式 args.model > 用户偏好 defaultModel > CLI 默认。
374
+ const model = args.model || o.defaultModel
375
+ if (model) argv.push('--model', String(model))
376
+ if (args.effort) argv.push('--effort', String(args.effort))
377
+ if (args.maxTurns !== undefined && args.maxTurns !== null) argv.push('--max-turns', String(clampInt(args.maxTurns, 50, 1, 500)))
378
+ if (Array.isArray(args.addDirs)) for (const d of args.addDirs) { if (d) argv.push('--add-dir', String(d)) }
379
+ if (args.sessionId) argv.push('--resume', String(args.sessionId))
380
+ else if (args.continueLatest) argv.push('--continue')
381
+ const timeoutSec = clampInt(args.timeoutSec, 300, 10, 3600)
382
+ // 端点/凭据注入(旧 preset/dynamic/MCP 三形态一致语义,宿主不必自算):
383
+ // authDomain 只在有 fs 能力的宿主读得到;dynamic 沙箱 → 沿用 CLI 自身端点。
384
+ const bk = o.backend || DEFAULT_BACKEND
385
+ const settings = o.settings || null
386
+ const authDomain = readBackendAuthDomain(bk, { env })
387
+ const tok = resolveEnToken(bk === 'codebuddy-en' && settings ? settings.codebuddyEnToken : null, { env })
388
+ const inject = endpointEnv(bk, settings ? settings.endpointOverride : null, authDomain, tok.token)
389
+ return { argv: argv, timeoutSec: timeoutSec, mode: mode, env: o.env || inject }
390
+ }
391
+
392
+ // 流事件折叠(旧 foldEvent 主体 verbatim;project 状态由 kit engine 持有)。
393
+ function foldStreamEvent(ev, p, summarizeArgs, MAX_ARG_LEN, MAX_TRAIL) {
394
+ if (!ev || !ev.type) return
395
+ if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {
396
+ for (const block of ev.message.content) {
397
+ if (block.type === 'tool_use') {
398
+ p._stepCounter = (p._stepCounter || 0) + 1
399
+ const stepIndex = p._stepCounter
400
+ if (!p._toolMap) p._toolMap = {}
401
+ p._toolMap[block.id] = { stepIndex: stepIndex, name: block.name }
402
+ const args = summarizeArgs(block.input)
403
+ p.trail.push({ stepIndex: stepIndex, state: 'ACTIVE', tool: block.name, args: args, at: new Date().toISOString() })
404
+ if (p.trail.length > MAX_TRAIL) p.trail.shift()
405
+ p.current = { tool: block.name, args: args, stepIndex: stepIndex, since: new Date().toISOString() }
406
+ } else if (block.type === 'thinking') {
407
+ p.current = { tool: 'thinking', args: { text: String(block.thinking || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
408
+ } else if (block.type === 'text') {
409
+ p.current = { tool: 'typing', args: { text: String(block.text || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
410
+ }
411
+ }
412
+ } else if (ev.type === 'user' && ev.message && Array.isArray(ev.message.content)) {
413
+ for (const block of ev.message.content) {
414
+ if (block.type === 'tool_result' && p._toolMap && p._toolMap[block.tool_use_id]) {
415
+ const rec = p._toolMap[block.tool_use_id]
416
+ p.trail.push({ stepIndex: rec.stepIndex, state: block.is_error ? 'ERROR' : 'DONE', tool: rec.name, args: null, at: new Date().toISOString() })
417
+ if (p.trail.length > MAX_TRAIL) p.trail.shift()
418
+ if (p.current && p.current.stepIndex === rec.stepIndex) p.current = null
419
+ }
420
+ }
421
+ }
422
+ }
423
+
424
+ const descriptor = {
425
+ id: 'codebuddy',
426
+ label: 'CB',
427
+ presetId: 'codebuddy-first',
428
+ defaultBackend: DEFAULT_BACKEND,
429
+ defaultMode: 'auto',
430
+ exeName: 'codebuddy',
431
+ binEnvVars: ['CODEBUDDY_BIN', 'CODEBUDDY_EN_BIN', 'WORKBUDDY_BIN'],
432
+ unavailableStatus: 'CODEBUDDY_UNAVAILABLE',
433
+ // 旧 renderResult verbatim 语义:标头用具体 backend('workbuddy OK'),仅当结果
434
+ // 无 backend 字段时回落 'codebuddy'(= provider.id)。agy/mimo 旧包标头硬编码
435
+ // provider 名,不设此旗。
436
+ backendLabel: true,
437
+
438
+ backends: () => BACKENDS.slice(),
439
+ normalizeBackend,
440
+ resolveBackend,
441
+
442
+ buildArgv: buildArgvCodebuddy,
443
+ parseJson: parseCodebuddyJson,
444
+ buildResult,
445
+ foldStreamEvent,
446
+ isLimited: isLimitedCodebuddy,
447
+ isTransientCliError,
448
+ failureHint,
449
+
450
+ // codebuddy-en 无凭据的确定性前置(v1.3.1 语义,经 kit preflight 钩子实现):
451
+ // 三通道皆空 → 直接 AUTH_REQUIRED(可操作指引进 stderr),不白跑一次 spawn。
452
+ // 其它后端一律放行。dynamic 沙箱无 fs → dsh-store 通道缺席,abort 提示即可。
453
+ preflight({ args, backend, engine, o }) {
454
+ if (backend !== 'codebuddy-en') return null
455
+ const settings = (o && o.getSettings && o.getSettings()) || null
456
+ const tok = resolveEnToken(settings ? settings.codebuddyEnToken : null, { env })
457
+ if (tok.token) return null
458
+ const authDomain = readBackendAuthDomain('codebuddy-en', { env })
459
+ const hint = endpointMismatchHint('codebuddy-en', authDomain, false)
460
+ return {
461
+ abort: {
462
+ ok: false,
463
+ status: 'AUTH_REQUIRED',
464
+ response: '',
465
+ sessionId: null,
466
+ durationSeconds: null,
467
+ numTurns: null,
468
+ totalTokens: null,
469
+ exitCode: null,
470
+ mode: (args && args.mode) || descriptor.defaultMode || 'auto',
471
+ backend: 'codebuddy-en',
472
+ stderr: hint
473
+ }
474
+ }
475
+ },
476
+
477
+ tools: {
478
+ run: {
479
+ name: 'codebuddy_run',
480
+ description: 'Dispatch a coding/build/debug/investigation task to the local codebuddy agent CLI and return its final answer. Prefer this for implementation, edits, refactors, multi-file investigation and debugging in every mode. DSH fully controls codebuddy: it always runs non-interactively with permissions auto-approved (codebuddy never prompts). Use read-only native tools only for quick lookups and for final build/test verification. In mode=auto the DSH plan state decides plan vs bypassPermissions. Set background=true for long tasks and collect the result via job_output.',
481
+ inputSchema: RUN_PARAMS
482
+ },
483
+ continue: {
484
+ name: 'codebuddy_continue',
485
+ description: 'Continue an existing codebuddy conversation with a follow-up prompt, reusing codebuddy context. Pass sessionId from a prior codebuddy_run result, or set latest=true to continue the most recent codebuddy conversation. Same DSH-controlled, no-prompt execution as codebuddy_run.',
486
+ inputSchema: CONTINUE_PARAMS
487
+ },
488
+ status: {
489
+ name: 'codebuddy_status',
490
+ description: 'Read a live snapshot of what the local codebuddy agent is currently doing. Returns one section per project (working directory): running count, the current step (tool name + arguments being executed, or agent_response thinking/typing), the recent step trail (tools executed, done/error), the last completed run status + session id, and per-project cumulative usage (runs + total tokens, since codebuddy exposes no quota API). Optional cwd filters to a single project. Call this to check on an in-flight codebuddy_run/codebuddy_continue without waiting for it to finish.',
491
+ inputSchema: STATUS_PARAMS
492
+ }
493
+ },
494
+
495
+ // codebuddy_models:实时列出本机 codebuddy 可用模型(账号探测优先,回落 CLI 名册)。
496
+ // 只在宿主有 spawn/fs 能力时注册(preset 注入 deps.process / MCP 注入 deps.nodeChild;
497
+ // dynamic 沙箱形态省略)。**失败必须 ok:false + 可操作错误**,绝不静默返回空列表或
498
+ // 伪造模型(工作手册红线 §7;对照 workbuddy-auth 的 catalog-store 静默降级 —— 不照抄)。
499
+ extraTools: (deps.process || deps.nodeChild || deps.nodeFs) ? [codebuddyModelsTool({
500
+ env, deps, BACKEND_ENUM, normalizeBackend, resolveBackend, modelCatalogDetailed, getAccountCatalog,
501
+ // faceEnv:让账号探测打到**请求的那个产品面**(与 buildArgv 完全同一套端点/凭据
502
+ // 注入规则)。缺了它,探测会走 CLI 自身默认登录面 —— 标着 codebuddy-en 实际却
503
+ // 问的是 codebuddy 面,得出的清单看着对其实是另一个面的(本轮修的就是这类偏差)。
504
+ faceEnv: (backend) => {
505
+ try {
506
+ const settings = (deps.settings && typeof deps.settings === 'object') ? deps.settings : {}
507
+ const authDomain = readBackendAuthDomain(backend, { env })
508
+ const tok = resolveEnToken(backend === 'codebuddy-en' ? settings.codebuddyEnToken : null, { env })
509
+ return endpointEnv(backend, settings.endpointOverride, authDomain, tok.token) || {}
510
+ } catch (e) { return {} }
511
+ }
512
+ })] : [],
513
+
514
+ // 设置分区(契约 §3):keystone 统一文件 {codebuddy:{...}};旧扁平文件的字段
515
+ // 级迁移由 keystone LEGACY_SOURCES 承担(字段名逐字相同)。
516
+ settings: {
517
+ keys: SETTINGS_KEYS,
518
+ secretKeys: ['codebuddyEnToken'],
519
+ defaults: () => normalizeSettings(null),
520
+ normalize: (raw) => normalizeSettings(raw),
521
+ 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 面,无视用户设置)。
528
+ const face = (currentPreferredBackend() && normalizeBackend(currentPreferredBackend())) || DEFAULT_BACKEND
529
+ const live = cachedCliModels(face, () => fetchHelpModelsSync(env))
530
+ let options = []
531
+ let note = '账号实际可用性以服务端实时裁决;日常任务优先免费(x0.00)。'
532
+ if (live && live.ok && live.ids.length) {
533
+ const detail = modelCatalogDetailed(face, { env, accountModels: live.ids })
534
+ const byId = new Map(detail.map((x) => [x.id, x]))
535
+ options = live.ids.map((id) => {
536
+ const d = byId.get(id)
537
+ return { value: id, label: (d && d.label) || id }
538
+ })
539
+ note = '实时来自本机 codebuddy CLI 的声明名册(' + live.ids.length + ' 项,随 CLI 版本更新);当前面:' + face + '。账号级权威清单见 codebuddy_models。'
540
+ } else {
541
+ note = '未能从 CLI 读取模型名册(' + String((live && live.error) || 'unknown') + ')—— 下拉为空,可手动输入模型 id。'
542
+ }
543
+ return {
544
+ titleSuffix: 'CodeBuddy',
545
+ fields: [
546
+ {
547
+ key: 'preferredBackend', label: '默认后端', type: 'select',
548
+ options: BACKENDS.map((b) => ({ value: b, label: BACKEND_LABELS[b] })),
549
+ note: '新会话未显式指定 backend 时用这里选的后端;单次调用可覆盖。codebuddy-en 需要 codebuddyEnToken 或 DSH 已配 workbuddy key。'
550
+ },
551
+ {
552
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true, placeholder: '(CLI 默认)',
553
+ options,
554
+ note
555
+ },
556
+ { key: 'codebuddyEnToken', label: 'WorkBuddy 国际版 Token', type: 'secret', note: '仅 backend="codebuddy-en" 需要。国际版登录 token 被 protector key 封装不落盘,只能手工提供;留空则自动尝试 DSH 凭据库的 WORKBUDDY_TOKEN。' },
557
+ { key: 'endpointOverride', label: '端点覆盖', type: 'text', placeholder: 'https://…/v2', note: '一般留空:端点按登录域自动对齐(www.codebuddy.cn 等)。仅在需要强制指定 API 端点时填写,且必须自带 /v2。' }
558
+ ]
559
+ }
560
+ },
561
+ diagnose(snap) {
562
+ const s = normalizeSettings(snap)
563
+ const lines = []
564
+ const seen = new Set()
565
+ // 默认后端一行;codebuddy-en 是 4 面里唯一需要凭据的,恒附一行状态。
566
+ for (const b of [s.preferredBackend, 'codebuddy-en']) {
567
+ if (seen.has(b)) continue
568
+ seen.add(b)
569
+ const d = diagnoseBackend(b, s, {})
570
+ lines.push(b + ': ' + (d.endpoint || '?') + '(登录域 ' + (d.authDomain || '未读到') + ',' + d.tokenHint + ')')
571
+ if (d.hint) lines.push(' ⚠ ' + d.hint)
572
+ }
573
+ return lines.join('\n')
574
+ }
575
+ },
576
+
577
+ mcp: { version: '0.2.2' }
578
+ }
579
+
580
+ // 三形态共用的工具逻辑(签名保持 keystone/队友接线契约不变)。
581
+ descriptor.runToolLogic = async function (args, exec) {
582
+ return this.runner.coreExecute(args, exec)
583
+ }
584
+ // 旧 preset continueTool.execute verbatim 映射(sessionId 优先,否则 latest)。
585
+ descriptor.continueToolLogic = async function (args, exec) {
586
+ const a = args || {}
587
+ const mapped = { prompt: a.prompt, backend: a.backend, mode: a.mode, model: a.model, effort: a.effort, maxTurns: a.maxTurns, cwd: a.cwd, timeoutSec: a.timeoutSec, background: a.background }
588
+ if (a.sessionId) mapped.sessionId = a.sessionId
589
+ else if (a.latest) mapped.continueLatest = true
590
+ return this.runner.coreExecute(mapped, exec)
591
+ }
592
+ // 旧 statusTool.execute verbatim:cwd 过滤 + 单项目聚合覆写(含 runs/totalTokens)。
593
+ descriptor.statusToolLogic = function (args) {
594
+ const a = args || {}
595
+ const snap = this.engine.statusSnapshot()
596
+ if (a.cwd) {
597
+ const key = String(a.cwd)
598
+ snap.projects = snap.projects.filter((p) => p.cwd === key)
599
+ const g = snap.projects[0]
600
+ if (g) { snap.state = g.state; snap.running = g.running; snap.current = g.current; snap.trail = g.trail; snap.lastStatus = g.lastStatus; snap.lastAt = g.lastAt; snap.lastSessionId = g.lastSessionId; snap.lastBackend = g.lastBackend; snap.fallbackActive = g.fallbackActive; snap.runs = g.runs; snap.totalTokens = g.totalTokens; snap.updatedAt = g.updatedAt }
601
+ }
602
+ return snap
603
+ }
604
+
605
+ // 供 preset/dynamic/MCP/测试形态复用的领域函数(不 import home-plugin,全部经
606
+ // 描述符暴露;MCP 面据 buildArgv/parseJson/buildResult/isLimited/failureHint 组
607
+ // 装真实 spawn 执行,语义与旧 mcp/codebuddy-mcp-server.mjs 一致)。
608
+ Object.assign(descriptor, {
609
+ policyText: POLICY_TEXT, limits: { LIMIT_RE: CODEBUDDY_LIMIT_RE },
610
+ backendLabels: BACKEND_LABELS, backendEndpoints: BACKEND_ENDPOINTS,
611
+ authDomainEndpoints: AUTH_DOMAIN_ENDPOINTS, backendAuthIds: BACKEND_AUTH_IDS,
612
+ staticModelIds: BACKEND_MODEL_IDS, endpointHost, resolveEndpoint, endpointEnv,
613
+ endpointMismatchHint, resolveEnToken, readDshWorkbuddyToken, readBackendAuthDomain,
614
+ diagnoseBackend, parseAccountModels, rememberAccountCatalog, getAccountCatalog,
615
+ normalizeProductConfig, extractModelIds, extractModelCredits, parseCreditValue,
616
+ formatCreditLabel, lookupModelCredits, normalizeSettings
617
+ })
618
+ // env 经 io 绑定:catalog 是模块级纯函数,若共用模块级 env,多 provider 实例会互相
619
+ // 覆盖(测试串扰)。这里每个实例调用时都带上自己的 env。
620
+ const withEnv = (fn) => (backend, io) => fn(backend, Object.assign({ env }, io || {}))
621
+ Object.assign(descriptor, {
622
+ backendModelCatalog: withEnv(backendModelCatalog),
623
+ modelCatalogDetailed: withEnv(modelCatalogDetailed),
624
+ formatModelCatalogText: withEnv(formatModelCatalogText)
625
+ })
626
+
627
+ descriptor.attach = function (hostOpts) {
628
+ host = hostOpts || {}
629
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
630
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
631
+ this.runner = runner
632
+ return runner
633
+ }
634
+ descriptor.hostOptions = () => host
635
+ return descriptor
636
+ }