@luchenglong/cli-bridge 0.2.3 → 0.2.5

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.
@@ -568,931 +568,1069 @@ function createRunner(o) {
568
568
  return { coreExecute, runSync, askFallback }
569
569
  }
570
570
 
571
- // providers/codebuddy.mjs — codebuddy provider descriptor(真移植,替换 Lead 冒烟占位)。
572
- //
573
- // 移植基线:codebuddy-first-bridge v1.6.x core/codebuddy-core.mjs 的纯逻辑
574
- // (后端注册表/端点对齐/凭据链/模型目录/buildArgv/parseCodebuddyJson/buildResult/
575
- // foldEvent/settings 清洗/三工具 schema)与 preset/codebuddy-first 内联语义,
576
- // 逐字保持(PROVIDER-CONTRACT.md §8 红线:工具入参语义与 schema 不许漂移)。
577
- // 与 provider 无关的骨架(状态引擎/行流/回退弹窗/展示层)在 core/bridge-kit.mjs。
578
- //
579
- // TODO(Lead 定案,0.1.0 不做):旧包 credits/促销面板的 modelPromotions /
580
- // isPromotionActive / activePromotionFor(约 200 行)不进统一设置面板;本版
581
- // modelCatalogDetailed 只给「倍率 + 授权」两标(无促销角标),行为差异在设置面板
582
- // 单列,运行面(buildArgv/CLI 选择)不受影响。
583
- //
584
- // 红线(PROVIDER-CONTRACT.md §8):
585
- // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现元环境字面量;
586
- // process/env/fs 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 attach(hostOpts)。
587
- // - 只允许 import '../core/bridge-kit.mjs' 一行。
588
- // - isLimited 用本文件自定义的中文限流表(旧 core verbatim),不用 kit 通用表。
589
-
590
- // ── 提示词策略段(旧 preset POLICY_TEXT verbatim;systemPrompt order 5)────────
591
- const POLICY_TEXT = [
592
- 'codebuddy-first execution policy (local codebuddy CLI bridge, with fallback + live indicator + live status tool).',
593
- '',
594
- '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).',
595
- '',
596
- 'Priority rule for EVERY mode (normal, plan, accept-edits, subagent/workflow/ralph delegation, and goal rounds):',
597
- '- 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.',
598
- '- Use native read/write/shell tools mainly for quick read-only lookups and for the final build/test verification of what codebuddy produced.',
599
- '- In plan mode, call codebuddy_run with mode=auto (or mode=plan); in accept-edits/normal mode codebuddy_run applies edits directly.',
600
- '- When you delegate to a DSH subagent or workflow, instruct that delegate to also prefer codebuddy_run.',
601
- '- For long-running tasks, call codebuddy_run with background=true and collect the result with job_output; use codebuddy_status to watch progress.',
602
- '',
603
- '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.',
604
- '',
605
- '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).',
606
- '',
607
- '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.'
608
- ].join('\n')
609
-
610
- // ── 限流/网络/认证失败判定(旧 core verbatim)。仅匹配 stderr + status;数字码
611
- // 加词边界(避免 "1500" 命中 500、"4013" 命中 401)。中文码(流量/受限/金额/
612
- // 余额/额度/认证/连接/断开 等)为 codebuddy 面专属,必须逐字保留。
613
- // 命名纪律(mimo 同款):本文件顶层名绝不与 core/bridge-kit.mjs 顶层导出同名 ——
614
- // dynamic 形态把 kit 与 provider 内联进同一脚本作用域,同名 const 直接炸语法
615
- // (LIMIT_RE 在 kit L33 已有,故此处带 CODEBUDDY_ 前缀)。
616
- 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
617
-
618
- // ── 后端注册表(旧 core verbatim:端点按登录域自动对齐)───────────────────────
619
- const BACKENDS = ['codebuddy', 'codebuddy-intl', 'codebuddy-en', 'workbuddy']
620
-
621
- const BACKEND_ENDPOINTS = {
622
- 'codebuddy': 'https://www.codebuddy.ai/v2',
623
- 'codebuddy-intl': 'https://www.codebuddy.ai/v2',
624
- 'codebuddy-en': 'https://www.workbuddy.ai/v2',
625
- 'workbuddy': 'https://copilot.tencent.com/v2'
626
- }
627
-
628
- const AUTH_DOMAIN_ENDPOINTS = {
629
- 'www.codebuddy.cn': 'https://www.codebuddy.cn/v2',
630
- 'www.codebuddy.ai': 'https://www.codebuddy.ai/v2',
631
- 'www.workbuddy.ai': 'https://www.workbuddy.ai/v2',
632
- 'copilot.tencent.com': 'https://copilot.tencent.com/v2'
633
- }
634
-
635
- const BACKEND_AUTH_IDS = {
636
- 'codebuddy': 'Tencent-Cloud.coding-copilot',
637
- 'codebuddy-intl': 'Tencent-Cloud.coding-copilot',
638
- 'codebuddy-en': 'workbuddy-desktop-ai',
639
- 'workbuddy': 'workbuddy-desktop'
640
- }
641
-
642
- const BACKEND_LABELS = {
643
- 'codebuddy': 'CodeBuddy 国内版(npm CLI)',
644
- 'codebuddy-intl': 'CodeBuddy 国际版(npm CLI · 国际面)',
645
- 'codebuddy-en': 'WorkBuddy 国际版(WorkBuddyAI 桌面 CLI)',
646
- 'workbuddy': 'WorkBuddy 国内版(桌面 CLI)'
647
- }
648
-
649
- const BACKEND_ALIASES = {
650
- 'workbuddy-en': 'codebuddy-en',
651
- 'workbuddy-ai': 'codebuddy-en',
652
- 'codebuddy-ioa': 'codebuddy-intl',
653
- 'codebuddy-international': 'codebuddy-intl',
654
- 'codebuddy-oversea': 'codebuddy-intl'
655
- }
656
-
657
- const DEFAULT_BACKEND = 'codebuddy'
658
-
659
- const SETTINGS_KEYS = ['preferredBackend', 'defaultModel', 'codebuddyEnToken', 'endpointOverride']
660
-
661
- // codebuddy-en 凭据的第三条通道:DSH 凭据库里可能已有的 workbuddy key(旧 core verbatim)。
662
- const CREDENTIAL_KEYS = ['WORKBUDDY_TOKEN', 'WORKBUDDY_AI_TOKEN', 'CODEBUDDY_EN_TOKEN']
663
-
664
- // 离线/读不到描述文件时的回退静态表(真机按账号实测快照,2026-09)。
665
- const BACKEND_MODEL_IDS = {
666
- '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'],
667
- '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'],
668
- // WorkBuddyAI 自制目录(product.json 顶层 37 项,按其 credits 排序:免费的在前)
669
- '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'],
670
- // WorkBuddy 国内桌面自制目录(product.json:applicationName=WorkBuddy)
671
- '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']
672
- }
673
-
674
- // 各后端真正生效的 product 描述文件位置(旧 core v1.6.1 verbatim)。
675
- const PRODUCT_DESCRIPTOR_ENV = {
676
- 'codebuddy': { env: 'CODEBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
677
- 'codebuddy-intl': { env: 'CODEBUDDY_INTL_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
678
- 'codebuddy-en': { env: 'CODEBUDDY_EN_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy-ai' },
679
- 'workbuddy': { env: 'WORKBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy' }
680
- }
681
-
682
- // 倍率跨命名匹配(账号清单 id → 描述文件 id,旧 core verbatim)。
683
- const CREDIT_ID_ALIASES = {
684
- 'kimi-k3-1': ['kimi-k3', 'kimi-k3-ioa'],
685
- 'hy3-x': ['hy3', 'hy3-ioa'],
686
- 'default': ['codewise-default-model-v2'],
687
- 'auto': ['hy3', 'hy3-ioa']
688
- }
689
-
690
- 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.'
691
-
692
- const BACKEND_ENUM = ['codebuddy', 'codebuddy-intl', 'codebuddy-ioa', 'codebuddy-international', 'codebuddy-en', 'workbuddy-en', 'workbuddy-ai', 'workbuddy']
693
-
694
- // ── 三工具 schema(旧 preset/codebuddy-first verbatim;契约 §8)────────────────
695
- const RUN_PARAMS = {
696
- type: 'object',
697
- additionalProperties: false,
698
- required: ['prompt'],
699
- properties: {
700
- prompt: { type: 'string', description: 'The full task/instruction for codebuddy. Be complete and self-contained.' },
701
- 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.' },
702
- mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'auto follows DSH plan state; plan = no writes; accept-edits = allow edits. Default auto.' },
703
- model: { type: 'string', description: MODEL_DESCRIPTION },
704
- effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
705
- maxTurns: { type: 'integer', description: 'Optional max agentic turns (1-500, default unlimited).' },
706
- cwd: { type: 'string', description: 'Working directory for codebuddy. Defaults to the DSH workspace root.' },
707
- addDirs: { type: 'array', items: { type: 'string' }, description: 'Extra directories to add to codebuddy workspace.' },
708
- timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
709
- background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
710
- }
711
- }
712
- const CONTINUE_PARAMS = {
713
- type: 'object',
714
- additionalProperties: false,
715
- required: ['prompt'],
716
- properties: {
717
- prompt: { type: 'string', description: 'Follow-up instruction for the ongoing codebuddy conversation.' },
718
- sessionId: { type: 'string', description: 'codebuddy session id to resume (from a prior codebuddy_run result).' },
719
- latest: { type: 'boolean', description: 'Continue the most recent codebuddy conversation instead of a specific id.' },
720
- 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).' },
721
- mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'Execution mode; default auto.' },
722
- 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).' },
723
- effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
724
- maxTurns: { type: 'integer', description: 'Optional max agentic turns.' },
725
- cwd: { type: 'string', description: "Working directory for codebuddy; when resuming, defaults to the resumed session's project directory." },
726
- timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
727
- background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
728
- }
729
- }
730
- const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
731
-
732
- function defineProvider (deps = {}) {
733
- const env = deps.env || {}
734
- let host = null // attach 后保存 hostOpts(preset/dynamic/MCP 形态宿主能力)
735
-
736
- // 宿主 fs/path 访问的统一入口:deps 注入优先;dynamic 内联体(无 import,运行在
737
- // 后端 Node 上下文)回退到 getBuiltinModule —— 与旧 core builtinModule() 的
738
- // typeof 守卫模式一致(这是旧 dynamic 端点修复生效的同一条通道,缺了它默认
739
- // 后端会回到 401 老病)。两者皆不可用时自然降级:读不到文件 = 静态表兜底。
740
- function builtinModule(name) {
741
- try {
742
- const proc = globalThis.process
743
- return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
744
- } catch (e) { return null }
745
- }
746
- function fsRead(p) {
747
- const nf = deps.nodeFs || builtinModule('node:fs')
748
- if (!nf || typeof nf.readFileSync !== 'function') return null
749
- try { return nf.readFileSync(p, 'utf8') } catch (e) { return null }
750
- }
751
- function pathJoin(...parts) {
752
- const np = deps.nodePath || builtinModule('node:path')
753
- if (np && typeof np.join === 'function') return np.join(...parts)
754
- return parts.join('/')
755
- }
756
- const pathSep = (deps.nodePath && deps.nodePath.sep) || (/[A-Za-z]:[\\/]/.test(env.USERPROFILE || env.APPDATA || '') ? '\\' : '/')
757
-
758
- // ── 端点/登录域(旧 core endpointHost verbatim:非法 URL 容错)───────────────
759
- function endpointHost(url) {
760
- const s = String(url || '').trim()
761
- if (!s) return ''
762
- try { return new URL(s).hostname.toLowerCase() } catch (e) { }
763
- const m = /^[a-z]+:\/\/([^/?#]+)/i.exec(s)
764
- return m ? m[1].toLowerCase() : ''
765
- }
766
-
767
- function resolveEndpoint(explicitBaseUrl, authDomain) {
768
- const explicit = String(explicitBaseUrl || '').trim()
769
- if (explicit) return explicit
770
- const d = String(authDomain || '').trim().toLowerCase()
771
- if (d && AUTH_DOMAIN_ENDPOINTS[d]) return AUTH_DOMAIN_ENDPOINTS[d]
772
- return null
773
- }
774
-
775
- function isBackend(v) { return BACKENDS.indexOf(v) >= 0 }
776
-
777
- // 后端名规范化(v1.3.3 verbatim):别名 + 大小写不敏感;非后端名原样返回。
778
- function normalizeBackend(v) {
779
- if (typeof v !== 'string') return v
780
- const lower = v.trim().toLowerCase()
781
- const aliased = BACKEND_ALIASES[lower] || lower
782
- return BACKENDS.indexOf(aliased) >= 0 ? aliased : v
783
- }
784
-
785
- // 后端解析优先级(旧 core verbatim):显式 > 会话归属 > 用户偏好 > 默认。
786
- function resolveBackend(args, target, preferredBackend) {
787
- if (args && isBackend(normalizeBackend(args.backend))) return normalizeBackend(args.backend)
788
- if (target && target.backend && isBackend(normalizeBackend(target.backend))) return normalizeBackend(target.backend)
789
- if (preferredBackend && isBackend(normalizeBackend(preferredBackend))) return normalizeBackend(preferredBackend)
790
- return DEFAULT_BACKEND
791
- }
792
-
793
- // 本次调用的端点/凭据 env 注入(旧 core endpointEnv verbatim 三规则)。
794
- function endpointEnv(backend, explicitBaseUrl, authDomain, authToken) {
795
- const out = {}
796
- const endpoint = resolveEndpoint(explicitBaseUrl, authDomain)
797
- const product = BACKEND_ENDPOINTS[backend]
798
- if (endpoint && endpointHost(endpoint) !== endpointHost(product)) {
799
- out.CODEBUDDY_BASE_URL = endpoint
800
- }
801
- if (backend === 'codebuddy-en') {
802
- const tok = String(authToken || '').trim()
803
- if (tok) out.CODEBUDDY_AUTH_TOKEN = tok
804
- }
805
- return Object.keys(out).length ? out : null
806
- }
807
-
808
- // 可操作提示(旧 core endpointMismatchHint 三分支 verbatim)。
809
- function endpointMismatchHint(backend, authDomain, hasToken) {
810
- if (backend === 'codebuddy-en' && !hasToken) {
811
- 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,免配置)。'
812
- }
813
- if (backend === 'codebuddy-intl') {
814
- return 'codebuddy-intl(CodeBuddy 国际版)使用同一个 npm CLI,但国际面模型由服务端按账号授权放行:未授权时 CLI 返回 400「model [...] is only available for authorized users」。若你用的是国内账号,请改用 backend="codebuddy"(国内面模型清单)或 backend="codebuddy-en"(WorkBuddy 国际版)。'
815
- }
816
- const d = String(authDomain || '').trim().toLowerCase()
817
- if (d && endpointHost(resolveEndpoint(null, d)) !== endpointHost(BACKEND_ENDPOINTS[backend])) {
818
- return backend + ' 的登录域是 ' + d + ',与产品端点 ' + BACKEND_ENDPOINTS[backend] + ' 不一致;桥接层已自动注入 CODEBUDDY_BASE_URL=' + AUTH_DOMAIN_ENDPOINTS[d] + '。若仍 401,请重新登录对应客户端。'
819
- }
820
- return null
821
- }
822
-
823
- // 从 auth 库读某后端登录域(旧 core readBackendAuthDomain verbatim 语义;fs 经
824
- // deps 注入。io 可覆盖 readFileSync/dir/env,供测试夹具与 MCP 面注入真实 fs)。
825
- function readBackendAuthDomain(backend, io) {
826
- const o = io || {}
827
- const id = BACKEND_AUTH_IDS[backend]
828
- if (!id) return null
829
- try {
830
- const read = o.readFileSync || fsRead
831
- if (typeof read !== 'function') return null
832
- const e = o.env || env
833
- let dir = o.dir
834
- if (!dir) {
835
- dir = e.CODEBUDDY_AUTH_DIR ||
836
- pathJoin(e.LOCALAPPDATA || 'C:\\Users\\lcl\\AppData\\Local', 'CodeBuddyExtension', 'Data', 'Public', 'auth')
837
- }
838
- const sep = String(dir).indexOf('\\') >= 0 ? '\\' : '/'
839
- const txt = read(dir + sep + id + '.info', 'utf8')
840
- if (txt == null) return null
841
- const raw = JSON.parse(txt)
842
- const d = raw && raw.auth && raw.auth.domain
843
- return typeof d === 'string' && d.trim() ? d.trim() : null
844
- } catch (e) { return null }
845
- }
846
-
847
- // DSH 凭据库第三通道(旧 core readDshWorkbuddyToken verbatim 语义;CODEBUDDY_
848
- // CREDENTIALS_DIR 覆盖测试夹具;fs 经 deps 注入)。
849
- function readDshWorkbuddyToken() {
850
- const overrideDir = env.CODEBUDDY_CREDENTIALS_DIR || null
851
- const home = overrideDir || env.DSH_HOME || null
852
- if (!home) return null
853
- const files = [home + '\\.credentials.yaml', home + '\\.env', home + '/.credentials.yaml', home + '/.env']
854
- for (const f of files) {
855
- const text = fsRead(f)
856
- if (!text) continue
857
- for (const key of CREDENTIAL_KEYS) {
858
- const m = text.match(new RegExp('^[ \\t]*' + key + '[ \\t]*[:=][ \\t]*(.+)$', 'm'))
859
- if (!m) continue
860
- const v = m[1].trim().replace(/\s+#.*$/, '').replace(/^['"]|['"]$/g, '').trim()
861
- // 只接受看起来是真实 token 的值(避免把 $VAR 引用或占位符当凭据)。
862
- if (v.length >= 40 && !v.startsWith('$') && !/^<.*>$/.test(v)) return v
863
- }
864
- }
865
- return null
866
- }
867
-
868
- // codebuddy-en 凭据链(旧 core verbatim):设置面板 > CODEBUDDY_AUTH_TOKEN >
869
- // DSH 凭据库。dynamic 沙箱无 fs → 第三通道自然缺席(旧 dynamic 本也有限)。
870
- function resolveEnToken(settingToken) {
871
- const s = String(settingToken || '').trim()
872
- if (s) return { token: s, source: 'setting' }
873
- const envTok = env.CODEBUDDY_AUTH_TOKEN || ''
874
- if (String(envTok).trim()) return { token: String(envTok).trim(), source: 'env' }
875
- const fromStore = readDshWorkbuddyToken()
876
- if (fromStore) return { token: fromStore, source: 'dsh-store' }
877
- return { token: null, source: null }
878
- }
879
-
880
- // ── 模型目录(面板/诊断用;无促销角标版,见头注 TODO)───────────────────────
881
- function accountConfigCandidates(backend) {
882
- const spec = PRODUCT_DESCRIPTOR_ENV[backend]
883
- if (!spec || !spec.accountDir) return []
884
- const home = env.USERPROFILE || env.HOME
885
- if (!home) return []
886
- const base = pathJoin(home, spec.accountDir.split('/').join(pathSep))
887
- return [
888
- pathJoin(base, 'cache', 'acc-product-config-v3.json'),
889
- pathJoin(base, 'local_storage', 'entry_d43e96994f944cfb77961c2ea7d04605.info'),
890
- pathJoin(base, 'local_storage', 'wb_entry_d43e96994f944cfb77961c2ea7d04605.info')
891
- ]
892
- }
893
-
894
- function productDescriptorCandidates(backend) {
895
- const spec = PRODUCT_DESCRIPTOR_ENV[backend]
896
- if (!spec) return []
897
- const out = []
898
- for (const p of accountConfigCandidates(backend)) out.push(p)
899
- if (env[spec.env]) out.push(env[spec.env])
900
- const rels = spec.fallbackRel ? [spec.rel, spec.fallbackRel] : [spec.rel]
901
- const push = (root) => { if (root) for (const r of rels) out.push(pathJoin(root, ...r.split('/'))) }
902
- if (backend === 'codebuddy' || backend === 'codebuddy-intl') {
903
- push(env.APPDATA ? pathJoin(env.APPDATA, 'npm', 'node_modules', '@tencent-ai', 'codebuddy-code') : null)
904
- } else if (backend === 'codebuddy-en') {
905
- push('C:\\Program Files\\WorkBuddyAI\\resources\\app.asar.unpacked\\cli')
906
- } else if (backend === 'workbuddy') {
907
- push('C:\\Program Files\\WorkBuddy\\resources\\app.asar.unpacked\\cli')
908
- }
909
- return out
910
- }
911
-
912
- function normalizeProductConfig(raw) {
913
- try {
914
- const obj = typeof raw === 'string' ? JSON.parse(raw) : raw
915
- if (!obj) return null
916
- if (Array.isArray(obj)) {
917
- // 数组形态:从后往前找第一个带 data 的条目(末尾最新)。
918
- for (let i = obj.length - 1; i >= 0; i--) {
919
- const e = obj[i]
920
- if (e && typeof e === 'object' && e.data && typeof e.data === 'object') return e.data
921
- }
922
- return null
923
- }
924
- if (typeof obj !== 'object') return null
925
- if (obj.data && typeof obj.data === 'object' && !Array.isArray(obj.models) && !Array.isArray(obj.agents)) return obj.data
926
- return obj
927
- } catch (e) { return null }
928
- }
929
-
930
- function extractModelIds(productJson) {
931
- try {
932
- const obj = normalizeProductConfig(productJson)
933
- if (!obj || typeof obj !== 'object') return null
934
- const pick = (arr) => {
935
- if (!Array.isArray(arr) || !arr.length) return null
936
- const ids = arr.map((m) => (typeof m === 'string' ? m : m && m.id)).filter((s) => typeof s === 'string' && s.trim())
937
- return ids.length ? [...new Set(ids)] : null
938
- }
939
- const agents = Array.isArray(obj.agents) ? obj.agents : []
940
- const cli = agents.find((a) => a && a.name === 'cli')
941
- const fromCli = cli ? pick(cli.models) : null
942
- const fromTop = pick(obj.models)
943
- if (fromCli && fromTop) return fromTop.length > fromCli.length ? fromTop : fromCli
944
- return fromCli || fromTop || null
945
- } catch (e) { return null }
946
- }
947
-
948
- function parseCreditValue(raw) {
949
- if (typeof raw !== 'string') return null
950
- const s = raw.trim()
951
- let m = s.match(/^[xX×]\s*([0-9]+(?:\.[0-9]+)?)/)
952
- if (!m) m = s.match(/^([0-9]+(?:\.[0-9]+)?)\s*[xX×]/)
953
- if (!m) return null
954
- const n = Number(m[1])
955
- return Number.isFinite(n) ? n : null
956
- }
957
-
958
- function formatCreditLabel(credits) {
959
- if (typeof credits !== 'number' || !Number.isFinite(credits)) return ''
960
- if (credits === 0) return '免费'
961
- return `x${credits.toFixed(2)}`
962
- }
963
-
964
- function extractModelCredits(productJson) {
965
- try {
966
- const obj = normalizeProductConfig(productJson)
967
- if (!obj || typeof obj !== 'object' || !Array.isArray(obj.models)) return null
968
- const map = new Map()
969
- for (const m of obj.models) {
970
- if (!m || typeof m !== 'object') continue
971
- const id = typeof m.id === 'string' ? m.id.trim() : ''
972
- if (!id) continue
973
- const n = parseCreditValue(m.credits)
974
- if (n !== null) map.set(id, n)
975
- }
976
- return map.size ? map : null
977
- } catch (e) { return null }
978
- }
979
-
980
- function lookupModelCredits(creditsMap, id) {
981
- if (!creditsMap || typeof id !== 'string') return null
982
- const norm = id.trim()
983
- const cands = [norm]
984
- if (norm.endsWith('-ioa')) cands.push(norm.slice(0, -4))
985
- else cands.push(norm + '-ioa')
986
- if (CREDIT_ID_ALIASES[norm]) cands.push(...CREDIT_ID_ALIASES[norm])
987
- for (const c of cands) {
988
- if (creditsMap.has(c)) {
989
- const v = creditsMap.get(c)
990
- if (typeof v === 'number') return v
991
- }
992
- }
993
- return null
994
- }
995
-
996
- function backendModelCatalog(backend, io) {
997
- const known = BACKEND_MODEL_IDS[backend] || []
998
- const read = (io && io.readFileSync) || fsRead
999
- let fromFile = null
1000
- let fromFileRich = null
1001
- // 旧 v1.6.1 语义:第一份有内容的 + 第一份带促销的,优先后者。
1002
- for (const p of productDescriptorCandidates(backend)) {
1003
- let txt = null
1004
- try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
1005
- if (txt == null) continue
1006
- const ids = extractModelIds(txt)
1007
- if (ids && ids.length) {
1008
- if (!fromFile) fromFile = ids
1009
- const obj = normalizeProductConfig(txt)
1010
- if (!fromFileRich && obj && Array.isArray(obj.modelPromotions)) fromFileRich = ids
1011
- }
1012
- if (fromFileRich) break
1013
- }
1014
- if (!fromFile) return known
1015
- return fromFileRich || fromFile
1016
- }
1017
-
1018
- // 服务端回吐的账号清单缓存(进程内,旧 core verbatim)。
1019
- const ACCOUNT_CATALOG_CACHE = new Map()
1020
- function rememberAccountCatalog(backend, ids) {
1021
- if (Array.isArray(ids) && ids.length) ACCOUNT_CATALOG_CACHE.set(backend, ids.slice())
1022
- }
1023
- function getAccountCatalog(backend) {
1024
- const v = ACCOUNT_CATALOG_CACHE.get(backend)
1025
- return v && v.length ? v.slice() : null
1026
- }
1027
-
1028
- // CLI 报错里解析「该账号当前支持的模型」(旧 core parseAccountModels verbatim)。
1029
- function parseAccountModels(text) {
1030
- const s = String(text || '')
1031
- const anchor = s.indexOf('Currently supported models for your account')
1032
- if (anchor < 0) return null
1033
- const tail = s.slice(anchor)
1034
- const ids = []
1035
- for (const line of tail.split(/\r?\n/)) {
1036
- const m = /^\s*[-*]\s+(\S+)\s*$/.exec(line)
1037
- if (!m) {
1038
- if (ids.length) break
1039
- continue
1040
- }
1041
- if (!ids.includes(m[1])) ids.push(m[1])
1042
- }
1043
- return ids.length ? ids : null
1044
- }
1045
-
1046
- // 带倍率/授权的详细清单(无促销角标,旧 v1.6.1 的 0.1.0 子集;排序规则 verbatim:
1047
- // 已授权在前 → 有倍率升序 → 无倍率殿后)。
1048
- function modelCatalogDetailed(backend, io) {
1049
- const o = io || {}
1050
- const fromFile = backendModelCatalog(backend, o)
1051
- const acct = (Array.isArray(o.accountModels) && o.accountModels.length) ? o.accountModels : getAccountCatalog(backend)
1052
- const ids = []
1053
- const authorized = new Set()
1054
- if (acct) for (const id of acct) { if (!ids.includes(id)) ids.push(id); authorized.add(id) }
1055
- for (const id of fromFile) if (!ids.includes(id)) ids.push(id)
1056
- const read = o.readFileSync || fsRead
1057
- let creditsMap = null
1058
- for (const p of productDescriptorCandidates(backend)) {
1059
- let txt = null
1060
- try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
1061
- if (txt == null) continue
1062
- const map = extractModelCredits(txt)
1063
- if (map) { creditsMap = map; break }
1064
- }
1065
- const items = ids.map((id) => {
1066
- const base = lookupModelCredits(creditsMap, id)
1067
- const credits = base
1068
- const hasCredits = typeof credits === 'number'
1069
- const suffix = formatCreditLabel(credits)
1070
- const marks = []
1071
- if (suffix) marks.push(suffix)
1072
- if (acct && !authorized.has(id)) marks.push('未授权')
1073
- return {
1074
- id,
1075
- credits,
1076
- baseCredits: base,
1077
- free: hasCredits && credits === 0,
1078
- hasCredits,
1079
- authorized: acct ? authorized.has(id) : null,
1080
- promotion: null,
1081
- label: marks.length ? `${id} · ${marks.join(' · ')}` : id
1082
- }
1083
- })
1084
- const rank = (x) => (x.authorized === false ? 1 : 0)
1085
- const withC = items.filter((x) => x.hasCredits).sort((a, b) => rank(a) - rank(b) || a.credits - b.credits)
1086
- const withoutC = items.filter((x) => !x.hasCredits).sort((a, b) => rank(a) - rank(b))
1087
- return [...withC, ...withoutC]
1088
- }
1089
-
1090
- function formatModelCatalogText(backend, io) {
1091
- return modelCatalogDetailed(backend, io).map((x) => x.label).join(', ')
1092
- }
1093
-
1094
- // ── 设置清洗(旧 normalizeBridgeSettings verbatim;updatedAt 透传)───────────
1095
- function normalizeSettings(raw) {
1096
- const snap = { preferredBackend: DEFAULT_BACKEND, defaultModel: '', codebuddyEnToken: '', endpointOverride: '' }
1097
- if (!raw || typeof raw !== 'object') return snap
1098
- if (typeof raw.preferredBackend === 'string') {
1099
- const nb = normalizeBackend(raw.preferredBackend)
1100
- if (typeof nb === 'string' && BACKENDS.indexOf(nb) >= 0) snap.preferredBackend = nb
1101
- }
1102
- if (typeof raw.defaultModel === 'string') snap.defaultModel = raw.defaultModel.trim()
1103
- if (typeof raw.codebuddyEnToken === 'string') snap.codebuddyEnToken = raw.codebuddyEnToken.trim()
1104
- if (typeof raw.endpointOverride === 'string') snap.endpointOverride = raw.endpointOverride.trim()
1105
- if (typeof raw.updatedAt === 'number' && raw.updatedAt > 0) snap.updatedAt = raw.updatedAt
1106
- return snap
1107
- }
1108
-
1109
- // 诊断(旧 diagnoseBackend verbatim;fs/env 走 deps)。
1110
- function diagnoseBackend(backend, settings, io) {
1111
- const o = io || {}
1112
- const e = o.env || env
1113
- const s = settings || normalizeSettings(null)
1114
- const authDomain = readBackendAuthDomain(backend, Object.assign({ env: e }, o))
1115
- const override = String(s.endpointOverride || '').trim()
1116
- const byDomain = resolveEndpoint(null, authDomain)
1117
- const endpoint = override || byDomain || BACKEND_ENDPOINTS[backend] || null
1118
- const endpointSource = override ? 'override' : (byDomain ? 'auth-domain' : 'product')
1119
- const tok = resolveEnToken(backend === 'codebuddy-en' ? s.codebuddyEnToken : null)
1120
- return {
1121
- backend: backend,
1122
- authDomain: authDomain,
1123
- endpoint: endpoint,
1124
- endpointSource: endpointSource,
1125
- tokenSource: backend === 'codebuddy-en' ? tok.source : 'not-needed',
1126
- tokenHint: tok.source === 'setting' ? '来自设置面板'
1127
- : tok.source === 'env' ? '来自环境变量 CODEBUDDY_AUTH_TOKEN'
1128
- : tok.source === 'dsh-store' ? '来自 DSH 凭据库(自动复用 WORKBUDDY_TOKEN)'
1129
- : backend === 'codebuddy-en' ? '缺失:国际版 token 不落盘,需在设置面板填写或先在 DSH 配 workbuddy provider'
1130
- : '无需填写(国内版由 CLI 自行登录)',
1131
- mismatch: endpointMismatchHint(backend, authDomain, !!tok.token) !== null,
1132
- hint: endpointMismatchHint(backend, authDomain, !!tok.token) || null,
1133
- defaultModel: String(s.defaultModel || '').trim() || '(CLI 默认)'
1134
- }
1135
- }
1136
-
1137
- // ── 结果判定(旧 isLimited/isTransientCliError/failureHint verbatim)─────────
1138
- function isLimitedCodebuddy(res) {
1139
- if (!res || res.ok) return false
1140
- // 前置凭据缺失:配置问题,不是限流(弹窗重试不会让 token 出现)。
1141
- if (res.status === 'AUTH_REQUIRED') return false
1142
- if (res.status === 'SPAWN_ERROR' || res.status === 'CODEBUDDY_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
1143
- const hay = String(res.stderr || '') + ' ' + String(res.status || '')
1144
- // 401/端点域不匹配:需要用户换登录域,不归限流类(旧 v1.3.0 verbatim)。
1145
- if (/401 authentication failed|differs from the current product endpoint/i.test(hay)) return false
1146
- return CODEBUDDY_LIMIT_RE.test(hay)
1147
- }
1148
-
1149
- function isTransientCliError(res) {
1150
- if (!res || res.ok) return false
1151
- if (isLimitedCodebuddy(res)) return false
1152
- return res.status === 'ERROR_DURING_EXECUTION'
1153
- }
1154
-
1155
- function failureHint(res) {
1156
- if (!res || res.ok) return ''
1157
- // AUTH_REQUIRED:stderr 已带完整指引,透传(旧 v1.3.1 verbatim)。
1158
- if (res.status === 'AUTH_REQUIRED') return '[诊断] ' + String(res.stderr || '')
1159
- if (isTransientCliError(res)) {
1160
- return res.retried
1161
- ? '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因),已自动重试 1 次仍失败。可换 model 再试一次;若仍失败请改用原生工具完成,或告知用户。'
1162
- : '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因)。直接重试同一请求通常即可通过;也可显式指定 model。不要据此认为任务本身有问题。'
1163
- }
1164
- if (res.status === 'PARSE_ERROR') {
1165
- return '[诊断] 未能从 codebuddy 输出解析出 result 事件(进程可能被中断或输出被截断)。可重试;持续出现请检查 codebuddy CLI 版本。'
1166
- }
1167
- if (/401 authentication failed|differs from the current product endpoint/i.test(String(res.stderr || ''))) {
1168
- return '[诊断] 认证失败(401):请求被送到的端点与当前 CLI 登录域不匹配(国际/国内登录互斥)。请让用户在对应产品域完成 `codebuddy` CLI 登录后重试;这不是限流,重试与回退都无效。'
1169
- }
1170
- return ''
1171
- }
1172
-
1173
- // stream-json 解析(旧 parseCodebuddyJson verbatim)。
1174
- function parseCodebuddyJson(stdoutText) {
1175
- const trimmed = String(stdoutText || '').trim()
1176
- if (!trimmed) return null
1177
- const lines = trimmed.split(/\r?\n/).filter(Boolean)
1178
- for (let i = lines.length - 1; i >= 0; i--) {
1179
- const ln = lines[i].trim()
1180
- if (!ln.startsWith('{')) continue
1181
- try {
1182
- const obj = JSON.parse(ln)
1183
- if (obj && obj.type === 'result') return obj
1184
- } catch (e) {}
1185
- }
1186
- try { return JSON.parse(trimmed) } catch (e) {}
1187
- return null
1188
- }
1189
-
1190
- // result 事件 → 统一结果对象(旧 buildResult verbatim,含账号清单收割)。
1191
- function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
1192
- const bk = backend || 'codebuddy'
1193
- const exitCode = outcome ? outcome.exitCode : null
1194
- const errText = parsed && typeof parsed.error === 'string' && parsed.error ? parsed.error : ''
1195
- const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
1196
- // v1.6.0:顺手收割服务端回吐的「本账号可用模型」清单(失败静默)。
1197
- try {
1198
- const harvest = parseAccountModels(stderr) || parseAccountModels(String(stdoutText || ''))
1199
- if (harvest && harvest.length) rememberAccountCatalog(bk, harvest)
1200
- } catch (e) { /* 收割失败不影响主流程 */ }
1201
- if (parsed && parsed.type === 'result') {
1202
- const isOk = exitCode === 0 && parsed.is_error === false && parsed.subtype === 'success'
1203
- let modelUsed = null
1204
- try {
1205
- if (parsed.modelUsage && typeof parsed.modelUsage === 'object') {
1206
- const names = Object.keys(parsed.modelUsage)
1207
- if (names.length) modelUsed = names.join('+')
1208
- }
1209
- } catch (e) { }
1210
- return {
1211
- ok: isOk,
1212
- status: String(parsed.subtype || (isOk ? 'SUCCESS' : 'ERROR')).toUpperCase(),
1213
- response: typeof parsed.result === 'string' ? parsed.result : '',
1214
- sessionId: typeof parsed.session_id === 'string' ? parsed.session_id : null,
1215
- durationSeconds: typeof parsed.duration_ms === 'number' ? parsed.duration_ms / 1000 : null,
1216
- numTurns: typeof parsed.num_turns === 'number' ? parsed.num_turns : null,
1217
- totalTokens: (parsed.usage && typeof parsed.usage.input_tokens === 'number' && typeof parsed.usage.output_tokens === 'number')
1218
- ? (parsed.usage.input_tokens + parsed.usage.output_tokens) : null,
1219
- exitCode: exitCode,
1220
- mode: mode,
1221
- backend: bk,
1222
- modelUsed: modelUsed,
1223
- stderr: stderr
1224
- }
1225
- }
1226
- return {
1227
- ok: false,
1228
- status: 'PARSE_ERROR',
1229
- response: '',
1230
- sessionId: null,
1231
- durationSeconds: null,
1232
- numTurns: null,
1233
- totalTokens: null,
1234
- exitCode: exitCode,
1235
- mode: mode,
1236
- backend: bk,
1237
- stderr: stderr,
1238
- rawStdout: String(stdoutText || '').slice(-2000)
1239
- }
1240
- }
1241
-
1242
- // 统一 argv 构造(旧 buildArgv verbatim;env 端点/凭据注入在本 provider 内完成,
1243
- // 因为 kit 只透传 opts,宿主三形态都从本函数的返回值取 built.env 下发 spawn)。
1244
- function buildArgvCodebuddy(prefix, args, opts) {
1245
- const o = opts || {}
1246
- const argv = [prefix[0], ...prefix.slice(1), '-p', String(args.prompt), '--output-format', 'stream-json']
1247
- let mode = args.mode || o.defaultMode || 'auto'
1248
- if (mode === 'auto') mode = o.planActive ? 'plan' : 'bypassPermissions'
1249
- if (mode === 'plan') {
1250
- argv.push('--permission-mode', 'plan')
1251
- argv.push('--allowedTools', 'Bash')
1252
- } else {
1253
- mode = 'bypassPermissions'
1254
- argv.push('--permission-mode', 'bypassPermissions')
1255
- }
1256
- // 模型优先级:显式 args.model > 用户偏好 defaultModel > CLI 默认。
1257
- const model = args.model || o.defaultModel
1258
- if (model) argv.push('--model', String(model))
1259
- if (args.effort) argv.push('--effort', String(args.effort))
1260
- if (args.maxTurns !== undefined && args.maxTurns !== null) argv.push('--max-turns', String(clampInt(args.maxTurns, 50, 1, 500)))
1261
- if (Array.isArray(args.addDirs)) for (const d of args.addDirs) { if (d) argv.push('--add-dir', String(d)) }
1262
- if (args.sessionId) argv.push('--resume', String(args.sessionId))
1263
- else if (args.continueLatest) argv.push('--continue')
1264
- const timeoutSec = clampInt(args.timeoutSec, 300, 10, 3600)
1265
- // 端点/凭据注入(旧 preset/dynamic/MCP 三形态一致语义,宿主不必自算):
1266
- // authDomain 只在有 fs 能力的宿主读得到;dynamic 沙箱 → 沿用 CLI 自身端点。
1267
- const bk = o.backend || DEFAULT_BACKEND
1268
- const settings = o.settings || null
1269
- const authDomain = readBackendAuthDomain(bk, {})
1270
- const tok = resolveEnToken(bk === 'codebuddy-en' && settings ? settings.codebuddyEnToken : null)
1271
- const inject = endpointEnv(bk, settings ? settings.endpointOverride : null, authDomain, tok.token)
1272
- return { argv: argv, timeoutSec: timeoutSec, mode: mode, env: o.env || inject }
1273
- }
1274
-
1275
- // 流事件折叠(旧 foldEvent 主体 verbatim;project 状态由 kit engine 持有)。
1276
- function foldStreamEvent(ev, p, summarizeArgs, MAX_ARG_LEN, MAX_TRAIL) {
1277
- if (!ev || !ev.type) return
1278
- if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {
1279
- for (const block of ev.message.content) {
1280
- if (block.type === 'tool_use') {
1281
- p._stepCounter = (p._stepCounter || 0) + 1
1282
- const stepIndex = p._stepCounter
1283
- if (!p._toolMap) p._toolMap = {}
1284
- p._toolMap[block.id] = { stepIndex: stepIndex, name: block.name }
1285
- const args = summarizeArgs(block.input)
1286
- p.trail.push({ stepIndex: stepIndex, state: 'ACTIVE', tool: block.name, args: args, at: new Date().toISOString() })
1287
- if (p.trail.length > MAX_TRAIL) p.trail.shift()
1288
- p.current = { tool: block.name, args: args, stepIndex: stepIndex, since: new Date().toISOString() }
1289
- } else if (block.type === 'thinking') {
1290
- p.current = { tool: 'thinking', args: { text: String(block.thinking || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
1291
- } else if (block.type === 'text') {
1292
- p.current = { tool: 'typing', args: { text: String(block.text || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
1293
- }
1294
- }
1295
- } else if (ev.type === 'user' && ev.message && Array.isArray(ev.message.content)) {
1296
- for (const block of ev.message.content) {
1297
- if (block.type === 'tool_result' && p._toolMap && p._toolMap[block.tool_use_id]) {
1298
- const rec = p._toolMap[block.tool_use_id]
1299
- p.trail.push({ stepIndex: rec.stepIndex, state: block.is_error ? 'ERROR' : 'DONE', tool: rec.name, args: null, at: new Date().toISOString() })
1300
- if (p.trail.length > MAX_TRAIL) p.trail.shift()
1301
- if (p.current && p.current.stepIndex === rec.stepIndex) p.current = null
1302
- }
1303
- }
1304
- }
1305
- }
1306
-
1307
- const descriptor = {
1308
- id: 'codebuddy',
1309
- label: 'CB',
1310
- presetId: 'codebuddy-first',
1311
- defaultBackend: DEFAULT_BACKEND,
1312
- defaultMode: 'auto',
1313
- exeName: 'codebuddy',
1314
- binEnvVars: ['CODEBUDDY_BIN', 'CODEBUDDY_EN_BIN', 'WORKBUDDY_BIN'],
1315
- unavailableStatus: 'CODEBUDDY_UNAVAILABLE',
1316
- // 旧 renderResult verbatim 语义:标头用具体 backend('workbuddy OK'),仅当结果
1317
- // 无 backend 字段时回落 'codebuddy'(= provider.id)。agy/mimo 旧包标头硬编码
1318
- // provider 名,不设此旗。
1319
- backendLabel: true,
1320
-
1321
- backends: () => BACKENDS.slice(),
1322
- normalizeBackend,
1323
- resolveBackend,
1324
-
1325
- buildArgv: buildArgvCodebuddy,
1326
- parseJson: parseCodebuddyJson,
1327
- buildResult,
1328
- foldStreamEvent,
1329
- isLimited: isLimitedCodebuddy,
1330
- isTransientCliError,
1331
- failureHint,
1332
-
1333
- // codebuddy-en 无凭据的确定性前置(v1.3.1 语义,经 kit preflight 钩子实现):
1334
- // 三通道皆空 → 直接 AUTH_REQUIRED(可操作指引进 stderr),不白跑一次 spawn。
1335
- // 其它后端一律放行。dynamic 沙箱无 fs → dsh-store 通道缺席,abort 提示即可。
1336
- preflight({ args, backend, engine, o }) {
1337
- if (backend !== 'codebuddy-en') return null
1338
- const settings = (o && o.getSettings && o.getSettings()) || null
1339
- const tok = resolveEnToken(settings ? settings.codebuddyEnToken : null)
1340
- if (tok.token) return null
1341
- const authDomain = readBackendAuthDomain('codebuddy-en', {})
1342
- const hint = endpointMismatchHint('codebuddy-en', authDomain, false)
1343
- return {
1344
- abort: {
1345
- ok: false,
1346
- status: 'AUTH_REQUIRED',
1347
- response: '',
1348
- sessionId: null,
1349
- durationSeconds: null,
1350
- numTurns: null,
1351
- totalTokens: null,
1352
- exitCode: null,
1353
- mode: (args && args.mode) || descriptor.defaultMode || 'auto',
1354
- backend: 'codebuddy-en',
1355
- stderr: hint
1356
- }
1357
- }
1358
- },
1359
-
1360
- tools: {
1361
- run: {
1362
- name: 'codebuddy_run',
1363
- 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.',
1364
- inputSchema: RUN_PARAMS
1365
- },
1366
- continue: {
1367
- name: 'codebuddy_continue',
1368
- 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.',
1369
- inputSchema: CONTINUE_PARAMS
1370
- },
1371
- status: {
1372
- name: 'codebuddy_status',
1373
- 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.',
1374
- inputSchema: STATUS_PARAMS
1375
- }
1376
- },
1377
-
1378
- extraTools: [],
1379
-
1380
- // 设置分区(契约 §3):keystone 统一文件 {codebuddy:{...}};旧扁平文件的字段
1381
- // 级迁移由 keystone LEGACY_SOURCES 承担(字段名逐字相同)。
1382
- settings: {
1383
- keys: SETTINGS_KEYS,
1384
- secretKeys: ['codebuddyEnToken'],
1385
- defaults: () => normalizeSettings(null),
1386
- normalize: (raw) => normalizeSettings(raw),
1387
- meta() {
1388
- // defaultModel 下拉 = 默认后端(codebuddy 面)的带倍率目录(升级 CLI 后
1389
- // 自动同步);其余三面目录不同,字段允许自定义输入即可覆盖。促销角标为
1390
- // 0.1.0 有意省略(见头注 TODO)。
1391
- const options = modelCatalogDetailed(DEFAULT_BACKEND, {}).map((x) => ({ value: x.id, label: x.label }))
1392
- return {
1393
- titleSuffix: 'CodeBuddy',
1394
- fields: [
1395
- {
1396
- key: 'preferredBackend', label: '默认后端', type: 'select',
1397
- options: BACKENDS.map((b) => ({ value: b, label: BACKEND_LABELS[b] })),
1398
- note: '新会话未显式指定 backend 时用这里选的后端;单次调用可覆盖。codebuddy-en 需要 codebuddyEnToken 或 DSH 已配 workbuddy key。'
1399
- },
1400
- {
1401
- key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true, placeholder: '(CLI 默认)',
1402
- options,
1403
- note: '账号实际可用性以服务端实时裁决(400 报文回吐权威清单,桥接自动缓存)。优先选能完成任务里最便宜的,日常任务优先免费(x0.00)。'
1404
- },
1405
- { key: 'codebuddyEnToken', label: 'WorkBuddy 国际版 Token', type: 'secret', note: '仅 backend="codebuddy-en" 需要。国际版登录 token 被 protector key 封装不落盘,只能手工提供;留空则自动尝试 DSH 凭据库的 WORKBUDDY_TOKEN。' },
1406
- { key: 'endpointOverride', label: '端点覆盖', type: 'text', placeholder: 'https://…/v2', note: '一般留空:端点按登录域自动对齐(www.codebuddy.cn 等)。仅在需要强制指定 API 端点时填写,且必须自带 /v2。' }
1407
- ]
1408
- }
1409
- },
1410
- diagnose(snap) {
1411
- const s = normalizeSettings(snap)
1412
- const lines = []
1413
- const seen = new Set()
1414
- // 默认后端一行;codebuddy-en 是 4 面里唯一需要凭据的,恒附一行状态。
1415
- for (const b of [s.preferredBackend, 'codebuddy-en']) {
1416
- if (seen.has(b)) continue
1417
- seen.add(b)
1418
- const d = diagnoseBackend(b, s, {})
1419
- lines.push(b + ': ' + (d.endpoint || '?') + '(登录域 ' + (d.authDomain || '未读到') + ',' + d.tokenHint + ')')
1420
- if (d.hint) lines.push(' ⚠ ' + d.hint)
1421
- }
1422
- return lines.join('\n')
1423
- }
1424
- },
1425
-
1426
- mcp: { version: '0.2.2' }
1427
- }
1428
-
1429
- // 三形态共用的工具逻辑(签名保持 keystone/队友接线契约不变)。
1430
- descriptor.runToolLogic = async function (args, exec) {
1431
- return this.runner.coreExecute(args, exec)
1432
- }
1433
- // 旧 preset continueTool.execute verbatim 映射(sessionId 优先,否则 latest)。
1434
- descriptor.continueToolLogic = async function (args, exec) {
1435
- const a = args || {}
1436
- 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 }
1437
- if (a.sessionId) mapped.sessionId = a.sessionId
1438
- else if (a.latest) mapped.continueLatest = true
1439
- return this.runner.coreExecute(mapped, exec)
1440
- }
1441
- // 旧 statusTool.execute verbatim:cwd 过滤 + 单项目聚合覆写(含 runs/totalTokens)。
1442
- descriptor.statusToolLogic = function (args) {
1443
- const a = args || {}
1444
- const snap = this.engine.statusSnapshot()
1445
- if (a.cwd) {
1446
- const key = String(a.cwd)
1447
- snap.projects = snap.projects.filter((p) => p.cwd === key)
1448
- const g = snap.projects[0]
1449
- 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 }
1450
- }
1451
- return snap
1452
- }
1453
-
1454
- // 供 preset/dynamic/MCP/测试形态复用的领域函数(不 import home-plugin,全部经
1455
- // 描述符暴露;MCP 面据 buildArgv/parseJson/buildResult/isLimited/failureHint 组
1456
- // 装真实 spawn 执行,语义与旧 mcp/codebuddy-mcp-server.mjs 一致)。
1457
- descriptor.policyText = POLICY_TEXT
1458
- descriptor.limits = { LIMIT_RE: CODEBUDDY_LIMIT_RE }
1459
- descriptor.backendLabels = BACKEND_LABELS
1460
- descriptor.backendEndpoints = BACKEND_ENDPOINTS
1461
- descriptor.authDomainEndpoints = AUTH_DOMAIN_ENDPOINTS
1462
- descriptor.backendAuthIds = BACKEND_AUTH_IDS
1463
- descriptor.staticModelIds = BACKEND_MODEL_IDS
1464
- descriptor.endpointHost = endpointHost
1465
- descriptor.resolveEndpoint = resolveEndpoint
1466
- descriptor.endpointEnv = endpointEnv
1467
- descriptor.endpointMismatchHint = endpointMismatchHint
1468
- descriptor.resolveEnToken = resolveEnToken
1469
- descriptor.readDshWorkbuddyToken = readDshWorkbuddyToken
1470
- descriptor.readBackendAuthDomain = readBackendAuthDomain
1471
- descriptor.diagnoseBackend = diagnoseBackend
1472
- descriptor.backendModelCatalog = backendModelCatalog
1473
- descriptor.modelCatalogDetailed = modelCatalogDetailed
1474
- descriptor.formatModelCatalogText = formatModelCatalogText
1475
- descriptor.parseAccountModels = parseAccountModels
1476
- descriptor.rememberAccountCatalog = rememberAccountCatalog
1477
- descriptor.getAccountCatalog = getAccountCatalog
1478
- descriptor.normalizeProductConfig = normalizeProductConfig
1479
- descriptor.extractModelIds = extractModelIds
1480
- descriptor.extractModelCredits = extractModelCredits
1481
- descriptor.parseCreditValue = parseCreditValue
1482
- descriptor.formatCreditLabel = formatCreditLabel
1483
- descriptor.lookupModelCredits = lookupModelCredits
1484
- descriptor.normalizeSettings = normalizeSettings
1485
-
1486
- descriptor.attach = function (hostOpts) {
1487
- host = hostOpts || {}
1488
- this.engine = createStatusEngine({ provider: this, publish: host.publish })
1489
- const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
1490
- this.runner = runner
1491
- return runner
1492
- }
1493
- descriptor.hostOptions = () => host
1494
- return descriptor
1495
- }
571
+ // providers/codebuddy.mjs — codebuddy provider descriptor(真移植,替换 Lead 冒烟占位)。
572
+ //
573
+ // 移植基线:codebuddy-first-bridge v1.6.x core/codebuddy-core.mjs 的纯逻辑
574
+ // (后端注册表/端点对齐/凭据链/模型目录/buildArgv/parseCodebuddyJson/buildResult/
575
+ // foldEvent/settings 清洗/三工具 schema)与 preset/codebuddy-first 内联语义,
576
+ // 逐字保持(PROVIDER-CONTRACT.md §8 红线:工具入参语义与 schema 不许漂移)。
577
+ // 与 provider 无关的骨架(状态引擎/行流/回退弹窗/展示层)在 core/bridge-kit.mjs。
578
+ //
579
+ // TODO(Lead 定案,0.1.0 不做):旧包 credits/促销面板的 modelPromotions /
580
+ // isPromotionActive / activePromotionFor(约 200 行)不进统一设置面板;本版
581
+ // modelCatalogDetailed 只给「倍率 + 授权」两标(无促销角标),行为差异在设置面板
582
+ // 单列,运行面(buildArgv/CLI 选择)不受影响。
583
+ //
584
+ // 红线(PROVIDER-CONTRACT.md §8):
585
+ // - 本文件会被 build 内联进 dynamic 沙箱(new Function):绝不出现元环境字面量;
586
+ // process/env/fs 只经 deps 注入或 typeof 守卫读取;宿主能力全部走 attach(hostOpts)。
587
+ // - 只允许 import '../core/bridge-kit.mjs' 一行。
588
+ // - isLimited 用本文件自定义的中文限流表(旧 core verbatim),不用 kit 通用表。
589
+ // ── 提示词策略段(旧 preset POLICY_TEXT verbatim;systemPrompt order 5)────────
590
+ const POLICY_TEXT = [
591
+ 'codebuddy-first execution policy (local codebuddy CLI bridge, with fallback + live indicator + live status tool).',
592
+ '',
593
+ '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).',
594
+ '',
595
+ 'Priority rule for EVERY mode (normal, plan, accept-edits, subagent/workflow/ralph delegation, and goal rounds):',
596
+ '- 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.',
597
+ '- Use native read/write/shell tools mainly for quick read-only lookups and for the final build/test verification of what codebuddy produced.',
598
+ '- In plan mode, call codebuddy_run with mode=auto (or mode=plan); in accept-edits/normal mode codebuddy_run applies edits directly.',
599
+ '- When you delegate to a DSH subagent or workflow, instruct that delegate to also prefer codebuddy_run.',
600
+ '- For long-running tasks, call codebuddy_run with background=true and collect the result with job_output; use codebuddy_status to watch progress.',
601
+ '',
602
+ '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.',
603
+ '',
604
+ '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).',
605
+ '',
606
+ '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.'
607
+ ].join('\n')
608
+
609
+ // ── 限流/网络/认证失败判定(旧 core verbatim)。仅匹配 stderr + status;数字码
610
+ // 加词边界(避免 "1500" 命中 500、"4013" 命中 401)。中文码(流量/受限/金额/
611
+ // 余额/额度/认证/连接/断开 等)为 codebuddy 面专属,必须逐字保留。
612
+ // 命名纪律(mimo 同款):本文件顶层名绝不与 core/bridge-kit.mjs 顶层导出同名 ——
613
+ // dynamic 形态把 kit 与 provider 内联进同一脚本作用域,同名 const 直接炸语法
614
+ // (LIMIT_RE 在 kit L33 已有,故此处带 CODEBUDDY_ 前缀)。
615
+ 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
616
+
617
+ // ── 后端注册表(旧 core verbatim:端点按登录域自动对齐)───────────────────────
618
+ const BACKENDS = ['codebuddy', 'codebuddy-intl', 'codebuddy-en', 'workbuddy']
619
+
620
+ const BACKEND_ENDPOINTS = {
621
+ 'codebuddy': 'https://www.codebuddy.ai/v2',
622
+ 'codebuddy-intl': 'https://www.codebuddy.ai/v2',
623
+ 'codebuddy-en': 'https://www.workbuddy.ai/v2',
624
+ 'workbuddy': 'https://copilot.tencent.com/v2'
625
+ }
626
+
627
+ const AUTH_DOMAIN_ENDPOINTS = {
628
+ 'www.codebuddy.cn': 'https://www.codebuddy.cn/v2',
629
+ 'www.codebuddy.ai': 'https://www.codebuddy.ai/v2',
630
+ 'www.workbuddy.ai': 'https://www.workbuddy.ai/v2',
631
+ 'copilot.tencent.com': 'https://copilot.tencent.com/v2'
632
+ }
633
+
634
+ const BACKEND_LABELS = {
635
+ 'codebuddy': 'CodeBuddy 国内版(npm CLI)',
636
+ 'codebuddy-intl': 'CodeBuddy 国际版(npm CLI · 国际面)',
637
+ 'codebuddy-en': 'WorkBuddy 国际版(WorkBuddyAI 桌面 CLI)',
638
+ 'workbuddy': 'WorkBuddy 国内版(桌面 CLI)'
639
+ }
640
+
641
+ const BACKEND_ALIASES = {
642
+ 'workbuddy-en': 'codebuddy-en',
643
+ 'workbuddy-ai': 'codebuddy-en',
644
+ 'codebuddy-ioa': 'codebuddy-intl',
645
+ 'codebuddy-international': 'codebuddy-intl',
646
+ 'codebuddy-oversea': 'codebuddy-intl'
647
+ }
648
+
649
+ const DEFAULT_BACKEND = 'codebuddy'
650
+
651
+ const SETTINGS_KEYS = ['preferredBackend', 'defaultModel', 'codebuddyEnToken', 'endpointOverride']
652
+
653
+ // codebuddy-en 凭据的第三条通道:DSH 凭据库里可能已有的 workbuddy key(旧 core verbatim)。
654
+
655
+ // 离线/读不到描述文件时的回退静态表(真机按账号实测快照,2026-09)。
656
+ // 模型目录相关常量与纯逻辑已拆到 ./codebuddy-catalog.mjs —— 主文件原 864 行远超
657
+ // 600 行红线(规则 §26)。
658
+ // • ESM 形态(preset / MCP / 测试):直接 import。
659
+ // • dynamic 沙箱形态:scripts/build.mjs 把该文件内联进同一作用域(模板顶部的
660
+ // 第三个占位标记),import 行被 stripModuleSyntax 剥掉,同名标识符天然可见。
661
+ // ⚠️ 本注释里绝不写出那个标记的字面量:build 做全局文本替换,注释中出现同样
662
+ // 会被替换成正文代码,把注释劈开 → 生成物语法崩。
663
+ // ── 三工具 schema(旧 preset/codebuddy-first verbatim;契约 §8)────────────────
664
+ const RUN_PARAMS = {
665
+ type: 'object',
666
+ additionalProperties: false,
667
+ required: ['prompt'],
668
+ properties: {
669
+ prompt: { type: 'string', description: 'The full task/instruction for codebuddy. Be complete and self-contained.' },
670
+ 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.' },
671
+ mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'auto follows DSH plan state; plan = no writes; accept-edits = allow edits. Default auto.' },
672
+ model: { type: 'string', description: MODEL_DESCRIPTION },
673
+ effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
674
+ maxTurns: { type: 'integer', description: 'Optional max agentic turns (1-500, default unlimited).' },
675
+ cwd: { type: 'string', description: 'Working directory for codebuddy. Defaults to the DSH workspace root.' },
676
+ addDirs: { type: 'array', items: { type: 'string' }, description: 'Extra directories to add to codebuddy workspace.' },
677
+ timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
678
+ background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
679
+ }
680
+ }
681
+ const CONTINUE_PARAMS = {
682
+ type: 'object',
683
+ additionalProperties: false,
684
+ required: ['prompt'],
685
+ properties: {
686
+ prompt: { type: 'string', description: 'Follow-up instruction for the ongoing codebuddy conversation.' },
687
+ sessionId: { type: 'string', description: 'codebuddy session id to resume (from a prior codebuddy_run result).' },
688
+ latest: { type: 'boolean', description: 'Continue the most recent codebuddy conversation instead of a specific id.' },
689
+ 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).' },
690
+ mode: { type: 'string', enum: ['auto', 'plan', 'accept-edits'], description: 'Execution mode; default auto.' },
691
+ 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).' },
692
+ effort: { type: 'string', enum: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'], description: 'Optional reasoning effort.' },
693
+ maxTurns: { type: 'integer', description: 'Optional max agentic turns.' },
694
+ cwd: { type: 'string', description: "Working directory for codebuddy; when resuming, defaults to the resumed session's project directory." },
695
+ timeoutSec: { type: 'integer', description: 'Run timeout seconds (10-3600, default 300); a DSH-side hang guard force-terminates at timeout+60s.' },
696
+ background: { type: 'boolean', description: 'Run as a background job and return a jobId immediately.' }
697
+ }
698
+ }
699
+ const STATUS_PARAMS = { type: 'object', additionalProperties: false, required: [], properties: { cwd: { type: 'string', description: 'Optional: filter the snapshot to a single project (working directory).' } } }
700
+
701
+ function defineProvider (deps = {}) {
702
+ const env = deps.env || {}
703
+ let host = null // attach 后保存 hostOpts(preset/dynamic/MCP 形态宿主能力)
704
+
705
+ // 宿主 fs/path 访问的统一入口:deps 注入优先;dynamic 内联体(无 import,运行在
706
+ // 后端 Node 上下文)回退到 getBuiltinModule —— 与旧 core builtinModule() 的
707
+ // typeof 守卫模式一致(这是旧 dynamic 端点修复生效的同一条通道,缺了它默认
708
+ // 后端会回到 401 老病)。两者皆不可用时自然降级:读不到文件 = 静态表兜底。
709
+ function builtinModule(name) {
710
+ try {
711
+ const proc = globalThis.process
712
+ return (proc && typeof proc.getBuiltinModule === 'function') ? proc.getBuiltinModule(name) : null
713
+ } catch (e) { return null }
714
+ }
715
+ function fsRead(p) {
716
+ const nf = deps.nodeFs || builtinModule('node:fs')
717
+ if (!nf || typeof nf.readFileSync !== 'function') return null
718
+ try { return nf.readFileSync(p, 'utf8') } catch (e) { return null }
719
+ }
720
+ function pathJoin(...parts) {
721
+ const np = deps.nodePath || builtinModule('node:path')
722
+ if (np && typeof np.join === 'function') return np.join(...parts)
723
+ return parts.join('/')
724
+ }
725
+ const pathSep = (deps.nodePath && deps.nodePath.sep) || (/[A-Za-z]:[\\/]/.test(env.USERPROFILE || env.APPDATA || '') ? '\\' : '/')
726
+
727
+ // 把宿主真实能力注入 catalog 模块:它从本闭包搬出后拿不到 env / fsRead / pathJoin /
728
+ // pathSep。未注入时 catalog 退到 getBuiltinModule 守卫(绝不抛)。内联到 dynamic
729
+ // 沙箱时 cbCatalogSetHost 同作用域可见,行为一致。
730
+ try {
731
+ cbCatalogSetHost(env, deps.nodePath || builtinModule('node:path'), deps.nodeFs || builtinModule('node:fs'))
732
+ } catch (e) { }
733
+
734
+ // ── 端点/登录域(旧 core endpointHost verbatim:非法 URL 容错)───────────────
735
+ function endpointHost(url) {
736
+ const s = String(url || '').trim()
737
+ if (!s) return ''
738
+ try { return new URL(s).hostname.toLowerCase() } catch (e) { }
739
+ const m = /^[a-z]+:\/\/([^/?#]+)/i.exec(s)
740
+ return m ? m[1].toLowerCase() : ''
741
+ }
742
+
743
+ function resolveEndpoint(explicitBaseUrl, authDomain) {
744
+ const explicit = String(explicitBaseUrl || '').trim()
745
+ if (explicit) return explicit
746
+ const d = String(authDomain || '').trim().toLowerCase()
747
+ if (d && AUTH_DOMAIN_ENDPOINTS[d]) return AUTH_DOMAIN_ENDPOINTS[d]
748
+ return null
749
+ }
750
+
751
+ function isBackend(v) { return BACKENDS.indexOf(v) >= 0 }
752
+
753
+ // 后端名规范化(v1.3.3 verbatim):别名 + 大小写不敏感;非后端名原样返回。
754
+ function normalizeBackend(v) {
755
+ if (typeof v !== 'string') return v
756
+ const lower = v.trim().toLowerCase()
757
+ const aliased = BACKEND_ALIASES[lower] || lower
758
+ return BACKENDS.indexOf(aliased) >= 0 ? aliased : v
759
+ }
760
+
761
+ // 后端解析优先级(旧 core verbatim):显式 > 会话归属 > 用户偏好 > 默认。
762
+ function resolveBackend(args, target, preferredBackend) {
763
+ if (args && isBackend(normalizeBackend(args.backend))) return normalizeBackend(args.backend)
764
+ if (target && target.backend && isBackend(normalizeBackend(target.backend))) return normalizeBackend(target.backend)
765
+ if (preferredBackend && isBackend(normalizeBackend(preferredBackend))) return normalizeBackend(preferredBackend)
766
+ return DEFAULT_BACKEND
767
+ }
768
+
769
+ // 本次调用的端点/凭据 env 注入(旧 core endpointEnv verbatim 三规则)。
770
+ function endpointEnv(backend, explicitBaseUrl, authDomain, authToken) {
771
+ const out = {}
772
+ const endpoint = resolveEndpoint(explicitBaseUrl, authDomain)
773
+ const product = BACKEND_ENDPOINTS[backend]
774
+ if (endpoint && endpointHost(endpoint) !== endpointHost(product)) {
775
+ out.CODEBUDDY_BASE_URL = endpoint
776
+ }
777
+ if (backend === 'codebuddy-en') {
778
+ const tok = String(authToken || '').trim()
779
+ if (tok) out.CODEBUDDY_AUTH_TOKEN = tok
780
+ }
781
+ return Object.keys(out).length ? out : null
782
+ }
783
+
784
+ // 可操作提示(旧 core endpointMismatchHint 三分支 verbatim)。
785
+ function endpointMismatchHint(backend, authDomain, hasToken) {
786
+ if (backend === 'codebuddy-en' && !hasToken) {
787
+ 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,免配置)。'
788
+ }
789
+ if (backend === 'codebuddy-intl') {
790
+ return 'codebuddy-intl(CodeBuddy 国际版)使用同一个 npm CLI,但国际面模型由服务端按账号授权放行:未授权时 CLI 返回 400「model [...] is only available for authorized users」。若你用的是国内账号,请改用 backend="codebuddy"(国内面模型清单)或 backend="codebuddy-en"(WorkBuddy 国际版)。'
791
+ }
792
+ const d = String(authDomain || '').trim().toLowerCase()
793
+ if (d && endpointHost(resolveEndpoint(null, d)) !== endpointHost(BACKEND_ENDPOINTS[backend])) {
794
+ return backend + ' 的登录域是 ' + d + ',与产品端点 ' + BACKEND_ENDPOINTS[backend] + ' 不一致;桥接层已自动注入 CODEBUDDY_BASE_URL=' + AUTH_DOMAIN_ENDPOINTS[d] + '。若仍 401,请重新登录对应客户端。'
795
+ }
796
+ return null
797
+ }
798
+
799
+ // 从 auth 库读某后端登录域(旧 core readBackendAuthDomain verbatim 语义;fs 经
800
+ // deps 注入。io 可覆盖 readFileSync/dir/env,供测试夹具与 MCP 面注入真实 fs)。
801
+
802
+ // ── 模型目录(面板/诊断用;无促销角标版,见头注 TODO)───────────────────────
803
+ // ── 设置清洗(旧 normalizeBridgeSettings verbatim;updatedAt 透传)───────────
804
+ function normalizeSettings(raw) {
805
+ const snap = { preferredBackend: DEFAULT_BACKEND, defaultModel: '', codebuddyEnToken: '', endpointOverride: '' }
806
+ if (!raw || typeof raw !== 'object') return snap
807
+ if (typeof raw.preferredBackend === 'string') {
808
+ const nb = normalizeBackend(raw.preferredBackend)
809
+ if (typeof nb === 'string' && BACKENDS.indexOf(nb) >= 0) snap.preferredBackend = nb
810
+ }
811
+ if (typeof raw.defaultModel === 'string') snap.defaultModel = raw.defaultModel.trim()
812
+ if (typeof raw.codebuddyEnToken === 'string') snap.codebuddyEnToken = raw.codebuddyEnToken.trim()
813
+ if (typeof raw.endpointOverride === 'string') snap.endpointOverride = raw.endpointOverride.trim()
814
+ if (typeof raw.updatedAt === 'number' && raw.updatedAt > 0) snap.updatedAt = raw.updatedAt
815
+ return snap
816
+ }
817
+
818
+ // 诊断(旧 diagnoseBackend verbatim;fs/env 走 deps)。
819
+ function diagnoseBackend(backend, settings, io) {
820
+ const o = io || {}
821
+ const e = o.env || env
822
+ const s = settings || normalizeSettings(null)
823
+ const authDomain = readBackendAuthDomain(backend, Object.assign({ env: e }, o))
824
+ const override = String(s.endpointOverride || '').trim()
825
+ const byDomain = resolveEndpoint(null, authDomain)
826
+ const endpoint = override || byDomain || BACKEND_ENDPOINTS[backend] || null
827
+ const endpointSource = override ? 'override' : (byDomain ? 'auth-domain' : 'product')
828
+ const tok = resolveEnToken(backend === 'codebuddy-en' ? s.codebuddyEnToken : null, { env })
829
+ return {
830
+ backend: backend,
831
+ authDomain: authDomain,
832
+ endpoint: endpoint,
833
+ endpointSource: endpointSource,
834
+ tokenSource: backend === 'codebuddy-en' ? tok.source : 'not-needed',
835
+ tokenHint: tok.source === 'setting' ? '来自设置面板'
836
+ : tok.source === 'env' ? '来自环境变量 CODEBUDDY_AUTH_TOKEN'
837
+ : tok.source === 'dsh-store' ? '来自 DSH 凭据库(自动复用 WORKBUDDY_TOKEN)'
838
+ : backend === 'codebuddy-en' ? '缺失:国际版 token 不落盘,需在设置面板填写或先在 DSH 配 workbuddy provider'
839
+ : '无需填写(国内版由 CLI 自行登录)',
840
+ mismatch: endpointMismatchHint(backend, authDomain, !!tok.token) !== null,
841
+ hint: endpointMismatchHint(backend, authDomain, !!tok.token) || null,
842
+ defaultModel: String(s.defaultModel || '').trim() || '(CLI 默认)'
843
+ }
844
+ }
845
+
846
+ // ── 结果判定(旧 isLimited/isTransientCliError/failureHint verbatim)─────────
847
+ function isLimitedCodebuddy(res) {
848
+ if (!res || res.ok) return false
849
+ // 前置凭据缺失:配置问题,不是限流(弹窗重试不会让 token 出现)。
850
+ if (res.status === 'AUTH_REQUIRED') return false
851
+ if (res.status === 'SPAWN_ERROR' || res.status === 'CODEBUDDY_UNAVAILABLE' || res.status === 'HUNG_TIMEOUT') return true
852
+ const hay = String(res.stderr || '') + ' ' + String(res.status || '')
853
+ // 401/端点域不匹配:需要用户换登录域,不归限流类(旧 v1.3.0 verbatim)。
854
+ if (/401 authentication failed|differs from the current product endpoint/i.test(hay)) return false
855
+ return CODEBUDDY_LIMIT_RE.test(hay)
856
+ }
857
+
858
+ function isTransientCliError(res) {
859
+ if (!res || res.ok) return false
860
+ if (isLimitedCodebuddy(res)) return false
861
+ return res.status === 'ERROR_DURING_EXECUTION'
862
+ }
863
+
864
+ function failureHint(res) {
865
+ if (!res || res.ok) return ''
866
+ // AUTH_REQUIRED:stderr 已带完整指引,透传(旧 v1.3.1 verbatim)。
867
+ if (res.status === 'AUTH_REQUIRED') return '[诊断] ' + String(res.stderr || '')
868
+ if (isTransientCliError(res)) {
869
+ return res.retried
870
+ ? '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因),已自动重试 1 次仍失败。可换 model 再试一次;若仍失败请改用原生工具完成,或告知用户。'
871
+ : '[诊断] codebuddy CLI 侧瞬时错误(error_during_execution,CLI 未给出原因)。直接重试同一请求通常即可通过;也可显式指定 model。不要据此认为任务本身有问题。'
872
+ }
873
+ if (res.status === 'PARSE_ERROR') {
874
+ return '[诊断] 未能从 codebuddy 输出解析出 result 事件(进程可能被中断或输出被截断)。可重试;持续出现请检查 codebuddy CLI 版本。'
875
+ }
876
+ if (/401 authentication failed|differs from the current product endpoint/i.test(String(res.stderr || ''))) {
877
+ return '[诊断] 认证失败(401):请求被送到的端点与当前 CLI 登录域不匹配(国际/国内登录互斥)。请让用户在对应产品域完成 `codebuddy` CLI 登录后重试;这不是限流,重试与回退都无效。'
878
+ }
879
+ return ''
880
+ }
881
+
882
+ // stream-json 解析(旧 parseCodebuddyJson verbatim)。
883
+ function parseCodebuddyJson(stdoutText) {
884
+ const trimmed = String(stdoutText || '').trim()
885
+ if (!trimmed) return null
886
+ const lines = trimmed.split(/\r?\n/).filter(Boolean)
887
+ for (let i = lines.length - 1; i >= 0; i--) {
888
+ const ln = lines[i].trim()
889
+ if (!ln.startsWith('{')) continue
890
+ try {
891
+ const obj = JSON.parse(ln)
892
+ if (obj && obj.type === 'result') return obj
893
+ } catch (e) {}
894
+ }
895
+ try { return JSON.parse(trimmed) } catch (e) {}
896
+ return null
897
+ }
898
+
899
+ // result 事件 → 统一结果对象(旧 buildResult verbatim,含账号清单收割)。
900
+ function buildResult(parsed, outcome, mode, stderrText, stdoutText, backend) {
901
+ const bk = backend || 'codebuddy'
902
+ const exitCode = outcome ? outcome.exitCode : null
903
+ const errText = parsed && typeof parsed.error === 'string' && parsed.error ? parsed.error : ''
904
+ const stderr = (stderrText ? String(stderrText).slice(-2000) : '') + (errText ? (stderrText ? ' ' : '') + errText : '')
905
+ // v1.6.0:顺手收割服务端回吐的「本账号可用模型」清单(失败静默)。
906
+ try {
907
+ const harvest = parseAccountModels(stderr) || parseAccountModels(String(stdoutText || ''))
908
+ if (harvest && harvest.length) rememberAccountCatalog(bk, harvest)
909
+ } catch (e) { /* 收割失败不影响主流程 */ }
910
+ if (parsed && parsed.type === 'result') {
911
+ const isOk = exitCode === 0 && parsed.is_error === false && parsed.subtype === 'success'
912
+ let modelUsed = null
913
+ try {
914
+ if (parsed.modelUsage && typeof parsed.modelUsage === 'object') {
915
+ const names = Object.keys(parsed.modelUsage)
916
+ if (names.length) modelUsed = names.join('+')
917
+ }
918
+ } catch (e) { }
919
+ return {
920
+ ok: isOk,
921
+ status: String(parsed.subtype || (isOk ? 'SUCCESS' : 'ERROR')).toUpperCase(),
922
+ response: typeof parsed.result === 'string' ? parsed.result : '',
923
+ sessionId: typeof parsed.session_id === 'string' ? parsed.session_id : null,
924
+ durationSeconds: typeof parsed.duration_ms === 'number' ? parsed.duration_ms / 1000 : null,
925
+ numTurns: typeof parsed.num_turns === 'number' ? parsed.num_turns : null,
926
+ totalTokens: (parsed.usage && typeof parsed.usage.input_tokens === 'number' && typeof parsed.usage.output_tokens === 'number')
927
+ ? (parsed.usage.input_tokens + parsed.usage.output_tokens) : null,
928
+ exitCode: exitCode,
929
+ mode: mode,
930
+ backend: bk,
931
+ modelUsed: modelUsed,
932
+ stderr: stderr
933
+ }
934
+ }
935
+ return {
936
+ ok: false,
937
+ status: 'PARSE_ERROR',
938
+ response: '',
939
+ sessionId: null,
940
+ durationSeconds: null,
941
+ numTurns: null,
942
+ totalTokens: null,
943
+ exitCode: exitCode,
944
+ mode: mode,
945
+ backend: bk,
946
+ stderr: stderr,
947
+ rawStdout: String(stdoutText || '').slice(-2000)
948
+ }
949
+ }
950
+
951
+ // 统一 argv 构造(旧 buildArgv verbatim;env 端点/凭据注入在本 provider 内完成,
952
+ // 因为 kit 只透传 opts,宿主三形态都从本函数的返回值取 built.env 下发 spawn)。
953
+ function buildArgvCodebuddy(prefix, args, opts) {
954
+ const o = opts || {}
955
+ const argv = [prefix[0], ...prefix.slice(1), '-p', String(args.prompt), '--output-format', 'stream-json']
956
+ let mode = args.mode || o.defaultMode || 'auto'
957
+ if (mode === 'auto') mode = o.planActive ? 'plan' : 'bypassPermissions'
958
+ if (mode === 'plan') {
959
+ argv.push('--permission-mode', 'plan')
960
+ argv.push('--allowedTools', 'Bash')
961
+ } else {
962
+ mode = 'bypassPermissions'
963
+ argv.push('--permission-mode', 'bypassPermissions')
964
+ }
965
+ // 模型优先级:显式 args.model > 用户偏好 defaultModel > CLI 默认。
966
+ const model = args.model || o.defaultModel
967
+ if (model) argv.push('--model', String(model))
968
+ if (args.effort) argv.push('--effort', String(args.effort))
969
+ if (args.maxTurns !== undefined && args.maxTurns !== null) argv.push('--max-turns', String(clampInt(args.maxTurns, 50, 1, 500)))
970
+ if (Array.isArray(args.addDirs)) for (const d of args.addDirs) { if (d) argv.push('--add-dir', String(d)) }
971
+ if (args.sessionId) argv.push('--resume', String(args.sessionId))
972
+ else if (args.continueLatest) argv.push('--continue')
973
+ const timeoutSec = clampInt(args.timeoutSec, 300, 10, 3600)
974
+ // 端点/凭据注入(旧 preset/dynamic/MCP 三形态一致语义,宿主不必自算):
975
+ // authDomain 只在有 fs 能力的宿主读得到;dynamic 沙箱 → 沿用 CLI 自身端点。
976
+ const bk = o.backend || DEFAULT_BACKEND
977
+ const settings = o.settings || null
978
+ const authDomain = readBackendAuthDomain(bk, { env })
979
+ const tok = resolveEnToken(bk === 'codebuddy-en' && settings ? settings.codebuddyEnToken : null, { env })
980
+ const inject = endpointEnv(bk, settings ? settings.endpointOverride : null, authDomain, tok.token)
981
+ return { argv: argv, timeoutSec: timeoutSec, mode: mode, env: o.env || inject }
982
+ }
983
+
984
+ // 流事件折叠(旧 foldEvent 主体 verbatim;project 状态由 kit engine 持有)。
985
+ function foldStreamEvent(ev, p, summarizeArgs, MAX_ARG_LEN, MAX_TRAIL) {
986
+ if (!ev || !ev.type) return
987
+ if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {
988
+ for (const block of ev.message.content) {
989
+ if (block.type === 'tool_use') {
990
+ p._stepCounter = (p._stepCounter || 0) + 1
991
+ const stepIndex = p._stepCounter
992
+ if (!p._toolMap) p._toolMap = {}
993
+ p._toolMap[block.id] = { stepIndex: stepIndex, name: block.name }
994
+ const args = summarizeArgs(block.input)
995
+ p.trail.push({ stepIndex: stepIndex, state: 'ACTIVE', tool: block.name, args: args, at: new Date().toISOString() })
996
+ if (p.trail.length > MAX_TRAIL) p.trail.shift()
997
+ p.current = { tool: block.name, args: args, stepIndex: stepIndex, since: new Date().toISOString() }
998
+ } else if (block.type === 'thinking') {
999
+ p.current = { tool: 'thinking', args: { text: String(block.thinking || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
1000
+ } else if (block.type === 'text') {
1001
+ p.current = { tool: 'typing', args: { text: String(block.text || '').slice(0, MAX_ARG_LEN) }, stepIndex: 0, since: new Date().toISOString() }
1002
+ }
1003
+ }
1004
+ } else if (ev.type === 'user' && ev.message && Array.isArray(ev.message.content)) {
1005
+ for (const block of ev.message.content) {
1006
+ if (block.type === 'tool_result' && p._toolMap && p._toolMap[block.tool_use_id]) {
1007
+ const rec = p._toolMap[block.tool_use_id]
1008
+ p.trail.push({ stepIndex: rec.stepIndex, state: block.is_error ? 'ERROR' : 'DONE', tool: rec.name, args: null, at: new Date().toISOString() })
1009
+ if (p.trail.length > MAX_TRAIL) p.trail.shift()
1010
+ if (p.current && p.current.stepIndex === rec.stepIndex) p.current = null
1011
+ }
1012
+ }
1013
+ }
1014
+ }
1015
+
1016
+ const descriptor = {
1017
+ id: 'codebuddy',
1018
+ label: 'CB',
1019
+ presetId: 'codebuddy-first',
1020
+ defaultBackend: DEFAULT_BACKEND,
1021
+ defaultMode: 'auto',
1022
+ exeName: 'codebuddy',
1023
+ binEnvVars: ['CODEBUDDY_BIN', 'CODEBUDDY_EN_BIN', 'WORKBUDDY_BIN'],
1024
+ unavailableStatus: 'CODEBUDDY_UNAVAILABLE',
1025
+ // 旧 renderResult verbatim 语义:标头用具体 backend('workbuddy OK'),仅当结果
1026
+ // 无 backend 字段时回落 'codebuddy'(= provider.id)。agy/mimo 旧包标头硬编码
1027
+ // provider 名,不设此旗。
1028
+ backendLabel: true,
1029
+
1030
+ backends: () => BACKENDS.slice(),
1031
+ normalizeBackend,
1032
+ resolveBackend,
1033
+
1034
+ buildArgv: buildArgvCodebuddy,
1035
+ parseJson: parseCodebuddyJson,
1036
+ buildResult,
1037
+ foldStreamEvent,
1038
+ isLimited: isLimitedCodebuddy,
1039
+ isTransientCliError,
1040
+ failureHint,
1041
+
1042
+ // codebuddy-en 无凭据的确定性前置(v1.3.1 语义,经 kit preflight 钩子实现):
1043
+ // 三通道皆空 → 直接 AUTH_REQUIRED(可操作指引进 stderr),不白跑一次 spawn。
1044
+ // 其它后端一律放行。dynamic 沙箱无 fs → dsh-store 通道缺席,abort 提示即可。
1045
+ preflight({ args, backend, engine, o }) {
1046
+ if (backend !== 'codebuddy-en') return null
1047
+ const settings = (o && o.getSettings && o.getSettings()) || null
1048
+ const tok = resolveEnToken(settings ? settings.codebuddyEnToken : null, { env })
1049
+ if (tok.token) return null
1050
+ const authDomain = readBackendAuthDomain('codebuddy-en', { env })
1051
+ const hint = endpointMismatchHint('codebuddy-en', authDomain, false)
1052
+ return {
1053
+ abort: {
1054
+ ok: false,
1055
+ status: 'AUTH_REQUIRED',
1056
+ response: '',
1057
+ sessionId: null,
1058
+ durationSeconds: null,
1059
+ numTurns: null,
1060
+ totalTokens: null,
1061
+ exitCode: null,
1062
+ mode: (args && args.mode) || descriptor.defaultMode || 'auto',
1063
+ backend: 'codebuddy-en',
1064
+ stderr: hint
1065
+ }
1066
+ }
1067
+ },
1068
+
1069
+ tools: {
1070
+ run: {
1071
+ name: 'codebuddy_run',
1072
+ 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.',
1073
+ inputSchema: RUN_PARAMS
1074
+ },
1075
+ continue: {
1076
+ name: 'codebuddy_continue',
1077
+ 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.',
1078
+ inputSchema: CONTINUE_PARAMS
1079
+ },
1080
+ status: {
1081
+ name: 'codebuddy_status',
1082
+ 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.',
1083
+ inputSchema: STATUS_PARAMS
1084
+ }
1085
+ },
1086
+
1087
+ // codebuddy_models:列出本机 codebuddy 可用模型(静态表 ∪ 描述文件 ∪ 账号清单)。
1088
+ // 只在宿主有 spawn/fs 能力时注册(preset 注入 deps.process / MCP 注入 deps.nodeChild;
1089
+ // dynamic 沙箱形态省略)。**失败必须 ok:false + 可操作错误**,绝不静默返回空列表或
1090
+ // 伪造模型(工作手册红线 §7;对照 workbuddy-auth 的 catalog-store 静默降级 —— 不照抄)。
1091
+ extraTools: (deps.process || deps.nodeChild || deps.nodeFs) ? [codebuddyModelsTool({
1092
+ env, deps, BACKEND_ENUM, normalizeBackend, resolveBackend, modelCatalogDetailed, getAccountCatalog
1093
+ })] : [],
1094
+
1095
+ // 设置分区(契约 §3):keystone 统一文件 {codebuddy:{...}};旧扁平文件的字段
1096
+ // 级迁移由 keystone LEGACY_SOURCES 承担(字段名逐字相同)。
1097
+ settings: {
1098
+ keys: SETTINGS_KEYS,
1099
+ secretKeys: ['codebuddyEnToken'],
1100
+ defaults: () => normalizeSettings(null),
1101
+ normalize: (raw) => normalizeSettings(raw),
1102
+ meta() {
1103
+ // defaultModel 下拉 = 默认后端(codebuddy 面)的带倍率目录(升级 CLI 后
1104
+ // 自动同步);其余三面目录不同,字段允许自定义输入即可覆盖。促销角标为
1105
+ // 0.1.0 有意省略(见头注 TODO)。
1106
+ const options = modelCatalogDetailed(DEFAULT_BACKEND, {}).map((x) => ({ value: x.id, label: x.label }))
1107
+ return {
1108
+ titleSuffix: 'CodeBuddy',
1109
+ fields: [
1110
+ {
1111
+ key: 'preferredBackend', label: '默认后端', type: 'select',
1112
+ options: BACKENDS.map((b) => ({ value: b, label: BACKEND_LABELS[b] })),
1113
+ note: '新会话未显式指定 backend 时用这里选的后端;单次调用可覆盖。codebuddy-en 需要 codebuddyEnToken 或 DSH 已配 workbuddy key。'
1114
+ },
1115
+ {
1116
+ key: 'defaultModel', label: '默认模型', type: 'select', allowCustom: true, placeholder: '(CLI 默认)',
1117
+ options,
1118
+ note: '账号实际可用性以服务端实时裁决(400 报文回吐权威清单,桥接自动缓存)。优先选能完成任务里最便宜的,日常任务优先免费(x0.00)。'
1119
+ },
1120
+ { key: 'codebuddyEnToken', label: 'WorkBuddy 国际版 Token', type: 'secret', note: '仅 backend="codebuddy-en" 需要。国际版登录 token 被 protector key 封装不落盘,只能手工提供;留空则自动尝试 DSH 凭据库的 WORKBUDDY_TOKEN。' },
1121
+ { key: 'endpointOverride', label: '端点覆盖', type: 'text', placeholder: 'https://…/v2', note: '一般留空:端点按登录域自动对齐(www.codebuddy.cn 等)。仅在需要强制指定 API 端点时填写,且必须自带 /v2。' }
1122
+ ]
1123
+ }
1124
+ },
1125
+ diagnose(snap) {
1126
+ const s = normalizeSettings(snap)
1127
+ const lines = []
1128
+ const seen = new Set()
1129
+ // 默认后端一行;codebuddy-en 是 4 面里唯一需要凭据的,恒附一行状态。
1130
+ for (const b of [s.preferredBackend, 'codebuddy-en']) {
1131
+ if (seen.has(b)) continue
1132
+ seen.add(b)
1133
+ const d = diagnoseBackend(b, s, {})
1134
+ lines.push(b + ': ' + (d.endpoint || '?') + '(登录域 ' + (d.authDomain || '未读到') + ',' + d.tokenHint + ')')
1135
+ if (d.hint) lines.push(' ⚠ ' + d.hint)
1136
+ }
1137
+ return lines.join('\n')
1138
+ }
1139
+ },
1140
+
1141
+ mcp: { version: '0.2.2' }
1142
+ }
1143
+
1144
+ // 三形态共用的工具逻辑(签名保持 keystone/队友接线契约不变)。
1145
+ descriptor.runToolLogic = async function (args, exec) {
1146
+ return this.runner.coreExecute(args, exec)
1147
+ }
1148
+ // 旧 preset continueTool.execute verbatim 映射(sessionId 优先,否则 latest)。
1149
+ descriptor.continueToolLogic = async function (args, exec) {
1150
+ const a = args || {}
1151
+ 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 }
1152
+ if (a.sessionId) mapped.sessionId = a.sessionId
1153
+ else if (a.latest) mapped.continueLatest = true
1154
+ return this.runner.coreExecute(mapped, exec)
1155
+ }
1156
+ // 旧 statusTool.execute verbatim:cwd 过滤 + 单项目聚合覆写(含 runs/totalTokens)。
1157
+ descriptor.statusToolLogic = function (args) {
1158
+ const a = args || {}
1159
+ const snap = this.engine.statusSnapshot()
1160
+ if (a.cwd) {
1161
+ const key = String(a.cwd)
1162
+ snap.projects = snap.projects.filter((p) => p.cwd === key)
1163
+ const g = snap.projects[0]
1164
+ 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 }
1165
+ }
1166
+ return snap
1167
+ }
1168
+
1169
+ // 供 preset/dynamic/MCP/测试形态复用的领域函数(不 import home-plugin,全部经
1170
+ // 描述符暴露;MCP 面据 buildArgv/parseJson/buildResult/isLimited/failureHint 组
1171
+ // 装真实 spawn 执行,语义与旧 mcp/codebuddy-mcp-server.mjs 一致)。
1172
+ Object.assign(descriptor, {
1173
+ policyText: POLICY_TEXT, limits: { LIMIT_RE: CODEBUDDY_LIMIT_RE },
1174
+ backendLabels: BACKEND_LABELS, backendEndpoints: BACKEND_ENDPOINTS,
1175
+ authDomainEndpoints: AUTH_DOMAIN_ENDPOINTS, backendAuthIds: BACKEND_AUTH_IDS,
1176
+ staticModelIds: BACKEND_MODEL_IDS, endpointHost, resolveEndpoint, endpointEnv,
1177
+ endpointMismatchHint, resolveEnToken, readDshWorkbuddyToken, readBackendAuthDomain,
1178
+ diagnoseBackend, parseAccountModels, rememberAccountCatalog, getAccountCatalog,
1179
+ normalizeProductConfig, extractModelIds, extractModelCredits, parseCreditValue,
1180
+ formatCreditLabel, lookupModelCredits, normalizeSettings
1181
+ })
1182
+ // env 经 io 绑定:catalog 是模块级纯函数,若共用模块级 env,多 provider 实例会互相
1183
+ // 覆盖(测试串扰)。这里每个实例调用时都带上自己的 env。
1184
+ const withEnv = (fn) => (backend, io) => fn(backend, Object.assign({ env }, io || {}))
1185
+ Object.assign(descriptor, {
1186
+ backendModelCatalog: withEnv(backendModelCatalog),
1187
+ modelCatalogDetailed: withEnv(modelCatalogDetailed),
1188
+ formatModelCatalogText: withEnv(formatModelCatalogText)
1189
+ })
1190
+
1191
+ descriptor.attach = function (hostOpts) {
1192
+ host = hostOpts || {}
1193
+ this.engine = createStatusEngine({ provider: this, publish: host.publish })
1194
+ const runner = createRunner(Object.assign({}, host, { provider: this, engine: this.engine }))
1195
+ this.runner = runner
1196
+ return runner
1197
+ }
1198
+ descriptor.hostOptions = () => host
1199
+ return descriptor
1200
+ }
1201
+
1202
+ // providers/codebuddy-catalog.mjs — codebuddy 模型目录/积分/描述文件解析(纯逻辑)。
1203
+ //
1204
+ // 从 providers/codebuddy.mjs 拆出:主文件原 864 行远超 600 行红线(规则 §26)。
1205
+ // 只放「模型目录相关」纯逻辑:静态表、描述文件候选路径、模型 id 抽取、积分倍率、
1206
+ // 账号清单收割、目录渲染。不含 CLI 调用、状态机、凭据链。
1207
+ //
1208
+ // 沙箱纪律(与 providers/*.mjs 同):本文件会被 scripts/build.mjs 经模板顶部的
1209
+ // 第三个占位标记内联进同一个 dynamic 沙箱脚本作用域 —— 所以:
1210
+ // 1) 不得 import 任何模块(import 行会被 stripModuleSyntax 剥掉,函数体留下但
1211
+ // 依赖丢失 → 运行期 ReferenceError);node 内建走 cbCatalog* 守卫;
1212
+ // 2) 顶层标识符不得与 bridge-kit / codebuddy.mjs 剩余部分撞名(同一作用域重复
1213
+ // 声明 = 构建期 Identifier already declared);
1214
+ // 3) 不得出现 import.meta 字面量;
1215
+ // 4) ⚠️ 注释里绝不写出那个占位标记的字面量:build 做全局文本替换,注释中出现
1216
+ // 同样会被替换成正文代码,把注释从中间劈开 → 生成物语法崩。
1217
+
1218
+ // ── 宿主能力注入(env / fs / path / sep)───────────────────────────────────
1219
+ // 本模块函数搬自主文件的闭包,拿不到那边的 env / fsRead / pathJoin / pathSep。
1220
+ // 由 codebuddy.mjs 在 defineProvider 里调 cbCatalogSetHost() 注入;未注入时退到
1221
+ // getBuiltinModule 守卫(沙箱里没有 → 返回 null / 默认分隔符,绝不抛)。
1222
+ // 名字一律带 cbCatalog_ 前缀:内联后与主文件的 fsRead/pathJoin 同处一个作用域。
1223
+ let cbCatalogEnv = {}
1224
+ let cbCatalogFs = null
1225
+ let cbCatalogPathSep = "/"
1226
+
1227
+ function cbCatalogSetHost(envObj, pathMod, fsMod) {
1228
+ if (envObj && typeof envObj === "object") cbCatalogEnv = envObj
1229
+ if (fsMod && typeof fsMod.readFileSync === "function") cbCatalogFs = fsMod
1230
+ if (pathMod && typeof pathMod.sep === "string") cbCatalogPathSep = pathMod.sep
1231
+ else if (/[A-Za-z]:[\\/]/.test(String((cbCatalogEnv && (cbCatalogEnv.USERPROFILE || cbCatalogEnv.APPDATA)) || ""))) cbCatalogPathSep = "\\"
1232
+ }
1233
+
1234
+ function cbCatalogRead(p, enc) {
1235
+ if (!p) return null
1236
+ try {
1237
+ if (cbCatalogFs && typeof cbCatalogFs.readFileSync === "function") return cbCatalogFs.readFileSync(p, enc || "utf8")
1238
+ const proc = globalThis.process
1239
+ const nf = (proc && typeof proc.getBuiltinModule === "function") ? proc.getBuiltinModule("node:fs") : null
1240
+ if (!nf || typeof nf.readFileSync !== "function") return null
1241
+ return nf.readFileSync(p, enc || "utf8")
1242
+ } catch (e) { return null }
1243
+ }
1244
+
1245
+ function cbCatalogPathJoin(...parts) {
1246
+ try {
1247
+ const proc = globalThis.process
1248
+ const np = (proc && typeof proc.getBuiltinModule === "function") ? proc.getBuiltinModule("node:path") : null
1249
+ if (np && typeof np.join === "function") return np.join(...parts)
1250
+ } catch (e) { }
1251
+ return parts.join("/")
1252
+ }
1253
+
1254
+ // ── 以下常量与函数原样搬自 providers/codebuddy.mjs(行为 zero-change)────────
1255
+
1256
+ const BACKEND_MODEL_IDS = {
1257
+ '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'],
1258
+ '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'],
1259
+ // WorkBuddyAI 自制目录(product.json 顶层 37 项,按其 credits 排序:免费的在前)
1260
+ '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'],
1261
+ // WorkBuddy 国内桌面自制目录(product.json:applicationName=WorkBuddy)
1262
+ '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']
1263
+ }
1264
+
1265
+ // 各后端真正生效的 product 描述文件位置(旧 core v1.6.1 verbatim)。
1266
+ const PRODUCT_DESCRIPTOR_ENV = {
1267
+ 'codebuddy': { env: 'CODEBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
1268
+ 'codebuddy-intl': { env: 'CODEBUDDY_INTL_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: null },
1269
+ 'codebuddy-en': { env: 'CODEBUDDY_EN_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy-ai' },
1270
+ 'workbuddy': { env: 'WORKBUDDY_MODELS_FILE', rel: 'product.ioa.json', fallbackRel: 'product.json', accountDir: '.workbuddy' }
1271
+ }
1272
+
1273
+ // 倍率跨命名匹配(账号清单 id → 描述文件 id,旧 core verbatim)。
1274
+ const CREDIT_ID_ALIASES = {
1275
+ 'kimi-k3-1': ['kimi-k3', 'kimi-k3-ioa'],
1276
+ 'hy3-x': ['hy3', 'hy3-ioa'],
1277
+ 'default': ['codewise-default-model-v2'],
1278
+ 'auto': ['hy3', 'hy3-ioa']
1279
+ }
1280
+
1281
+ 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.'
1282
+
1283
+ const BACKEND_ENUM = ['codebuddy', 'codebuddy-intl', 'codebuddy-ioa', 'codebuddy-international', 'codebuddy-en', 'workbuddy-en', 'workbuddy-ai', 'workbuddy']
1284
+
1285
+ function accountConfigCandidates(backend, io) {
1286
+ const e = (io && io.env) || cbCatalogEnv
1287
+ const spec = PRODUCT_DESCRIPTOR_ENV[backend]
1288
+ if (!spec || !spec.accountDir) return []
1289
+ const home = e.USERPROFILE || e.HOME
1290
+ if (!home) return []
1291
+ const base = cbCatalogPathJoin(home, spec.accountDir.split('/').join(cbCatalogPathSep))
1292
+ return [
1293
+ cbCatalogPathJoin(base, 'cache', 'acc-product-config-v3.json'),
1294
+ cbCatalogPathJoin(base, 'local_storage', 'entry_d43e96994f944cfb77961c2ea7d04605.info'),
1295
+ cbCatalogPathJoin(base, 'local_storage', 'wb_entry_d43e96994f944cfb77961c2ea7d04605.info')
1296
+ ]
1297
+ }
1298
+
1299
+ function productDescriptorCandidates(backend, io) {
1300
+ const e = (io && io.env) || cbCatalogEnv
1301
+ const spec = PRODUCT_DESCRIPTOR_ENV[backend]
1302
+ if (!spec) return []
1303
+ const out = []
1304
+ for (const p of accountConfigCandidates(backend, io)) out.push(p)
1305
+ if (e[spec.env]) out.push(e[spec.env])
1306
+ const rels = spec.fallbackRel ? [spec.rel, spec.fallbackRel] : [spec.rel]
1307
+ const push = (root) => { if (root) for (const r of rels) out.push(cbCatalogPathJoin(root, ...r.split('/'))) }
1308
+ if (backend === 'codebuddy' || backend === 'codebuddy-intl') {
1309
+ push(e.APPDATA ? cbCatalogPathJoin(e.APPDATA, 'npm', 'node_modules', '@tencent-ai', 'codebuddy-code') : null)
1310
+ } else if (backend === 'codebuddy-en') {
1311
+ push('C:\\Program Files\\WorkBuddyAI\\resources\\app.asar.unpacked\\cli')
1312
+ } else if (backend === 'workbuddy') {
1313
+ push('C:\\Program Files\\WorkBuddy\\resources\\app.asar.unpacked\\cli')
1314
+ }
1315
+ return out
1316
+ }
1317
+
1318
+ function normalizeProductConfig(raw) {
1319
+ try {
1320
+ const obj = typeof raw === 'string' ? JSON.parse(raw) : raw
1321
+ if (!obj) return null
1322
+ if (Array.isArray(obj)) {
1323
+ // 数组形态:从后往前找第一个带 data 的条目(末尾最新)。
1324
+ for (let i = obj.length - 1; i >= 0; i--) {
1325
+ const e = obj[i]
1326
+ if (e && typeof e === 'object' && e.data && typeof e.data === 'object') return e.data
1327
+ }
1328
+ return null
1329
+ }
1330
+ if (typeof obj !== 'object') return null
1331
+ if (obj.data && typeof obj.data === 'object' && !Array.isArray(obj.models) && !Array.isArray(obj.agents)) return obj.data
1332
+ return obj
1333
+ } catch (e) { return null }
1334
+ }
1335
+
1336
+ function extractModelIds(productJson) {
1337
+ try {
1338
+ const obj = normalizeProductConfig(productJson)
1339
+ if (!obj || typeof obj !== 'object') return null
1340
+ const pick = (arr) => {
1341
+ if (!Array.isArray(arr) || !arr.length) return null
1342
+ const ids = arr.map((m) => (typeof m === 'string' ? m : m && m.id)).filter((s) => typeof s === 'string' && s.trim())
1343
+ return ids.length ? [...new Set(ids)] : null
1344
+ }
1345
+ const agents = Array.isArray(obj.agents) ? obj.agents : []
1346
+ const cli = agents.find((a) => a && a.name === 'cli')
1347
+ const fromCli = cli ? pick(cli.models) : null
1348
+ const fromTop = pick(obj.models)
1349
+ if (fromCli && fromTop) return fromTop.length > fromCli.length ? fromTop : fromCli
1350
+ return fromCli || fromTop || null
1351
+ } catch (e) { return null }
1352
+ }
1353
+
1354
+ function parseCreditValue(raw) {
1355
+ if (typeof raw !== 'string') return null
1356
+ const s = raw.trim()
1357
+ let m = s.match(/^[xX×]\s*([0-9]+(?:\.[0-9]+)?)/)
1358
+ if (!m) m = s.match(/^([0-9]+(?:\.[0-9]+)?)\s*[xX×]/)
1359
+ if (!m) return null
1360
+ const n = Number(m[1])
1361
+ return Number.isFinite(n) ? n : null
1362
+ }
1363
+
1364
+ function formatCreditLabel(credits) {
1365
+ if (typeof credits !== 'number' || !Number.isFinite(credits)) return ''
1366
+ if (credits === 0) return '免费'
1367
+ return `x${credits.toFixed(2)}`
1368
+ }
1369
+
1370
+ function extractModelCredits(productJson) {
1371
+ try {
1372
+ const obj = normalizeProductConfig(productJson)
1373
+ if (!obj || typeof obj !== 'object' || !Array.isArray(obj.models)) return null
1374
+ const map = new Map()
1375
+ for (const m of obj.models) {
1376
+ if (!m || typeof m !== 'object') continue
1377
+ const id = typeof m.id === 'string' ? m.id.trim() : ''
1378
+ if (!id) continue
1379
+ const n = parseCreditValue(m.credits)
1380
+ if (n !== null) map.set(id, n)
1381
+ }
1382
+ return map.size ? map : null
1383
+ } catch (e) { return null }
1384
+ }
1385
+
1386
+ function lookupModelCredits(creditsMap, id) {
1387
+ if (!creditsMap || typeof id !== 'string') return null
1388
+ const norm = id.trim()
1389
+ const cands = [norm]
1390
+ if (norm.endsWith('-ioa')) cands.push(norm.slice(0, -4))
1391
+ else cands.push(norm + '-ioa')
1392
+ if (CREDIT_ID_ALIASES[norm]) cands.push(...CREDIT_ID_ALIASES[norm])
1393
+ for (const c of cands) {
1394
+ if (creditsMap.has(c)) {
1395
+ const v = creditsMap.get(c)
1396
+ if (typeof v === 'number') return v
1397
+ }
1398
+ }
1399
+ return null
1400
+ }
1401
+
1402
+ function backendModelCatalog(backend, io) {
1403
+ const known = BACKEND_MODEL_IDS[backend] || []
1404
+ const read = (io && io.readFileSync) || cbCatalogRead
1405
+ let fromFile = null
1406
+ let fromFileRich = null
1407
+ // 旧 v1.6.1 语义:第一份有内容的 + 第一份带促销的,优先后者。
1408
+ for (const p of productDescriptorCandidates(backend, io)) {
1409
+ let txt = null
1410
+ try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
1411
+ if (txt == null) continue
1412
+ const ids = extractModelIds(txt)
1413
+ if (ids && ids.length) {
1414
+ if (!fromFile) fromFile = ids
1415
+ const obj = normalizeProductConfig(txt)
1416
+ if (!fromFileRich && obj && Array.isArray(obj.modelPromotions)) fromFileRich = ids
1417
+ }
1418
+ if (fromFileRich) break
1419
+ }
1420
+ if (!fromFile) return known
1421
+ return fromFileRich || fromFile
1422
+ }
1423
+
1424
+ // 服务端回吐的账号清单缓存(进程内,旧 core verbatim)。
1425
+ const ACCOUNT_CATALOG_CACHE = new Map()
1426
+ function rememberAccountCatalog(backend, ids) {
1427
+ if (Array.isArray(ids) && ids.length) ACCOUNT_CATALOG_CACHE.set(backend, ids.slice())
1428
+ }
1429
+ function getAccountCatalog(backend) {
1430
+ const v = ACCOUNT_CATALOG_CACHE.get(backend)
1431
+ return v && v.length ? v.slice() : null
1432
+ }
1433
+
1434
+ // CLI 报错里解析「该账号当前支持的模型」(旧 core parseAccountModels verbatim)。
1435
+ function parseAccountModels(text) {
1436
+ const s = String(text || '')
1437
+ const anchor = s.indexOf('Currently supported models for your account')
1438
+ if (anchor < 0) return null
1439
+ const tail = s.slice(anchor)
1440
+ const ids = []
1441
+ for (const line of tail.split(/\r?\n/)) {
1442
+ const m = /^\s*[-*]\s+(\S+)\s*$/.exec(line)
1443
+ if (!m) {
1444
+ if (ids.length) break
1445
+ continue
1446
+ }
1447
+ if (!ids.includes(m[1])) ids.push(m[1])
1448
+ }
1449
+ return ids.length ? ids : null
1450
+ }
1451
+
1452
+ // 带倍率/授权的详细清单(无促销角标,旧 v1.6.1 的 0.1.0 子集;排序规则 verbatim:
1453
+ // 已授权在前 → 有倍率升序 → 无倍率殿后)。
1454
+ function modelCatalogDetailed(backend, io) {
1455
+ const o = io || {}
1456
+ const fromFile = backendModelCatalog(backend, o)
1457
+ const acct = (Array.isArray(o.accountModels) && o.accountModels.length) ? o.accountModels : getAccountCatalog(backend)
1458
+ const ids = []
1459
+ const authorized = new Set()
1460
+ if (acct) for (const id of acct) { if (!ids.includes(id)) ids.push(id); authorized.add(id) }
1461
+ for (const id of fromFile) if (!ids.includes(id)) ids.push(id)
1462
+ const read = o.readFileSync || cbCatalogRead
1463
+ let creditsMap = null
1464
+ for (const p of productDescriptorCandidates(backend, io)) {
1465
+ let txt = null
1466
+ try { txt = read ? read(p, 'utf8') : null } catch (e) { continue }
1467
+ if (txt == null) continue
1468
+ const map = extractModelCredits(txt)
1469
+ if (map) { creditsMap = map; break }
1470
+ }
1471
+ const items = ids.map((id) => {
1472
+ const base = lookupModelCredits(creditsMap, id)
1473
+ const credits = base
1474
+ const hasCredits = typeof credits === 'number'
1475
+ const suffix = formatCreditLabel(credits)
1476
+ const marks = []
1477
+ if (suffix) marks.push(suffix)
1478
+ if (acct && !authorized.has(id)) marks.push('未授权')
1479
+ return {
1480
+ id,
1481
+ credits,
1482
+ baseCredits: base,
1483
+ free: hasCredits && credits === 0,
1484
+ hasCredits,
1485
+ authorized: acct ? authorized.has(id) : null,
1486
+ promotion: null,
1487
+ label: marks.length ? `${id} · ${marks.join(' · ')}` : id
1488
+ }
1489
+ })
1490
+ const rank = (x) => (x.authorized === false ? 1 : 0)
1491
+ const withC = items.filter((x) => x.hasCredits).sort((a, b) => rank(a) - rank(b) || a.credits - b.credits)
1492
+ const withoutC = items.filter((x) => !x.hasCredits).sort((a, b) => rank(a) - rank(b))
1493
+ return [...withC, ...withoutC]
1494
+ }
1495
+
1496
+ function formatModelCatalogText(backend, io) {
1497
+ return modelCatalogDetailed(backend, io).map((x) => x.label).join(', ')
1498
+ }
1499
+
1500
+
1501
+ const BACKEND_AUTH_IDS = {
1502
+ 'codebuddy': 'Tencent-Cloud.coding-copilot',
1503
+ 'codebuddy-intl': 'Tencent-Cloud.coding-copilot',
1504
+ 'codebuddy-en': 'workbuddy-desktop-ai',
1505
+ 'workbuddy': 'workbuddy-desktop'
1506
+ }
1507
+
1508
+ const CREDENTIAL_KEYS = ['WORKBUDDY_TOKEN', 'WORKBUDDY_AI_TOKEN', 'CODEBUDDY_EN_TOKEN']
1509
+
1510
+ // ── 凭据读取(搬自 codebuddy.mjs;fs/path 走 cbCatalog* 守卫,env 经 io 或注入)
1511
+ function readBackendAuthDomain(backend, io) {
1512
+ const o = io || {}
1513
+ const id = BACKEND_AUTH_IDS[backend]
1514
+ if (!id) return null
1515
+ try {
1516
+ const read = o.readFileSync || cbCatalogRead
1517
+ if (typeof read !== 'function') return null
1518
+ const e = o.env || env
1519
+ let dir = o.dir
1520
+ if (!dir) {
1521
+ dir = e.CODEBUDDY_AUTH_DIR ||
1522
+ cbCatalogPathJoin(e.LOCALAPPDATA || 'C:\\Users\\lcl\\AppData\\Local', 'CodeBuddyExtension', 'Data', 'Public', 'auth')
1523
+ }
1524
+ const sep = String(dir).indexOf('\\') >= 0 ? '\\' : '/'
1525
+ const txt = read(dir + sep + id + '.info', 'utf8')
1526
+ if (txt == null) return null
1527
+ const raw = JSON.parse(txt)
1528
+ const d = raw && raw.auth && raw.auth.domain
1529
+ return typeof d === 'string' && d.trim() ? d.trim() : null
1530
+ } catch (e) { return null }
1531
+ }
1532
+
1533
+ // DSH 凭据库第三通道(旧 core readDshWorkbuddyToken verbatim 语义;CODEBUDDY_
1534
+ // CREDENTIALS_DIR 覆盖测试夹具;fs 经 deps 注入)。
1535
+ function readDshWorkbuddyToken(io) {
1536
+ const e = (io && io.env) || cbCatalogEnv
1537
+ const read = (io && io.readFileSync) || cbCatalogRead
1538
+ const overrideDir = e.CODEBUDDY_CREDENTIALS_DIR || null
1539
+ const home = overrideDir || e.DSH_HOME || null
1540
+ if (!home) return null
1541
+ const files = [home + '\\.credentials.yaml', home + '\\.env', home + '/.credentials.yaml', home + '/.env']
1542
+ for (const f of files) {
1543
+ const text = read(f)
1544
+ if (!text) continue
1545
+ for (const key of CREDENTIAL_KEYS) {
1546
+ const m = text.match(new RegExp('^[ \\t]*' + key + '[ \\t]*[:=][ \\t]*(.+)$', 'm'))
1547
+ if (!m) continue
1548
+ const v = m[1].trim().replace(/\s+#.*$/, '').replace(/^['"]|['"]$/g, '').trim()
1549
+ // 只接受看起来是真实 token 的值(避免把 $VAR 引用或占位符当凭据)。
1550
+ if (v.length >= 40 && !v.startsWith('$') && !/^<.*>$/.test(v)) return v
1551
+ }
1552
+ }
1553
+ return null
1554
+ }
1555
+
1556
+ // codebuddy-en 凭据链(旧 core verbatim):设置面板 > CODEBUDDY_AUTH_TOKEN >
1557
+ // DSH 凭据库。dynamic 沙箱无 fs → 第三通道自然缺席(旧 dynamic 本也有限)。
1558
+ function resolveEnToken(settingToken, io) {
1559
+ const e = (io && io.env) || cbCatalogEnv
1560
+ const s = String(settingToken || '').trim()
1561
+ if (s) return { token: s, source: 'setting' }
1562
+ const envTok = e.CODEBUDDY_AUTH_TOKEN || ''
1563
+ if (String(envTok).trim()) return { token: String(envTok).trim(), source: 'env' }
1564
+ const fromStore = readDshWorkbuddyToken(io)
1565
+ if (fromStore) return { token: fromStore, source: 'dsh-store' }
1566
+ return { token: null, source: null }
1567
+ }
1568
+
1569
+ // ── codebuddy_models 工具定义(搬自主文件;纯逻辑,依赖经 ctx 注入)────────────
1570
+ // ctx = { env, deps, resolveBackend, modelCatalogDetailed, getAccountCatalog }
1571
+ function codebuddyModelsTool(ctx) {
1572
+ const c = ctx || {}
1573
+ const deps = c.deps || {}
1574
+ const env = c.env || {}
1575
+ return {
1576
+ name: 'codebuddy_models',
1577
+ description: 'List the models available to the local codebuddy CLI for a given backend. Merges three layers: the built-in product descriptor id table, any descriptor file on disk, and the account catalogue harvested from a previous CLI run (authorized ids first). Each item carries its credit multiplier (x0.00 = free). Use it to pick a model before codebuddy_run, or to see which ids are free. Returns ok:false with an actionable error when no catalogue can be read — it never invents a model list.',
1578
+ inputSchema: {
1579
+ type: 'object', additionalProperties: false, required: [],
1580
+ properties: {
1581
+ backend: { type: 'string', enum: c.BACKEND_ENUM, description: 'Which product face to list (default: the preferred backend).' },
1582
+ freeOnly: { type: 'boolean', description: 'Return only x0.00 (free) models.' },
1583
+ authorizedOnly: { type: 'boolean', description: 'Return only ids the current account is licensed for (harvested from a prior run).' }
1584
+ }
1585
+ },
1586
+ render: (args, value) => {
1587
+ const v = value || {}
1588
+ if (!v.ok) return [{ type: 'text', text: 'codebuddy_models failed: ' + String(v.error || 'unknown') }]
1589
+ const list = Array.isArray(v.models) ? v.models : []
1590
+ if (!list.length) return [{ type: 'text', text: 'codebuddy_models: no models matched (backend=' + (v.backend || '?') + ')' }]
1591
+ const lines = ['codebuddy models [' + v.backend + '] (' + list.length + '):']
1592
+ for (const m of list.slice(0, 40)) {
1593
+ const flags = []
1594
+ if (m.authorized) flags.push('authorized')
1595
+ if (m.credits === 0) flags.push('free')
1596
+ lines.push(' ' + m.id + (m.creditLabel ? ' ' + m.creditLabel : '') + (flags.length ? ' [' + flags.join(',') + ']' : ''))
1597
+ }
1598
+ if (list.length > 40) lines.push(' … and ' + (list.length - 40) + ' more')
1599
+ lines.push('source: ' + (v.source || 'unknown') + (v.accountCatalogue ? ' · account catalogue available' : ' · no account catalogue yet (run once to harvest)'))
1600
+ return [{ type: 'text', text: lines.join('\n') }]
1601
+ },
1602
+ async logic(args) {
1603
+ const a = args || {}
1604
+ const preferred = (deps.settings && deps.settings.preferredBackend) || null
1605
+ const backend = c.normalizeBackend(a.backend) || c.resolveBackend({}, null, preferred)
1606
+ let items = []
1607
+ try {
1608
+ items = c.modelCatalogDetailed(backend, { env }) || []
1609
+ } catch (e) {
1610
+ return { ok: false, backend, error: 'catalogue read failed: ' + String(e && e.message || e) }
1611
+ }
1612
+ if (!Array.isArray(items) || !items.length) {
1613
+ return {
1614
+ ok: false, backend,
1615
+ error: 'no model catalogue could be read for backend "' + backend + '". Check that the codebuddy CLI is installed (CODEBUDDY_BIN) and that its product descriptor exists, or run the CLI once so the account catalogue can be harvested.'
1616
+ }
1617
+ }
1618
+ const acctIds = c.getAccountCatalog(backend)
1619
+ const accountCatalogue = !!(acctIds && acctIds.length)
1620
+ let list = items.map((x) => ({
1621
+ id: x.id, authorized: !!x.authorized, credits: typeof x.credits === 'number' ? x.credits : null,
1622
+ creditLabel: x.creditLabel || x.label || '', label: x.label || x.id
1623
+ }))
1624
+ if (a.authorizedOnly) list = list.filter((m) => m.authorized)
1625
+ if (a.freeOnly) list = list.filter((m) => m.credits === 0)
1626
+ return {
1627
+ ok: true, backend, models: list, count: list.length,
1628
+ source: accountCatalogue ? 'account+descriptor' : 'descriptor',
1629
+ accountCatalogue
1630
+ }
1631
+ }
1632
+ }
1633
+ }
1496
1634
 
1497
1635
  // core/scheduling.mjs — CLI 调度(启用集合 + 调用优先级)单源纯逻辑。
1498
1636
  //