cc-viewer 1.9.34 → 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 (40) hide show
  1. package/cli.js +355 -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-dQkBQGgg.js → ArchivePreview-ezRMkut5.js} +1 -1
  5. package/dist/assets/{AudioPreview-B6gJoe0v.js → AudioPreview-MxQVazDj.js} +1 -1
  6. package/dist/assets/{MdxEditorPanel-COJDASLB.js → MdxEditorPanel-CmG2jyvK.js} +1 -1
  7. package/dist/assets/{Mobile-Cq04x2pS.js → Mobile-BerOQqT4.js} +1 -1
  8. package/dist/assets/{ProxyStatsModal-BRtZRf0B.js → ProxyStatsModal-dqlP2r2c.js} +1 -1
  9. package/dist/assets/{SubtitlePreview-C67JiAyR.js → SubtitlePreview-CHRRgV95.js} +1 -1
  10. package/dist/assets/index-DBmXRTLE.js +2 -0
  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 +114 -25
  16. package/server/lib/anthropic-auth-placeholder.js +147 -0
  17. package/server/lib/continuation-args.js +25 -0
  18. package/server/lib/im/im-bridge-core.js +59 -14
  19. package/server/lib/im/im-permissions.js +48 -0
  20. package/server/lib/im/im-process-manager.js +6 -5
  21. package/server/lib/im-deny.js +4 -1
  22. package/server/lib/interceptor-core.js +51 -0
  23. package/server/lib/proxy-session-registry.js +156 -0
  24. package/server/lib/scheduled-task-executor.js +6 -3
  25. package/server/lib/sdk-manager.js +376 -88
  26. package/server/lib/session-start-bridge.js +7 -1
  27. package/server/lib/update-job.js +3 -3
  28. package/server/lib/v2/session-select.js +18 -2
  29. package/server/lib/v2/v2-writer.js +249 -21
  30. package/server/proxy.js +15 -7
  31. package/server/pty-manager.js +62 -41
  32. package/server/routes/events.js +16 -4
  33. package/server/routes/preferences.js +108 -24
  34. package/server/routes/resume.js +271 -27
  35. package/server/routes/update.js +15 -2
  36. package/server/routes/workspaces.js +112 -29
  37. package/server/server.js +60 -10
  38. package/dist/assets/App-CZ0L1Cvm.js +0 -2
  39. package/dist/assets/index-Cb1Ur9uR.js +0 -2
  40. package/dist/assets/seqResourceLoaders-BQo28rrY.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-Cb1Ur9uR.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.34",
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
@@ -632,6 +661,28 @@ const _v2Writer = new V2Writer({
632
661
  });
633
662
  export { _v2Writer };
634
663
 
664
+ /**
665
+ * Retire a CLOSED random-key SDK session's routing (2026-11) so its late traffic (a
666
+ * draining child's heartbeat/completion) can no longer move `_currentSid` /
667
+ * `_currentSidByInstance` into its old dir. Called ONLY from the explicit SDK close path
668
+ * (routes/resume.js, when closeSdkSession reports wasFreshKey===true) — never from a
669
+ * launch or initForWorkspace/resetForLiveRelaunch: a same-cwd sibling stays LIVE and
670
+ * depends on its per-instance pointers surviving a relaunch.
671
+ */
672
+ export function retireInstance(instanceKey) {
673
+ try { _v2Writer.retireInstance(instanceKey); } catch (err) { reportSwallowed('interceptor.retire-instance', err); }
674
+ }
675
+
676
+ /**
677
+ * Release a CLOSED instance's per-instance routing state WITHOUT retiring the key
678
+ * (2026-11, same-cwd sibling close). Used by the SDK close path for a DETERMINISTIC cwd
679
+ * key (wasFreshKey=false) — that key is re-created on a normal relaunch, so it must be
680
+ * cleared, never retired. See v2-writer.releaseInstance.
681
+ */
682
+ export function releaseInstance(instanceKey) {
683
+ try { _v2Writer.releaseInstance(instanceKey); } catch (err) { reportSwallowed('interceptor.release-instance', err); }
684
+ }
685
+
635
686
  // S6b: the live read source — the current v2 session dir once the writer has
636
687
  // resolved a session; '' before the first request (readers treat a missing
637
688
  // path as an empty stream, same as v1's not-yet-created file did).
@@ -705,6 +756,11 @@ export function getLiveLogSource({ serveInFlight = true } = {}) {
705
756
  export function markSessionStart(payload) {
706
757
  try {
707
758
  const { source, sessionId, transcriptPath, cwd } = payload || {};
759
+ // Same-cwd twin routing (R1): the PTY that spawned this claude stamped its
760
+ // instanceKey into the env, forwarded by session-start-bridge. Validate the
761
+ // shape before letting it steer the resume-switch routing.
762
+ const rawInst = (payload && typeof payload.instanceKey === 'string') ? payload.instanceKey : '';
763
+ const instanceKey = /^ccv-[0-9a-f]+$/.test(rawInst) ? rawInst : null;
708
764
  // 'resume' re-binds the writer AND feeds snapshot Bind B; 'fork' feeds only
709
765
  // Bind B (a fork mints a fresh wire sid + the fork mark suppresses adoption,
710
766
  // so the writer routes it correctly without a switch). Everything else is
@@ -740,8 +796,11 @@ export function markSessionStart(payload) {
740
796
  _v2Writer.beginResumeSwitch({
741
797
  transcriptUuid,
742
798
  hookSid: (typeof sessionId === 'string' && sessionId) ? sessionId : null,
743
- // Keyed by the resumed conversation's project (bound = undefined default).
799
+ // Keyed by the resumed conversation's project (bound = undefined default)
800
+ // AND by this instance, so a same-cwd twin's /resume switch is consumed
801
+ // only by that twin's own next main request, never a sibling's.
744
802
  project: resumeProject || undefined,
803
+ instanceKey,
745
804
  });
746
805
  };
747
806
  if (!resumeProject || (_projectName && resumeProject === _projectName)) {
@@ -837,6 +896,14 @@ _syncContinuationMode(); // seed from the CLI env at module load (`ccv -c`)
837
896
  _loadProxyProfile();
838
897
  try { watchFile(PROFILE_PATH, { interval: 1500 }, _loadProxyProfile); } catch { }
839
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 } }));
840
907
 
841
908
  // Retry config: initial load + watchFile cross-process sync (UI writes
842
909
  // retry-config.json → hot-reloaded within 1.5s, mirroring PROFILE_PATH above).
@@ -849,10 +916,12 @@ const _initPromise = Promise.resolve();
849
916
 
850
917
  export { LOG_FILE, _initPromise, _projectName, _logDir };
851
918
 
852
- // 工作区模式:绑定指定路径的项目(v2 会话目录由 V2Writer 按需创建)。
853
- // forceNew 仅存于签名兼容(Electron multi-tab 传入):v2 下每个 claude 进程
854
- // 天然是新 session,无旧文件可复用。
855
- export function initForWorkspace(projectPath, { forceNew = false } = {}) { // eslint-disable-line no-unused-vars
919
+ // Workspace mode: bind the project at the given path (v2 session dirs are
920
+ // created on demand by V2Writer). forceNew (a second claude instance in the
921
+ // same cwd) keeps the live twin's session bindings/owner.lock on a same-project
922
+ // re-bind — the new process gets a fresh sid and a fresh dir; the twin's must
923
+ // not be cleared.
924
+ export function initForWorkspace(projectPath, { forceNew = false, preserveLiveTwin = false } = {}) {
856
925
  const projectName = projectKeyForCwd(projectPath);
857
926
  const dir = join(LOG_DIR, projectName);
858
927
  try { mkdirSync(dir, { recursive: true }); } catch {}
@@ -870,7 +939,22 @@ export function initForWorkspace(projectPath, { forceNew = false } = {}) { // es
870
939
  // Fresh workspace context — no carried names apply; future requests must
871
940
  // create session dirs under the NEW project.
872
941
  _agentSpawnRegistry.clear();
873
- _v2Writer.resetSessions(previousProject || null); // also clears the per-process `-c` adoption latch
942
+ // forceNew on the SAME project: a live same-cwd twin keeps its session
943
+ // bindings + owner.lock claims (releasing them would expose its dirs to a
944
+ // sibling's cold-load/adoption). Only launch-boundary state that could hijack
945
+ // or misroute the fresh twin is cleared. Any other switch keeps the old
946
+ // scoped reset semantics.
947
+ //
948
+ // SDK +1 (preserveLiveTwin, 2026-11): the same-cwd sibling stays LIVE and the new
949
+ // child always carries x-ccv-instance, so it never enters the process-global
950
+ // `_pendingNoSid` bucket. resetForLiveRelaunch's project-level clear
951
+ // (`_pendingNoSidByInstance`/`_lateHandles`) would instead drain the SURVIVING
952
+ // sibling's in-flight buckets — so the SDK +1 path skips the writer reset entirely.
953
+ if (forceNew && previousProject && previousProject === projectName) {
954
+ if (!preserveLiveTwin) _v2Writer.resetForLiveRelaunch(projectName);
955
+ } else {
956
+ _v2Writer.resetSessions(previousProject || null); // also clears the per-process `-c` adoption latch
957
+ }
874
958
  // A `--fork-session` / `-r` launch marks fork/resume intent; neither must
875
959
  // leak into a LATER workspace's `-c` (in a long-lived server that would
876
960
  // permanently suppress adoption). Clear both marks per launch and re-sync —
@@ -1214,8 +1298,13 @@ export function setupInterceptor() {
1214
1298
  // 仅当「确实无需分类」(无 profile + 无角色分配 + live 未启用)才短路。
1215
1299
  let _fetchUrl = url;
1216
1300
  let _fetchOpts = options;
1217
- const _skipClassify = !_activeProfile && _roleIds.subagent === 'follow' && _roleIds.teammate === 'follow'
1218
- && !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);
1219
1308
  // 最高优先级硬判据(review 第二轮二次验证 P1-1 残余,与 contentFilter.js:158 同构):
1220
1309
  // 请求头 x-claude-code-agent-id 是 SDK 命名队友(name@…)/ 匿名子代理(hex)的判别信号,
1221
1310
  // 不依赖 system 文本 —— body 正则(TEAMMATE_SYSTEM_RE / cc_is_subagent)对「SDK 身份行 +
@@ -1235,7 +1324,7 @@ export function setupInterceptor() {
1235
1324
  isHeartbeat: !!requestEntry?.isHeartbeat,
1236
1325
  });
1237
1326
  }
1238
- const _effProfile = _effectiveRoleProfile(_proxyRole);
1327
+ const _effProfile = _effectiveRoleProfile(_proxyRole, _ccvInstance);
1239
1328
  // 生效模型解析提到块外:live system 改写(步骤 3.5)需要在无 baseURL 的纯模型
1240
1329
  // profile 下也能拿到目标模型;_targetModel 为 null 时回落到请求自身的 model。
1241
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
+ }
@@ -0,0 +1,25 @@
1
+ // Shared continuation-arg stripping for "fresh session" launches (forceNew).
2
+ // Consumed by the workspace launch route (packages/app/server/routes/workspaces.js)
3
+ // and the Electron main process (apps/electron/electron/main.js via async import) —
4
+ // keep this the single source of truth so the two argv paths can never drift.
5
+ //
6
+ // `-r`/`--resume` carry a VALUE in the next argv slot — the orphan would land as
7
+ // claude's first positional prompt; `--continue=<x>`/`--resume=<x>` single-token
8
+ // forms and `--fork-session` (invalid without a continue flag) must go too.
9
+
10
+ const VALUE_FLAGS = new Set(['-r', '--resume']);
11
+ const LONE_FLAGS = new Set(['-c', '--continue', '-r', '--resume', '--fork-session']);
12
+
13
+ export function stripContinuationArgs(args) {
14
+ if (!Array.isArray(args)) return [];
15
+ const out = [];
16
+ for (let i = 0; i < args.length; i++) {
17
+ const a = args[i];
18
+ if (typeof a !== 'string') continue;
19
+ if (VALUE_FLAGS.has(a)) { i++; continue; } // flag + its value
20
+ if (LONE_FLAGS.has(a)) continue;
21
+ if (a.startsWith('--continue=') || a.startsWith('--resume=')) continue;
22
+ out.push(a);
23
+ }
24
+ return out;
25
+ }
@@ -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 };