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
@@ -35,6 +35,7 @@ import { reportSwallowed } from '../lib/error-report.js';
35
35
  import { resolve as _pathResolve, dirname as _pathDirname, sep as _pathSep } from 'node:path';
36
36
  import { createHash, randomBytes } from 'node:crypto';
37
37
  import { registerSdkSessionLister } from './sdk-session-index.js';
38
+ import { seedSessionProxyProfile, clearSessionProxyProfile, clearSessionProxyProfiles } from './proxy-session-registry.js';
38
39
  import { readPrefsRaw } from './prefs-store.js';
39
40
  import { projectKeyForCwd } from './system-prompt-snapshots.js';
40
41
  import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
@@ -213,6 +214,14 @@ export function listSdkSessions() {
213
214
 
214
215
  registerSdkSessionLister(listSdkSessions);
215
216
 
217
+ /** Whether a session is registered for the given anchor (cwd/project/instanceKey).
218
+ * Used by the IM worker's isSessionAvailable so a dropped/closed session fails fast
219
+ * (noSession) instead of queuing into a 2-minute timeout (review-concurrency P1-2). */
220
+ export function hasSession(anchor) {
221
+ if (!anchor) return _active() != null;
222
+ return _sessionForAnchor(anchor, { allowPrimaryFallback: true }) != null;
223
+ }
224
+
216
225
  /**
217
226
  * The BOUND cwd's primary session instanceKey (2026-11, WS attach-stamp coherence).
218
227
  * The single source of truth for the bound identity: resume.js's `/api/live-processes`
@@ -519,6 +528,8 @@ function _createSession(cwd, { freshKey = false } = {}) {
519
528
  let _launchResume = null; // startup continuation intent { continue, resumeId, forkSession } — first query only
520
529
  let _userArgs = []; // remaining user args → options.extraArgs passthrough
521
530
  let _claudeExecutable = null; // pathToClaudeCodeExecutable — resolved with the same priority as PTY mode (configured → codefuse → native → PATH → npm) so SDK sessions don't fall back to a PATH claude that host security policy may kill on headless spawn
531
+ let _unattended = false; // runImSdkMode (IM worker): no human can answer any approval modal
532
+ let _insideLogDir = false; // caller asserts the cwd is the IM worker dir under LOG_DIR (cli.js passes true) → skip model-prompt matching so the IM persona wins
522
533
  // Resident-query state. `_activeQuery` (the Query handle) and `_queryBusy` (a turn in
523
534
  // flight) are deliberately decoupled: an idle resident query is alive but not busy.
524
535
  let _activeQuery = null;
@@ -658,7 +669,7 @@ function _createSession(cwd, { freshKey = false } = {}) {
658
669
  }
659
670
 
660
671
  /** Adopt launch config (initSdkSession writes it here). */
661
- function _init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable }) {
672
+ function _init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir }) {
662
673
  _permissionMode = permissionMode || 'default';
663
674
  _childEnv = env || null;
664
675
  _settings = settings || null;
@@ -666,6 +677,8 @@ function _createSession(cwd, { freshKey = false } = {}) {
666
677
  _launchResume = launchResume || null;
667
678
  _userArgs = Array.isArray(userArgs) ? userArgs : [];
668
679
  _claudeExecutable = claudeExecutable || null;
680
+ _unattended = unattended === true;
681
+ _insideLogDir = insideLogDir === true;
669
682
  // Re-init (tests / hot reload) must not leave a zombie resident generation alive.
670
683
  _teardownResident();
671
684
  _resetFullState();
@@ -1025,6 +1038,41 @@ function _createSession(cwd, { freshKey = false } = {}) {
1025
1038
  canUseTool: _handleCanUseTool,
1026
1039
  ..._permissionMode === 'bypassPermissions' && { allowDangerouslySkipPermissions: true },
1027
1040
  };
1041
+ // IM worker (CCV_IM_DENY=1): the child deliberately drops CCV_IM_DENY/CCVIEWER_PORT, so the
1042
+ // settings-file PreToolUse bridge stays dormant in the SDK child. And under bypassPermissions the
1043
+ // CLI shadows canUseTool entirely (CLAUDE_SDK_CAN_USE_TOOL_SHADOWED) — so this in-process
1044
+ // PreToolUse hook is the IM worker's AUTHORITATIVE enforcement layer, running inside the CLI
1045
+ // engine regardless of permission mode (a hook deny is authoritative even under bypass). For an
1046
+ // unattended IM worker it ALSO denies the interactive tools (AskUserQuestion/ExitPlanMode) and
1047
+ // publish, which would otherwise hang with nobody to answer them.
1048
+ if (process.env.CCV_IM_DENY === '1') {
1049
+ options.hooks = {
1050
+ PreToolUse: [{
1051
+ hooks: [async (input) => {
1052
+ try {
1053
+ const toolName = input?.tool_name;
1054
+ // Unattended IM worker: interactive prompts and publish can never be answered —
1055
+ // deny them at the engine layer (bypass shadows canUseTool, so this hook is the
1056
+ // only place they can be stopped without hanging).
1057
+ if (_unattended && (toolName === 'AskUserQuestion' || toolName === 'ExitPlanMode')) {
1058
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'Unattended IM session: interactive prompts are unavailable. Ask the user in plain chat text instead.' } };
1059
+ }
1060
+ const verdict = evaluateImDeny(toolName, input?.tool_input ?? {});
1061
+ if (verdict.deny) {
1062
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: `cc-viewer IM guard: ${verdict.reason}` } };
1063
+ }
1064
+ } catch (err) {
1065
+ // Fail-closed: this hook is the IM worker's authoritative enforcement layer
1066
+ // (bypass shadows canUseTool). An evaluation error must not silently allow the
1067
+ // tool — deny and surface it, rather than fail open (review-security P2-1).
1068
+ reportSwallowed('sdk-manager.im-hook', err);
1069
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'cc-viewer IM guard: evaluation error' } };
1070
+ }
1071
+ return {};
1072
+ }],
1073
+ }],
1074
+ };
1075
+ }
1028
1076
  // env carries the loopback-proxy base URL — the SDK passes it through to the
1029
1077
  // spawned CLI verbatim (verified against sdk.mjs: env defaults to process.env
1030
1078
  // and is only ever added to, never filtered).
@@ -1098,6 +1146,9 @@ function _createSession(cwd, { freshKey = false } = {}) {
1098
1146
  launchSettings: _settings,
1099
1147
  resume: resumeIntent,
1100
1148
  persistPending: !resumeIntent,
1149
+ // IM worker (runImSdkMode): skip the model-prompt pin/match machinery so the
1150
+ // IM_<id>/CC_APPEND_SYSTEM.md persona is not replaced by a LOG_DIR/system_prompt entry.
1151
+ insideLogDir: _insideLogDir === true,
1101
1152
  });
1102
1153
  options.extraArgs = launchArgsToExtraArgs([...launchArgs, ...lc.sysPrompt.args]);
1103
1154
  } catch (err) {
@@ -1877,7 +1928,12 @@ function _createSession(cwd, { freshKey = false } = {}) {
1877
1928
  // Per-workspace (2026-10): carry the session's own cwd so the server
1878
1929
  // can route turn_end to THIS workspace's SSE scope (SDK mode has no
1879
1930
  // Stop-hook POST, so this callback is the only turn-end producer).
1880
- try { _onTurnEnd({ sessionId: _sessionId, ts: Date.now(), cwd: _cwd }); }
1931
+ try { _onTurnEnd({ sessionId: _sessionId, ts: Date.now(), cwd: _cwd,
1932
+ // resultText: the authoritative final assistant text from the SDK result message.
1933
+ // IM workers (runImSdkMode) have no transcript_path, so the bridge falls back to
1934
+ // this when the interceptor live text is empty. Purely additive — existing
1935
+ // consumers ignore it.
1936
+ resultText: typeof msg.result === 'string' ? msg.result : null }); }
1881
1937
  catch (err) { console.warn('[sdk-manager] onTurnEnd threw:', err?.message); }
1882
1938
  }
1883
1939
  if (rec) _settleTurn(rec);
@@ -2137,6 +2193,9 @@ function _createSession(cwd, { freshKey = false } = {}) {
2137
2193
  * publish force-approval below (an IM worker gets a hard deny, not a modal);
2138
2194
  * 2. npm-publish hard gate — forced through the perm approval branch even in
2139
2195
  * bypassPermissions mode (perm-bridge.js's bypass exemption equivalent);
2196
+ * 2b. unattended IM worker (runImSdkMode) — no human can answer a modal, so the
2197
+ * interactive tools (ExitPlanMode/AskUserQuestion) and publish are denied
2198
+ * immediately and everything else auto-allows, instead of parking 5min/24h;
2140
2199
  * 3. bypass early-allow — bypass auto-approves everything else, but NEVER
2141
2200
  * short-circuits the ExitPlanMode/AskUserQuestion interactive branches;
2142
2201
  * 4. the three regular branches (plan / ask / perm).
@@ -2168,6 +2227,26 @@ function _createSession(cwd, { freshKey = false } = {}) {
2168
2227
  // perm branch below.
2169
2228
  const isPublish = isPublishCommand(toolName, input);
2170
2229
 
2230
+ // 2b. Unattended IM worker (runImSdkMode): no human can answer any approval modal,
2231
+ // so never park. The IM hard deny above already ran; here we deny the interactive
2232
+ // tools and the publish floor immediately with an actionable message and auto-allow
2233
+ // everything else. Without this, an unattended bypass session would still hang 5min
2234
+ // (publish/ExitPlanMode) or 24h (AskUserQuestion) on those paths.
2235
+ // NOTE: runImSdkMode runs permissionMode 'bypassPermissions', under which the CLI does
2236
+ // NOT invoke canUseTool at all (CLAUDE_SDK_CAN_USE_TOOL_SHADOWED) — so for the IM worker
2237
+ // this branch is dormant defense-in-depth, and the authoritative IM enforcement layer is
2238
+ // the in-process PreToolUse hook mounted in _ensureResidentQuery (see options.hooks).
2239
+ // It stays live for any future non-bypass unattended caller.
2240
+ if (_unattended && process.env.CCV_IM_DENY === '1') {
2241
+ if (toolName === 'ExitPlanMode' || toolName === 'AskUserQuestion') {
2242
+ return { behavior: 'deny', message: 'Unattended IM session: interactive prompts are unavailable. Ask the user in plain chat text instead.' };
2243
+ }
2244
+ if (isPublish) {
2245
+ return { behavior: 'deny', message: 'Unattended IM session: publishing commands are blocked.' };
2246
+ }
2247
+ return { behavior: 'allow', updatedInput: input };
2248
+ }
2249
+
2171
2250
  // 3. Bypass mode auto-approves everything except publish and the two
2172
2251
  // interactive tools — those keep their UI channels so a forwarded
2173
2252
  // ExitPlanMode/AskUserQuestion still reaches the user.
@@ -3093,6 +3172,19 @@ export function __isEphemeralHostForTests(cwd) {
3093
3172
  return false;
3094
3173
  }
3095
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
+
3096
3188
  /**
3097
3189
  * Initialize (or re-initialize) a workspace's SDK session.
3098
3190
  * Does NOT start a query — waits for the first user message via sendUserMessage().
@@ -3120,7 +3212,7 @@ export function __isEphemeralHostForTests(cwd) {
3120
3212
  * must come from the same selection as PTY mode, else the SDK spawns a PATH claude that
3121
3213
  * host security tooling (e.g. agent-security headless guards) may SIGKILL on spawn
3122
3214
  */
3123
- export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable } = {}) {
3215
+ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir } = {}) {
3124
3216
  void projectName; // reserved (display name comes from the wire path)
3125
3217
  // Process-global callbacks (cli.js registers one wiring; every session reuses it). Only
3126
3218
  // OVERWRITE when a callback is actually passed — a later per-workspace init (the launch
@@ -3141,8 +3233,9 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3141
3233
  // and tears down ONLY this session's prior generation (tests / hot reload) — other
3142
3234
  // workspaces' sessions (and same-cwd siblings) are untouched.
3143
3235
  const sess = _getOrCreateSession(cwd);
3144
- sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable });
3236
+ sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir });
3145
3237
  _activeKey = sess.instanceKey;
3238
+ _seedProxyBindingForSession(sess);
3146
3239
  }
3147
3240
 
3148
3241
  /**
@@ -3186,6 +3279,7 @@ export function createSdkSession(cwd, cfg) {
3186
3279
  sess._markFreshLaunch();
3187
3280
  _adoptProcessWiring();
3188
3281
  _activeKey = sess.instanceKey;
3282
+ _seedProxyBindingForSession(sess);
3189
3283
  return { instanceKey: sess.instanceKey };
3190
3284
  }
3191
3285
 
@@ -3366,6 +3460,7 @@ export function stopSession() {
3366
3460
  }
3367
3461
  _sessions.clear();
3368
3462
  _activeKey = null;
3463
+ clearSessionProxyProfiles();
3369
3464
  // Process-global wiring is cleared on the HARD teardown boundary. initSdkSession only
3370
3465
  // overwrites a callback when one is actually passed (so a per-workspace launch init
3371
3466
  // cannot wipe cli.js's process-wide wiring mid-run); that guard means an init that
@@ -3410,6 +3505,9 @@ export function attachSdkSession(anchor) {
3410
3505
  if (!sess) return { ok: false, reason: 'not-found' };
3411
3506
  const switched = sess.instanceKey !== _activeKey;
3412
3507
  _activeKey = sess.instanceKey;
3508
+ // Activating a session binds its proxy (seeded from the global default when the
3509
+ // session predates the mapping or its binding was cleared).
3510
+ _seedProxyBindingForSession(sess);
3413
3511
  return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
3414
3512
  }
3415
3513
 
@@ -3464,6 +3562,7 @@ export function closeSdkSession(anchor = {}) {
3464
3562
  // close/relaunch triggered by one of those frames must register a fresh session,
3465
3563
  // never be deleted by the tail of the older close operation.
3466
3564
  _sessions.delete(sess.instanceKey);
3565
+ clearSessionProxyProfile(sess.instanceKey);
3467
3566
  if (killedActive) {
3468
3567
  // Prefer a SAME-CWD sibling (the twin the user most likely wants next), else fall
3469
3568
  // back to the next registered session (Map insertion order).
@@ -221,7 +221,7 @@ export class UpdateJob {
221
221
  try { await handler(this.state.version); }
222
222
  catch (err) { this.setState({ status: 'restart_required', error: err.message }); throw err; }
223
223
  }
224
- async start() {
224
+ async start({ force = false } = {}) {
225
225
  if (['checking', 'downloading', 'installing', 'restarting', 'restart_required'].includes(this.state.status)) return this.getState();
226
226
  if (!this.state.version || !this.state.release) {
227
227
  const state = await this.check();
@@ -237,11 +237,11 @@ export class UpdateJob {
237
237
  return this.getState();
238
238
  }
239
239
  }
240
- this.setState({ status: 'downloading', error: null, downloaded: 0, total: null });
240
+ this.setState({ status: 'downloading', error: null, errorCode: null, downloaded: 0, total: null });
241
241
  const directory = dirname(UPDATE_STATE_FILE);
242
242
  let file;
243
243
  try {
244
- if (await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
244
+ if (!force && await (this.options.hasOtherInstanceImpl || hasOtherNormalInstance)({ currentPort: this.options.currentPort })) throw updateError('Exit other cc-viewer instances before updating', 'another_instance');
245
245
  const root = await (this.options.resolveRootImpl || resolveNpmInstallRoot)();
246
246
  const actualRoot = await realpath(root);
247
247
  await withFileLockAsync(join(dirname(UPDATE_STATE_FILE), 'update-install.lock'), async () => {
package/server/proxy.js CHANGED
@@ -136,12 +136,19 @@ export function startProxy() {
136
136
  // req.url 是 origin-form 相对路径,new URL 需补基址,否则锚定判定落空到宽松正则。
137
137
  const _reqPath = (() => { try { return new URL(req.url || '/', 'http://x').pathname; } catch { return req.url || ''; } })();
138
138
  const _isUtility = /\/messages\/count_tokens$/.test(_reqPath) || /^\/api\/eval\/sdk-/.test(_reqPath);
139
+ // Per-session override: the spawned claude self-reports its instanceKey via
140
+ // x-ccv-instance; a bound session's proxy choice overrides the global one. This
141
+ // must stay consistent with the interceptor fetch hook's per-request rewrite.
142
+ const _instKey = (() => {
143
+ const v = findHeader(headers, 'x-ccv-instance');
144
+ return (typeof v === 'string' && /^ccv-[0-9a-f]+$/.test(v)) ? v : undefined;
145
+ })();
139
146
  let roleProfile;
140
147
  let _role; // live system 改写的 role 门(仅 main 生效);未分类 → undefined → main 语义
141
148
  const _needClassify = body.length > 0 && isAnthropicApiPath(_reqPath) && !_isUtility;
142
149
  // 角色分类在两种情况下都必须做:显式角色分配(选路)或 live system 已启用
143
150
  // (否则默认配置下 subagent/teammate 会以 role=undefined 穿过 proxy 侧门被注入主 system)。
144
- if (_needClassify && (interceptor.hasExplicitRoleAssignments() || liveSystemPromptEnabled())) {
151
+ if (_needClassify && (interceptor.hasExplicitRoleAssignments(_instKey) || liveSystemPromptEnabled())) {
145
152
  let parsedBody = null;
146
153
  try { parsedBody = JSON.parse(body.toString('utf8')); } catch { /* 非 JSON body → 保持 main 语义 */ }
147
154
  if (parsedBody && typeof parsedBody === 'object') {
@@ -157,13 +164,13 @@ export function startProxy() {
157
164
  _role = _agent
158
165
  ? (_agent.named ? 'teammate' : 'subagent')
159
166
  : classifyProxyRole(parsedBody, {});
160
- if (interceptor.hasExplicitRoleAssignments()) {
161
- roleProfile = interceptor.getEffectiveRoleProfile(_role);
167
+ if (interceptor.hasExplicitRoleAssignments(_instKey)) {
168
+ roleProfile = interceptor.getEffectiveRoleProfile(_role, _instKey);
162
169
  }
163
170
  } catch (err) { reportSwallowed('proxy.role-classify', err); }
164
171
  }
165
172
  }
166
- const originalBaseUrl = getOriginalBaseUrl(roleProfile);
173
+ const originalBaseUrl = getOriginalBaseUrl(roleProfile !== undefined ? roleProfile : interceptor.getEffectiveMainProfile(_instKey));
167
174
 
168
175
  const fetchOptions = {
169
176
  method: req.method,
@@ -185,7 +192,7 @@ export function startProxy() {
185
192
  // 模型替换由重试引擎用 resolveProfileModel 纯函数完成(interceptor 对 trace 请求会再跑一次,幂等 no-op)。
186
193
  // 非大模型 API 请求走原逻辑(同样用 x-cc-viewer-trace 让 interceptor 记录,但不经重试引擎)。
187
194
  if (isAnthropicApiPath(fullUrl)) {
188
- await handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, { role: _role, isUtility: _isUtility });
195
+ await handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, { role: _role, isUtility: _isUtility, instanceKey: _instKey });
189
196
  return;
190
197
  }
191
198
 
@@ -304,8 +311,9 @@ const _retryConfigGetter = () => interceptor._retryConfigState;
304
311
  async function handleLlmApiRequest(req, res, fullUrl, fetchOptions, body, proxyDispatcher, roleProfile, liveCtx = {}) {
305
312
  const statsEnabled = process.env.CCV_PROXY_STATS !== 'off';
306
313
  const retryConfig = _retryConfigGetter(); // live binding:每请求取最新重试配置
307
- // 角色解析后的有效 profile(上游/模型替换/统计归属)。undefined = 未分类 → 沿用 main 活跃 profile。
308
- const profile = roleProfile !== undefined ? roleProfile : (interceptor._activeProfile || null);
314
+ // 角色解析后的有效 profile(上游/模型替换/统计归属)。undefined = 未分类 → 沿用 main 活跃 profile
315
+ // (会话有绑定时为该会话的 main,否则为全局 _activeProfile)。
316
+ const profile = roleProfile !== undefined ? roleProfile : (interceptor.getEffectiveMainProfile(liveCtx.instanceKey) || null);
309
317
 
310
318
  // 清理可能的 trace 头(singleFetch 会重新加,避免旧值干扰);interceptor 会正常记录请求
311
319
  // 同时清理 hop-by-hop / 传输编码头:body 已被 buffer 成完整 Buffer,
@@ -3,12 +3,13 @@ import { normalizeSessionCwd } from './lib/v2/layout.js';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { join, dirname, sep, resolve } from 'node:path';
5
5
  import { chmodSync, statSync, existsSync } from 'node:fs';
6
- import { platform, arch, homedir } from 'node:os';
6
+ import { platform, arch } from 'node:os';
7
7
  import { createRequire } from 'node:module';
8
8
  import { prepareEmbeddedShellSpawn, stripClaudeNoFlickerUnlessOptedIn, applyClaudeAltScreenPref } from './lib/terminal-env.js';
9
9
  import { killPtyTree } from './lib/term-signals.js';
10
10
  import { findSafeSliceStart, splitTrailingIncomplete } from './lib/ansi-safe-slice.js';
11
11
  import { imDir } from './lib/im/im-lock.js';
12
+ import { buildImDenySettings } from './lib/im/im-permissions.js';
12
13
  import { resolveSpawnModel } from './lib/spawn-model-resolver.js';
13
14
  import { mergeSettingsIntoArgs } from './lib/settings-merge.js';
14
15
  import { projectKeyForCwd } from './lib/system-prompt-snapshots.js';
@@ -522,34 +523,8 @@ async function _spawnClaudeImpl(key, proxyPort, cwd, extraArgs = [], claudePath
522
523
  // Note: under bypass mode whether deny is still honored depends on Claude Code's
523
524
  // behavior; the truly reliable enforcement layer is perm-bridge.js's PreToolUse deny
524
525
  // (CCV_IM_DENY). This is a best-effort defense-in-depth layer.
525
- if (process.env.CCV_IM_DENY === '1') {
526
- const home = homedir();
527
- settingsObj.permissions = {
528
- deny: [
529
- 'Bash(sudo:*)', 'Bash(rm -rf:*)', 'Bash(rm -fr:*)',
530
- 'Bash(git push:*)', 'Bash(npm publish:*)', 'Bash(ssh:*)', 'Bash(scp:*)',
531
- `Read(${home}/.ssh/**)`, `Edit(${home}/.ssh/**)`, `Write(${home}/.ssh/**)`,
532
- `Read(${home}/.aws/**)`, `Edit(${home}/.aws/**)`, `Write(${home}/.aws/**)`,
533
- // File-precise: protect the deny mechanism itself (settings/hooks), the IM
534
- // credential store (preferences.json), and the credential vault (credentials.json +
535
- // master.key), but do not block all of ~/.claude — the worker's working directory
536
- // sits under ~/.claude/cc-viewer/IM_<id>/ and must stay writable.
537
- `Edit(${home}/.claude/settings.json)`, `Write(${home}/.claude/settings.json)`,
538
- `Edit(${home}/.claude/settings.local.json)`, `Write(${home}/.claude/settings.local.json)`,
539
- `Edit(${home}/.claude/cc-viewer/preferences.json)`, `Write(${home}/.claude/cc-viewer/preferences.json)`,
540
- // preferences.json 现承载定时任务定义(含 prompt);运行历史/旧版任务文件同理拒读拒写。
541
- `Read(${home}/.claude/cc-viewer/preferences.json)`,
542
- `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)`,
543
- `Read(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Edit(${home}/.claude/cc-viewer/scheduled-tasks.json)`, `Write(${home}/.claude/cc-viewer/scheduled-tasks.json)`,
544
- `Read(${home}/.claude/cc-viewer/credentials.json)`, `Edit(${home}/.claude/cc-viewer/credentials.json)`, `Write(${home}/.claude/cc-viewer/credentials.json)`,
545
- `Read(${home}/.claude/cc-viewer/master.key)`, `Edit(${home}/.claude/cc-viewer/master.key)`, `Write(${home}/.claude/cc-viewer/master.key)`,
546
- // Backup copies of the vault (cc-viewer-config-backups/<ts>/) hold the same decryption
547
- // kit (credentials.json + master.key) — deny the whole subtree or an IM worker could read
548
- // a rolled backup and decrypt every secret.
549
- `Read(${home}/.claude/cc-viewer-config-backups/**)`, `Edit(${home}/.claude/cc-viewer-config-backups/**)`, `Write(${home}/.claude/cc-viewer-config-backups/**)`,
550
- ],
551
- };
552
- }
526
+ // Shared with the SDK IM worker (runImSdkMode) via buildImDenySettings().
527
+ Object.assign(settingsObj, buildImDenySettings());
553
528
  // Inject --thinking-display summarized; skip injection when either of these holds:
554
529
  // - the path is in the rejection set (it crashed because of this last time)
555
530
  // - env CCV_SKIP_THINKING_DISPLAY=1 (user global opt-out, consistent with cli.js)
@@ -3,8 +3,10 @@ import { existsSync, readFileSync, writeFileSync, mkdirSync, copyFileSync, unlin
3
3
  import { join, dirname } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { LOG_DIR, setLogDir, getClaudeConfigDir, discoverClaudeExecutables, resolveExplicitClaudePath, CLAUDE_EXECUTABLE_PREF_KEY } from '../../findcc.js';
6
- import { PROFILE_PATH, _defaultConfig, getActiveProfileId, getStoredRoles, isOfficialDefaultEndpoint, setActiveProfileForWorkspace, _loadProxyProfile, hydrateProfilesWithApiKeys, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState } from '../interceptor.js';
6
+ import { PROFILE_PATH, _defaultConfig, getActiveProfileId, getStoredRoles, isOfficialDefaultEndpoint, setActiveProfileForWorkspace, _loadProxyProfile, getGlobalDefaultProfileId, hydrateProfilesWithApiKeys, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState } from '../interceptor.js';
7
7
  import { migrateProxyProfileList, isValidRoleValue, PROXY_ROLE_KEYS } from '../lib/interceptor-core.js';
8
+ import { getSessionProxy, setSessionProxyProfile, pruneSessionProxyProfiles } from '../lib/proxy-session-registry.js';
9
+ import { filterClientsByInstance } from '../lib/v2/view-router.js';
8
10
  import { DEFAULT_RETRY_CONFIG, validateRetryConfig, resolveRetryConfig } from '../lib/proxy/proxy-retry.js';
9
11
  import { discoverCcSwitchProviders, mergeImportedProfiles } from '../lib/ccswitch-import.js';
10
12
  import { reportSwallowed } from '../lib/error-report.js';
@@ -319,6 +321,22 @@ function claudeSettingsPost(req, res, parsedUrl, isLocal, deps) {
319
321
  });
320
322
  }
321
323
 
324
+ // ── Per-session proxy binding helpers (GET /api/proxy-profiles?instanceKey=) ──────
325
+ // A binding counts as "session-scoped" only when its main is still resolvable: 'max'
326
+ // (explicit Default) or a profile id present in the served list. A dangling binding
327
+ // (profile deleted out from under it) falls back to the global view instead of
328
+ // surfacing an id the UI can't render.
329
+ function sessionScopedBindingPresent(binding, data) {
330
+ if (!binding || typeof binding.main !== 'string' || !binding.main) return false;
331
+ if (binding.main === 'max') return true;
332
+ const list = data && Array.isArray(data.profiles) ? data.profiles : [];
333
+ return list.some((p) => p && p.id === binding.main);
334
+ }
335
+ function sessionBindingActive(binding) { return binding.main; }
336
+ function sessionBindingRoles(binding) {
337
+ return { subagent: binding.roles?.subagent || 'follow', teammate: binding.roles?.teammate || 'follow' };
338
+ }
339
+
322
340
  function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
323
341
  try {
324
342
  let data = existsSync(PROFILE_PATH) ? JSON.parse(readFileSync(PROFILE_PATH, 'utf-8')) : deps.defaultProxyProfiles;
@@ -349,13 +367,24 @@ function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
349
367
  data = { ...data, profiles: hydrateProfilesWithApiKeys(data.profiles) };
350
368
  }
351
369
  // 用 interceptor.getActiveProfileId() 返回 effective active(workspace > profile.json.active > 'max')
352
- const effectiveActive = getActiveProfileId();
370
+ // Per-session override: ?instanceKey= with an existing binding resolves that session's
371
+ // OWN main/roles (and marks sessionScoped) instead of the process-global value.
372
+ const globalActive = getGlobalDefaultProfileId();
373
+ const reqInstance = (() => {
374
+ const v = parsedUrl && parsedUrl.searchParams && typeof parsedUrl.searchParams.get === 'function'
375
+ ? parsedUrl.searchParams.get('instanceKey') : null;
376
+ return (typeof v === 'string' && /^ccv-[0-9a-f]+$/.test(v)) ? v : null;
377
+ })();
378
+ const sessionBinding = reqInstance ? getSessionProxy(reqInstance) : undefined;
379
+ const sessionScoped = sessionScopedBindingPresent(sessionBinding, data);
380
+ const effectiveActive = sessionScoped ? sessionBindingActive(sessionBinding) : getActiveProfileId();
381
+ const effectiveRoles = sessionScoped ? sessionBindingRoles(sessionBinding) : getStoredRoles();
353
382
  // 本机(127.0.0.1)= admin:下发明文 profile.apiKey 供本人在编辑表单(👁 折叠)里查阅/复制;已授权
354
383
  // 的远程客户端只拿脱敏值(****+后4位)。保存时若回传脱敏值,POST 侧 isMasked() 会保留磁盘原值。
355
384
  // 镜像 /api/auth/state 的密码、/api/dingtalk/status 的 appSecret 策略。
356
385
  // roles 返回**存储值**(不做休眠调整):休眠只是请求侧不生效,若返回有效值,UI 缓存后
357
386
  // 在下次无关 POST 回写会把休眠中的分配清掉。officialDefault 驱动 UI 隐藏角色分配区。
358
- const full = { ...data, active: effectiveActive, roles: getStoredRoles(), officialDefault: isOfficialDefaultEndpoint() };
387
+ const full = { ...data, active: effectiveActive, roles: effectiveRoles, officialDefault: isOfficialDefaultEndpoint(), globalActive, sessionScoped, ...(reqInstance ? { instanceKey: reqInstance } : {}) };
359
388
  const payload = isLocal ? full : deps.maskProfiles(full);
360
389
  // defaultConfig.apiKey 始终脱敏:它在列表里是常显文本(无 👁 折叠),且 Max/OAuth 默认配置的 key
361
390
  // 可能是 OAuth token;只有可编辑 profile 的 key 才按 isLocal 明文下发。
@@ -371,7 +400,7 @@ function proxyProfilesGet(req, res, parsedUrl, isLocal, deps) {
371
400
  function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
372
401
  let body = '';
373
402
  req.on('data', chunk => { body += chunk; if (body.length > deps.MAX_POST_BODY) req.destroy(); });
374
- req.on('end', () => {
403
+ req.on('end', async () => {
375
404
  try {
376
405
  const incoming = JSON.parse(body);
377
406
  if (!incoming || typeof incoming !== 'object' || !Array.isArray(incoming.profiles)) {
@@ -379,10 +408,53 @@ function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
379
408
  res.end(JSON.stringify({ error: 'Invalid profile data: profiles must be an array' }));
380
409
  return;
381
410
  }
411
+ // active/roles 作用域:'session'(按 instanceKey 写会话映射,不落盘)/
412
+ // 'global'(设为全局默认 + workspace)/ 缺省(旧客户端 = 现状,workspace+全局回退)。
413
+ // 在读/校验阶段只确定 scope 与 instanceKey;active/roles 的具体校验在 sanitizedRoles
414
+ // 之后、落盘之前(见下),以便 roles-only 会话调用也有合法判定依据。
415
+ const scope = incoming.scope === 'session' || incoming.scope === 'global' ? incoming.scope : null;
416
+ const hasActive = typeof incoming.active === 'string' && incoming.active;
417
+ let sessionKey = (typeof incoming.instanceKey === 'string' && /^ccv-[0-9a-f]+$/.test(incoming.instanceKey)) ? incoming.instanceKey : null;
382
418
  // 确保 max profile 始终存在
383
419
  if (!incoming.profiles.some(p => p.id === 'max')) {
384
420
  incoming.profiles = [{ id: 'max', name: 'Default' }, ...(incoming.profiles || [])];
385
421
  }
422
+ // 角色分配校验:只认 subagent/teammate 两个 key(roles.main 之类的杂键直接丢弃);
423
+ // 值必须是 follow / max / 入参 profiles 里存在的 id(按将落盘的列表校验,而非旧文件),
424
+ // 非法值归 'follow'(宽容风格,不 400)。被删 profile 的悬空角色由读取时归 follow 兜底。
425
+ let sanitizedRoles;
426
+ if (incoming.roles && typeof incoming.roles === 'object' && !Array.isArray(incoming.roles)) {
427
+ const byId = new Map(incoming.profiles.map(p => [p.id, p]));
428
+ sanitizedRoles = {};
429
+ for (const k of PROXY_ROLE_KEYS) {
430
+ if (!(k in incoming.roles)) continue; // 未提交的 key 不进 patch → 合并时保留存储值
431
+ const v = incoming.roles[k];
432
+ // key 提交了但值非法(非字符串 / 悬空 id)→ 归 'follow'(显式纠正,不是保留)
433
+ sanitizedRoles[k] = (typeof v === 'string' && v && isValidRoleValue(v, byId)) ? v : 'follow';
434
+ }
435
+ }
436
+ // session 作用域的兜底寻址 + 校验。必须在落盘之前完成——被拒(400)的请求不得改写
437
+ // profile.json / vault。
438
+ if (scope === 'session' && !sessionKey) {
439
+ // Fallback: an older/again-loading frontend may legitimately lack the key on the
440
+ // bound view. Resolve the bound session's primary instance server-side (dynamic
441
+ // import — never eagerly load the Agent SDK in PTY mode) instead of silently
442
+ // degrading to a global write that wouldn't reach the (already-seeded) session.
443
+ try {
444
+ const boundCwd = process.env.CCV_PROJECT_DIR || process.cwd();
445
+ const sdk = await import('../lib/sdk-manager.js');
446
+ const resolved = sdk.resolveBoundPrimaryInstanceKey(boundCwd);
447
+ if (typeof resolved === 'string' && /^ccv-[0-9a-f]+$/.test(resolved)) sessionKey = resolved;
448
+ } catch (err) { reportSwallowed('proxy-profiles.resolve-session-key', err); }
449
+ }
450
+ if (scope === 'session') {
451
+ const byId = new Map(incoming.profiles.map(p => [p.id, p]));
452
+ if (!sessionKey || (hasActive && !isValidRoleValue(incoming.active, byId)) || (!hasActive && !sanitizedRoles)) {
453
+ res.writeHead(400, { 'Content-Type': 'application/json' });
454
+ res.end(JSON.stringify({ error: 'Invalid instanceKey/profile for session scope' }));
455
+ return;
456
+ }
457
+ }
386
458
  // Only the profiles list is written to profile.json; `active` is no longer persisted here
387
459
  // (avoids cross-process clobbering). The existing file's `active` field is preserved so an
388
460
  // older ccv or a hand editor can still fall back to it. Read-merge-write INSIDE the lock
@@ -398,34 +470,46 @@ function proxyProfilesPost(req, res, parsedUrl, isLocal, deps) {
398
470
  existing.profiles = strippedProfiles;
399
471
  return existing;
400
472
  }, { mode: 0o600, strictCorrupt: true, fallback: {} });
401
- // 角色分配校验:只认 subagent/teammate 两个 key(roles.main 之类的杂键直接丢弃);
402
- // 值必须是 follow / max / 入参 profiles 里存在的 id(按将落盘的列表校验,而非旧文件),
403
- // 非法值归 'follow'(宽容风格,不 400)。被删 profile 的悬空角色由读取时归 follow 兜底。
404
- let sanitizedRoles;
405
- if (incoming.roles && typeof incoming.roles === 'object' && !Array.isArray(incoming.roles)) {
406
- const byId = new Map(incoming.profiles.map(p => [p.id, p]));
407
- sanitizedRoles = {};
408
- for (const k of PROXY_ROLE_KEYS) {
409
- if (!(k in incoming.roles)) continue; // 未提交的 key 不进 patch → 合并时保留存储值
410
- const v = incoming.roles[k];
411
- // key 提交了但值非法(非字符串 / 悬空 id)→ 归 'follow'(显式纠正,不是保留)
412
- sanitizedRoles[k] = (typeof v === 'string' && v && isValidRoleValue(v, byId)) ? v : 'follow';
413
- }
414
- }
415
473
  // active/roles 走 workspace 级别存储(当前进程独占);合并语义:缺省字段保留文件现值
416
- const hasActive = typeof incoming.active === 'string' && incoming.active;
417
- if (hasActive || sanitizedRoles) {
474
+ if (scope === 'session') {
475
+ // 会话级:写进程内映射(主代理 + 角色),不碰 workspace 文件 / 全局默认。
476
+ // roles 按 key 合并:未提交的角色保留会话现值(与 workspace mergeActivePayload 同语义)。
477
+ const existing = getSessionProxy(sessionKey);
478
+ setSessionProxyProfile(sessionKey, {
479
+ main: hasActive ? incoming.active : (existing?.main || getGlobalDefaultProfileId()),
480
+ roles: {
481
+ subagent: sanitizedRoles && 'subagent' in sanitizedRoles ? sanitizedRoles.subagent : (existing?.roles?.subagent || 'follow'),
482
+ teammate: sanitizedRoles && 'teammate' in sanitizedRoles ? sanitizedRoles.teammate : (existing?.roles?.teammate || 'follow'),
483
+ },
484
+ });
485
+ _loadProxyProfile(); // 列表可能同时变了
486
+ } else if (hasActive || sanitizedRoles) {
418
487
  setActiveProfileForWorkspace(hasActive ? incoming.active : undefined, sanitizedRoles);
419
488
  } else {
420
489
  _loadProxyProfile(); // 仅列表变化时也刷新一次以反映删除 / 重命名
421
490
  }
422
- // SSE 广播仅给本进程客户端(sendEventToClients 本就是 per-process;另外 active 不跨进程)
423
- const effectiveActive = getActiveProfileId();
491
+ // 清理悬空会话映射:只针对"本次确实从列表中消失"的 profile id(而非整张提交列表),
492
+ // 避免陈旧 tab 的全量列表把别的会话仍有效的绑定清掉。与 scope 无关。
493
+ if (pruneSessionProxyProfiles) {
494
+ // incoming.profiles 已是落盘后的全量;任何不在这张表里的绑定 id 都是悬空。
495
+ // 注意:这是删 profile 的唯一入口,故以新列表为准清理是安全的。
496
+ pruneSessionProxyProfiles(new Set(incoming.profiles.map(p => p.id)));
497
+ }
498
+ // SSE:session 变更只发同实例客户端(别戳到其他会话的 tab);global/列表刷新全发。
499
+ // session 作用域下生效的 active 是该会话映射里的 main(roles-only 调用时回退到现值)。
500
+ const sessionNow = scope === 'session' ? getSessionProxy(sessionKey) : null;
501
+ const effectiveActive = scope === 'session' ? (sessionNow?.main || null) : getActiveProfileId();
424
502
  const activeProfile = incoming.profiles?.find(p => p.id === effectiveActive) || null;
425
503
  const maskedProfile = activeProfile?.apiKey ? { ...activeProfile, apiKey: deps.maskApiKey(activeProfile.apiKey) } : activeProfile;
426
- sendEventToClients(deps.clients, 'proxy_profile', { active: effectiveActive, profile: maskedProfile, roles: getStoredRoles() });
504
+ const globalActive = getGlobalDefaultProfileId();
505
+ if (scope === 'session') {
506
+ const targets = filterClientsByInstance(deps.clients, sessionKey);
507
+ sendEventToClients(targets, 'proxy_profile', { active: effectiveActive, profile: maskedProfile, instanceKey: sessionKey, roles: sessionNow ? sessionBindingRoles(sessionNow) : undefined, globalActive });
508
+ } else {
509
+ sendEventToClients(deps.clients, 'proxy_profile', { active: effectiveActive, profile: maskedProfile, roles: getStoredRoles(), global: true, globalActive });
510
+ }
427
511
  res.writeHead(200, { 'Content-Type': 'application/json' });
428
- res.end(JSON.stringify({ ok: true }));
512
+ res.end(JSON.stringify({ ok: true, scope: scope || 'global', active: effectiveActive, globalActive }));
429
513
  } catch {
430
514
  res.writeHead(400, { 'Content-Type': 'application/json' });
431
515
  res.end(JSON.stringify({ error: 'Invalid JSON' }));
@@ -35,8 +35,21 @@ async function start(req, res, parsedUrl, isLocal, deps) {
35
35
  json(res, 200, deps.updateJob.getState());
36
36
  return;
37
37
  }
38
- deps.updateJob.start().catch((err) => reportSwallowed('update.start', err));
39
- json(res, 202, deps.updateJob.getState());
38
+ // Read an optional { force: true } body so the UI can let the user bypass the
39
+ // "another instance is running" guard after an explicit confirmation. Body
40
+ // parse failure / empty body / non-stream req (tests) all fall back to
41
+ // force=false (legacy behavior).
42
+ const finish = (body) => {
43
+ let force = false;
44
+ try { force = body ? JSON.parse(body)?.force === true : false; }
45
+ catch { /* tolerate non-JSON / empty body as force=false */ }
46
+ deps.updateJob.start({ force }).catch((err) => reportSwallowed('update.start', err));
47
+ json(res, 202, deps.updateJob.getState());
48
+ };
49
+ if (typeof req?.on !== 'function') { finish(''); return; }
50
+ let body = '';
51
+ req.on('data', (chunk) => { body += chunk; if (body.length > 64 * 1024) req.destroy(); });
52
+ req.on('end', () => finish(body));
40
53
  }
41
54
 
42
55
  async function restart(req, res, parsedUrl, isLocal, deps) {
package/server/server.js CHANGED
@@ -1705,11 +1705,13 @@ async function _doStart() {
1705
1705
  interactions,
1706
1706
  });
1707
1707
  // IM adapters no longer run in the main ccv. Each enabled IM runs as an independent,
1708
- // detached worker process (im-process-manager). Two CLI-mode cases:
1709
- // - WORKER (CCV_IM_PLATFORM set): connect ONLY this one platform to the singleton PTY.
1710
- // - MAIN ccv: connect NOTHING in-process; reconcile spawns/adopts the enabled IM workers.
1711
- // (Non-CLI workspace/SDK modes do neither — IM only makes sense with the singleton PTY.)
1712
- if (isCliMode && process.env.CCV_IM_PLATFORM) {
1708
+ // detached worker process (im-process-manager). Three CLI-mode cases:
1709
+ // - PTY WORKER (CCV_IM_PLATFORM set, !CCV_SDK_MODE): connect ONLY this one platform to the singleton PTY.
1710
+ // - SDK WORKER (CCV_IM_PLATFORM set, CCV_SDK_MODE): cli.js starts the bridge itself AFTER
1711
+ // initSdkSession (see runImSdkMode) — starting it here would race inbound messages
1712
+ // against an unregistered SDK session.
1713
+ // - MAIN ccv (no CCV_IM_PLATFORM): connect NOTHING in-process; reconcile spawns/adopts the enabled IM workers.
1714
+ if (isCliMode && !isSdkMode && process.env.CCV_IM_PLATFORM) {
1713
1715
  const id = process.env.CCV_IM_PLATFORM;
1714
1716
  const pmb = await import('./pty-manager.js');
1715
1717
  try {
@@ -1730,9 +1732,10 @@ async function _doStart() {
1730
1732
  } catch (e) {
1731
1733
  console.error(`[CC Viewer] IM worker startBridge(${id}) failed:`, e?.message || e);
1732
1734
  }
1733
- } else if (isCliMode) {
1735
+ } else if (isCliMode && !process.env.CCV_IM_PLATFORM) {
1734
1736
  // 主 ccv:先 stopAll(无在进程实例时为 no-op,防御升级残留)再 reconcile,
1735
1737
  // 杜绝"旧在进程连接 + 新 detached worker"同时连同一机器人导致丢/重消息。
1738
+ // (SDK worker 已被第一分支的 !isSdkMode 排除,不会走到这里误 reconcile 自己。)
1736
1739
  try { await imCore.stopAll(); } catch { /* no in-process instances */ }
1737
1740
  imProcMgr.reconcileImProcesses().catch((e) => console.error('[CC Viewer] IM reconcile failed:', e?.message || e));
1738
1741
  }