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
package/dist/index.html CHANGED
@@ -21,7 +21,7 @@
21
21
  // 整体显示大小已弃用 CSS zoom:Electron 改用 webFrame.setZoomFactor(首屏抢占见
22
22
  // electron/tab-content-preload.js),纯浏览器交由用户用浏览器自带快捷键缩放,故此处不再设 zoom。
23
23
  </script>
24
- <script type="module" crossorigin src="./assets/index-OTFFui4C.js"></script>
24
+ <script type="module" crossorigin src="./assets/index-DBmXRTLE.js"></script>
25
25
  <link rel="modulepreload" crossorigin href="./assets/vendor-antd-C5Wsfsxn.js">
26
26
  <link rel="modulepreload" crossorigin href="./assets/vendor-codemirror-DPXDhteu.js">
27
27
  <link rel="modulepreload" crossorigin href="./assets/vendor-mdxeditor-DLPCj_fe.js">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.35",
3
+ "version": "1.9.36",
4
4
  "description": "Claude Code logging, visualization, and management toolkit — launch a web viewer alongside Claude Code with full request/response tracing, proxy, and mobile support",
5
5
  "license": "MIT",
6
6
  "main": "server.js",
package/server/i18n.js CHANGED
@@ -3099,6 +3099,10 @@ const i18nData = {
3099
3099
  "tr": "IM botu '{id}' zaten çalışıyor (pid {pid}); ikinci bir örnek başlatılması reddedildi.",
3100
3100
  "uk": "IM-бот '{id}' вже запущено (pid {pid}); запуск другого екземпляра відхилено."
3101
3101
  },
3102
+ "cli.imSdkUnavailable": {
3103
+ "zh": "Agent SDK 不可用(缺少 @anthropic-ai/claude-agent-sdk),IM worker '{id}' 回退到 PTY 模式;首次运行可能卡在信任/旁路确认。",
3104
+ "en": "Agent SDK unavailable (missing @anthropic-ai/claude-agent-sdk) — IM worker '{id}' falls back to PTY mode and may block on the first-run trust/bypass prompt."
3105
+ },
3102
3106
  };
3103
3107
 
3104
3108
  // 将 { key: { lang: text } } 转换为 { lang: { key: text } }
@@ -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 } 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 请求
@@ -398,6 +402,7 @@ function _loadProxyProfile() {
398
402
  profiles.push({ ...p, apiKey });
399
403
  }
400
404
  _profilesById = new Map(profiles.map(p => [p.id, p]));
405
+ _globalDefaultId = (typeof data.active === 'string' && data.active) ? data.active : 'max';
401
406
  // active 解析优先级:workspace override > profile.json.active (兼容老数据 / 全局回退) > null
402
407
  const ws = _readWorkspaceActive();
403
408
  _roleIds = ws.roles;
@@ -406,6 +411,7 @@ function _loadProxyProfile() {
406
411
  _activeProfile = (active && active.id !== 'max') ? active : null;
407
412
  } catch (err) {
408
413
  _activeProfile = null;
414
+ _globalDefaultId = 'max';
409
415
  _roleIds = normalizeRoles(undefined);
410
416
  _profilesById = new Map();
411
417
  if (process.env.CCV_DEBUG_HOTSWITCH) {
@@ -495,31 +501,54 @@ export function isOfficialDefaultEndpoint() {
495
501
  return !CUSTOM_API_HOST || /(^|\.)anthropic\.com$/i.test(CUSTOM_API_HOST);
496
502
  }
497
503
 
504
+ // Per-session main profile: fold the session binding (instanceKey) on top of the
505
+ // process-global _activeProfile. An unbound session returns _activeProfile unchanged.
506
+ function _mainProfileForInstance(instanceKey) {
507
+ if (typeof instanceKey !== 'string' || !/^ccv-[0-9a-f]+$/.test(instanceKey)) return _activeProfile;
508
+ return resolveSessionMainProfile(getSessionProxy(instanceKey), _profilesById, _activeProfile);
509
+ }
510
+
511
+ // proxy.js 消费方:当前生效的 main profile(可按 instanceKey 覆盖)。
512
+ function getEffectiveMainProfile(instanceKey) {
513
+ return _mainProfileForInstance(instanceKey);
514
+ }
515
+
516
+ // 全局默认(profile.json.active),供「设为全局默认」/ 新会话 seed 的 UI 回显。
517
+ function getGlobalDefaultProfileId() {
518
+ return _globalDefaultId;
519
+ }
520
+
498
521
  // 请求时的有效角色 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;
522
+ // 存储的 sub/teammate 分配不生效(Max 订阅保护;main 切走后原样恢复)。按会话 main 判定。
523
+ function _effectiveRoleProfile(role, instanceKey) {
524
+ const main = _mainProfileForInstance(instanceKey);
525
+ const p = resolveSessionRoleProfile(role, getSessionProxy(instanceKey), _profilesById, _activeProfile, _roleIds);
526
+ if (role !== 'main' && !main && isOfficialDefaultEndpoint()) return null;
503
527
  return p;
504
528
  }
505
529
 
506
530
  // proxy.js 消费方:属主进程在 body 缓冲后按角色选上游,与 hook 的改写保持同一解析路径。
507
- function getEffectiveRoleProfile(role) {
508
- return _effectiveRoleProfile(role);
531
+ function getEffectiveRoleProfile(role, instanceKey) {
532
+ return _effectiveRoleProfile(role, instanceKey);
509
533
  }
510
534
 
511
535
  // proxy.js 分类短路用:存在显式角色分配(非 follow)才值得在属主进程解析 body 分类——
512
- // 无分配时任意角色都解析到 main 活跃 profile,分类不影响选路。
513
- function hasExplicitRoleAssignments() {
514
- return _roleIds.subagent !== 'follow' || _roleIds.teammate !== 'follow';
536
+ // 无分配时任意角色都解析到 main 活跃 profile,分类不影响选路。会话绑定也算"有分配"。
537
+ // (只判 roles:会话 main 与全局默认的差异已由 getEffectiveMainProfile 在选路/改写两端
538
+ // 直接处理,不需要为此对每个 LLM 请求做 body 分类解析。)
539
+ function hasExplicitRoleAssignments(instanceKey) {
540
+ if (_roleIds.subagent !== 'follow' || _roleIds.teammate !== 'follow') return true;
541
+ const sess = typeof instanceKey === 'string' ? getSessionProxy(instanceKey) : undefined;
542
+ if (!sess) return false;
543
+ return sess.roles.subagent !== 'follow' || sess.roles.teammate !== 'follow';
515
544
  }
516
545
 
517
- // 测试用:当前各角色的有效 profile(main 恒为 _activeProfile)。
518
- function getProxyRoleProfiles() {
546
+ // 测试用:当前各角色的有效 profile(main 恒为会话/全局 main)。
547
+ function getProxyRoleProfiles(instanceKey) {
519
548
  return {
520
- main: _activeProfile,
521
- subagent: _effectiveRoleProfile('subagent'),
522
- teammate: _effectiveRoleProfile('teammate'),
549
+ main: _mainProfileForInstance(instanceKey),
550
+ subagent: _effectiveRoleProfile('subagent', instanceKey),
551
+ teammate: _effectiveRoleProfile('teammate', instanceKey),
523
552
  };
524
553
  }
525
554
 
@@ -560,7 +589,7 @@ function _replaceProxyAuthHeaders(headers, apiKey) {
560
589
  return { headers: newHeaders, matchedAuthKey, matchedXApiKey };
561
590
  }
562
591
 
563
- export { _activeProfile, _defaultConfig, _loadProxyProfile, PROFILE_PATH, setActiveProfileForWorkspace, getActiveProfileId, getStoredRoles, getProxyRoleProfiles, getEffectiveRoleProfile, hasExplicitRoleAssignments, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState };
592
+ export { _activeProfile, _defaultConfig, _loadProxyProfile, PROFILE_PATH, setActiveProfileForWorkspace, getActiveProfileId, getStoredRoles, getProxyRoleProfiles, getEffectiveRoleProfile, getEffectiveMainProfile, getGlobalDefaultProfileId, hasExplicitRoleAssignments, RETRY_CONFIG_PATH, _retryConfigState, _loadRetryConfigState };
564
593
 
565
594
  // 1.7.0: the v1 single-file write path is retired — logs live in per-session
566
595
  // v2 dirs owned by V2Writer. Only the project binding (name + dir) remains
@@ -867,6 +896,14 @@ _syncContinuationMode(); // seed from the CLI env at module load (`ccv -c`)
867
896
  _loadProxyProfile();
868
897
  try { watchFile(PROFILE_PATH, { interval: 1500 }, _loadProxyProfile); } catch { }
869
898
  _armWorkspaceActiveWatcher();
899
+ // Let the per-session registry resolve the global default (profile.json.active) from the
900
+ // live value instead of re-reading disk on every session seed.
901
+ registerGlobalDefaultProvider(() => _globalDefaultId);
902
+ // Seed a fresh session with the WORKSPACE-EFFECTIVE main (getActiveProfileId: workspace
903
+ // override > profile.json.active) and the workspace's stored role assignments — so a
904
+ // seeded session matches the legacy behavior (same upstream AND same role routing as an
905
+ // unbound request), instead of silently dropping pre-existing role assignments.
906
+ registerSeedProvider(() => ({ main: getActiveProfileId(), roles: { ..._roleIds } }));
870
907
 
871
908
  // Retry config: initial load + watchFile cross-process sync (UI writes
872
909
  // retry-config.json → hot-reloaded within 1.5s, mirroring PROFILE_PATH above).
@@ -1261,8 +1298,13 @@ export function setupInterceptor() {
1261
1298
  // 仅当「确实无需分类」(无 profile + 无角色分配 + live 未启用)才短路。
1262
1299
  let _fetchUrl = url;
1263
1300
  let _fetchOpts = options;
1264
- const _skipClassify = !_activeProfile && _roleIds.subagent === 'follow' && _roleIds.teammate === 'follow'
1265
- && !liveSystemPromptEnabled();
1301
+ // Per-session override: the spawned claude self-reports its instanceKey via
1302
+ // x-ccv-instance (validated into requestEntry._ccvInstance upstream). When this
1303
+ // request belongs to a bound session, its proxy choice overrides the global one.
1304
+ const _ccvInstance = requestEntry?._ccvInstance;
1305
+ const _reqMain = _mainProfileForInstance(_ccvInstance);
1306
+ const _skipClassify = !_reqMain && _roleIds.subagent === 'follow' && _roleIds.teammate === 'follow'
1307
+ && !liveSystemPromptEnabled() && !hasExplicitRoleAssignments(_ccvInstance);
1266
1308
  // 最高优先级硬判据(review 第二轮二次验证 P1-1 残余,与 contentFilter.js:158 同构):
1267
1309
  // 请求头 x-claude-code-agent-id 是 SDK 命名队友(name@…)/ 匿名子代理(hex)的判别信号,
1268
1310
  // 不依赖 system 文本 —— body 正则(TEAMMATE_SYSTEM_RE / cc_is_subagent)对「SDK 身份行 +
@@ -1282,7 +1324,7 @@ export function setupInterceptor() {
1282
1324
  isHeartbeat: !!requestEntry?.isHeartbeat,
1283
1325
  });
1284
1326
  }
1285
- const _effProfile = _effectiveRoleProfile(_proxyRole);
1327
+ const _effProfile = _effectiveRoleProfile(_proxyRole, _ccvInstance);
1286
1328
  // 生效模型解析提到块外:live system 改写(步骤 3.5)需要在无 baseURL 的纯模型
1287
1329
  // profile 下也能拿到目标模型;_targetModel 为 null 时回落到请求自身的 model。
1288
1330
  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
+ }
@@ -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
+ }
@@ -1,9 +1,9 @@
1
1
  // IM 进程管理(父进程侧)—— 由主交互式 ccv 调用,负责把每个启用的 IM 作为 detached 常驻
2
- // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImMode)持有 im.lock;
3
- // 本模块只读锁 + 探活 + spawn/kill。
2
+ // 子进程拉起 / 停止 / 查询状态 / 启动时 reconcile。worker 自身(cli.js runImSdkMode / `--im-sdk`,
3
+ // `--im-pty` 为 legacy PTY 排障口)持有 im.lock;本模块只读锁 + 探活 + spawn/kill。
4
4
  //
5
5
  // 设计:detached + unref(主 ccv 关闭后 worker 仍在线);停止时杀**进程组**清理 worker 的
6
- // Claude PTY + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
6
+ // Claude 会话 + proxy 等孙进程;env 用「前缀剥离 + 白名单回填」杜绝 CCV_*/CCVIEWER_* 泄漏。
7
7
  // v1 不做常驻 supervisor(reconcile-on-startup + 配置保存即驱动 已覆盖主路径,且避免多主进程互斗)。
8
8
  import { spawn as nodeSpawn, execSync } from 'node:child_process';
9
9
  import { openSync, closeSync, mkdirSync } from 'node:fs';
@@ -54,7 +54,8 @@ export function buildChildEnv(id, base = process.env) {
54
54
  }
55
55
 
56
56
  /**
57
- * 以 detached 子进程拉起一个 IM worker:`node cli.js --im <id> --no-open`,cwd=IM_<id>/。
57
+ * 以 detached 子进程拉起一个 IM worker:`node cli.js --im-sdk <id> --no-open`,cwd=IM_<id>/。
58
+ * (SDK worker 是默认形态;cli.js 把裸 `--im` 也映射为 SDK,`--im-pty` 为隐藏排障口。)
58
59
  * @param {string} id
59
60
  * @param {{ spawnImpl?: Function }} [opts] 测试可注入 spawnImpl
60
61
  * @returns {{ pid:number|undefined, dir:string, outLog:string }}
@@ -86,7 +87,7 @@ export function spawnImProcess(id, opts = {}) {
86
87
  stdio = ['ignore', fd, fd];
87
88
  } catch { /* 无法开日志文件时退化为 ignore */ }
88
89
 
89
- const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im', id, '--no-open'], {
90
+ const child = spawnImpl(resolveNodeBinary(), [CLI_JS, '--im-sdk', id, '--no-open'], {
90
91
  cwd: dir,
91
92
  env: buildChildEnv(id),
92
93
  stdio,
@@ -94,7 +94,10 @@ export function evaluateImDeny(toolName, toolInput = {}, opts = {}) {
94
94
  return { deny: false };
95
95
  }
96
96
 
97
- if (toolName === 'Read') {
97
+ // Read-class tools: Read (file_path), Grep/Glob (path), NotebookRead (notebook_path).
98
+ // Grep/Glob 的 path 指向被读取的目录/文件 —— 否则 `Grep {path:'~/.ssh'}` 会绕过 Read 路径层
99
+ // 把凭证内容读进上下文再随答复外带(review-security P1-3)。复用同一套读取判定。
100
+ if (toolName === 'Read' || toolName === 'Grep' || toolName === 'Glob' || toolName === 'NotebookRead') {
98
101
  const abs = pathOf(toolInput, home);
99
102
  if (!abs) return { deny: false };
100
103
  if (isVaultFile(abs) || isTaskDataFile(abs)) return { deny: true, reason: 'read of the credential vault / master key' };
@@ -751,3 +751,54 @@ export function isValidRoleValue(v, profilesById) {
751
751
  if (typeof v !== 'string' || !v) return false;
752
752
  return !!(profilesById && typeof profilesById.get === 'function' && profilesById.get(v));
753
753
  }
754
+
755
+ // ─── Per-session (per-instanceKey) proxy resolution ───────────────────────────
756
+ // A session binding is { main, roles:{subagent,teammate} } (see
757
+ // lib/proxy-session-registry.js). These pure functions fold a session binding on top
758
+ // of the process-global profile so a request can be rerouted per session. They are
759
+ // the SINGLE source of truth shared by proxy.js (upstream pick) and the interceptor
760
+ // fetch hook (URL/auth/model rewrite) — the two layers must never diverge.
761
+ //
762
+ // mapped === undefined means "this session has no binding" (PTY / ephemeral / an
763
+ // external caller): the request follows the legacy global profile exactly as before.
764
+ // A present binding with main==='max' means the session explicitly chose Default:
765
+ // return null (no rewrite) and DO NOT follow the global profile afterwards.
766
+
767
+ // Resolve a session's effective MAIN profile.
768
+ // sessionEntry: the binding (or undefined when unbound)
769
+ // profilesById: Map<profileId, profile>
770
+ // legacyMain: the process-global effective main profile (_activeProfile)
771
+ export function resolveSessionMainProfile(sessionEntry, profilesById, legacyMain) {
772
+ if (sessionEntry === undefined || sessionEntry === null) return legacyMain || null;
773
+ const main = sessionEntry.main;
774
+ if (main === 'max') return null; // explicit Default
775
+ if (typeof main === 'string' && main) {
776
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(main) : undefined;
777
+ return hit || legacyMain || null; // dangling id → fall back to the legacy global
778
+ }
779
+ return legacyMain || null;
780
+ }
781
+
782
+ // Resolve an effective ROLE profile for a session. Precedence:
783
+ // session role explicit id/'max' (per-session role assignment)
784
+ // session role 'follow' → the SESSION's main (so main+subagent stay together)
785
+ // workspace role id/'max' (legacyRoleIds, when the session has no binding/override)
786
+ // legacyMain
787
+ // 'role' is 'main' | 'subagent' | 'teammate'.
788
+ export function resolveSessionRoleProfile(role, sessionEntry, profilesById, legacyMain, legacyRoleIds) {
789
+ const sessionMain = resolveSessionMainProfile(sessionEntry, profilesById, legacyMain);
790
+ if (role === 'main') return sessionMain;
791
+ const sessionRole = sessionEntry && sessionEntry.roles ? sessionEntry.roles[role] : undefined;
792
+ if (typeof sessionRole === 'string' && sessionRole && sessionRole !== 'follow') {
793
+ if (sessionRole === 'max') return null; // explicit Default for this role
794
+ const hit = profilesById && typeof profilesById.get === 'function' ? profilesById.get(sessionRole) : undefined;
795
+ return hit || sessionMain;
796
+ }
797
+ // session role is 'follow'/absent → follow the session main. When the session has NO
798
+ // binding at all, defer to the legacy workspace role assignment (existing behavior).
799
+ if (sessionEntry === undefined || sessionEntry === null) {
800
+ return resolveRoleProfile(role, legacyRoleIds, profilesById, legacyMain);
801
+ }
802
+ return sessionMain;
803
+ }
804
+