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
@@ -14,7 +14,8 @@ import { homedir } from 'node:os';
14
14
  import { fileURLToPath, pathToFileURL } from 'node:url';
15
15
  import { dirname, join, basename } from 'node:path';
16
16
  import { LOG_DIR } from '../findcc.js';
17
- import { assembleStreamMessage, createStreamAssembler, isAnthropicApiPath, isMainAgentRequest, replaceTopLevelModel, replaceTopLevelSystem, injectOutputConfigEffort, resolveProfileModel, extractAgentSpawnPairs, classifyProxyRole, resolveRoleProfile, normalizeRoles, mergeActivePayload } from './lib/interceptor-core.js';
17
+ import { assembleStreamMessage, createStreamAssembler, isAnthropicApiPath, isMainAgentRequest, replaceTopLevelModel, replaceTopLevelSystem, injectOutputConfigEffort, resolveProfileModel, extractAgentSpawnPairs, classifyProxyRole, resolveRoleProfile, resolveSessionMainProfile, resolveSessionRoleProfile, normalizeRoles, mergeActivePayload } from './lib/interceptor-core.js';
18
+ import { registerGlobalDefaultProvider, registerSeedProvider, getSessionProxy, reseedSeedOriginBindings } from './lib/proxy-session-registry.js';
18
19
  import { V2Writer } from './lib/v2/v2-writer.js';
19
20
  import { reportSwallowed } from './lib/error-report.js';
20
21
  import { latestMainSessionDir, sessionHasMainTurn, sessionHasCompletedMainTurn } from './lib/v2/session-select.js';
@@ -247,6 +248,9 @@ let _activeProfile = null; // { id, name, baseURL?, apiKey?, effort?, ANTHROPIC_
247
248
  // Per-role state (STORED values, never dormancy-adjusted — dormancy is enforced per request):
248
249
  let _roleIds = normalizeRoles(undefined); // { subagent, teammate }
249
250
  let _profilesById = new Map(); // id → profile object from profile.json
251
+ // Global default (profile.json.active) mirrored for the session registry's seed
252
+ // fallback. Independent of _activeProfile (which is workspace-override-first).
253
+ let _globalDefaultId = 'max';
250
254
 
251
255
  // proxy 属主进程(ccv run / runCliMode / Electron mgmt+tab-worker)同样参与角色分流:
252
256
  // proxy.js 在 body 缓冲后按角色选上游 + 供重试引擎做模型替换,本 hook 对 trace 请求
@@ -285,7 +289,7 @@ function _getActiveProfileFilePath() {
285
289
 
286
290
  function _readWorkspaceActive() {
287
291
  const p = _getActiveProfileFilePath();
288
- const empty = { activeId: null, roles: normalizeRoles(undefined) };
292
+ const empty = { activeId: null, roles: normalizeRoles(undefined), unreadable: false };
289
293
  if (!p) return empty;
290
294
  try {
291
295
  if (existsSync(p)) {
@@ -293,11 +297,14 @@ function _readWorkspaceActive() {
293
297
  return {
294
298
  activeId: typeof data?.activeId === 'string' ? data.activeId : null,
295
299
  roles: normalizeRoles(data?.roles),
300
+ unreadable: false,
296
301
  };
297
302
  }
298
303
  } catch (err) {
299
- // 损坏的工作区文件会把 active/roles 静默回落默认 —— 属"丢数据"级,必须记账(有节流)
304
+ // 损坏的工作区文件会把 active/roles 静默回落默认 —— 属"丢数据"级,必须记账(有节流)。
305
+ // 标记 unreadable=true 让重算跳过(避免把 seed 绑定误降级为全局默认后又 flap 回来)。
300
306
  reportSwallowed('proxy-profile.workspace-read', err);
307
+ return { ...empty, unreadable: true };
301
308
  }
302
309
  return empty;
303
310
  }
@@ -398,14 +405,23 @@ function _loadProxyProfile() {
398
405
  profiles.push({ ...p, apiKey });
399
406
  }
400
407
  _profilesById = new Map(profiles.map(p => [p.id, p]));
408
+ _globalDefaultId = (typeof data.active === 'string' && data.active) ? data.active : 'max';
401
409
  // active 解析优先级:workspace override > profile.json.active (兼容老数据 / 全局回退) > null
402
410
  const ws = _readWorkspaceActive();
403
411
  _roleIds = ws.roles;
404
412
  const activeId = ws.activeId || data.active;
405
413
  const active = profiles.find(p => p.id === activeId);
406
414
  _activeProfile = (active && active.id !== 'max') ? active : null;
415
+ // Re-align seed-origin session bindings with the workspace's just-loaded active/roles.
416
+ // Runs on every successful load — setActiveProfileForWorkspace, both watchFile callbacks,
417
+ // and initForWorkspace/resetWorkspace re-arms all converge here, so no separate trigger is
418
+ // needed. Skip on the catch path (a corrupt profile.json is fail-closed) and when the
419
+ // workspace file itself is unreadable — re-seeding to the global default in either case
420
+ // would just downgrade the bindings and flap back once the file recovers.
421
+ if (!ws.unreadable) _reconcileSeedBindings(activeId);
407
422
  } catch (err) {
408
423
  _activeProfile = null;
424
+ _globalDefaultId = 'max';
409
425
  _roleIds = normalizeRoles(undefined);
410
426
  _profilesById = new Map();
411
427
  if (process.env.CCV_DEBUG_HOTSWITCH) {
@@ -414,6 +430,25 @@ function _loadProxyProfile() {
414
430
  }
415
431
  }
416
432
 
433
+ // Re-align seed-origin session bindings with the current workspace's active/roles after a
434
+ // successful (re)load. Only bindings auto-seeded from THIS workspace are updated — explicit
435
+ // user choices (origin 'user') are never overwritten. Scoped by _projectName so a workspace
436
+ // switch never rewrites sessions that belong to a different workspace; skipped entirely when
437
+ // no workspace is bound (resetWorkspace / pre-selection). By design (reviewed), only the
438
+ // currently-bound workspace reconciles in real time — a seed binding for another live
439
+ // workspace converges when that workspace is next activated (initForWorkspace → this path).
440
+ function _reconcileSeedBindings(activeId) {
441
+ if (!_projectName) return;
442
+ try {
443
+ reseedSeedOriginBindings(
444
+ { main: (typeof activeId === 'string' && activeId) ? activeId : 'max', roles: _roleIds },
445
+ { workspace: _projectName },
446
+ );
447
+ } catch (err) {
448
+ reportSwallowed('proxy-profile.reseed-session-bindings', err);
449
+ }
450
+ }
451
+
417
452
  // 为 server.js::POST /api/proxy-profiles 使用,切换当前 workspace 的 active / roles。
418
453
  // 合并语义:activeId 或 roles 传 undefined = 保留文件现值(只改角色不动 main,反之亦然)。
419
454
  // activeId 有参时同时写两个位置,彼此互为兜底:
@@ -495,31 +530,54 @@ export function isOfficialDefaultEndpoint() {
495
530
  return !CUSTOM_API_HOST || /(^|\.)anthropic\.com$/i.test(CUSTOM_API_HOST);
496
531
  }
497
532
 
533
+ // Per-session main profile: fold the session binding (instanceKey) on top of the
534
+ // process-global _activeProfile. An unbound session returns _activeProfile unchanged.
535
+ function _mainProfileForInstance(instanceKey) {
536
+ if (typeof instanceKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instanceKey)) return _activeProfile;
537
+ return resolveSessionMainProfile(getSessionProxy(instanceKey), _profilesById, _activeProfile);
538
+ }
539
+
540
+ // proxy.js 消费方:当前生效的 main profile(可按 instanceKey 覆盖)。
541
+ function getEffectiveMainProfile(instanceKey) {
542
+ return _mainProfileForInstance(instanceKey);
543
+ }
544
+
545
+ // 全局默认(profile.json.active),供「设为全局默认」/ 新会话 seed 的 UI 回显。
546
+ function getGlobalDefaultProfileId() {
547
+ return _globalDefaultId;
548
+ }
549
+
498
550
  // 请求时的有效角色 profile(含休眠强制)。休眠规则:main=Default(无改写)且端点为官方时,
499
- // 存储的 sub/teammate 分配不生效(Max 订阅保护;main 切走后原样恢复)。
500
- function _effectiveRoleProfile(role) {
501
- const p = resolveRoleProfile(role, _roleIds, _profilesById, _activeProfile);
502
- if (role !== 'main' && !_activeProfile && isOfficialDefaultEndpoint()) return null;
551
+ // 存储的 sub/teammate 分配不生效(Max 订阅保护;main 切走后原样恢复)。按会话 main 判定。
552
+ function _effectiveRoleProfile(role, instanceKey) {
553
+ const main = _mainProfileForInstance(instanceKey);
554
+ const p = resolveSessionRoleProfile(role, getSessionProxy(instanceKey), _profilesById, _activeProfile, _roleIds);
555
+ if (role !== 'main' && !main && isOfficialDefaultEndpoint()) return null;
503
556
  return p;
504
557
  }
505
558
 
506
559
  // proxy.js 消费方:属主进程在 body 缓冲后按角色选上游,与 hook 的改写保持同一解析路径。
507
- function getEffectiveRoleProfile(role) {
508
- return _effectiveRoleProfile(role);
560
+ function getEffectiveRoleProfile(role, instanceKey) {
561
+ return _effectiveRoleProfile(role, instanceKey);
509
562
  }
510
563
 
511
564
  // proxy.js 分类短路用:存在显式角色分配(非 follow)才值得在属主进程解析 body 分类——
512
- // 无分配时任意角色都解析到 main 活跃 profile,分类不影响选路。
513
- function hasExplicitRoleAssignments() {
514
- return _roleIds.subagent !== 'follow' || _roleIds.teammate !== 'follow';
565
+ // 无分配时任意角色都解析到 main 活跃 profile,分类不影响选路。会话绑定也算"有分配"。
566
+ // (只判 roles:会话 main 与全局默认的差异已由 getEffectiveMainProfile 在选路/改写两端
567
+ // 直接处理,不需要为此对每个 LLM 请求做 body 分类解析。)
568
+ function hasExplicitRoleAssignments(instanceKey) {
569
+ if (_roleIds.subagent !== 'follow' || _roleIds.teammate !== 'follow') return true;
570
+ const sess = typeof instanceKey === 'string' ? getSessionProxy(instanceKey) : undefined;
571
+ if (!sess) return false;
572
+ return sess.roles.subagent !== 'follow' || sess.roles.teammate !== 'follow';
515
573
  }
516
574
 
517
- // 测试用:当前各角色的有效 profile(main 恒为 _activeProfile)。
518
- function getProxyRoleProfiles() {
575
+ // 测试用:当前各角色的有效 profile(main 恒为会话/全局 main)。
576
+ function getProxyRoleProfiles(instanceKey) {
519
577
  return {
520
- main: _activeProfile,
521
- subagent: _effectiveRoleProfile('subagent'),
522
- teammate: _effectiveRoleProfile('teammate'),
578
+ main: _mainProfileForInstance(instanceKey),
579
+ subagent: _effectiveRoleProfile('subagent', instanceKey),
580
+ teammate: _effectiveRoleProfile('teammate', instanceKey),
523
581
  };
524
582
  }
525
583
 
@@ -560,7 +618,7 @@ function _replaceProxyAuthHeaders(headers, apiKey) {
560
618
  return { headers: newHeaders, matchedAuthKey, matchedXApiKey };
561
619
  }
562
620
 
563
- export { _activeProfile, _defaultConfig, _loadProxyProfile, PROFILE_PATH, setActiveProfileForWorkspace, getActiveProfileId, getStoredRoles, getProxyRoleProfiles, getEffectiveRoleProfile, hasExplicitRoleAssignments, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState };
621
+ export { _activeProfile, _defaultConfig, _loadProxyProfile, PROFILE_PATH, setActiveProfileForWorkspace, getActiveProfileId, getStoredRoles, getProxyRoleProfiles, getEffectiveRoleProfile, getEffectiveMainProfile, getGlobalDefaultProfileId, hasExplicitRoleAssignments, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState };
564
622
 
565
623
  // 1.7.0: the v1 single-file write path is retired — logs live in per-session
566
624
  // v2 dirs owned by V2Writer. Only the project binding (name + dir) remains
@@ -867,6 +925,14 @@ _syncContinuationMode(); // seed from the CLI env at module load (`ccv -c`)
867
925
  _loadProxyProfile();
868
926
  try { watchFile(PROFILE_PATH, { interval: 1500 }, _loadProxyProfile); } catch { }
869
927
  _armWorkspaceActiveWatcher();
928
+ // Let the per-session registry resolve the global default (profile.json.active) from the
929
+ // live value instead of re-reading disk on every session seed.
930
+ registerGlobalDefaultProvider(() => _globalDefaultId);
931
+ // Seed a fresh session with the WORKSPACE-EFFECTIVE main (getActiveProfileId: workspace
932
+ // override > profile.json.active) and the workspace's stored role assignments — so a
933
+ // seeded session matches the legacy behavior (same upstream AND same role routing as an
934
+ // unbound request), instead of silently dropping pre-existing role assignments.
935
+ registerSeedProvider(() => ({ main: getActiveProfileId(), roles: { ..._roleIds } }));
870
936
 
871
937
  // Retry config: initial load + watchFile cross-process sync (UI writes
872
938
  // retry-config.json → hot-reloaded within 1.5s, mirroring PROFILE_PATH above).
@@ -1261,8 +1327,13 @@ export function setupInterceptor() {
1261
1327
  // 仅当「确实无需分类」(无 profile + 无角色分配 + live 未启用)才短路。
1262
1328
  let _fetchUrl = url;
1263
1329
  let _fetchOpts = options;
1264
- const _skipClassify = !_activeProfile && _roleIds.subagent === 'follow' && _roleIds.teammate === 'follow'
1265
- && !liveSystemPromptEnabled();
1330
+ // Per-session override: the spawned claude self-reports its instanceKey via
1331
+ // x-ccv-instance (validated into requestEntry._ccvInstance upstream). When this
1332
+ // request belongs to a bound session, its proxy choice overrides the global one.
1333
+ const _ccvInstance = requestEntry?._ccvInstance;
1334
+ const _reqMain = _mainProfileForInstance(_ccvInstance);
1335
+ const _skipClassify = !_reqMain && _roleIds.subagent === 'follow' && _roleIds.teammate === 'follow'
1336
+ && !liveSystemPromptEnabled() && !hasExplicitRoleAssignments(_ccvInstance);
1266
1337
  // 最高优先级硬判据(review 第二轮二次验证 P1-1 残余,与 contentFilter.js:158 同构):
1267
1338
  // 请求头 x-claude-code-agent-id 是 SDK 命名队友(name@…)/ 匿名子代理(hex)的判别信号,
1268
1339
  // 不依赖 system 文本 —— body 正则(TEAMMATE_SYSTEM_RE / cc_is_subagent)对「SDK 身份行 +
@@ -1282,7 +1353,7 @@ export function setupInterceptor() {
1282
1353
  isHeartbeat: !!requestEntry?.isHeartbeat,
1283
1354
  });
1284
1355
  }
1285
- const _effProfile = _effectiveRoleProfile(_proxyRole);
1356
+ const _effProfile = _effectiveRoleProfile(_proxyRole, _ccvInstance);
1286
1357
  // 生效模型解析提到块外:live system 改写(步骤 3.5)需要在无 baseURL 的纯模型
1287
1358
  // profile 下也能拿到目标模型;_targetModel 为 null 时回落到请求自身的 model。
1288
1359
  const _rb0 = requestEntry?.body;
@@ -0,0 +1,147 @@
1
+ // Placeholder ANTHROPIC_API_KEY injection for spawned claude child processes.
2
+ //
3
+ // Root cause: Claude Code 2.1.x in interactive (non-print) mode runs an "unauthenticated
4
+ // connectivity check" at startup when the process carries no credential at all (no OAuth
5
+ // login state, no ANTHROPIC_AUTH_TOKEN, no ANTHROPIC_API_KEY), and judges the probe harshly —
6
+ // failing it prints "Not logged in / Please run /login" (or a connectivity error) and exits.
7
+ // In cc-viewer the real credential is injected by the proxy layer at forward time (the active
8
+ // proxy profile's apiKey is decrypted from the credential vault and written into the outgoing
9
+ // headers), so the spawned claude process itself holds no credential — which makes this startup
10
+ // check fire 100% of the time in CLI/SDK modes.
11
+ //
12
+ // Fix: when the user has not explicitly provided a credential via env, inject a placeholder
13
+ // ANTHROPIC_API_KEY so claude skips the unauthenticated check. The real credential is still
14
+ // injected by the proxy layer; the placeholder in outgoing requests is stripped/overwritten
15
+ // there, so it never pollutes the upstream API. We never overwrite a user-supplied
16
+ // ANTHROPIC_AUTH_TOKEN / ANTHROPIC_API_KEY.
17
+ //
18
+ // Why ANTHROPIC_API_KEY and not ANTHROPIC_AUTH_TOKEN (double-source warning): claude 2.1.199
19
+ // warns "Both ANTHROPIC_AUTH_TOKEN and /login managed key set" when an env token source and an
20
+ // apiKey source are both non-none at the same time. Injecting ANTHROPIC_API_KEY keeps a single
21
+ // source and avoids that banner.
22
+ //
23
+ // Hard constraint: the placeholder value must appear in
24
+ // ~/.claude.json:customApiKeyResponses.approved — in interactive TUI mode claude only silently
25
+ // accepts an ANTHROPIC_API_KEY that is in `approved` (otherwise it shows a custom-API-key
26
+ // confirmation dialog). So the placeholder value here and the value ensureApiKeyApproved writes
27
+ // must be byte-identical; both share this module's CCV_API_KEY_PLACEHOLDER.
28
+ //
29
+ // Known trade-off: the placeholder is only safe when the proxy layer rewrites auth. With no
30
+ // proxy profile configured (direct api.anthropic.com), the proxy does not rewrite auth and the
31
+ // placeholder goes out as-is → 401 on the first /v1/messages (an in-session auth error, not a
32
+ // startup crash). That scenario means the user must supply a real credential anyway; treated as
33
+ // an acceptable improvement (startup crash → in-session auth error), not a regression.
34
+ //
35
+ // The placeholder is a non-secret literal that the claude child (Bash/MCP/hooks) inherits via
36
+ // env — it is only "make claude skip the check", NOT a real credential; never use it as a token
37
+ // in child scripts. Note ANTHROPIC_API_KEY is the default env name every Anthropic SDK reads.
38
+ import { readFileSync, writeFileSync, existsSync, mkdirSync, statSync, unlinkSync } from 'node:fs';
39
+ import { dirname } from 'node:path';
40
+ import { randomBytes } from 'node:crypto';
41
+ import { resolveClaudeJsonPath } from './ensure-hooks.js';
42
+ import { getClaudeConfigDir } from '../../findcc.js';
43
+ import { renameSyncWithRetry } from './file-api.js';
44
+ import { reportSwallowed } from './error-report.js';
45
+
46
+ // The placeholder value. 10 chars: the full string and its slice(-20) truncation both match
47
+ // `approved` either way (the read side compares slice(-20)), so the two semantics agree.
48
+ // Non-secret by design — see the header comment.
49
+ export const CCV_API_KEY_PLACEHOLDER = 'ccv-proxy';
50
+
51
+ /**
52
+ * When env has neither ANTHROPIC_AUTH_TOKEN nor ANTHROPIC_API_KEY, inject the placeholder
53
+ * ANTHROPIC_API_KEY in place. If either is already present (user-supplied), leave it untouched.
54
+ * Both keys are checked and either non-empty one suppresses injection — critical: if the user
55
+ * pre-set a real ANTHROPIC_AUTH_TOKEN, also injecting a placeholder ANTHROPIC_API_KEY would make
56
+ * claude see both an env token source and an env apiKey source (the same double-source warning).
57
+ *
58
+ * Note: OAuth login state (~/.claude/.credentials.json) is intentionally NOT in this env check —
59
+ * even with OAuth present we still inject when env has no token/key. That is the desired behavior:
60
+ * the injection exists to make claude skip its own auth check; the placeholder in outgoing
61
+ * requests is replaced by the proxy layer with the real credential.
62
+ *
63
+ * @param {Record<string, string|undefined>} env child-process env to inject into (mutated)
64
+ * @returns {boolean} true = injected the placeholder this call; false = a credential existed
65
+ */
66
+ export function ensurePlaceholderApiKey(env) {
67
+ if (!env || typeof env !== 'object') return false;
68
+ // Normalize: a whitespace-only credential key is deleted outright. Upstream's credential-source
69
+ // detection keys on "exists / truthy", so a blank string could be read as set → double-source.
70
+ for (const k of ['ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_API_KEY']) {
71
+ if (typeof env[k] === 'string' && env[k].trim() === '') delete env[k];
72
+ }
73
+ const hasToken = typeof env.ANTHROPIC_AUTH_TOKEN === 'string' && env.ANTHROPIC_AUTH_TOKEN.trim() !== '';
74
+ const hasApiKey = typeof env.ANTHROPIC_API_KEY === 'string' && env.ANTHROPIC_API_KEY.trim() !== '';
75
+ if (hasToken || hasApiKey) return false;
76
+ env.ANTHROPIC_API_KEY = CCV_API_KEY_PLACEHOLDER;
77
+ return true;
78
+ }
79
+
80
+ /**
81
+ * Resolve the ANTHROPIC_API_KEY actually in effect for the child env after normalization:
82
+ * the env's own key when non-blank (trimmed), else the placeholder value ensurePlaceholderApiKey
83
+ * would inject. Callers pass this to ensureApiKeyApproved so we approve the key the child truly
84
+ * carries (not the parent process's).
85
+ * @param {Record<string, string|undefined>} env already-normalized child env
86
+ * @returns {string} the effective ANTHROPIC_API_KEY (trimmed, never empty)
87
+ */
88
+ export function resolveEffectiveApiKey(env) {
89
+ const v = env && typeof env === 'object' ? env.ANTHROPIC_API_KEY : undefined;
90
+ return (typeof v === 'string' && v.trim() !== '') ? v.trim() : CCV_API_KEY_PLACEHOLDER;
91
+ }
92
+
93
+ /**
94
+ * Approve the child's effective ANTHROPIC_API_KEY in ~/.claude.json's
95
+ * customApiKeyResponses.approved so interactive TUI mode silently accepts it (no custom-API-key
96
+ * confirmation dialog). Idempotent, never overwrites other entries, atomic write, refuses to
97
+ * write back a corrupt/unreadable file.
98
+ * @param {{ configDir?: string, key?: string }} [opts]
99
+ */
100
+ export function ensureApiKeyApproved({ configDir, key } = {}) {
101
+ try {
102
+ const claudeJsonPath = resolveClaudeJsonPath(configDir || getClaudeConfigDir());
103
+ let claudeJson = null;
104
+ if (existsSync(claudeJsonPath)) {
105
+ try {
106
+ claudeJson = JSON.parse(readFileSync(claudeJsonPath, 'utf-8'));
107
+ if (!claudeJson || typeof claudeJson !== 'object' || Array.isArray(claudeJson)) {
108
+ console.warn(`[cc-viewer] ${claudeJsonPath} is not a JSON object, skipping apiKey approval write`);
109
+ return;
110
+ }
111
+ } catch (err) {
112
+ // P0 safety rule: unreadable/corrupt file → never overwrite.
113
+ console.warn(`[cc-viewer] ${claudeJsonPath} is unreadable/unparseable (${err.message}), skipping apiKey approval write to avoid overwriting user config`);
114
+ return;
115
+ }
116
+ } else {
117
+ claudeJson = {}; // first run: safe to start from empty object
118
+ }
119
+
120
+ const approved = (typeof key === 'string' && key.trim() !== '') ? key.trim() : CCV_API_KEY_PLACEHOLDER;
121
+ // Upstream stores approvals keyed by the key's slice(-20) tail; write both forms defensively
122
+ // is unnecessary — the value is < 20 chars so full == tail. Keep a single canonical entry.
123
+ if (!claudeJson.customApiKeyResponses || typeof claudeJson.customApiKeyResponses !== 'object' || Array.isArray(claudeJson.customApiKeyResponses)) {
124
+ claudeJson.customApiKeyResponses = {};
125
+ }
126
+ const bag = claudeJson.customApiKeyResponses;
127
+ if (!Array.isArray(bag.approved)) bag.approved = [];
128
+ const tail = approved.slice(-20);
129
+ if (bag.approved.includes(tail)) return; // idempotent
130
+
131
+ bag.approved.push(tail);
132
+ // Atomic write: tmp file + rename, preserving original file mode.
133
+ try { mkdirSync(dirname(claudeJsonPath), { recursive: true }); } catch { /* existing dir / home */ }
134
+ const tmpPath = `${claudeJsonPath}.tmp.${process.pid}.${randomBytes(4).toString('hex')}`;
135
+ try {
136
+ let targetMode = 0o600;
137
+ try { targetMode = statSync(claudeJsonPath).mode & 0o777; } catch { /* new file */ }
138
+ writeFileSync(tmpPath, JSON.stringify(claudeJson, null, 2), { encoding: 'utf-8', mode: targetMode });
139
+ renameSyncWithRetry(tmpPath, claudeJsonPath);
140
+ } catch (err) {
141
+ try { if (existsSync(tmpPath)) unlinkSync(tmpPath); } catch { /* ignore */ }
142
+ throw err;
143
+ }
144
+ } catch (err) {
145
+ reportSwallowed('ccv.ensureApiKeyApproved', err);
146
+ }
147
+ }
@@ -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
  }
@@ -1,12 +1,20 @@
1
- // Generic IM bridge orchestrator — platform-agnostic glue between one bound Claude Code PTY
2
- // session and N IM platform adapters (DingTalk, Feishu, …).
1
+ // Generic IM bridge orchestrator — platform-agnostic glue between one bound Claude Code session
2
+ // and N IM platform adapters (DingTalk, Feishu, …).
3
+ //
4
+ // Two worker shapes share this core. PTY workers bind a node-pty `claude` CLI and inject PTY-shaped
5
+ // deps; headless SDK workers (runImSdkMode) bind an Agent SDK session and inject the optional
6
+ // headless deps instead. Each site feature-detects (typeof === 'function') and falls back to PTY:
7
+ // sendPrompt(text, onComplete) — inject the origin-marked prompt (no bracketed-paste framing)
8
+ // interrupt() — interrupt the current turn (replaces writeToPty('\x1b'))
9
+ // isSessionAvailable() — replaces getPtyState().running && getPtyKind()==='claude'
10
+ // getReplyText() — final reply text when there is no transcript_path
3
11
  //
4
12
  // Inbound (IM → session): adapter normalizes its platform event → onInbound(normalized, ackCtx)
5
13
  // → ack immediately → msgId dedup → access control → /stop interrupt OR inject the text as a
6
- // prompt (bracketed paste, ⟦im:<id>⟧ origin marker).
14
+ // prompt (bracketed paste for PTY, plain marked text for SDK, ⟦im:<id>⟧ origin marker).
7
15
  // Outbound (session → IM): on the debounced turn_end, read the Claude session transcript JSONL
8
- // (path forwarded from the Stop hook), assemble the last main-agent text turn, chunk it, and
9
- // push via the owning adapter's sendOne.
16
+ // (PTY: path forwarded from the Stop hook) or getReplyText() (SDK), assemble the last
17
+ // main-agent text turn, chunk it, and push via the owning adapter's sendOne.
10
18
  //
11
19
  // SINGLE SHARED PTY ⇒ SINGLE-FLIGHT INJECTION. Only one adapter may have an injected turn in
12
20
  // flight at a time (`activeInjection`, a core-global). It replaces the per-adapter pendingReply:
@@ -23,6 +31,7 @@ import { existsSync, readFileSync, appendFileSync } from 'node:fs';
23
31
  import { join } from 'node:path';
24
32
  import { LOG_DIR } from '../../../findcc.js';
25
33
  import { t } from '../../i18n.js';
34
+ import { reportSwallowed } from '../error-report.js';
26
35
  import { upsertSender } from './im-senders.js';
27
36
 
28
37
  // ─── tunables (shared across platforms; per-platform rate caps come from adapter.rateLimit) ───
@@ -264,6 +273,12 @@ async function streamTick(inst, since) {
264
273
  }
265
274
  }
266
275
  function armActiveInjection(inst, target, since) {
276
+ // Reset the turn-scoped live text unconditionally at the start of every injection.
277
+ // Previously this only happened on the streaming-card path, so an SDK worker (whose
278
+ // getReplyText falls back to the live text) could leak the PREVIOUS turn's text when
279
+ // the user had no AI-card template configured. PTY workers are unaffected (they read
280
+ // the transcript instead).
281
+ try { inst.bridgeDeps?.resetLiveText?.(); } catch { /* best-effort */ }
267
282
  activeInjection = { platformId: inst.adapter.id, since, target, transcriptPath: null };
268
283
  if (activeInjectionTimer) clearTimeout(activeInjectionTimer);
269
284
  activeInjectionTimer = setTimeout(async () => {
@@ -311,7 +326,7 @@ function armActiveInjection(inst, target, since) {
311
326
  // 同时要求 updateAckCard:能逐字推却无法 finalize 会让卡片永远停在流式中途、停在「生成中」。
312
327
  && typeof inst.adapter.updateAckCard === 'function';
313
328
  if (canStream) {
314
- inst.bridgeDeps.resetLiveText?.();
329
+ // liveText 已在 armActiveInjection 入口无条件 reset(每轮恰好一次),此处不再重复。
315
330
  if (inst.store) inst.store.lastAiCardError = null; // 清上一轮的诊断残留
316
331
  inst._streamPushedLen = 0;
317
332
  inst._streamFrames = 0;
@@ -565,7 +580,13 @@ function handleInboundInner(inst, normalized) {
565
580
  if (!text) return; // non-text messages (image/voice/file) are ignored in v1
566
581
 
567
582
  if (isStopCommand(text)) {
568
- inst.bridgeDeps.writeToPty('\x1b'); // ESC interrupts the current turn (NOT killPty)
583
+ // Headless (SDK) workers interrupt via the SDK; PTY workers send ESC. Both interrupt the
584
+ // current turn (NOT kill the session).
585
+ if (typeof inst.bridgeDeps.interrupt === 'function') {
586
+ try { inst.bridgeDeps.interrupt(); } catch { /* best-effort */ }
587
+ } else {
588
+ inst.bridgeDeps.writeToPty('\x1b'); // ESC interrupts the current turn (NOT killPty)
589
+ }
569
590
  audit(inst, 'stop', { conversationId });
570
591
  const stoppedInst = activeInjection ? instances.get(activeInjection.platformId) : null;
571
592
  const stoppedTarget = activeInjection?.target;
@@ -600,8 +621,12 @@ function drainQueue(inst) {
600
621
  while (inst.queue.length) {
601
622
  if (activeInjection || d.isStreaming()) return; // a turn is in flight (any platform)
602
623
  const item = inst.queue[0];
603
- const st = d.getPtyState();
604
- if (!st.running || d.getPtyKind() !== 'claude') {
624
+ // Availability gate. Headless (SDK) workers report via isSessionAvailable(); PTY workers
625
+ // via getPtyState().running + getPtyKind()==='claude'.
626
+ const available = typeof d.isSessionAvailable === 'function'
627
+ ? d.isSessionAvailable()
628
+ : (() => { const st = d.getPtyState(); return !!(st && st.running) && d.getPtyKind() === 'claude'; })();
629
+ if (!available) {
605
630
  inst.queue.shift();
606
631
  void sendReply(inst, item, tr(inst, 'noSession'));
607
632
  continue;
@@ -624,7 +649,7 @@ function drainQueue(inst) {
624
649
  }
625
650
  inst.queue.shift();
626
651
  const cfg = d.getConfig();
627
- const skipPerm = d.getPtySkipPermissions();
652
+ const skipPerm = typeof d.getPtySkipPermissions === 'function' ? d.getPtySkipPermissions() : false;
628
653
  // 独立 IM worker 模型下,worker 本就以 --dangerously-skip-permissions 自主运行(安全由
629
654
  // 强制 allowlist + PreToolUse 硬拦截 + 注入的 permissions.deny 保证)。因此对 IM worker:
630
655
  // - 不应用 blockOnSkipPermissions(否则 skipPerm 恒真 → 拦下每条消息让机器人彻底失能,
@@ -658,7 +683,7 @@ function drainQueue(inst) {
658
683
  // React to a failed injection (PTY gone/died mid-write → onComplete(false)). Without this the
659
684
  // prompt never submits, no turn_end ever comes, and the slot wedges until the timeout. Only
660
685
  // act if THIS injection still owns the slot (a /stop or timeout may have released it).
661
- d.writeToPtySequential(bracketPasteSubmit(markOrigin(inst.adapter.id, item.senderId, item.content)), (ok) => {
686
+ const onInjected = (ok) => {
662
687
  if (ok) return;
663
688
  if (!activeInjection || activeInjection.platformId !== inst.adapter.id || activeInjection.since !== since) return;
664
689
  audit(inst, 'inject-failed', { conversationId: item.conversationId });
@@ -669,7 +694,12 @@ function drainQueue(inst) {
669
694
  if (!cardUpdated) void sendReply(inst, item, tr(inst, 'injectFailed'));
670
695
  drainAll();
671
696
  })().catch(() => {});
672
- }, { settleMs: 250 });
697
+ };
698
+ // Headless (SDK) workers get the already origin-marked prompt as plain text (no
699
+ // bracketed-paste framing); PTY workers get the framed sequence for the terminal.
700
+ const marked = markOrigin(inst.adapter.id, item.senderId, item.content);
701
+ if (typeof d.sendPrompt === 'function') d.sendPrompt(marked, onInjected);
702
+ else d.writeToPtySequential(bracketPasteSubmit(marked), onInjected, { settleMs: 250 });
673
703
  return; // one at a time; resume on the next turn_end
674
704
  }
675
705
  }
@@ -700,12 +730,22 @@ export async function notifyTurnEnd(sessionId, ts, transcriptPath) {
700
730
  // Keyed on ts, NOT reply text.
701
731
  if (ts && ts === inst.lastRepliedTurnTs) { drainAll(); return; }
702
732
  inst.lastRepliedTurnTs = ts || null;
733
+ // Capture the reply text BEFORE drainAll(): draining re-arms the next queued injection, whose
734
+ // armActiveInjection() unconditionally resets the live text — so reading getReplyText() after
735
+ // drainAll() would lose THIS turn's interceptor live text (and fall back to lastResultText,
736
+ // which an error turn leaves empty). Read first, then resume the queues.
737
+ let text = extractLastAssistantText(transcriptPath);
738
+ // Headless (SDK) workers have no transcript_path — fall back to the dep-provided reply text
739
+ // (interceptor live text preferred, SDK result text as the authoritative fallback).
740
+ if (!text && typeof inst.bridgeDeps?.getReplyText === 'function') {
741
+ try { text = inst.bridgeDeps.getReplyText() || ''; }
742
+ catch (e) { reportSwallowed('im-bridge.getReplyText', e); text = ''; }
743
+ }
744
+ if (!text) text = tr(inst, 'noTextReply');
703
745
  // Resume every platform's queue NOW (the slot is already released). The reply send below is
704
746
  // independent of the single-flight slot, so a slow/rate-limited sendOne must not starve the
705
747
  // other platform's queued prompt behind this await.
706
748
  drainAll();
707
- let text = extractLastAssistantText(transcriptPath);
708
- if (!text) text = tr(inst, 'noTextReply');
709
749
 
710
750
  // Try to update the ack card in-place with the reply. Fall back to sendReply on failure.
711
751
  const handle = await ackP?.catch(() => null);
@@ -841,6 +881,11 @@ export function isBridgeRunning(id) {
841
881
  return !!(inst && inst.running);
842
882
  }
843
883
 
884
+ /** Test seam: read the deps currently registered on a bridge instance (null if none). */
885
+ export function __getBridgeDepsForTests(id) {
886
+ return instances.get(id)?.bridgeDeps ?? null;
887
+ }
888
+
844
889
  export function getBridgeStatus(id) {
845
890
  const inst = instances.get(id);
846
891
  if (!inst) return { running: false, connected: false, connectionState: 'disconnected', lastError: null, boundConversationId: null };
@@ -0,0 +1,48 @@
1
+ // IM worker 的 permissions.deny 防御层(PTY 与 SDK 两条启动路径共用)。
2
+ //
3
+ // IM worker 恒以 skip-permissions / bypassPermissions 运行,权限安全由三层组成:
4
+ // 1. 发送人白名单(im-bridge-core access control);
5
+ // 2. CCV_IM_DENY=1 的 IM 硬拦截(可靠的执行层):PTY 走 perm-bridge.js 的 settings PreToolUse
6
+ // hook;SDK worker 因子进程剥离 CCV_IM_DENY/CCVIEWER_PORT 使该 settings bridge 休眠,且
7
+ // bypass 下 CLI 不调 canUseTool(CLAUDE_SDK_CAN_USE_TOOL_SHADOWED),故权威层是 sdk-manager
8
+ // 挂载的 in-process PreToolUse hook —— 两条路径共用同一个 evaluateImDeny 纯函数判定;
9
+ // 3. 本文件注入的 permissions.deny —— CLI 侧的 best-effort 纵深防御。
10
+ // 注意:deny 只收紧不放松(优先级最高),不会破坏用户既有 permissions。真正可靠的执行层是第 2 层。
11
+ // 该数组曾是 pty-manager.js 的内联块;SDK worker(runImSdkMode)需要同一份规则,故抽成共享 helper。
12
+ import { homedir } from 'node:os';
13
+
14
+ /**
15
+ * 返回要合并进 per-spawn settings 的对象。仅当 CCV_IM_DENY === '1' 时返回
16
+ * { permissions: { deny: [...] } },否则返回 {}(调用方直接展开即可)。
17
+ */
18
+ export function buildImDenySettings() {
19
+ if (process.env.CCV_IM_DENY !== '1') return {};
20
+ const home = homedir();
21
+ return {
22
+ permissions: {
23
+ deny: [
24
+ 'Bash(sudo:*)', 'Bash(rm -rf:*)', 'Bash(rm -fr:*)',
25
+ 'Bash(git push:*)', 'Bash(npm publish:*)', 'Bash(ssh:*)', 'Bash(scp:*)',
26
+ `Read(${home}/.ssh/**)`, `Edit(${home}/.ssh/**)`, `Write(${home}/.ssh/**)`,
27
+ `Read(${home}/.aws/**)`, `Edit(${home}/.aws/**)`, `Write(${home}/.aws/**)`,
28
+ // File-precise: protect the deny mechanism itself (settings/hooks), the IM
29
+ // credential store (preferences.json), and the credential vault (credentials.json +
30
+ // master.key), but do not block all of ~/.claude — the worker's working directory
31
+ // sits under ~/.claude/cc-viewer/IM_<id>/ and must stay writable.
32
+ `Edit(${home}/.claude/settings.json)`, `Write(${home}/.claude/settings.json)`,
33
+ `Edit(${home}/.claude/settings.local.json)`, `Write(${home}/.claude/settings.local.json)`,
34
+ `Edit(${home}/.claude/cc-viewer/preferences.json)`, `Write(${home}/.claude/cc-viewer/preferences.json)`,
35
+ // preferences.json 现承载定时任务定义(含 prompt);运行历史/旧版任务文件同理拒读拒写。
36
+ `Read(${home}/.claude/cc-viewer/preferences.json)`,
37
+ `Read(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-task-runs.json)`, `Write(${home}/.claude/cc-viewer/scheduled-task-runs.json)`,
38
+ `Read(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Write(${home}/.claude/cc-viewer/scheduled-tasks.json)`,
39
+ `Read(${home}/.claude/cc-viewer/credentials.json)`, `Edit(${home}/.claude/cc-viewer/credentials.json)`, `Write(${home}/.claude/cc-viewer/credentials.json)`,
40
+ `Read(${home}/.claude/cc-viewer/master.key)`, `Edit(${home}/.claude/cc-viewer/master.key)`, `Write(${home}/.claude/cc-viewer/master.key)`,
41
+ // Backup copies of the vault (cc-viewer-config-backups/<ts>/) hold the same decryption
42
+ // kit (credentials.json + master.key) — deny the whole subtree or an IM worker could read
43
+ // a rolled backup and decrypt every secret.
44
+ `Read(${home}/.claude/cc-viewer-config-backups/**)`, `Edit(${home}/.claude/cc-viewer-config-backups/**)`, `Write(${home}/.claude/cc-viewer-config-backups/**)`,
45
+ ],
46
+ },
47
+ };
48
+ }