cc-viewer 1.9.35 → 1.9.37

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.
Files changed (106) hide show
  1. package/README.md +1 -1
  2. package/cli.js +352 -59
  3. package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
  4. package/dist/assets/App-C_AI6A4g.js +2 -0
  5. package/dist/assets/{ArchivePreview-BSBVB9bY.js → ArchivePreview-BBXuZnGC.js} +1 -1
  6. package/dist/assets/{AudioPreview-WxWptR0I.js → AudioPreview-BmqzQZGt.js} +1 -1
  7. package/dist/assets/{MdxEditorPanel-Dq7kpPGA.js → MdxEditorPanel-BLcS9OVC.js} +1 -1
  8. package/dist/assets/Mobile-4mZy680Y.js +1 -0
  9. package/dist/assets/{Mobile-B5V_-6Hc.css → Mobile-B_8Wt_hT.css} +1 -1
  10. package/dist/assets/ProxyStatsModal-BDLwkqxD.js +1 -0
  11. package/dist/assets/{SubtitlePreview-CN3-SniA.js → SubtitlePreview-ei5OtiKq.js} +1 -1
  12. package/dist/assets/{_baseUniq-ClHxNSma.js → _baseUniq-xRiWMqOw.js} +1 -1
  13. package/dist/assets/{arc-ClGYU-1i.js → arc-edNwlWnI.js} +1 -1
  14. package/dist/assets/{architectureDiagram-Q4EWVU46-El3lNwsp.js → architectureDiagram-Q4EWVU46-SMfdtr57.js} +1 -1
  15. package/dist/assets/{blockDiagram-DXYQGD6D-DH290jST.js → blockDiagram-DXYQGD6D-BxAsQG58.js} +1 -1
  16. package/dist/assets/{c4Diagram-AHTNJAMY-BQMsMwnY.js → c4Diagram-AHTNJAMY-DvEHTYBD.js} +1 -1
  17. package/dist/assets/{channel-C-OnmeWg.js → channel-Ce5Cf3nY.js} +1 -1
  18. package/dist/assets/{chunk-4BX2VUAB-PRxJ3zS8.js → chunk-4BX2VUAB--OnGvs-9.js} +1 -1
  19. package/dist/assets/{chunk-4TB4RGXK-C_TKsRMW.js → chunk-4TB4RGXK-MSrYeKo5.js} +1 -1
  20. package/dist/assets/{chunk-55IACEB6-nGpnU7E4.js → chunk-55IACEB6-CD4rh-7b.js} +1 -1
  21. package/dist/assets/{chunk-EDXVE4YY-D0-9hlXC.js → chunk-EDXVE4YY-CrAxlPfF.js} +1 -1
  22. package/dist/assets/{chunk-FMBD7UC4-hKmwmsrB.js → chunk-FMBD7UC4-CMb4qB5t.js} +1 -1
  23. package/dist/assets/{chunk-OYMX7WX6-CZnR4qSn.js → chunk-OYMX7WX6-CEP3GJND.js} +1 -1
  24. package/dist/assets/{chunk-QZHKN3VN-CGtdnavD.js → chunk-QZHKN3VN-Xko480I7.js} +1 -1
  25. package/dist/assets/{chunk-YZCP3GAM-GPB3qNXk.js → chunk-YZCP3GAM-xKPv2jAr.js} +1 -1
  26. package/dist/assets/classDiagram-6PBFFD2Q-CAw9u3mr.js +1 -0
  27. package/dist/assets/classDiagram-v2-HSJHXN6E-CAw9u3mr.js +1 -0
  28. package/dist/assets/clone-CW1SPXDP.js +1 -0
  29. package/dist/assets/{cose-bilkent-S5V4N54A-9L57MjYD.js → cose-bilkent-S5V4N54A-Dd5Fpol9.js} +1 -1
  30. package/dist/assets/{dagre-KV5264BT-CNkz8gO7.js → dagre-KV5264BT-BH00hKa4.js} +1 -1
  31. package/dist/assets/{diagram-5BDNPKRD-DQBFzIFl.js → diagram-5BDNPKRD-BJZlGmRA.js} +1 -1
  32. package/dist/assets/{diagram-G4DWMVQ6-CTwwGTIV.js → diagram-G4DWMVQ6-BTj-YG-C.js} +1 -1
  33. package/dist/assets/{diagram-MMDJMWI5-BKEsMMNd.js → diagram-MMDJMWI5-2ZD4VZMB.js} +1 -1
  34. package/dist/assets/{diagram-TYMM5635-BgAqGIDJ.js → diagram-TYMM5635-mTEHpW4W.js} +1 -1
  35. package/dist/assets/{erDiagram-SMLLAGMA-BuR-DOkX.js → erDiagram-SMLLAGMA-DTOSCCrk.js} +1 -1
  36. package/dist/assets/{flowDiagram-DWJPFMVM-CtEs3omg.js → flowDiagram-DWJPFMVM-C4ZAoiRL.js} +1 -1
  37. package/dist/assets/{ganttDiagram-T4ZO3ILL-aEyreBxU.js → ganttDiagram-T4ZO3ILL-C56IAugD.js} +1 -1
  38. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B0jK9QeS.js → gitGraphDiagram-UUTBAWPF-fvtnUb6S.js} +1 -1
  39. package/dist/assets/{graph-ehKfRbVz.js → graph-CnqqDZhs.js} +1 -1
  40. package/dist/assets/index-B15ZeDb-.css +1 -0
  41. package/dist/assets/{index-Brys6nSs.js → index-BUkls72j.js} +1 -1
  42. package/dist/assets/{index-CtricoKb.js → index-CEinmFtX.js} +1 -1
  43. package/dist/assets/index-CVnJzK-y.js +2 -0
  44. package/dist/assets/{index-B0uKNGh1.js → index-CcAn_gE2.js} +1 -1
  45. package/dist/assets/{index-Dns_OQOp.js → index-CdN-CkKM.js} +1 -1
  46. package/dist/assets/{index-D5KJq71j.js → index-DjoCHMpJ.js} +1 -1
  47. package/dist/assets/{index-CH6ZHNzo.js → index-Dq3ex7Ip.js} +1 -1
  48. package/dist/assets/{index-BDj-fJNP.js → index-F9AcG6Ef.js} +1 -1
  49. package/dist/assets/{infoDiagram-42DDH7IO-CUntIdK6.js → infoDiagram-42DDH7IO-B-b77lg9.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-UXIWVN3A-CtCGMBTX.js → ishikawaDiagram-UXIWVN3A-B1ituugL.js} +1 -1
  51. package/dist/assets/{journeyDiagram-VCZTEJTY-DCRvOrOx.js → journeyDiagram-VCZTEJTY-DvFc_1_L.js} +1 -1
  52. package/dist/assets/{jszip.min-DZsXbJ4A.js → jszip.min-Br1yL7Q3.js} +1 -1
  53. package/dist/assets/{kanban-definition-6JOO6SKY-jEtOSXmn.js → kanban-definition-6JOO6SKY-B-3zDwdJ.js} +1 -1
  54. package/dist/assets/{layout-C-6TbhHY.js → layout-B8tT3Nrd.js} +1 -1
  55. package/dist/assets/{linear-DQg_Idt4.js → linear-BVxRmpuU.js} +1 -1
  56. package/dist/assets/{mermaid.core-C_rq53MX.js → mermaid.core-TpktUJt6.js} +2 -2
  57. package/dist/assets/{min-BqPulfFi.js → min-4AuCZ0ho.js} +1 -1
  58. package/dist/assets/{mindmap-definition-QFDTVHPH-CNsFBo-7.js → mindmap-definition-QFDTVHPH-MQeup-Jb.js} +1 -1
  59. package/dist/assets/{pieDiagram-DEJITSTG-BDn3Cz--.js → pieDiagram-DEJITSTG-mSFlWRpV.js} +1 -1
  60. package/dist/assets/{quadrantDiagram-34T5L4WZ-CsrLWd-H.js → quadrantDiagram-34T5L4WZ-BE2AHw1J.js} +1 -1
  61. package/dist/assets/{requirementDiagram-MS252O5E-DPzJKSB5.js → requirementDiagram-MS252O5E-CSat0Shv.js} +1 -1
  62. package/dist/assets/{sankeyDiagram-XADWPNL6-DYDGySQ1.js → sankeyDiagram-XADWPNL6-jSfdI1J9.js} +1 -1
  63. package/dist/assets/seqResourceLoaders-BT5ki0J4.js +2 -0
  64. package/dist/assets/{seqResourceLoaders-b9deQDrA.css → seqResourceLoaders-CXgVOdgW.css} +2 -2
  65. package/dist/assets/{sequenceDiagram-FGHM5R23-HVWMhF8a.js → sequenceDiagram-FGHM5R23-n8z9Vixi.js} +1 -1
  66. package/dist/assets/{stateDiagram-FHFEXIEX-BtcEUJOY.js → stateDiagram-FHFEXIEX-Dn_y_D8r.js} +1 -1
  67. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DWDh2D71.js → stateDiagram-v2-QKLJ7IA2-BB1b-66S.js} +1 -1
  68. package/dist/assets/{timeline-definition-GMOUNBTQ-B81djDNu.js → timeline-definition-GMOUNBTQ-Bvy0hn9D.js} +1 -1
  69. package/dist/assets/{vendor-antd-C5Wsfsxn.js → vendor-antd-BciJO790.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-DPXDhteu.js → vendor-codemirror-BVX6n7ix.js} +1 -1
  71. package/dist/assets/{vendor-mdxeditor-DLPCj_fe.js → vendor-mdxeditor-BlcXEhaG.js} +2 -2
  72. package/dist/assets/{vendor-qrcode-BzB5n5mK.js → vendor-qrcode-DVibqC0x.js} +1 -1
  73. package/dist/assets/{vendor-virtuoso-Beq6R5oo.js → vendor-virtuoso-CsBSMJ5R.js} +1 -1
  74. package/dist/assets/{vennDiagram-DHZGUBPP-BeitG2yA.js → vennDiagram-DHZGUBPP-BVqFkdla.js} +1 -1
  75. package/dist/assets/{wardley-RL74JXVD-BCzOL4u_.js → wardley-RL74JXVD-BIAqGP0w.js} +1 -1
  76. package/dist/assets/{wardleyDiagram-NUSXRM2D-20SEChwk.js → wardleyDiagram-NUSXRM2D-DGUvrzIN.js} +1 -1
  77. package/dist/assets/{xychartDiagram-5P7HB3ND-Behle0ry.js → xychartDiagram-5P7HB3ND-BjEJgIoR.js} +1 -1
  78. package/dist/index.html +5 -5
  79. package/package.json +1 -1
  80. package/server/i18n.js +4 -0
  81. package/server/interceptor.js +92 -21
  82. package/server/lib/anthropic-auth-placeholder.js +147 -0
  83. package/server/lib/builtin-model-prompts.js +16 -7
  84. package/server/lib/im/im-bridge-core.js +59 -14
  85. package/server/lib/im/im-permissions.js +48 -0
  86. package/server/lib/im/im-process-manager.js +6 -5
  87. package/server/lib/im-deny.js +4 -1
  88. package/server/lib/interceptor-core.js +51 -0
  89. package/server/lib/model-system-prompts.js +207 -13
  90. package/server/lib/proxy-session-registry.js +219 -0
  91. package/server/lib/sdk-manager.js +103 -4
  92. package/server/lib/update-job.js +3 -3
  93. package/server/proxy.js +15 -7
  94. package/server/pty-manager.js +4 -29
  95. package/server/routes/preferences.js +108 -24
  96. package/server/routes/update.js +15 -2
  97. package/server/server.js +9 -6
  98. package/dist/assets/App-COZPgAGQ.js +0 -2
  99. package/dist/assets/Mobile-DtdwYlSK.js +0 -1
  100. package/dist/assets/ProxyStatsModal-BZPBbxOC.js +0 -1
  101. package/dist/assets/classDiagram-6PBFFD2Q-DigyQWGQ.js +0 -1
  102. package/dist/assets/classDiagram-v2-HSJHXN6E-DigyQWGQ.js +0 -1
  103. package/dist/assets/clone-DwpJyNdv.js +0 -1
  104. package/dist/assets/index-BLzca-ta.css +0 -1
  105. package/dist/assets/index-OTFFui4C.js +0 -2
  106. package/dist/assets/seqResourceLoaders-BXk6JJEc.js +0 -2
@@ -1,9 +1,9 @@
1
1
  // IM 进程管理(父进程侧)—— 由主交互式 ccv 调用,负责把每个启用的 IM 作为 detached 常驻
2
- // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImMode)持有 im.lock;
3
- // 本模块只读锁 + 探活 + spawn/kill。
2
+ // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImSdkMode / `--im-sdk`,
3
+ // `--im-pty` 为 legacy PTY 排障口)持有 im.lock;本模块只读锁 + 探活 + spawn/kill。
4
4
  //
5
5
  // 设计:detached + unref(主 ccv 关闭后 worker 仍在线);停止时杀**进程组**清理 worker 的
6
- // Claude PTY + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
6
+ // Claude 会话 + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
7
7
  // v1 不做常驻 supervisor(reconcile-on-startup + 配置保存即驱动 已覆盖主路径,且避免多主进程互斗)。
8
8
  import { spawn as nodeSpawn, execSync } from 'node:child_process';
9
9
  import { openSync, closeSync, mkdirSync } from 'node:fs';
@@ -54,7 +54,8 @@ export function buildChildEnv(id, base = process.env) {
54
54
  }
55
55
 
56
56
  /**
57
- * 以 detached 子进程拉起一个 IM worker:`node cli.js --im <id> --no-open`,cwd=IM_<id>/。
57
+ * 以 detached 子进程拉起一个 IM worker:`node cli.js --im-sdk <id> --no-open`,cwd=IM_<id>/。
58
+ * (SDK worker 是默认形态;cli.js 把裸 `--im` 也映射为 SDK,`--im-pty` 为隐藏排障口。)
58
59
  * @param {string} id
59
60
  * @param {{ spawnImpl?: Function }} [opts] 测试可注入 spawnImpl
60
61
  * @returns {{ pid:number|undefined, dir:string, outLog:string }}
@@ -86,7 +87,7 @@ export function spawnImProcess(id, opts = {}) {
86
87
  stdio = ['ignore', fd, fd];
87
88
  } catch { /* 无法开日志文件时退化为 ignore */ }
88
89
 
89
- const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im', id, '--no-open'], {
90
+ const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im-sdk', id, '--no-open'], {
90
91
  cwd: dir,
91
92
  env: buildChildEnv(id),
92
93
  stdio,
@@ -94,7 +94,10 @@ export function evaluateImDeny(toolName, toolInput = {}, opts = {}) {
94
94
  return { deny: false };
95
95
  }
96
96
 
97
- if (toolName === 'Read') {
97
+ // Read-class tools: Read (file_path), Grep/Glob (path), NotebookRead (notebook_path).
98
+ // Grep/Glob 的 path 指向被读取的目录/文件 —— 否则 `Grep {path:'~/.ssh'}` 会绕过 Read 路径层
99
+ // 把凭证内容读进上下文再随答复外带(review-security P1-3)。复用同一套读取判定。
100
+ if (toolName === 'Read' || toolName === 'Grep' || toolName === 'Glob' || toolName === 'NotebookRead') {
98
101
  const abs = pathOf(toolInput, home);
99
102
  if (!abs) return { deny: false };
100
103
  if (isVaultFile(abs) || isTaskDataFile(abs)) return { deny: true, reason: 'read of the credential vault / master key' };
@@ -751,3 +751,54 @@ export function isValidRoleValue(v, profilesById) {
751
751
  if (typeof v !== 'string' || !v) return false;
752
752
  return !!(profilesById && typeof profilesById.get === 'function' && profilesById.get(v));
753
753
  }
754
+
755
+ // ─── Per-session (per-instanceKey) proxy resolution ───────────────────────────
756
+ // A session binding is { main, roles:{subagent,teammate} } (see
757
+ // lib/proxy-session-registry.js). These pure functions fold a session binding on top
758
+ // of the process-global profile so a request can be rerouted per session. They are
759
+ // the SINGLE source of truth shared by proxy.js (upstream pick) and the interceptor
760
+ // fetch hook (URL/auth/model rewrite) — the two layers must never diverge.
761
+ //
762
+ // mapped === undefined means "this session has no binding" (PTY / ephemeral / an
763
+ // external caller): the request follows the legacy global profile exactly as before.
764
+ // A present binding with main==='max' means the session explicitly chose Default:
765
+ // return null (no rewrite) and DO NOT follow the global profile afterwards.
766
+
767
+ // Resolve a session's effective MAIN profile.
768
+ // sessionEntry: the binding (or undefined when unbound)
769
+ // profilesById: Map<profileId, profile>
770
+ // legacyMain: the process-global effective main profile (_activeProfile)
771
+ export function resolveSessionMainProfile(sessionEntry, profilesById, legacyMain) {
772
+ if (sessionEntry === undefined || sessionEntry === null) return legacyMain || null;
773
+ const main = sessionEntry.main;
774
+ if (main === 'max') return null; // explicit Default
775
+ if (typeof main === 'string' && main) {
776
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(main) : undefined;
777
+ return hit || legacyMain || null; // dangling id → fall back to the legacy global
778
+ }
779
+ return legacyMain || null;
780
+ }
781
+
782
+ // Resolve an effective ROLE profile for a session. Precedence:
783
+ // session role explicit id/'max' (per-session role assignment)
784
+ // session role 'follow' → the SESSION's main (so main+subagent stay together)
785
+ // workspace role id/'max' (legacyRoleIds, when the session has no binding/override)
786
+ // legacyMain
787
+ // 'role' is 'main' | 'subagent' | 'teammate'.
788
+ export function resolveSessionRoleProfile(role, sessionEntry, profilesById, legacyMain, legacyRoleIds) {
789
+ const sessionMain = resolveSessionMainProfile(sessionEntry, profilesById, legacyMain);
790
+ if (role === 'main') return sessionMain;
791
+ const sessionRole = sessionEntry && sessionEntry.roles ? sessionEntry.roles[role] : undefined;
792
+ if (typeof sessionRole === 'string' && sessionRole && sessionRole !== 'follow') {
793
+ if (sessionRole === 'max') return null; // explicit Default for this role
794
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(sessionRole) : undefined;
795
+ return hit || sessionMain;
796
+ }
797
+ // session role is 'follow'/absent → follow the session main. When the session has NO
798
+ // binding at all, defer to the legacy workspace role assignment (existing behavior).
799
+ if (sessionEntry === undefined || sessionEntry === null) {
800
+ return resolveRoleProfile(role, legacyRoleIds, profilesById, legacyMain);
801
+ }
802
+ return sessionMain;
803
+ }
804
+
@@ -5,16 +5,18 @@ import { isNonEmptyFile } from './file-api.js';
5
5
  // 「按模型定制 system prompt」的文件夹与文件名语法。
6
6
  // 全局目录 <LOG_DIR>/system_prompt/ 与工作区目录 <workspace>/system_prompt/ 各放一套;
7
7
  // 启动时用「当前生效配置解析出的模型 id」(spawn-model-resolver.js:激活的三方 proxy profile
8
- // 模型映射 > env > settings.json;无配置信号则不注入)做不区分大小写的子串匹配(条目名
9
- // "OPUS" 命中 "claude-opus-4-8[1m]"),命中的文件整体取代工作区默认的 CC_SYSTEM.md /
10
- // CC_APPEND_SYSTEM.md。
8
+ // 模型映射 > env > settings.json;无配置信号则不注入)做分层段匹配——ident 链锁定家族
9
+ // (条目名 "OPUS" 命中 "claude-opus-4-8[1m]",容忍厂商前缀),版本号只排序消歧不否决;
10
+ // 段匹配全 miss 时回退旧子串。命中的文件整体取代工作区默认的 CC_SYSTEM.md / CC_APPEND_SYSTEM.md。
11
11
  //
12
12
  // Model-specific system prompt files. Two scopes share the same folder name
13
13
  // (MODEL_PROMPT_DIR): global <LOG_DIR>/system_prompt/ and per-workspace
14
14
  // <workspace>/system_prompt/. At spawn the model id resolved from the ACTIVE
15
15
  // configuration (spawn-model-resolver.js — never from past usage records) is
16
- // matched case-insensitively as a substring against entry names; a match fully
17
- // replaces the workspace Default sentinels for that launch.
16
+ // matched by layered segment matching: the ident chain pins the family (tolerating
17
+ // any vendor prefix), the version only ranks candidates and never vetoes, and a
18
+ // legacy substring predicate is the fallback. A match fully replaces the workspace
19
+ // Default sentinels for that launch.
18
20
  //
19
21
  // Known limitations (by design):
20
22
  // - An entry named "haiku" only matches when haiku is explicitly configured as
@@ -231,10 +233,11 @@ export function deleteModelPrompt(dir, name) {
231
233
 
232
234
  /**
233
235
  * 在候选目录序列中为 modelId 匹配模型条目。
234
- * 匹配 = 双方都转小写后做子串包含("OPUS" 命中 "claude-opus-4-8[1m]")。
236
+ * 匹配 = 分层段匹配:ident 链锁定家族("OPUS" 命中 "claude-opus-4-8[1m]",容忍厂商前缀),
237
+ * 版本号只排序消歧不否决;段匹配全 miss 时回退旧子串(保住非规范命名)。
235
238
  * candidates 按「工作区在前」传入:工作区一旦有命中即短路,全局哪怕名字更长也不再看
236
239
  * (用户决策:工作区覆盖全局;名字长度只在同一 scope 内当消歧规则)。
237
- * 同 scope 多条命中:名字最长者胜("OPUS-4" 压过 "OPUS"),等长按字典序,确定性兜底。
240
+ * 同 scope 多条命中:先按版本贴近度(_score),再段数、名字长、精确、字典序。
238
241
  * Match modelId against candidate dirs (workspace-first short-circuit).
239
242
  *
240
243
  * @param {string|null} modelId e.g. 'claude-opus-4-8[1m]'
@@ -242,8 +245,8 @@ export function deleteModelPrompt(dir, name) {
242
245
  * @returns {{ path: string, fileName: string, name: string, mode: 'override'|'append', scope: 'workspace'|'global' } | null}
243
246
  */
244
247
  // 模型 id 别名表:第三方代理常把模型名归一化成不带厂商前缀的简写(kimi profile 把
245
- // `k3[1m]` 剥后缀后得到裸 `k3`),而条目名通常带前缀(KIMI / KIMI-K3)。别名在子串
246
- // 匹配前把解析名展开成「所有等价拼写」,任一变体命中即算命中。key 与变体都是小写
248
+ // `k3[1m]` 剥后缀后得到裸 `k3`),而条目名通常带前缀(KIMI / KIMI-K3)。别名在段匹配
249
+ // 前把解析名展开成「所有等价拼写」,任一变体命中即算命中。key 与变体都是小写
247
250
  // 完整词(精确等值,非子串),只在解析名**恰好等于** key 时展开,避免误放大。
248
251
  // Model id aliases: third-party proxies often normalize model names to a bare
249
252
  // shorthand (the kimi profile strips `k3[1m]` → `k3`), while entry names carry the
@@ -282,6 +285,190 @@ export function expandModelIdVariants(modelId) {
282
285
  return modelIdVariants(stripped);
283
286
  }
284
287
 
288
+ // ── 分层段匹配 ─────────────────────────────────────────────────────────────
289
+ // 模型 id 是「分段结构化标识」,不是不透明字符串:厂商前缀 + 家族名 + 版本 + 后缀。
290
+ // 纯子串在版本跳变(V4 → V4.1)或带厂商前缀(vendor/…)时断裂落空。这里把 id 切成
291
+ // token → segment(ident + 版本元组)再比较:ident 链锁定家族(必须命中),版本只用于
292
+ // 排序消歧、不否决命中——版本对不上时仍落回同家族条目,不掉兜底。
293
+ // 单一实现,勿在别处复制(builtin-model-prompts.js 经 export 复用)。
294
+ //
295
+ // Layered segment matching: a model id is structured (vendor prefix + family +
296
+ // version + suffix), not an opaque string. Tokenize → segment (ident + version
297
+ // tuple) → compare. The ident chain pins the family (must match); the version
298
+ // only ranks candidates, never vetoes a family hit, so an unknown version still
299
+ // lands on its family entry instead of the fallback.
300
+
301
+ const NUM_TOKEN_RE = /^[0-9]+$/;
302
+
303
+ /**
304
+ * 把模型 id 切成小写 token 序列:版本字面量(含内部 `.` 分量)拆成独立数字,
305
+ * 字母串原样保留,其余一切字符(/ - : _ 等)都当分隔符、不产生 token。
306
+ * 白名单词法:`.` 的职责是版本分量分隔而非字段分隔;未来下划线命名自动正确。
307
+ * Tokenize a model id: version literals split into numeric components, letter
308
+ * runs kept, every other char is a separator.
309
+ *
310
+ * @param {string} id
311
+ * @returns {string[]} e.g. 'vendor/DeepSeek-V4.1-Flash-1017' → ['vendor','deepseek','v','4','1','flash','1017']
312
+ */
313
+ export function modelIdTokens(id) {
314
+ if (!id || typeof id !== 'string') return [];
315
+ const s = id.replace(/\s*\[[^\]]*\]$/, '').toLowerCase(); // 剥 [1m] 类后缀,沿用 expandModelIdVariants 语义
316
+ const out = [];
317
+ const re = /\d+(?:\.\d+)*|[a-z]+/g;
318
+ let m;
319
+ while ((m = re.exec(s))) {
320
+ const t = m[0];
321
+ if (NUM_TOKEN_RE.test(t[0])) {
322
+ for (const n of t.split('.')) out.push(n); // 版本 → 独立数字分量
323
+ } else {
324
+ out.push(t);
325
+ }
326
+ }
327
+ return out;
328
+ }
329
+
330
+ /**
331
+ * 把 token 序列切段:每个字母串(ident)与其后连续数字合并为一个 segment
332
+ * { ident, nums[] };前导纯数字自成一段(ident: null)。
333
+ * Group tokens into segments: an ident plus its trailing numeric run.
334
+ *
335
+ * @param {string[]} tokens
336
+ * @returns {Array<{ ident: string|null, nums: string[] }>}
337
+ */
338
+ export function modelIdSegments(tokens) {
339
+ const out = [];
340
+ for (let i = 0; i < tokens.length; i++) {
341
+ if (NUM_TOKEN_RE.test(tokens[i])) {
342
+ out.push({ ident: null, nums: [tokens[i]] });
343
+ continue;
344
+ }
345
+ const seg = { ident: tokens[i], nums: [] };
346
+ while (i + 1 < tokens.length && NUM_TOKEN_RE.test(tokens[i + 1])) seg.nums.push(tokens[++i]);
347
+ out.push(seg);
348
+ }
349
+ return out;
350
+ }
351
+
352
+ /**
353
+ * 段比较:entry 首段(必须带 ident)在 id 段序列中起锚(容忍任意厂商前缀),逐段要求
354
+ * ident 严格相等。版本不否决命中,只累计匹配得分。厂商前缀可能与家族同名
355
+ * (deepseek/deepseek-v4-flash),首段 ident 在 id 里出现多次时逐处起锚、取最优,
356
+ * 避免锚在厂商段上静默 miss。
357
+ * 返回 { matched, score, exact } 或 null;exact = 版本与尾段都完全一致。
358
+ * Compare segment lists: anchor on every occurrence of the entry's first ident
359
+ * (a vendor prefix may repeat the family name), keep the best; ident equality is
360
+ * required per segment; the version only scores, never vetoes.
361
+ *
362
+ * @param {Array<{ ident: string|null, nums: string[] }>} entrySegs
363
+ * @param {Array<{ ident: string|null, nums: string[] }>} idSegs
364
+ * @returns {{ matched: true, score: number, exact: boolean } | null}
365
+ */
366
+ export function matchSegments(entrySegs, idSegs) {
367
+ if (!entrySegs.length || entrySegs[0].ident === null) return null;
368
+ let best = null;
369
+ for (let start = 0; start < idSegs.length; start++) {
370
+ if (idSegs[start].ident !== entrySegs[0].ident) continue;
371
+ const r = matchSegmentsAt(entrySegs, idSegs, start);
372
+ if (r && (!best || r.score > best.score || (r.score === best.score && r.exact))) best = r;
373
+ }
374
+ return best;
375
+ }
376
+
377
+ // 在指定起锚位置比较一次;ident 链断裂返回 null。版本计分(排序只认 score 主键,数值刻意拉开):
378
+ // 精确(entry 分量与 id 前缀逐位相等且等长) → 4
379
+ // 前缀(逐位相等但 id 版本更长,如 v{4} ⊑ v{4,1}) → 3
380
+ // 同 major、minor 分叉(glm-5.3 vs glm-5.4) → 2/(1+|Δminor|)
381
+ // —— 同一条版本线,更接近的成员胜出:GLM-5.4 落 GLM-5.3 而非 GLM-5.2
382
+ // 跨 major(glm-5.3 vs glm-6) → 1 + major×1e-3
383
+ // —— 不否决,贴向最高 major 的同族条目:GLM-6 落 GLM-5.3 而非 GLM-5.2
384
+ // 完全对不上(ident 对齐但无任何版本可比) → 0(仍命中,不否决)
385
+ // 版本永不否决:ident 链已锁家族,分数再低也命中、由排序落到最贴近的同家族条目而非兜底。
386
+ function matchSegmentsAt(entrySegs, idSegs, start) {
387
+ let score = 0;
388
+ let exact = true;
389
+ for (let k = 0; k < entrySegs.length; k++) {
390
+ const e = entrySegs[k];
391
+ const s = idSegs[start + k];
392
+ if (!s || e.ident !== s.ident) return null;
393
+ if (e.nums.length > 0) {
394
+ let allEq = true;
395
+ for (let n = 0; n < e.nums.length; n++) {
396
+ if (e.nums[n] !== s.nums[n]) { allEq = false; break; }
397
+ }
398
+ if (allEq && e.nums.length === s.nums.length) {
399
+ score += 4; // 逐位等长精确(allEq ⇒ major 必等,无跨 major 分支)
400
+ } else if (allEq) {
401
+ score += 3; exact = false; // 前缀(id 版本更长)
402
+ } else if (e.nums[0] === s.nums[0]) {
403
+ // 同 major、minor 分叉(相邻版本线):按 minor 贴近度给分,越接近越高,量纲 (1,2]——
404
+ // 恒大于任何「跨 major」分值 (0,1),保证 major 匹配永远压过跨 major。分量缺省按 0 计。
405
+ // GLM-5.4 落 GLM-5.3(1.5) 而非更旧的 GLM-5.2(≈1.33)。
406
+ const gap = Math.abs(Number(e.nums[1] ?? 0) - Number(s.nums[1] ?? 0));
407
+ score += 1 + 1 / (1 + gap);
408
+ exact = false;
409
+ } else {
410
+ // 跨 major(不否决):贴向「版本最高的同族条目」——模型 id 越新,越应落到同主线
411
+ // 里最高的既有条目(GLM-6 → GLM-5.3 而非 GLM-5.2);id 版本低于所有条目时同样取
412
+ // 最高(族内兜底,避免老 id 拿到最旧 prompt)。分数随 entry 版本单调递增,量纲
413
+ // (0,1):恒小于任何「同 major」分值 (1,2],故同 major 条目永远压过跨 major 条目。
414
+ let entryVal = 0;
415
+ let weight = 1;
416
+ for (let n = 0; n < e.nums.length; n++) {
417
+ entryVal += Number(e.nums[n] ?? 0) * weight;
418
+ weight /= 10;
419
+ }
420
+ score += entryVal / (entryVal + 1);
421
+ exact = false;
422
+ }
423
+ } else if (s.nums.length > 0) {
424
+ exact = false; // entry 无版本而 id 有 → 不算精确
425
+ }
426
+ }
427
+ if (start + entrySegs.length < idSegs.length) exact = false; // entry 后还有段
428
+ return { matched: true, score, exact };
429
+ }
430
+
431
+ // 段匹配消歧排序:版本贴近度(score) > 段数多 > 名字长 > 精确(exact) > 字典序。
432
+ // score 已编码「同主线 > 跨主线精确」的权重(见 matchSegments 注释),故 score 是主键,
433
+ // exact 退为最终 tiebreak(同分时精确版更具体)。两层共用(内置层条目 name=match 大写、
434
+ // 长度与 matchLower 恒等,故直接读 name)。
435
+ // Segment-match disambiguation: version proximity (score) > segment count > exact.
436
+ // Shared by both layers; entries must carry _score/_exact/_segCount plus a name field.
437
+ export function segmentHitRank(a, b) {
438
+ if (a._score !== b._score) return b._score - a._score;
439
+ if (a._segCount !== b._segCount) return b._segCount - a._segCount;
440
+ if (a.name.length !== b.name.length) return b.name.length - a.name.length;
441
+ if (a._exact !== b._exact) return a._exact ? -1 : 1;
442
+ return a.name.localeCompare(b.name);
443
+ }
444
+
445
+ // 在候选条目里为每个 variant 取最优段匹配(best-of-variants),返回带排序字段的命中数组。
446
+ // 两层共用,消除「逐条目 × 逐变体取 best」的重复实现。
447
+ // Collect the best segment hit per entry across every id variant. Shared by both layers.
448
+ export function collectSegmentHits(entries, idSegsList, getEntrySegs) {
449
+ const hits = [];
450
+ for (const e of entries) {
451
+ const entrySegs = getEntrySegs(e);
452
+ let best = null;
453
+ for (const idSegs of idSegsList) {
454
+ const r = matchSegments(entrySegs, idSegs);
455
+ if (r && (!best || r.score > best.score || (r.score === best.score && r.exact))) best = r;
456
+ }
457
+ if (best) hits.push({ ...e, _exact: best.exact, _score: best.score, _segCount: entrySegs.length });
458
+ }
459
+ return hits;
460
+ }
461
+
462
+ // 旧子串命中谓词:段匹配全 miss 时的兜底,保住官方用户非规范命名(OPU、4-8 等)。
463
+ // 两层共用——内置层同样回退(vendor 前缀可能与家族同名导致段匹配锚错起点时,子串仍能救回)。
464
+ // Legacy substring predicate, kept as the fallback so non-canonical names still hit.
465
+ export function substringHits(variants, entries) {
466
+ return entries.filter((e) => {
467
+ const key = (e.matchLower || e.name.toLowerCase());
468
+ return variants.some((v) => v.includes(key));
469
+ });
470
+ }
471
+
285
472
  export function matchModelPrompt(modelId, candidates) {
286
473
  if (!modelId || typeof modelId !== 'string') return null;
287
474
  if (!Array.isArray(candidates)) return null;
@@ -289,12 +476,19 @@ export function matchModelPrompt(modelId, candidates) {
289
476
  // 若用户层不剥后缀而内置层剥(k3[1m] + 用户有 KIMI-K3_SYSTEM.md),用户文件会
290
477
  // 静默 miss、内置反客为主 —— 违反「用户文件永远优先」,两层必须同语义。
291
478
  const variants = expandModelIdVariants(modelId);
479
+ const idSegsList = variants.map((v) => modelIdSegments(modelIdTokens(v)));
292
480
  for (const cand of candidates) {
293
481
  if (!cand || !cand.dir) continue;
294
- const hits = listModelPrompts(cand.dir).filter((e) => {
295
- const entryName = e.name.toLowerCase();
296
- return variants.some((v) => v.includes(entryName));
297
- });
482
+ const entries = listModelPrompts(cand.dir);
483
+ // 主路径:段匹配(ident 锁家族,版本排序消歧不否决)。
484
+ let hits = collectSegmentHits(entries, idSegsList, (e) => modelIdSegments(modelIdTokens(e.name)));
485
+ if (hits.length) {
486
+ hits.sort(segmentHitRank);
487
+ const e = hits[0];
488
+ return { path: join(cand.dir, e.fileName), fileName: e.fileName, name: e.name, mode: e.mode, scope: cand.scope };
489
+ }
490
+ // 兜底:旧子串(保住官方用户非规范命名 OPU / 4-8 等,两层同语义)。
491
+ hits = substringHits(variants, entries);
298
492
  if (!hits.length) continue;
299
493
  hits.sort((a, b) => b.name.length - a.name.length || a.name.localeCompare(b.name));
300
494
  const e = hits[0];
@@ -0,0 +1,219 @@
1
+ // Per-session (per SDK instance) proxy binding. Maps an SDK instanceKey to the
2
+ // session's proxy choice ({ main, roles, origin, workspace? }) so one session's
3
+ // proxy change never leaks into another session sharing the same ccv process.
4
+ //
5
+ // This is intentionally process-local and IN-MEMORY ONLY: bindings are seeded when
6
+ // a session is registered/activated and dropped when it closes or the process stops.
7
+ // Nothing is persisted — a restart simply has no bindings (matches the product
8
+ // requirement that the choice need not survive a restart).
9
+ //
10
+ // Boundary: this is an L1 lib. It must NOT import sdk-manager (that would eagerly
11
+ // load the Agent SDK in PTY mode) or interceptor (an L2 consumer). interceptor
12
+ // registers a global-default provider here; proxy.js and the fetch hook read the
13
+ // per-request override through interceptor, never from sdk-manager directly.
14
+ import { readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { LOG_DIR } from '../../findcc.js';
17
+ import { reportSwallowed } from './error-report.js';
18
+
19
+ const INSTANCE_KEY_RE = /^ccv-[0-9a-f]+$/;
20
+ const MAX_ENTRIES = 1024; // defensive cap: an unbounded map would be a slow leak
21
+
22
+ // instanceKey -> {
23
+ // main: profileId|'max',
24
+ // roles: { subagent, teammate },
25
+ // origin: 'seed'|'user', // provenance: snapshotted at seed vs explicit session-scope choice
26
+ // workspace?: string, // seed only: owning workspace's project key (opaque to this module)
27
+ // }
28
+ // 'max' is the explicit "Default" (no rewrite) value and MUST be stored verbatim —
29
+ // an absent mapping means "not bound" (fall back to the process-global profile),
30
+ // which is a different thing from "this session explicitly chose Default".
31
+ //
32
+ // `origin` exists so a workspace active/roles change can re-align ONLY the bindings that
33
+ // were auto-seeded from the workspace ('seed') and never the ones a user explicitly picked
34
+ // ('user'). Entries without `origin` (in-memory survivors of a hot reload) are treated as
35
+ // 'user' — we never auto-overwrite a choice we cannot prove was seeded.
36
+ const _byInstance = new Map();
37
+
38
+ let _globalDefaultProvider = null;
39
+ // Returns { main, roles } used to SEED a fresh session's binding — the workspace-effective
40
+ // main (getActiveProfileId: workspace override > profile.json.active) and the workspace's
41
+ // stored role assignments, so a seeded session matches the legacy behavior exactly (same
42
+ // upstream as an unbound request AND the same sub/teammate routing).
43
+ let _seedProvider = null;
44
+
45
+ export function isValidInstanceKey(key) {
46
+ return typeof key === 'string' && INSTANCE_KEY_RE.test(key);
47
+ }
48
+
49
+ // interceptor registers the live global-default reader (profile.json.active) here so
50
+ // seeding can resolve the default without this module importing interceptor (L2).
51
+ export function registerGlobalDefaultProvider(fn) {
52
+ _globalDefaultProvider = typeof fn === 'function' ? fn : null;
53
+ }
54
+
55
+ // interceptor registers the workspace-effective seed reader ({ main, roles }).
56
+ export function registerSeedProvider(fn) {
57
+ _seedProvider = typeof fn === 'function' ? fn : null;
58
+ }
59
+
60
+ // The global default profile id: the registered provider first (live value), then a
61
+ // one-off disk read of profile.json.active (so sdk-manager tests / early boot that
62
+ // haven't registered a provider still resolve), then 'max'.
63
+ export function getGlobalDefaultProfileId() {
64
+ if (_globalDefaultProvider) {
65
+ try {
66
+ const v = _globalDefaultProvider();
67
+ if (typeof v === 'string' && v) return v;
68
+ } catch (err) {
69
+ reportSwallowed('proxy-session-registry.defaultProvider', err);
70
+ }
71
+ }
72
+ try {
73
+ const data = JSON.parse(readFileSync(join(LOG_DIR, 'profile.json'), 'utf8'));
74
+ if (typeof data?.active === 'string' && data.active) return data.active;
75
+ } catch { /* missing/corrupt profile.json → fall through to 'max' */ }
76
+ return 'max';
77
+ }
78
+
79
+ // The seed { main, roles } for a fresh session: the registered seed provider first;
80
+ // falls back to the global default main with follow/follow roles.
81
+ function _seedValue() {
82
+ if (_seedProvider) {
83
+ try {
84
+ const v = _seedProvider();
85
+ if (v && typeof v === 'object' && typeof v.main === 'string' && v.main) {
86
+ return {
87
+ main: v.main,
88
+ roles: {
89
+ subagent: typeof v.roles?.subagent === 'string' && v.roles.subagent ? v.roles.subagent : 'follow',
90
+ teammate: typeof v.roles?.teammate === 'string' && v.roles.teammate ? v.roles.teammate : 'follow',
91
+ },
92
+ };
93
+ }
94
+ } catch (err) {
95
+ reportSwallowed('proxy-session-registry.seedProvider', err);
96
+ }
97
+ }
98
+ return { main: getGlobalDefaultProfileId(), roles: { subagent: 'follow', teammate: 'follow' } };
99
+ }
100
+
101
+ export function getSessionProxy(instanceKey) {
102
+ if (!isValidInstanceKey(instanceKey)) return undefined;
103
+ return _byInstance.get(instanceKey);
104
+ }
105
+
106
+ // Normalize a { main, roles } payload into the stored shape. 'max' is a valid explicit
107
+ // Default for main and for each role; unknown/invalid values fall back to the global
108
+ // default main and follow/follow roles.
109
+ function _normalizeBinding({ main, roles } = {}) {
110
+ return {
111
+ main: typeof main === 'string' && main ? main : getGlobalDefaultProfileId(),
112
+ roles: {
113
+ subagent: typeof roles?.subagent === 'string' && roles.subagent ? roles.subagent : 'follow',
114
+ teammate: typeof roles?.teammate === 'string' && roles.teammate ? roles.teammate : 'follow',
115
+ },
116
+ };
117
+ }
118
+
119
+ // Validate + FIFO-evict + write. `origin` records the caller's intent ('user' vs 'seed');
120
+ // `workspace` is stored only for seed bindings so a later workspace change can be scoped
121
+ // to the sessions that belong to it.
122
+ function _writeBinding(instanceKey, value, origin, workspace) {
123
+ if (!isValidInstanceKey(instanceKey)) return false;
124
+ const binding = { ..._normalizeBinding(value), origin };
125
+ if (origin === 'seed' && typeof workspace === 'string' && workspace) binding.workspace = workspace;
126
+ if (_byInstance.size >= MAX_ENTRIES && !_byInstance.has(instanceKey)) {
127
+ // Evict the oldest entry (Map preserves insertion order).
128
+ const oldest = _byInstance.keys().next().value;
129
+ _byInstance.delete(oldest);
130
+ }
131
+ _byInstance.set(instanceKey, binding);
132
+ return true;
133
+ }
134
+
135
+ // Overwrite a session's binding (user-driven change). Once a user has explicitly chosen,
136
+ // the binding is pinned as 'user' and is never auto-overwritten by a workspace change for
137
+ // the life of the session (it is only dropped when the session closes or the process stops).
138
+ export function setSessionProxyProfile(instanceKey, value = {}) {
139
+ return _writeBinding(instanceKey, value, 'user');
140
+ }
141
+
142
+ // Seed a session's binding ONLY when none exists yet (a returning/reattached session
143
+ // must never lose the choice the user already made). Seeds from the workspace-effective
144
+ // main + stored roles (via the seed provider) so a fresh session matches legacy behavior.
145
+ // `workspace` marks the binding as belonging to that workspace so it can be re-aligned
146
+ // when that workspace's active/roles change.
147
+ export function seedSessionProxyProfile(instanceKey, workspace) {
148
+ if (!isValidInstanceKey(instanceKey)) return false;
149
+ if (_byInstance.has(instanceKey)) return false;
150
+ return _writeBinding(instanceKey, _seedValue(), 'seed', workspace);
151
+ }
152
+
153
+ export function isSeedOriginBinding(entry) {
154
+ return !!entry && entry.origin === 'seed';
155
+ }
156
+
157
+ // Re-align seed-origin bindings to the workspace's current { main, roles }. Only entries
158
+ // seeded from a workspace are updated; explicit 'user' choices and provenance-less entries
159
+ // are left untouched. When `workspace` is given, only bindings belonging to it change.
160
+ // `nextSeed.main` is required — a missing/empty main is a no-op (returns 0). Returns the
161
+ // number of bindings updated (for tests/diagnostics). Uses Map.set on an existing key so
162
+ // FIFO insertion order is preserved. Each updated entry gets its own roles copy so a later
163
+ // in-place role edit (pruneSessionProxyProfiles) can never bleed across sibling bindings.
164
+ export function reseedSeedOriginBindings(nextSeed, { workspace } = {}) {
165
+ if (!nextSeed || typeof nextSeed.main !== 'string' || !nextSeed.main) return 0;
166
+ const n = _normalizeBinding(nextSeed);
167
+ let updated = 0;
168
+ for (const [key, entry] of _byInstance) {
169
+ if (!isSeedOriginBinding(entry)) continue;
170
+ if (workspace !== undefined && entry.workspace !== workspace) continue;
171
+ const roles = entry.roles || {};
172
+ if (entry.main === n.main
173
+ && roles.subagent === n.roles.subagent
174
+ && roles.teammate === n.roles.teammate) continue;
175
+ _byInstance.set(key, { ...entry, main: n.main, roles: { ...n.roles } });
176
+ updated++;
177
+ }
178
+ return updated;
179
+ }
180
+
181
+ export function clearSessionProxyProfile(instanceKey) {
182
+ return _byInstance.delete(instanceKey);
183
+ }
184
+
185
+ export function clearSessionProxyProfiles() {
186
+ _byInstance.clear();
187
+ }
188
+
189
+ // A deleted profile must not leave a dangling binding behind: drop mappings whose
190
+ // main (or a role) points at a profile that no longer exists. 'max' and 'follow'
191
+ // are always valid. Resolution also falls back at read time, so this is belt+braces.
192
+ export function pruneSessionProxyProfiles(validIds) {
193
+ if (!(validIds instanceof Set)) return;
194
+ const valid = (id) => id === 'max' || id === 'follow' || validIds.has(id);
195
+ for (const [key, entry] of _byInstance) {
196
+ if (!valid(entry.main)) { _byInstance.delete(key); continue; }
197
+ if (!valid(entry.roles.subagent)) entry.roles.subagent = 'follow';
198
+ if (!valid(entry.roles.teammate)) entry.roles.teammate = 'follow';
199
+ }
200
+ }
201
+
202
+ export function listSessionProxyProfiles() {
203
+ return [..._byInstance.entries()].map(([instanceKey, v]) => ({ instanceKey, ...v }));
204
+ }
205
+
206
+ export function __resetSessionProxyProfilesForTests() {
207
+ _byInstance.clear();
208
+ // NOTE: providers (_globalDefaultProvider / _seedProvider) are owned by the registrar
209
+ // (interceptor) and intentionally NOT cleared here — clearing them would silently
210
+ // degrade later seeds to the disk fallback within the same process.
211
+ }
212
+
213
+ // Insert a raw entry verbatim (e.g. one with no `origin`) to lock down the migration
214
+ // behavior for pre-provenance in-memory bindings.
215
+ export function __putRawEntryForTests(instanceKey, entry) {
216
+ if (!isValidInstanceKey(instanceKey)) return false;
217
+ _byInstance.set(instanceKey, entry);
218
+ return true;
219
+ }