cc-viewer 1.9.36 → 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 (90) hide show
  1. package/README.md +1 -1
  2. package/dist/assets/{App-C_S65Ygt.js → App-C_AI6A4g.js} +2 -2
  3. package/dist/assets/{ArchivePreview-ezRMkut5.js → ArchivePreview-BBXuZnGC.js} +1 -1
  4. package/dist/assets/{AudioPreview-MxQVazDj.js → AudioPreview-BmqzQZGt.js} +1 -1
  5. package/dist/assets/{MdxEditorPanel-CmG2jyvK.js → MdxEditorPanel-BLcS9OVC.js} +1 -1
  6. package/dist/assets/Mobile-4mZy680Y.js +1 -0
  7. package/dist/assets/{Mobile-B5V_-6Hc.css → Mobile-B_8Wt_hT.css} +1 -1
  8. package/dist/assets/ProxyStatsModal-BDLwkqxD.js +1 -0
  9. package/dist/assets/{SubtitlePreview-CHRRgV95.js → SubtitlePreview-ei5OtiKq.js} +1 -1
  10. package/dist/assets/{_baseUniq-ClHxNSma.js → _baseUniq-xRiWMqOw.js} +1 -1
  11. package/dist/assets/{arc-ClGYU-1i.js → arc-edNwlWnI.js} +1 -1
  12. package/dist/assets/{architectureDiagram-Q4EWVU46-El3lNwsp.js → architectureDiagram-Q4EWVU46-SMfdtr57.js} +1 -1
  13. package/dist/assets/{blockDiagram-DXYQGD6D-DH290jST.js → blockDiagram-DXYQGD6D-BxAsQG58.js} +1 -1
  14. package/dist/assets/{c4Diagram-AHTNJAMY-BQMsMwnY.js → c4Diagram-AHTNJAMY-DvEHTYBD.js} +1 -1
  15. package/dist/assets/{channel-C-OnmeWg.js → channel-Ce5Cf3nY.js} +1 -1
  16. package/dist/assets/{chunk-4BX2VUAB-PRxJ3zS8.js → chunk-4BX2VUAB--OnGvs-9.js} +1 -1
  17. package/dist/assets/{chunk-4TB4RGXK-C_TKsRMW.js → chunk-4TB4RGXK-MSrYeKo5.js} +1 -1
  18. package/dist/assets/{chunk-55IACEB6-nGpnU7E4.js → chunk-55IACEB6-CD4rh-7b.js} +1 -1
  19. package/dist/assets/{chunk-EDXVE4YY-D0-9hlXC.js → chunk-EDXVE4YY-CrAxlPfF.js} +1 -1
  20. package/dist/assets/{chunk-FMBD7UC4-hKmwmsrB.js → chunk-FMBD7UC4-CMb4qB5t.js} +1 -1
  21. package/dist/assets/{chunk-OYMX7WX6-CZnR4qSn.js → chunk-OYMX7WX6-CEP3GJND.js} +1 -1
  22. package/dist/assets/{chunk-QZHKN3VN-CGtdnavD.js → chunk-QZHKN3VN-Xko480I7.js} +1 -1
  23. package/dist/assets/{chunk-YZCP3GAM-GPB3qNXk.js → chunk-YZCP3GAM-xKPv2jAr.js} +1 -1
  24. package/dist/assets/classDiagram-6PBFFD2Q-CAw9u3mr.js +1 -0
  25. package/dist/assets/classDiagram-v2-HSJHXN6E-CAw9u3mr.js +1 -0
  26. package/dist/assets/clone-CW1SPXDP.js +1 -0
  27. package/dist/assets/{cose-bilkent-S5V4N54A-9L57MjYD.js → cose-bilkent-S5V4N54A-Dd5Fpol9.js} +1 -1
  28. package/dist/assets/{dagre-KV5264BT-CNkz8gO7.js → dagre-KV5264BT-BH00hKa4.js} +1 -1
  29. package/dist/assets/{diagram-5BDNPKRD-DQBFzIFl.js → diagram-5BDNPKRD-BJZlGmRA.js} +1 -1
  30. package/dist/assets/{diagram-G4DWMVQ6-CTwwGTIV.js → diagram-G4DWMVQ6-BTj-YG-C.js} +1 -1
  31. package/dist/assets/{diagram-MMDJMWI5-BKEsMMNd.js → diagram-MMDJMWI5-2ZD4VZMB.js} +1 -1
  32. package/dist/assets/{diagram-TYMM5635-BgAqGIDJ.js → diagram-TYMM5635-mTEHpW4W.js} +1 -1
  33. package/dist/assets/{erDiagram-SMLLAGMA-BuR-DOkX.js → erDiagram-SMLLAGMA-DTOSCCrk.js} +1 -1
  34. package/dist/assets/{flowDiagram-DWJPFMVM-CtEs3omg.js → flowDiagram-DWJPFMVM-C4ZAoiRL.js} +1 -1
  35. package/dist/assets/{ganttDiagram-T4ZO3ILL-aEyreBxU.js → ganttDiagram-T4ZO3ILL-C56IAugD.js} +1 -1
  36. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B0jK9QeS.js → gitGraphDiagram-UUTBAWPF-fvtnUb6S.js} +1 -1
  37. package/dist/assets/{graph-ehKfRbVz.js → graph-CnqqDZhs.js} +1 -1
  38. package/dist/assets/index-B15ZeDb-.css +1 -0
  39. package/dist/assets/{index-Brys6nSs.js → index-BUkls72j.js} +1 -1
  40. package/dist/assets/{index-CtricoKb.js → index-CEinmFtX.js} +1 -1
  41. package/dist/assets/index-CVnJzK-y.js +2 -0
  42. package/dist/assets/{index-B0uKNGh1.js → index-CcAn_gE2.js} +1 -1
  43. package/dist/assets/{index-Dns_OQOp.js → index-CdN-CkKM.js} +1 -1
  44. package/dist/assets/{index-D5KJq71j.js → index-DjoCHMpJ.js} +1 -1
  45. package/dist/assets/{index-CH6ZHNzo.js → index-Dq3ex7Ip.js} +1 -1
  46. package/dist/assets/{index-BDj-fJNP.js → index-F9AcG6Ef.js} +1 -1
  47. package/dist/assets/{infoDiagram-42DDH7IO-CUntIdK6.js → infoDiagram-42DDH7IO-B-b77lg9.js} +1 -1
  48. package/dist/assets/{ishikawaDiagram-UXIWVN3A-CtCGMBTX.js → ishikawaDiagram-UXIWVN3A-B1ituugL.js} +1 -1
  49. package/dist/assets/{journeyDiagram-VCZTEJTY-DCRvOrOx.js → journeyDiagram-VCZTEJTY-DvFc_1_L.js} +1 -1
  50. package/dist/assets/{jszip.min-DZsXbJ4A.js → jszip.min-Br1yL7Q3.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-jEtOSXmn.js → kanban-definition-6JOO6SKY-B-3zDwdJ.js} +1 -1
  52. package/dist/assets/{layout-C-6TbhHY.js → layout-B8tT3Nrd.js} +1 -1
  53. package/dist/assets/{linear-DQg_Idt4.js → linear-BVxRmpuU.js} +1 -1
  54. package/dist/assets/{mermaid.core-C_rq53MX.js → mermaid.core-TpktUJt6.js} +2 -2
  55. package/dist/assets/{min-BqPulfFi.js → min-4AuCZ0ho.js} +1 -1
  56. package/dist/assets/{mindmap-definition-QFDTVHPH-CNsFBo-7.js → mindmap-definition-QFDTVHPH-MQeup-Jb.js} +1 -1
  57. package/dist/assets/{pieDiagram-DEJITSTG-BDn3Cz--.js → pieDiagram-DEJITSTG-mSFlWRpV.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-34T5L4WZ-CsrLWd-H.js → quadrantDiagram-34T5L4WZ-BE2AHw1J.js} +1 -1
  59. package/dist/assets/{requirementDiagram-MS252O5E-DPzJKSB5.js → requirementDiagram-MS252O5E-CSat0Shv.js} +1 -1
  60. package/dist/assets/{sankeyDiagram-XADWPNL6-DYDGySQ1.js → sankeyDiagram-XADWPNL6-jSfdI1J9.js} +1 -1
  61. package/dist/assets/seqResourceLoaders-BT5ki0J4.js +2 -0
  62. package/dist/assets/{seqResourceLoaders-b9deQDrA.css → seqResourceLoaders-CXgVOdgW.css} +2 -2
  63. package/dist/assets/{sequenceDiagram-FGHM5R23-HVWMhF8a.js → sequenceDiagram-FGHM5R23-n8z9Vixi.js} +1 -1
  64. package/dist/assets/{stateDiagram-FHFEXIEX-BtcEUJOY.js → stateDiagram-FHFEXIEX-Dn_y_D8r.js} +1 -1
  65. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DWDh2D71.js → stateDiagram-v2-QKLJ7IA2-BB1b-66S.js} +1 -1
  66. package/dist/assets/{timeline-definition-GMOUNBTQ-B81djDNu.js → timeline-definition-GMOUNBTQ-Bvy0hn9D.js} +1 -1
  67. package/dist/assets/{vendor-antd-C5Wsfsxn.js → vendor-antd-BciJO790.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-DPXDhteu.js → vendor-codemirror-BVX6n7ix.js} +1 -1
  69. package/dist/assets/{vendor-mdxeditor-DLPCj_fe.js → vendor-mdxeditor-BlcXEhaG.js} +2 -2
  70. package/dist/assets/{vendor-qrcode-BzB5n5mK.js → vendor-qrcode-DVibqC0x.js} +1 -1
  71. package/dist/assets/{vendor-virtuoso-Beq6R5oo.js → vendor-virtuoso-CsBSMJ5R.js} +1 -1
  72. package/dist/assets/{vennDiagram-DHZGUBPP-BeitG2yA.js → vennDiagram-DHZGUBPP-BVqFkdla.js} +1 -1
  73. package/dist/assets/{wardley-RL74JXVD-BCzOL4u_.js → wardley-RL74JXVD-BIAqGP0w.js} +1 -1
  74. package/dist/assets/{wardleyDiagram-NUSXRM2D-20SEChwk.js → wardleyDiagram-NUSXRM2D-DGUvrzIN.js} +1 -1
  75. package/dist/assets/{xychartDiagram-5P7HB3ND-Behle0ry.js → xychartDiagram-5P7HB3ND-BjEJgIoR.js} +1 -1
  76. package/dist/index.html +5 -5
  77. package/package.json +1 -1
  78. package/server/interceptor.js +32 -3
  79. package/server/lib/builtin-model-prompts.js +16 -7
  80. package/server/lib/model-system-prompts.js +207 -13
  81. package/server/lib/proxy-session-registry.js +75 -12
  82. package/server/lib/sdk-manager.js +16 -5
  83. package/dist/assets/Mobile-BerOQqT4.js +0 -1
  84. package/dist/assets/ProxyStatsModal-dqlP2r2c.js +0 -1
  85. package/dist/assets/classDiagram-6PBFFD2Q-DigyQWGQ.js +0 -1
  86. package/dist/assets/classDiagram-v2-HSJHXN6E-DigyQWGQ.js +0 -1
  87. package/dist/assets/clone-DwpJyNdv.js +0 -1
  88. package/dist/assets/index-BLzca-ta.css +0 -1
  89. package/dist/assets/index-DBmXRTLE.js +0 -2
  90. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +0 -2
@@ -15,7 +15,7 @@ import { createHash } from 'node:crypto';
15
15
  import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
16
  import { tmpdir } from 'node:os';
17
17
  import { join } from 'node:path';
18
- import { expandModelIdVariants, normalizeModelName } from './model-system-prompts.js';
18
+ import { expandModelIdVariants, normalizeModelName, modelIdTokens, modelIdSegments, matchSegments, collectSegmentHits, segmentHitRank, substringHits } from './model-system-prompts.js';
19
19
  import { listSystemPromptPresets } from './system-prompt-presets.js';
20
20
  import { renameSyncWithRetry } from './file-api.js';
21
21
  import { reportSwallowed } from '../lib/error-report.js';
@@ -63,6 +63,9 @@ export function listBuiltinModelPrompts() {
63
63
  name,
64
64
  mode: p.defaultMode === 'override' ? 'override' : 'append',
65
65
  matchLower: p.match.toLowerCase(),
66
+ // 预计算段,供 matchBuiltinModelPrompt 复用(避免每次匹配重算)。
67
+ // Precomputed segments, reused by the matcher to avoid re-tokenizing per call.
68
+ segs: modelIdSegments(modelIdTokens(p.match.toLowerCase())),
66
69
  text: p.text,
67
70
  });
68
71
  }
@@ -70,10 +73,11 @@ export function listBuiltinModelPrompts() {
70
73
  }
71
74
 
72
75
  /**
73
- * 按 modelId 匹配内置条目:别名展开(expandModelIdVariants,先 lowercase)后任一变体
74
- * 包含 preset 的 match 即命中;多命中取 match 最长者、等长字典序(对齐 matchModelPrompt
75
- * 的消歧规则)。
76
- * Match a model id against built-in entries (alias-expanded substring, longest wins).
76
+ * 按 modelId 匹配内置条目:别名展开(expandModelIdVariants,先 lowercase)后切段,
77
+ * 与用户层同一套段匹配(ident 锁家族、版本排序消歧不否决);段匹配全 miss 时与用户层
78
+ * 同样回退旧子串(vendor 前缀可能与家族同名、锚错起点时子串仍能救回,两层保持同语义)。
79
+ * 多命中按「版本贴近度 > 段数多 > 名字长 > 精确 > 字典序」消歧(复用 segmentHitRank)。
80
+ * Match a model id against built-in entries (segment match + shared substring fallback).
77
81
  *
78
82
  * @param {string|null} modelId
79
83
  * @returns {{ id: string, name: string, mode: 'override'|'append', text: string } | null}
@@ -81,9 +85,14 @@ export function listBuiltinModelPrompts() {
81
85
  export function matchBuiltinModelPrompt(modelId) {
82
86
  const variants = expandModelIdVariants(modelId);
83
87
  if (!variants.length) return null;
84
- const hits = listBuiltinModelPrompts().filter((e) => variants.some((v) => v.includes(e.matchLower)));
88
+ const idSegsList = variants.map((v) => modelIdSegments(modelIdTokens(v)));
89
+ const entries = listBuiltinModelPrompts();
90
+ // 主路径:段匹配(与用户层同一套 collectSegmentHits + segmentHitRank)。
91
+ let hits = collectSegmentHits(entries, idSegsList, (e) => e.segs);
92
+ // 兜底:段匹配全 miss 时回退旧子串(与用户层同语义)。
93
+ if (!hits.length) hits = substringHits(variants, entries);
85
94
  if (!hits.length) return null;
86
- hits.sort((a, b) => b.matchLower.length - a.matchLower.length || a.name.localeCompare(b.name));
95
+ hits.sort(segmentHitRank);
87
96
  const e = hits[0];
88
97
  return { id: e.id, name: e.name, mode: e.mode, text: e.text };
89
98
  }
@@ -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];
@@ -1,6 +1,6 @@
1
1
  // Per-session (per SDK instance) proxy binding. Maps an SDK instanceKey to the
2
- // session's proxy choice ({ main, roles }) so one session's proxy change never
3
- // leaks into another session sharing the same ccv process.
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
4
  //
5
5
  // This is intentionally process-local and IN-MEMORY ONLY: bindings are seeded when
6
6
  // a session is registered/activated and dropped when it closes or the process stops.
@@ -19,10 +19,20 @@ import { reportSwallowed } from './error-report.js';
19
19
  const INSTANCE_KEY_RE = /^ccv-[0-9a-f]+$/;
20
20
  const MAX_ENTRIES = 1024; // defensive cap: an unbounded map would be a slow leak
21
21
 
22
- // instanceKey -> { main: profileId|'max', roles: { subagent, teammate } }
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
+ // }
23
28
  // 'max' is the explicit "Default" (no rewrite) value and MUST be stored verbatim —
24
29
  // an absent mapping means "not bound" (fall back to the process-global profile),
25
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.
26
36
  const _byInstance = new Map();
27
37
 
28
38
  let _globalDefaultProvider = null;
@@ -93,34 +103,79 @@ export function getSessionProxy(instanceKey) {
93
103
  return _byInstance.get(instanceKey);
94
104
  }
95
105
 
96
- // Overwrite a session's binding (user-driven change). Unknown keys are dropped;
97
- // 'max' is a valid explicit Default for main and for each role.
98
- export function setSessionProxyProfile(instanceKey, { main, roles } = {}) {
99
- if (!isValidInstanceKey(instanceKey)) return false;
100
- const entry = {
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 {
101
111
  main: typeof main === 'string' && main ? main : getGlobalDefaultProfileId(),
102
112
  roles: {
103
113
  subagent: typeof roles?.subagent === 'string' && roles.subagent ? roles.subagent : 'follow',
104
114
  teammate: typeof roles?.teammate === 'string' && roles.teammate ? roles.teammate : 'follow',
105
115
  },
106
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;
107
126
  if (_byInstance.size >= MAX_ENTRIES && !_byInstance.has(instanceKey)) {
108
127
  // Evict the oldest entry (Map preserves insertion order).
109
128
  const oldest = _byInstance.keys().next().value;
110
129
  _byInstance.delete(oldest);
111
130
  }
112
- _byInstance.set(instanceKey, entry);
131
+ _byInstance.set(instanceKey, binding);
113
132
  return true;
114
133
  }
115
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
+
116
142
  // Seed a session's binding ONLY when none exists yet (a returning/reattached session
117
143
  // must never lose the choice the user already made). Seeds from the workspace-effective
118
144
  // main + stored roles (via the seed provider) so a fresh session matches legacy behavior.
119
- export function seedSessionProxyProfile(instanceKey) {
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) {
120
148
  if (!isValidInstanceKey(instanceKey)) return false;
121
149
  if (_byInstance.has(instanceKey)) return false;
122
- const seed = _seedValue();
123
- return setSessionProxyProfile(instanceKey, { main: seed.main, roles: seed.roles });
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;
124
179
  }
125
180
 
126
181
  export function clearSessionProxyProfile(instanceKey) {
@@ -154,3 +209,11 @@ export function __resetSessionProxyProfilesForTests() {
154
209
  // (interceptor) and intentionally NOT cleared here — clearing them would silently
155
210
  // degrade later seeds to the disk fallback within the same process.
156
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
+ }
@@ -3172,6 +3172,19 @@ export function __isEphemeralHostForTests(cwd) {
3172
3172
  return false;
3173
3173
  }
3174
3174
 
3175
+ // Seed the per-session proxy binding for a session (no-op when already bound, so a
3176
+ // re-init/attach never clobbers a user's choice). The seed VALUE comes from the registry's
3177
+ // provider (the currently-bound workspace's effective active/roles); the WORKSPACE tag comes
3178
+ // from the session's own cwd, so a later change to that workspace can re-align the binding.
3179
+ // Known limitation: when a session whose cwd ≠ the currently-bound workspace is seeded
3180
+ // (e.g. attaching a session from another workspace, or IM-SDK mode where cwd is LOG_DIR/IM_*),
3181
+ // the value reflects the bound workspace while the tag is the session's own — it self-heals
3182
+ // the next time that workspace is activated (initForWorkspace → reconcile).
3183
+ function _seedProxyBindingForSession(sess) {
3184
+ if (!sess || !sess.instanceKey) return;
3185
+ seedSessionProxyProfile(sess.instanceKey, projectKeyForCwd(sess.cwd));
3186
+ }
3187
+
3175
3188
  /**
3176
3189
  * Initialize (or re-initialize) a workspace's SDK session.
3177
3190
  * Does NOT start a query — waits for the first user message via sendUserMessage().
@@ -3222,9 +3235,7 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3222
3235
  const sess = _getOrCreateSession(cwd);
3223
3236
  sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir });
3224
3237
  _activeKey = sess.instanceKey;
3225
- // Seed the per-session proxy binding from the global default (no-op when the
3226
- // session is already bound, so a re-init never clobbers a user's choice).
3227
- seedSessionProxyProfile(sess.instanceKey);
3238
+ _seedProxyBindingForSession(sess);
3228
3239
  }
3229
3240
 
3230
3241
  /**
@@ -3268,7 +3279,7 @@ export function createSdkSession(cwd, cfg) {
3268
3279
  sess._markFreshLaunch();
3269
3280
  _adoptProcessWiring();
3270
3281
  _activeKey = sess.instanceKey;
3271
- seedSessionProxyProfile(sess.instanceKey);
3282
+ _seedProxyBindingForSession(sess);
3272
3283
  return { instanceKey: sess.instanceKey };
3273
3284
  }
3274
3285
 
@@ -3496,7 +3507,7 @@ export function attachSdkSession(anchor) {
3496
3507
  _activeKey = sess.instanceKey;
3497
3508
  // Activating a session binds its proxy (seeded from the global default when the
3498
3509
  // session predates the mapping or its binding was cleared).
3499
- seedSessionProxyProfile(sess.instanceKey);
3510
+ _seedProxyBindingForSession(sess);
3500
3511
  return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
3501
3512
  }
3502
3513