cc-viewer 1.9.35 → 1.9.36

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 (31) hide show
  1. package/cli.js +352 -59
  2. package/dist/assets/{App-CjP88gbM.css → App-BJIeZQK0.css} +1 -1
  3. package/dist/assets/App-C_S65Ygt.js +2 -0
  4. package/dist/assets/{ArchivePreview-BSBVB9bY.js → ArchivePreview-ezRMkut5.js} +1 -1
  5. package/dist/assets/{AudioPreview-WxWptR0I.js → AudioPreview-MxQVazDj.js} +1 -1
  6. package/dist/assets/{MdxEditorPanel-Dq7kpPGA.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
  7. package/dist/assets/{Mobile-DtdwYlSK.js → Mobile-BerOQqT4.js} +1 -1
  8. package/dist/assets/{ProxyStatsModal-BZPBbxOC.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
  9. package/dist/assets/{SubtitlePreview-CN3-SniA.js → SubtitlePreview-CHRRgV95.js} +1 -1
  10. package/dist/assets/{index-OTFFui4C.js → index-DBmXRTLE.js} +2 -2
  11. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +2 -0
  12. package/dist/index.html +1 -1
  13. package/package.json +1 -1
  14. package/server/i18n.js +4 -0
  15. package/server/interceptor.js +61 -19
  16. package/server/lib/anthropic-auth-placeholder.js +147 -0
  17. package/server/lib/im/im-bridge-core.js +59 -14
  18. package/server/lib/im/im-permissions.js +48 -0
  19. package/server/lib/im/im-process-manager.js +6 -5
  20. package/server/lib/im-deny.js +4 -1
  21. package/server/lib/interceptor-core.js +51 -0
  22. package/server/lib/proxy-session-registry.js +156 -0
  23. package/server/lib/sdk-manager.js +92 -4
  24. package/server/lib/update-job.js +3 -3
  25. package/server/proxy.js +15 -7
  26. package/server/pty-manager.js +4 -29
  27. package/server/routes/preferences.js +108 -24
  28. package/server/routes/update.js +15 -2
  29. package/server/server.js +9 -6
  30. package/dist/assets/App-COZPgAGQ.js +0 -2
  31. package/dist/assets/seqResourceLoaders-BXk6JJEc.js +0 -2
@@ -0,0 +1,156 @@
1
+ // Per-session (per SDK instance) proxy binding. Maps an SDK instanceKey to the
2
+ // session's proxy choice ({ main, roles }) so one session's proxy change never
3
+ // leaks into another session sharing the same ccv process.
4
+ //
5
+ // This is intentionally process-local and IN-MEMORY ONLY: bindings are seeded when
6
+ // a session is registered/activated and dropped when it closes or the process stops.
7
+ // Nothing is persisted — a restart simply has no bindings (matches the product
8
+ // requirement that the choice need not survive a restart).
9
+ //
10
+ // Boundary: this is an L1 lib. It must NOT import sdk-manager (that would eagerly
11
+ // load the Agent SDK in PTY mode) or interceptor (an L2 consumer). interceptor
12
+ // registers a global-default provider here; proxy.js and the fetch hook read the
13
+ // per-request override through interceptor, never from sdk-manager directly.
14
+ import { readFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ import { LOG_DIR } from '../../findcc.js';
17
+ import { reportSwallowed } from './error-report.js';
18
+
19
+ const INSTANCE_KEY_RE = /^ccv-[0-9a-f]+$/;
20
+ const MAX_ENTRIES = 1024; // defensive cap: an unbounded map would be a slow leak
21
+
22
+ // instanceKey -> { main: profileId|'max', roles: { subagent, teammate } }
23
+ // 'max' is the explicit "Default" (no rewrite) value and MUST be stored verbatim —
24
+ // an absent mapping means "not bound" (fall back to the process-global profile),
25
+ // which is a different thing from "this session explicitly chose Default".
26
+ const _byInstance = new Map();
27
+
28
+ let _globalDefaultProvider = null;
29
+ // Returns { main, roles } used to SEED a fresh session's binding — the workspace-effective
30
+ // main (getActiveProfileId: workspace override > profile.json.active) and the workspace's
31
+ // stored role assignments, so a seeded session matches the legacy behavior exactly (same
32
+ // upstream as an unbound request AND the same sub/teammate routing).
33
+ let _seedProvider = null;
34
+
35
+ export function isValidInstanceKey(key) {
36
+ return typeof key === 'string' && INSTANCE_KEY_RE.test(key);
37
+ }
38
+
39
+ // interceptor registers the live global-default reader (profile.json.active) here so
40
+ // seeding can resolve the default without this module importing interceptor (L2).
41
+ export function registerGlobalDefaultProvider(fn) {
42
+ _globalDefaultProvider = typeof fn === 'function' ? fn : null;
43
+ }
44
+
45
+ // interceptor registers the workspace-effective seed reader ({ main, roles }).
46
+ export function registerSeedProvider(fn) {
47
+ _seedProvider = typeof fn === 'function' ? fn : null;
48
+ }
49
+
50
+ // The global default profile id: the registered provider first (live value), then a
51
+ // one-off disk read of profile.json.active (so sdk-manager tests / early boot that
52
+ // haven't registered a provider still resolve), then 'max'.
53
+ export function getGlobalDefaultProfileId() {
54
+ if (_globalDefaultProvider) {
55
+ try {
56
+ const v = _globalDefaultProvider();
57
+ if (typeof v === 'string' && v) return v;
58
+ } catch (err) {
59
+ reportSwallowed('proxy-session-registry.defaultProvider', err);
60
+ }
61
+ }
62
+ try {
63
+ const data = JSON.parse(readFileSync(join(LOG_DIR, 'profile.json'), 'utf8'));
64
+ if (typeof data?.active === 'string' && data.active) return data.active;
65
+ } catch { /* missing/corrupt profile.json → fall through to 'max' */ }
66
+ return 'max';
67
+ }
68
+
69
+ // The seed { main, roles } for a fresh session: the registered seed provider first;
70
+ // falls back to the global default main with follow/follow roles.
71
+ function _seedValue() {
72
+ if (_seedProvider) {
73
+ try {
74
+ const v = _seedProvider();
75
+ if (v && typeof v === 'object' && typeof v.main === 'string' && v.main) {
76
+ return {
77
+ main: v.main,
78
+ roles: {
79
+ subagent: typeof v.roles?.subagent === 'string' && v.roles.subagent ? v.roles.subagent : 'follow',
80
+ teammate: typeof v.roles?.teammate === 'string' && v.roles.teammate ? v.roles.teammate : 'follow',
81
+ },
82
+ };
83
+ }
84
+ } catch (err) {
85
+ reportSwallowed('proxy-session-registry.seedProvider', err);
86
+ }
87
+ }
88
+ return { main: getGlobalDefaultProfileId(), roles: { subagent: 'follow', teammate: 'follow' } };
89
+ }
90
+
91
+ export function getSessionProxy(instanceKey) {
92
+ if (!isValidInstanceKey(instanceKey)) return undefined;
93
+ return _byInstance.get(instanceKey);
94
+ }
95
+
96
+ // Overwrite a session's binding (user-driven change). Unknown keys are dropped;
97
+ // 'max' is a valid explicit Default for main and for each role.
98
+ export function setSessionProxyProfile(instanceKey, { main, roles } = {}) {
99
+ if (!isValidInstanceKey(instanceKey)) return false;
100
+ const entry = {
101
+ main: typeof main === 'string' && main ? main : getGlobalDefaultProfileId(),
102
+ roles: {
103
+ subagent: typeof roles?.subagent === 'string' && roles.subagent ? roles.subagent : 'follow',
104
+ teammate: typeof roles?.teammate === 'string' && roles.teammate ? roles.teammate : 'follow',
105
+ },
106
+ };
107
+ if (_byInstance.size >= MAX_ENTRIES && !_byInstance.has(instanceKey)) {
108
+ // Evict the oldest entry (Map preserves insertion order).
109
+ const oldest = _byInstance.keys().next().value;
110
+ _byInstance.delete(oldest);
111
+ }
112
+ _byInstance.set(instanceKey, entry);
113
+ return true;
114
+ }
115
+
116
+ // Seed a session's binding ONLY when none exists yet (a returning/reattached session
117
+ // must never lose the choice the user already made). Seeds from the workspace-effective
118
+ // main + stored roles (via the seed provider) so a fresh session matches legacy behavior.
119
+ export function seedSessionProxyProfile(instanceKey) {
120
+ if (!isValidInstanceKey(instanceKey)) return false;
121
+ if (_byInstance.has(instanceKey)) return false;
122
+ const seed = _seedValue();
123
+ return setSessionProxyProfile(instanceKey, { main: seed.main, roles: seed.roles });
124
+ }
125
+
126
+ export function clearSessionProxyProfile(instanceKey) {
127
+ return _byInstance.delete(instanceKey);
128
+ }
129
+
130
+ export function clearSessionProxyProfiles() {
131
+ _byInstance.clear();
132
+ }
133
+
134
+ // A deleted profile must not leave a dangling binding behind: drop mappings whose
135
+ // main (or a role) points at a profile that no longer exists. 'max' and 'follow'
136
+ // are always valid. Resolution also falls back at read time, so this is belt+braces.
137
+ export function pruneSessionProxyProfiles(validIds) {
138
+ if (!(validIds instanceof Set)) return;
139
+ const valid = (id) => id === 'max' || id === 'follow' || validIds.has(id);
140
+ for (const [key, entry] of _byInstance) {
141
+ if (!valid(entry.main)) { _byInstance.delete(key); continue; }
142
+ if (!valid(entry.roles.subagent)) entry.roles.subagent = 'follow';
143
+ if (!valid(entry.roles.teammate)) entry.roles.teammate = 'follow';
144
+ }
145
+ }
146
+
147
+ export function listSessionProxyProfiles() {
148
+ return [..._byInstance.entries()].map(([instanceKey, v]) => ({ instanceKey, ...v }));
149
+ }
150
+
151
+ export function __resetSessionProxyProfilesForTests() {
152
+ _byInstance.clear();
153
+ // NOTE: providers (_globalDefaultProvider / _seedProvider) are owned by the registrar
154
+ // (interceptor) and intentionally NOT cleared here — clearing them would silently
155
+ // degrade later seeds to the disk fallback within the same process.
156
+ }
@@ -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.
@@ -3120,7 +3199,7 @@ export function __isEphemeralHostForTests(cwd) {
3120
3199
  * must come from the same selection as PTY mode, else the SDK spawns a PATH claude that
3121
3200
  * host security tooling (e.g. agent-security headless guards) may SIGKILL on spawn
3122
3201
  */
3123
- export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable } = {}) {
3202
+ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broadcastWs, permissionMode, runWaterfallHook, onAgentLoopStart, onAgentLoopEnd, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir } = {}) {
3124
3203
  void projectName; // reserved (display name comes from the wire path)
3125
3204
  // Process-global callbacks (cli.js registers one wiring; every session reuses it). Only
3126
3205
  // OVERWRITE when a callback is actually passed — a later per-workspace init (the launch
@@ -3141,8 +3220,11 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3141
3220
  // and tears down ONLY this session's prior generation (tests / hot reload) — other
3142
3221
  // workspaces' sessions (and same-cwd siblings) are untouched.
3143
3222
  const sess = _getOrCreateSession(cwd);
3144
- sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable });
3223
+ sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir });
3145
3224
  _activeKey = sess.instanceKey;
3225
+ // Seed the per-session proxy binding from the global default (no-op when the
3226
+ // session is already bound, so a re-init never clobbers a user's choice).
3227
+ seedSessionProxyProfile(sess.instanceKey);
3146
3228
  }
3147
3229
 
3148
3230
  /**
@@ -3186,6 +3268,7 @@ export function createSdkSession(cwd, cfg) {
3186
3268
  sess._markFreshLaunch();
3187
3269
  _adoptProcessWiring();
3188
3270
  _activeKey = sess.instanceKey;
3271
+ seedSessionProxyProfile(sess.instanceKey);
3189
3272
  return { instanceKey: sess.instanceKey };
3190
3273
  }
3191
3274
 
@@ -3366,6 +3449,7 @@ export function stopSession() {
3366
3449
  }
3367
3450
  _sessions.clear();
3368
3451
  _activeKey = null;
3452
+ clearSessionProxyProfiles();
3369
3453
  // Process-global wiring is cleared on the HARD teardown boundary. initSdkSession only
3370
3454
  // overwrites a callback when one is actually passed (so a per-workspace launch init
3371
3455
  // cannot wipe cli.js's process-wide wiring mid-run); that guard means an init that
@@ -3410,6 +3494,9 @@ export function attachSdkSession(anchor) {
3410
3494
  if (!sess) return { ok: false, reason: 'not-found' };
3411
3495
  const switched = sess.instanceKey !== _activeKey;
3412
3496
  _activeKey = sess.instanceKey;
3497
+ // Activating a session binds its proxy (seeded from the global default when the
3498
+ // session predates the mapping or its binding was cleared).
3499
+ seedSessionProxyProfile(sess.instanceKey);
3413
3500
  return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
3414
3501
  }
3415
3502
 
@@ -3464,6 +3551,7 @@ export function closeSdkSession(anchor = {}) {
3464
3551
  // close/relaunch triggered by one of those frames must register a fresh session,
3465
3552
  // never be deleted by the tail of the older close operation.
3466
3553
  _sessions.delete(sess.instanceKey);
3554
+ clearSessionProxyProfile(sess.instanceKey);
3467
3555
  if (killedActive) {
3468
3556
  // Prefer a SAME-CWD sibling (the twin the user most likely wants next), else fall
3469
3557
  // 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)