cc-viewer 1.9.36 → 1.9.38

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 (102) hide show
  1. package/README.md +5 -1
  2. package/cli.js +4 -0
  3. package/dist/assets/App-CF8BZExv.js +2 -0
  4. package/dist/assets/App-DwLJPKiz.css +1 -0
  5. package/dist/assets/{ArchivePreview-ezRMkut5.js → ArchivePreview-BwkACTcN.js} +1 -1
  6. package/dist/assets/{AudioPreview-MxQVazDj.js → AudioPreview-Bzzv-8w2.js} +1 -1
  7. package/dist/assets/{MdxEditorPanel-CmG2jyvK.js → MdxEditorPanel-DgInZmjn.js} +1 -1
  8. package/dist/assets/{Mobile-B5V_-6Hc.css → Mobile-B_8Wt_hT.css} +1 -1
  9. package/dist/assets/Mobile-BwxpuUXE.js +1 -0
  10. package/dist/assets/ProxyStatsModal-C0EVF31b.js +1 -0
  11. package/dist/assets/{SubtitlePreview-CHRRgV95.js → SubtitlePreview-D3MhYKJS.js} +1 -1
  12. package/dist/assets/{_baseUniq-ClHxNSma.js → _baseUniq-uUw7d1E3.js} +1 -1
  13. package/dist/assets/{arc-ClGYU-1i.js → arc-BOWuMiV4.js} +1 -1
  14. package/dist/assets/{architectureDiagram-Q4EWVU46-El3lNwsp.js → architectureDiagram-Q4EWVU46-h5aWPWJ4.js} +1 -1
  15. package/dist/assets/{blockDiagram-DXYQGD6D-DH290jST.js → blockDiagram-DXYQGD6D-CudvZcvo.js} +1 -1
  16. package/dist/assets/{c4Diagram-AHTNJAMY-BQMsMwnY.js → c4Diagram-AHTNJAMY-DYlZi3dM.js} +1 -1
  17. package/dist/assets/{channel-C-OnmeWg.js → channel-XJqusGHw.js} +1 -1
  18. package/dist/assets/{chunk-4BX2VUAB-PRxJ3zS8.js → chunk-4BX2VUAB-CLpyEaWp.js} +1 -1
  19. package/dist/assets/{chunk-4TB4RGXK-C_TKsRMW.js → chunk-4TB4RGXK-BAuE3fNK.js} +1 -1
  20. package/dist/assets/{chunk-55IACEB6-nGpnU7E4.js → chunk-55IACEB6-B4tW65z_.js} +1 -1
  21. package/dist/assets/{chunk-EDXVE4YY-D0-9hlXC.js → chunk-EDXVE4YY-Bb7xoST0.js} +1 -1
  22. package/dist/assets/{chunk-FMBD7UC4-hKmwmsrB.js → chunk-FMBD7UC4-CTkqi9Np.js} +1 -1
  23. package/dist/assets/{chunk-OYMX7WX6-CZnR4qSn.js → chunk-OYMX7WX6-uQdTKgLj.js} +1 -1
  24. package/dist/assets/{chunk-QZHKN3VN-CGtdnavD.js → chunk-QZHKN3VN-C6ugcDBb.js} +1 -1
  25. package/dist/assets/{chunk-YZCP3GAM-GPB3qNXk.js → chunk-YZCP3GAM-Hp9H2dEu.js} +1 -1
  26. package/dist/assets/classDiagram-6PBFFD2Q-CqAo3MbD.js +1 -0
  27. package/dist/assets/classDiagram-v2-HSJHXN6E-CqAo3MbD.js +1 -0
  28. package/dist/assets/clone-BIwWiqgh.js +1 -0
  29. package/dist/assets/{cose-bilkent-S5V4N54A-9L57MjYD.js → cose-bilkent-S5V4N54A-BqngH0-b.js} +1 -1
  30. package/dist/assets/{dagre-KV5264BT-CNkz8gO7.js → dagre-KV5264BT-CB2GDseU.js} +1 -1
  31. package/dist/assets/{diagram-5BDNPKRD-DQBFzIFl.js → diagram-5BDNPKRD-DLymVFaP.js} +1 -1
  32. package/dist/assets/{diagram-G4DWMVQ6-CTwwGTIV.js → diagram-G4DWMVQ6-D90wHjyV.js} +1 -1
  33. package/dist/assets/{diagram-MMDJMWI5-BKEsMMNd.js → diagram-MMDJMWI5-BUN9g8qX.js} +1 -1
  34. package/dist/assets/{diagram-TYMM5635-BgAqGIDJ.js → diagram-TYMM5635-I51WOx9p.js} +1 -1
  35. package/dist/assets/{erDiagram-SMLLAGMA-BuR-DOkX.js → erDiagram-SMLLAGMA-CR1_hpJO.js} +1 -1
  36. package/dist/assets/{flowDiagram-DWJPFMVM-CtEs3omg.js → flowDiagram-DWJPFMVM-CiwoAZbF.js} +1 -1
  37. package/dist/assets/{ganttDiagram-T4ZO3ILL-aEyreBxU.js → ganttDiagram-T4ZO3ILL-CJXNdMQL.js} +1 -1
  38. package/dist/assets/{gitGraphDiagram-UUTBAWPF-B0jK9QeS.js → gitGraphDiagram-UUTBAWPF-BaZdjuy6.js} +1 -1
  39. package/dist/assets/{graph-ehKfRbVz.js → graph-CpnKw6r1.js} +1 -1
  40. package/dist/assets/index-B15ZeDb-.css +1 -0
  41. package/dist/assets/{index-B0uKNGh1.js → index-BrAqjeq3.js} +1 -1
  42. package/dist/assets/{index-CtricoKb.js → index-BzeiQo_V.js} +1 -1
  43. package/dist/assets/{index-Dns_OQOp.js → index-C1VAmODt.js} +1 -1
  44. package/dist/assets/{index-D5KJq71j.js → index-C5FKlPaZ.js} +1 -1
  45. package/dist/assets/index-D-DhPfzj.js +2 -0
  46. package/dist/assets/{index-Brys6nSs.js → index-D3x00_V6.js} +1 -1
  47. package/dist/assets/{index-CH6ZHNzo.js → index-DL6PUDDq.js} +1 -1
  48. package/dist/assets/{index-BDj-fJNP.js → index-VjrFIlap.js} +1 -1
  49. package/dist/assets/{infoDiagram-42DDH7IO-CUntIdK6.js → infoDiagram-42DDH7IO-BvyXlqWb.js} +1 -1
  50. package/dist/assets/{ishikawaDiagram-UXIWVN3A-CtCGMBTX.js → ishikawaDiagram-UXIWVN3A-CwbVWeK4.js} +1 -1
  51. package/dist/assets/{journeyDiagram-VCZTEJTY-DCRvOrOx.js → journeyDiagram-VCZTEJTY-DDVzhfoW.js} +1 -1
  52. package/dist/assets/{jszip.min-DZsXbJ4A.js → jszip.min-RVG0sxQ-.js} +1 -1
  53. package/dist/assets/{kanban-definition-6JOO6SKY-jEtOSXmn.js → kanban-definition-6JOO6SKY-CC9zdzb4.js} +1 -1
  54. package/dist/assets/{layout-C-6TbhHY.js → layout-BP8agUEZ.js} +1 -1
  55. package/dist/assets/{linear-DQg_Idt4.js → linear-D2xrTRbP.js} +1 -1
  56. package/dist/assets/{mermaid.core-C_rq53MX.js → mermaid.core-iygJ4rTs.js} +2 -2
  57. package/dist/assets/{min-BqPulfFi.js → min-DZABGYh9.js} +1 -1
  58. package/dist/assets/{mindmap-definition-QFDTVHPH-CNsFBo-7.js → mindmap-definition-QFDTVHPH-DonHZQOo.js} +1 -1
  59. package/dist/assets/{pieDiagram-DEJITSTG-BDn3Cz--.js → pieDiagram-DEJITSTG-CEn16Sb_.js} +1 -1
  60. package/dist/assets/{quadrantDiagram-34T5L4WZ-CsrLWd-H.js → quadrantDiagram-34T5L4WZ-385okL2K.js} +1 -1
  61. package/dist/assets/{requirementDiagram-MS252O5E-DPzJKSB5.js → requirementDiagram-MS252O5E-B7AA6wNS.js} +1 -1
  62. package/dist/assets/{sankeyDiagram-XADWPNL6-DYDGySQ1.js → sankeyDiagram-XADWPNL6-BE2hbI0P.js} +1 -1
  63. package/dist/assets/seqResourceLoaders-BdxjrasH.css +41 -0
  64. package/dist/assets/seqResourceLoaders-DPto114V.js +2 -0
  65. package/dist/assets/{sequenceDiagram-FGHM5R23-HVWMhF8a.js → sequenceDiagram-FGHM5R23-DUbU1ZOb.js} +1 -1
  66. package/dist/assets/{stateDiagram-FHFEXIEX-BtcEUJOY.js → stateDiagram-FHFEXIEX-BKKvwNQM.js} +1 -1
  67. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DWDh2D71.js → stateDiagram-v2-QKLJ7IA2-qXlEdp-K.js} +1 -1
  68. package/dist/assets/{timeline-definition-GMOUNBTQ-B81djDNu.js → timeline-definition-GMOUNBTQ-DQnlfuvY.js} +1 -1
  69. package/dist/assets/{vendor-antd-C5Wsfsxn.js → vendor-antd-DTdiXvO1.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-DPXDhteu.js → vendor-codemirror-Dg_w9qS2.js} +1 -1
  71. package/dist/assets/{vendor-mdxeditor-DLPCj_fe.js → vendor-mdxeditor-DNrU6OL8.js} +2 -2
  72. package/dist/assets/{vendor-qrcode-BzB5n5mK.js → vendor-qrcode-BdV5qU8N.js} +1 -1
  73. package/dist/assets/{vendor-virtuoso-Beq6R5oo.js → vendor-virtuoso-BQELbHyq.js} +1 -1
  74. package/dist/assets/{vennDiagram-DHZGUBPP-BeitG2yA.js → vennDiagram-DHZGUBPP-B51WBYoK.js} +1 -1
  75. package/dist/assets/{wardley-RL74JXVD-BCzOL4u_.js → wardley-RL74JXVD-DQSgSi6f.js} +1 -1
  76. package/dist/assets/{wardleyDiagram-NUSXRM2D-20SEChwk.js → wardleyDiagram-NUSXRM2D-B5PCvQWU.js} +1 -1
  77. package/dist/assets/{xychartDiagram-5P7HB3ND-Behle0ry.js → xychartDiagram-5P7HB3ND-fY2LLKhL.js} +1 -1
  78. package/dist/index.html +5 -5
  79. package/node_modules/@ccv/core/src/sdk-task-label.js +70 -0
  80. package/package.json +1 -1
  81. package/server/interceptor.js +32 -3
  82. package/server/lib/builtin-model-prompts.js +16 -7
  83. package/server/lib/chat-queue.js +159 -31
  84. package/server/lib/compact-inject-guard.js +100 -0
  85. package/server/lib/model-system-prompts.js +207 -13
  86. package/server/lib/project-prefs.js +12 -5
  87. package/server/lib/proxy-session-registry.js +75 -12
  88. package/server/lib/sdk-manager.js +129 -7
  89. package/server/lib/task-state.js +11 -0
  90. package/server/routes/preferences.js +17 -2
  91. package/server/server.js +207 -0
  92. package/dist/assets/App-BJIeZQK0.css +0 -1
  93. package/dist/assets/App-C_S65Ygt.js +0 -2
  94. package/dist/assets/Mobile-BerOQqT4.js +0 -1
  95. package/dist/assets/ProxyStatsModal-dqlP2r2c.js +0 -1
  96. package/dist/assets/classDiagram-6PBFFD2Q-DigyQWGQ.js +0 -1
  97. package/dist/assets/classDiagram-v2-HSJHXN6E-DigyQWGQ.js +0 -1
  98. package/dist/assets/clone-DwpJyNdv.js +0 -1
  99. package/dist/assets/index-BLzca-ta.css +0 -1
  100. package/dist/assets/index-DBmXRTLE.js +0 -2
  101. package/dist/assets/seqResourceLoaders-BOVRL7Y-.js +0 -2
  102. package/dist/assets/seqResourceLoaders-b9deQDrA.css +0 -41
@@ -39,6 +39,7 @@ import { seedSessionProxyProfile, clearSessionProxyProfile, clearSessionProxyPro
39
39
  import { readPrefsRaw } from './prefs-store.js';
40
40
  import { projectKeyForCwd } from './system-prompt-snapshots.js';
41
41
  import { AGENT_PROMPT_SNIPPET_LEN } from '@ccv/core/contentFilter';
42
+ import { hasWireTaskLabel } from '@ccv/core/sdk-task-label';
42
43
  import {
43
44
  computeAutoApprove,
44
45
  createAutoApproveState,
@@ -473,6 +474,21 @@ function _normalizeSdkTask(msg) {
473
474
  const _SDK_TASK_TERMINAL = new Set(['completed', 'failed', 'stopped', 'killed']);
474
475
  function _foldSdkTask(prev, frame) {
475
476
  const next = { ...(prev || {}), taskId: frame.taskId };
477
+ // A task_started re-fire opens a NEW run for this taskId (the client tracker
478
+ // does the same — sdkTaskTracker.js resets status to in_progress on re-fire,
479
+ // "a task id may be reused after session reset or completion"). Reset the
480
+ // run-scoped fields so a previous incarnation's terminal state does not leak
481
+ // into the new run: a status-only task_notification/summary/usage/endTime
482
+ // from the old run must not survive, and the new run starts in 'running'.
483
+ // Without this, merge semantics (post fold-bug fix) would let `completed`
484
+ // stick across the re-fire, and the next reconnect replay would clobber the
485
+ // client's correct in_progress row back to the stale terminal one.
486
+ if (frame.subtype === 'task_started') {
487
+ delete next.status;
488
+ delete next.summary;
489
+ delete next.usage;
490
+ delete next.endTime;
491
+ }
476
492
  if (frame.sessionId != null) next.sessionId = frame.sessionId;
477
493
  if (frame.toolUseId != null) next.toolUseId = frame.toolUseId;
478
494
  if (frame.taskType != null) next.taskType = frame.taskType;
@@ -1820,8 +1836,13 @@ function _createSession(cwd, { freshKey = false } = {}) {
1820
1836
  _sdkTaskTable = new Map();
1821
1837
  _sdkTaskTableSessionId = sdkTaskFrame.sessionId;
1822
1838
  }
1839
+ // Read prev BEFORE the LRU delete — otherwise _foldSdkTask always
1840
+ // sees undefined and "merge" silently becomes "replace", wiping the
1841
+ // started frame's description/toolUseId/promptSnippet on any
1842
+ // status-only task_updated / task_notification.
1843
+ const prev = _sdkTaskTable.get(sdkTaskFrame.taskId);
1823
1844
  _sdkTaskTable.delete(sdkTaskFrame.taskId); // re-insert for LRU order
1824
- _sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(_sdkTaskTable.get(sdkTaskFrame.taskId), sdkTaskFrame));
1845
+ _sdkTaskTable.set(sdkTaskFrame.taskId, _foldSdkTask(prev, sdkTaskFrame));
1825
1846
  while (_sdkTaskTable.size > _SDK_TASK_TABLE_CAP) {
1826
1847
  const oldest = _sdkTaskTable.keys().next().value;
1827
1848
  _sdkTaskTable.delete(oldest);
@@ -2836,6 +2857,39 @@ function _createSession(cwd, { freshKey = false } = {}) {
2836
2857
  return [];
2837
2858
  }
2838
2859
 
2860
+ /**
2861
+ * 960K forced compaction only: skips the idle gate and directly "enqueues one + send-now immediately",
2862
+ * equivalent to the user manually sending now — after interrupting the current turn (q.interrupt), drain pushes this item out as the next turn.
2863
+ * Reuses _sendQueuedNow's full lifecycle (occupies the dispatch slot / _interruptTurn / _suppressDrain reset),
2864
+ * avoiding the naive "interrupt + sendUserMessage" combination getting the message stuck in the queue (_interruptTurn sets
2865
+ * _suppressDrain=true, and busy enqueue does not reset it). Returns _sendQueuedNow's result (the cancelled list).
2866
+ */
2867
+ function _forceSendUserMessage(text) {
2868
+ if (!_query) throw new Error('Agent SDK not available');
2869
+ // The dispatch slot is owned by another in-flight send-now/drain: forcing now would have to
2870
+ // preempt THAT, which the queue model forbids. Enqueue-then-send-now would silently park the
2871
+ // /compact at the FIFO tail and still look like a success upstream (the "fake success" the
2872
+ // rollback path exists to prevent). Fail fast so the caller reports a real, retryable failure.
2873
+ if (_dispatching) {
2874
+ const err = new Error('force-send while another message is dispatching');
2875
+ err.code = 'busy';
2876
+ throw err;
2877
+ }
2878
+ const item = _makeQueueItem(text);
2879
+ _messageQueue.push(item);
2880
+ const cancelled = _sendQueuedNow(item.id);
2881
+ // _sendQueuedNow succeeded only if it actually took the dispatch slot (item no longer queued).
2882
+ const stillQueued = _messageQueue.some((it) => it.id === item.id);
2883
+ if (stillQueued) {
2884
+ // Defensive: slot was free a moment ago but the item wasn't dispatched — don't leave a ghost.
2885
+ _messageQueue = _messageQueue.filter((it) => it.id !== item.id);
2886
+ const err = new Error('force-send did not take the dispatch slot');
2887
+ err.code = 'busy';
2888
+ throw err;
2889
+ }
2890
+ return { ok: true, cancelled: Array.isArray(cancelled) ? cancelled : [] };
2891
+ }
2892
+
2839
2893
  /** Remove one queued message (bubble ×). Returns true when found. The dispatching
2840
2894
  * item is locked until _startTurn accepts it: reject and re-broadcast so a stale
2841
2895
  * enabled bubble converges instead of silently dropping a message mid-commit. */
@@ -3016,6 +3070,7 @@ function _createSession(cwd, { freshKey = false } = {}) {
3016
3070
  sendUserMessage: _sendUserMessage,
3017
3071
  interruptTurn: _interruptTurn,
3018
3072
  sendQueuedNow: _sendQueuedNow,
3073
+ forceSendUserMessage: _forceSendUserMessage,
3019
3074
  removeQueued: _removeQueued,
3020
3075
  clearQueued: _clearQueued,
3021
3076
  getQueueSnapshot: _getQueueSnapshot,
@@ -3029,6 +3084,26 @@ function _createSession(cwd, { freshKey = false } = {}) {
3029
3084
  const head = _pendingTurns[0] || null;
3030
3085
  return { type: 'sdk-session-state', state: _lastSessionState, sessionId: _sessionId || null, cwd: _cwd, instanceKey, turnId: _currentTurnId(), turnStartedAt: head ? head.startedAt : _lastTurnStartedAt, pendingApprovals: _pendingApprovals.size };
3031
3086
  },
3087
+ // Atomic "can a turn start immediately" gate snapshot (used by compact injection etc.): returns all fields needed for live busy/idle in one call.
3088
+ // Difference from getSessionStateSnapshot: state is derived from the live `_queryBusy`/`_pendingTurns`,
3089
+ // not `_lastSessionState` (the latter still lingers at 'idle' during _startTurn's ensure window, causing misjudgment).
3090
+ // When a fresh/resume session has not announced yet, _lastSessionState is null → state is derived as 'idle'
3091
+ // (in that case _queryBusy/_pendingTurns are the truth for busy/idle).
3092
+ getTurnGate: () => {
3093
+ const queueLen = _getQueueSnapshot().length;
3094
+ const busy = _queryBusy || _pendingTurns.length > 0;
3095
+ const pendingApprovals = _pendingApprovals.size;
3096
+ return {
3097
+ exists: true,
3098
+ state: busy ? 'running' : (_lastSessionState || 'idle'),
3099
+ turnId: _currentTurnId(),
3100
+ pendingApprovals,
3101
+ queueLen,
3102
+ instanceKey,
3103
+ // Judgment for injecting a turn immediately: idle + no turn in flight + no pending approval + empty queue.
3104
+ idle: !busy && pendingApprovals === 0 && queueLen === 0,
3105
+ };
3106
+ },
3032
3107
  getContextUsageSnapshot: () => _lastContextUsage,
3033
3108
  getMcpStatusSnapshot: () => _lastMcpStatus,
3034
3109
  getSkillsSnapshot: () => _lastSkillsSnapshot,
@@ -3038,12 +3113,21 @@ function _createSession(cwd, { freshKey = false } = {}) {
3038
3113
  // otherwise a client that missed the session boundary keeps its stale agents.
3039
3114
  // skipTranscript entries are tracked (they carry the session boundary) but hidden
3040
3115
  // from the replay, matching the live path that never shows ambient tasks.
3116
+ // Label-less TERMINAL entries are also hidden: the predicate (hasWireTaskLabel)
3117
+ // is shared with the client tracker and treats null/empty/whitespace-only
3118
+ // description+summary as "no label" — a terminal ghost would render as a bare
3119
+ // `#id` on the HUD with no live update to relabel it. In-flight entries stay
3120
+ // visible regardless of label so a later task_progress(description) frame
3121
+ // can still enrich them. Label-less entries still live in the table for
3122
+ // session-boundary detection and LRU bookkeeping; the filter only spares
3123
+ // the replay payload.
3041
3124
  getSdkTaskSnapshot: () => ({
3042
3125
  type: 'sdk-task-snapshot',
3043
3126
  cwd: _cwd,
3044
3127
  instanceKey,
3045
3128
  sessionId: _sdkTaskTableSessionId,
3046
- tasks: [..._sdkTaskTable.values()].filter((t) => t.skipTranscript !== true),
3129
+ tasks: [..._sdkTaskTable.values()].filter((t) =>
3130
+ t.skipTranscript !== true && hasWireTaskLabel(t)),
3047
3131
  }),
3048
3132
  fetchContextUsage: async () => {
3049
3133
  // On-demand fetch for the HTTP route: refresh the snapshot, broadcast to all clients,
@@ -3172,6 +3256,19 @@ export function __isEphemeralHostForTests(cwd) {
3172
3256
  return false;
3173
3257
  }
3174
3258
 
3259
+ // Seed the per-session proxy binding for a session (no-op when already bound, so a
3260
+ // re-init/attach never clobbers a user's choice). The seed VALUE comes from the registry's
3261
+ // provider (the currently-bound workspace's effective active/roles); the WORKSPACE tag comes
3262
+ // from the session's own cwd, so a later change to that workspace can re-align the binding.
3263
+ // Known limitation: when a session whose cwd ≠ the currently-bound workspace is seeded
3264
+ // (e.g. attaching a session from another workspace, or IM-SDK mode where cwd is LOG_DIR/IM_*),
3265
+ // the value reflects the bound workspace while the tag is the session's own — it self-heals
3266
+ // the next time that workspace is activated (initForWorkspace → reconcile).
3267
+ function _seedProxyBindingForSession(sess) {
3268
+ if (!sess || !sess.instanceKey) return;
3269
+ seedSessionProxyProfile(sess.instanceKey, projectKeyForCwd(sess.cwd));
3270
+ }
3271
+
3175
3272
  /**
3176
3273
  * Initialize (or re-initialize) a workspace's SDK session.
3177
3274
  * Does NOT start a query — waits for the first user message via sendUserMessage().
@@ -3222,9 +3319,7 @@ export function initSdkSession(cwd, projectName, { onTurnEnd, onQueryError, broa
3222
3319
  const sess = _getOrCreateSession(cwd);
3223
3320
  sess.init({ permissionMode, env, settings, model, launchResume, userArgs, claudeExecutable, unattended, insideLogDir });
3224
3321
  _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);
3322
+ _seedProxyBindingForSession(sess);
3228
3323
  }
3229
3324
 
3230
3325
  /**
@@ -3268,7 +3363,7 @@ export function createSdkSession(cwd, cfg) {
3268
3363
  sess._markFreshLaunch();
3269
3364
  _adoptProcessWiring();
3270
3365
  _activeKey = sess.instanceKey;
3271
- seedSessionProxyProfile(sess.instanceKey);
3366
+ _seedProxyBindingForSession(sess);
3272
3367
  return { instanceKey: sess.instanceKey };
3273
3368
  }
3274
3369
 
@@ -3410,6 +3505,21 @@ export function sendQueuedNow(id, anchor) {
3410
3505
  return sess ? sess.sendQueuedNow(id) : [];
3411
3506
  }
3412
3507
 
3508
+ /** 960K forced compaction: interrupt the current turn and inject one message immediately (routed to the anchor's session). */
3509
+ export function forceSendUserMessage(text, anchor) {
3510
+ if (!_query) throw new Error('Agent SDK not available');
3511
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3512
+ if (!sess) {
3513
+ const targetName = (anchor && (anchor.cwd || anchor.project || anchor.instanceKey)) || 'active';
3514
+ console.warn(`[sdk-manager] no SDK session for force-send to "${targetName}"`);
3515
+ const err = new Error('no SDK session for force send');
3516
+ err.code = 'not-delivered';
3517
+ throw err;
3518
+ }
3519
+ if (anchor && sess.instanceKey !== _activeKey) _activeKey = sess.instanceKey;
3520
+ return sess.forceSendUserMessage(text);
3521
+ }
3522
+
3413
3523
  /** Remove one queued message of the ACTIVE session (or an anchor's session —
3414
3524
  * a targeted action; does not switch active). */
3415
3525
  export function removeQueued(id, anchor) {
@@ -3496,7 +3606,7 @@ export function attachSdkSession(anchor) {
3496
3606
  _activeKey = sess.instanceKey;
3497
3607
  // Activating a session binds its proxy (seeded from the global default when the
3498
3608
  // session predates the mapping or its binding was cleared).
3499
- seedSessionProxyProfile(sess.instanceKey);
3609
+ _seedProxyBindingForSession(sess);
3500
3610
  return { ok: true, key: sess.instanceKey, instanceKey: sess.instanceKey, cwd: sess.cwd, switched };
3501
3611
  }
3502
3612
 
@@ -3652,6 +3762,18 @@ export function getSessionStateSnapshot(anchor) {
3652
3762
  return sess ? sess.getSessionStateSnapshot() : null;
3653
3763
  }
3654
3764
 
3765
+ /**
3766
+ * Atomic "can a turn start right now" gate for the anchored session (compaction inject).
3767
+ * Resolved with allowPrimaryFallback:true — the SAME resolver sendUserMessage uses — so the
3768
+ * gate's target is the session a send would actually land on (a same-cwd ambiguous project
3769
+ * anchor resolves to the primary rather than reporting "no session"). Returns null when the
3770
+ * anchor resolves to no registered session (callers treat that as not-idle / target-gone).
3771
+ */
3772
+ export function getTurnGate(anchor) {
3773
+ const sess = anchor ? _sessionForAnchor(anchor, { allowPrimaryFallback: true }) : _active();
3774
+ return sess ? sess.getTurnGate() : null;
3775
+ }
3776
+
3655
3777
  /** WS reconnect replay getter for the context-usage frame. No anchor → active session. */
3656
3778
  export function getContextUsageSnapshot(anchor) {
3657
3779
  const sess = anchor ? _sessionForAnchor(anchor) : _active();
@@ -14,6 +14,17 @@
14
14
  * the single-workspace behavior is byte-identical.
15
15
  *
16
16
  * L1-lib: pure module, Node builtins only, no imports.
17
+ *
18
+ * PTY-vs-SDK label policy: this module deliberately does NOT filter stub
19
+ * entries whose subject/description are both null. A PTY stub is the intended
20
+ * placeholder for a task whose TaskCreated hook was lost (or fired before
21
+ * cc-viewer started watching) — the HUD shows `#id` for a beat until the next
22
+ * TaskUpdate(subject) / TaskCompleted(subject) lands. That is a live,
23
+ * in-flight row, NOT an SDK-mode "label-less ghost" (a terminal residue with
24
+ * neither description nor summary on the wire). The SDK-side label-less filter
25
+ * is scoped to TERMINAL entries only and lives in sdk-manager.js /
26
+ * sdkTaskTracker.js / @ccv/core/sdk-task-label; PTY snapshot semantics stay
27
+ * byte-identical here.
17
28
  */
18
29
 
19
30
  /** @type {Map<string, {sessionId: string|null, tasks: Map<string, object>, lastUsedAt: number}>} */
@@ -150,9 +150,24 @@ function preferencesPost(req, res, parsedUrl, isLocal, deps) {
150
150
  // prefsByProject(项目独立配置 fork)只能经 admin-only 的 /api/project-prefs/* 修改;元字段
151
151
  // (_isLocal/_projectScoped/…)仅 GET 回包,绝不让它们经 /api/preferences 落盘污染。
152
152
  delete incoming.prefsByProject;
153
- // 定时任务只能经 /api/scheduled-tasks (admin+same-origin) 写 —— 任何客户端(含 admin)
154
- // 都不得借 prefs POST 注入/清空/覆盖任务(claim CAS、调度状态校验只在 store 层做)。
153
+ // Scheduled tasks are writable only via /api/scheduled-tasks (admin+same-origin) — no client
154
+ // (admin included) may inject/clear/overwrite tasks through a prefs POST (claim CAS and schedule
155
+ // state validation live only in the store layer).
155
156
  delete incoming.scheduledTasks;
157
+ // Compaction rules are machine-global, and executionTiming:'auto' is auto-injected by the frontend
158
+ // without confirmation — the danger class is identical to scheduledTasks. Non-admin clients (an
159
+ // open no-password LAN session, or a cross-site form) must not plant a "low threshold + auto +
160
+ // arbitrary script" rule into every session of the host operator. Admin-only; stripped otherwise.
161
+ if (!isAdminReq(req, isLocal)) {
162
+ delete incoming.contextCompaction;
163
+ } else if (Object.prototype.hasOwnProperty.call(incoming, 'contextCompaction')) {
164
+ // Admin writes still require same-origin (blocks cross-site form POSTs; same gate as CLAUDE_EXECUTABLE).
165
+ if (!isSameOriginBrowserRequest(req, parsedUrl)) {
166
+ res.writeHead(403, { 'Content-Type': 'application/json' });
167
+ res.end(JSON.stringify({ error: 'Same-origin request required' }));
168
+ return;
169
+ }
170
+ }
156
171
  for (const k of Object.keys(incoming)) if (k[0] === '_') delete incoming[k];
157
172
  // IM bridge configs 同理:只能经 admin-only 的 /api/dingtalk/config、/api/im/* 修改,禁止借
158
173
  // /api/preferences 植入凭据。
package/server/server.js CHANGED
@@ -54,6 +54,7 @@ import { setProxyStatsListener, setSlowUpstreamListener } from './lib/proxy/prox
54
54
  import * as imCore from './lib/im/im-bridge-core.js';
55
55
  import * as imProcMgr from './lib/im/im-process-manager.js';
56
56
  import * as chatQueue from './lib/chat-queue.js';
57
+ import { createCompactInjectGuard } from './lib/compact-inject-guard.js';
57
58
  import { reportSwallowed } from './lib/error-report.js';
58
59
  import { takeInheritedAccessToken } from './lib/access-token.js';
59
60
  import { cancelAutoApproveState } from './lib/auto-approve.js';
@@ -1950,6 +1951,42 @@ async function setupTerminalWebSocket(httpServer) {
1950
1951
  writeToPtySequentialFor,
1951
1952
  getPtyKind,
1952
1953
  isStreaming: () => streamingState.active,
1954
+ // Target-scoped busy probes for injectCommand (context compaction): scope the idle check
1955
+ // to the ANCHOR's workspace, not the globally-bound one. The scope key MUST be normalized
1956
+ // with normalizeProducerScope first — producers fold the BOUND project to the '' bucket
1957
+ // (scopeKeyForEntry / _resolveScopeForHookPayload), so a raw `scopeKeyOf(boundName, …)`
1958
+ // would read a never-written bucket and report a streaming bound TUI as idle (review P0).
1959
+ isStreamingFor: (anchor) => {
1960
+ if (!anchor || typeof anchor !== 'object') return streamingState.active;
1961
+ const p = anchor.project || (anchor.cwd ? projectKeyForCwd(anchor.cwd) : null) || null;
1962
+ const inst = (typeof anchor.instanceKey === 'string' && anchor.instanceKey) || null;
1963
+ const sc = normalizeProducerScope({ project: p, instance: inst }, _projectName || '');
1964
+ const direct = scopeKeyOf(sc.project, sc.instance);
1965
+ if (streamingStateFor(direct).active === true) return true;
1966
+ // Anchor without an instance key (a project-only view of parallel workspaces): the producer
1967
+ // writes buckets keyed `project\0instance`, so a project-level direct lookup misses — also scan
1968
+ // every active instance bucket under this project.
1969
+ if (!sc.instance && sc.project) {
1970
+ const prefix = `${sc.project}\0`;
1971
+ for (const k of activeStreamingScopes()) { if (k.startsWith(prefix)) return true; }
1972
+ }
1973
+ return false;
1974
+ },
1975
+ isTurnActiveFor: (anchor) => {
1976
+ if (!anchor || typeof anchor !== 'object') return turnActive.active === true;
1977
+ const p = anchor.project || (anchor.cwd ? projectKeyForCwd(anchor.cwd) : null) || null;
1978
+ const inst = (typeof anchor.instanceKey === 'string' && anchor.instanceKey) || null;
1979
+ const sc = normalizeProducerScope({ project: p, instance: inst }, _projectName || '');
1980
+ const direct = scopeKeyOf(sc.project, sc.instance);
1981
+ if (turnStateFor(direct).active === true) return true;
1982
+ if (!sc.instance && sc.project) {
1983
+ const prefix = `${sc.project}\0`;
1984
+ for (const k of activeTurnScopes()) { if (k.startsWith(prefix)) return true; }
1985
+ }
1986
+ return false;
1987
+ },
1988
+ getPtyKindFor: (anchor) => getPtyKindFor(anchor),
1989
+ getQueueSnapshot: (anchor) => chatQueue.getSnapshot(anchor),
1953
1990
  hasPendingApproval: () => pendingAskHooks.size > 0 || pendingPermHooks.size > 0,
1954
1991
  hasExternalInjection: () => imCore.anyActiveInjection(),
1955
1992
  hasLivePtyFor: (anchor) => {
@@ -3167,6 +3204,147 @@ async function setupTerminalWebSocket(httpServer) {
3167
3204
  catch (e2) { reportSwallowed('server.sdk-send-failed-send', e2); }
3168
3205
  });
3169
3206
  }
3207
+ } else if (msg.type === 'compact-inject') {
3208
+ // Context compaction: after the user agrees via the frontend confirm bar, request injection of `/compact <script>`.
3209
+ // Trigger decisions live in the frontend; the server does authoritative idle validation + anchor routing + multi-tab dedup.
3210
+ // The compact-inject-done ack goes only to the initiating ws (directed); on success broadcast
3211
+ // context-compaction-injected so other tabs close the bar + enter cooldown.
3212
+ const reply = (payload) => {
3213
+ try { if (ws.readyState === 1) ws.send(JSON.stringify({ type: 'compact-inject-done', reqId: payload.reqId, ...payload })); }
3214
+ catch (e) { reportSwallowed('server.compact-inject.reply', e); }
3215
+ };
3216
+ const reqId = (typeof msg.reqId === 'string' && /^[A-Za-z0-9_-]{1,64}$/.test(msg.reqId)) ? msg.reqId : null;
3217
+ const text = typeof msg.text === 'string' ? msg.text.trim() : '';
3218
+ const project = (typeof msg.project === 'string' && msg.project) ? msg.project : null;
3219
+ const instanceKey = (typeof msg.instanceKey === 'string' && msg.instanceKey) ? msg.instanceKey : null;
3220
+ const anchor = (project || instanceKey) ? { project: project || undefined, instanceKey: instanceKey || undefined } : null;
3221
+ // 960K forced compaction: the only path allowed to inject mid-stream (interrupts the current session). Other sources never inject mid-stream.
3222
+ const isForce = msg.force === true;
3223
+ if (!reqId || !/^\/compact(\s|$)/.test(text) || text.length > 20000) { reply({ reqId, ok: false, reason: 'bad-text' }); return; }
3224
+ if (!anchor) { reply({ reqId, ok: false, reason: 'no-anchor' }); return; }
3225
+
3226
+ // Resolve the target's real identity (broadcast/dedup keys use the resolved value; never echo the raw project — a raw basename
3227
+ // for projects containing spaces/CJK would be silently dropped).
3228
+ let resolvedProject = project;
3229
+ let resolvedInstance = instanceKey;
3230
+
3231
+ if (isSdkMode) {
3232
+ const gate = _sdkGetTurnGate ? _sdkGetTurnGate(anchor) : null;
3233
+ if (!gate) { reply({ reqId, ok: false, reason: 'session-inactive' }); return; }
3234
+ resolvedInstance = gate.instanceKey || instanceKey;
3235
+ // Atomic gate: idle + no turn in flight + no pending approval + empty queue; otherwise reply busy so the frontend retries next turn.
3236
+ // 960K forced compaction skips the idle gate (it exists precisely to interrupt a busy current turn).
3237
+ if (!isForce && !gate.idle) { reply({ reqId, ok: false, reason: 'busy' }); return; }
3238
+ } else {
3239
+ // PTY mode: target liveness precheck (a dead target is rejected immediately, no polling). Use the module-level
3240
+ // _ptyGetKindFor/_ptyListLive (pty-manager is wired at init); the WS handler scope
3241
+ // has no local destructuring from await import.
3242
+ const live = (() => {
3243
+ try {
3244
+ if (instanceKey) return _ptyGetKindFor ? _ptyGetKindFor({ instanceKey }) === 'claude' : undefined;
3245
+ if (project) return _ptyListLive ? _ptyListLive().some((pty) => pty.ptyKind === 'claude' && projectKeyForCwd(pty.cwd) === project) : undefined;
3246
+ } catch (e) { reportSwallowed('server.compact-inject.liveness', e); }
3247
+ return undefined;
3248
+ })();
3249
+ if (live === false) { reply({ reqId, ok: false, reason: 'target-gone' }); return; }
3250
+ }
3251
+
3252
+ // Dedup key: the resolved target identity (project + instanceKey). When project is missing, degrade to the instance key
3253
+ // (scopeKeyOf(null, inst) collapses to the BOUND_SCOPE ''); never treat an empty-key badScope as a
3254
+ // fake duplicate success (that would make the frontend markInjected + cooldown while nothing was injected).
3255
+ const scopeKey = resolvedProject
3256
+ ? scopeKeyOf(resolvedProject, resolvedInstance)
3257
+ : (resolvedInstance ? `inst:${resolvedInstance}` : null);
3258
+ if (!scopeKey) { reply({ reqId, ok: false, reason: 'no-anchor' }); return; }
3259
+ const g = compactInjectGuard.tryBegin(scopeKey);
3260
+ // In-flight ≠ succeeded: the lock holder may still be polling for idle; if it eventually fails, treating it as duplicate would let
3261
+ // this end fake success (nothing injected). In-flight replies busy (retryable); only the success window replies duplicate (review P2-3).
3262
+ if (!g.allowed) {
3263
+ if (g.inFlight) { reply({ reqId, ok: false, reason: 'busy' }); return; }
3264
+ reply({ reqId, ok: true, duplicate: true }); return;
3265
+ }
3266
+
3267
+ const finishOk = () => {
3268
+ compactInjectGuard.commit(scopeKey);
3269
+ reply({ reqId, ok: true });
3270
+ // Broadcast so other tabs in the same scope close the bar + enter cooldown (converged by resolved identity).
3271
+ try { broadcastWsMessage({ type: 'context-compaction-injected', project: resolvedProject || undefined, instanceKey: resolvedInstance || undefined, ts: Date.now() }); }
3272
+ catch (e) { reportSwallowed('server.compact-inject.broadcast', e); }
3273
+ };
3274
+ const finishFail = (reason) => {
3275
+ // busy / failure both release immediately, not occupying the window, allowing genuine retries.
3276
+ compactInjectGuard.release(scopeKey);
3277
+ reply({ reqId, ok: false, reason });
3278
+ };
3279
+
3280
+ if (isSdkMode) {
3281
+ // 960K forced compaction: enqueue + immediate send-now (once the current turn is interrupted, drain pushes out /compact).
3282
+ if (isForce) {
3283
+ if (!_sdkForceSendUserMessage) { finishFail('no-deps'); return; }
3284
+ try {
3285
+ const result = _sdkForceSendUserMessage(text, { project: resolvedProject || undefined, instanceKey: resolvedInstance || undefined });
3286
+ // force interrupt calls _cancelAllApprovals: broadcast close signals for the cancelled approval popups,
3287
+ // otherwise the popups hang forever (a deleted pending cannot recover via reconnect replay).
3288
+ const cancelled = (result && Array.isArray(result.cancelled)) ? result.cancelled : [];
3289
+ try { _broadcastApprovalCloses(cancelled, 'Force compaction'); } catch (e) { reportSwallowed('server.compact-inject.approval-close', e); }
3290
+ finishOk();
3291
+ } catch (err) {
3292
+ reportSwallowed('server.compact-inject.sdk-force', err);
3293
+ if (err && err.code === 'not-delivered') { compactInjectGuard.rollback(scopeKey); finishFail('not-delivered'); }
3294
+ else if (err && err.code === 'busy') { finishFail('busy'); } // dispatch slot occupied: retryable, no fake success
3295
+ else finishFail('error');
3296
+ }
3297
+ return;
3298
+ }
3299
+ if (!_sdkSendUserMessage) { finishFail('no-deps'); return; }
3300
+ // Ack on ACCEPTANCE — sendUserMessage's promise resolves only when the turn SETTLES
3301
+ // (cli.js:987: never await it), so the ack must fire synchronously, not behind it.
3302
+ // But an early ROUTING failure surfaces as an immediate rejection (`not-delivered`
3303
+ // on a teardown-raced/closed query, thrown at the first await inside the async fn) —
3304
+ // map that to a directed failure ack so the client doesn't fake-success + cooldown
3305
+ // for a `/compact` that never landed. The guard's success window is likewise rolled
3306
+ // back via release() so a real retry isn't deduped for 60s.
3307
+ let p;
3308
+ try {
3309
+ p = _sdkSendUserMessage(text, { project: resolvedProject || undefined, instanceKey: resolvedInstance || undefined });
3310
+ } catch (err) {
3311
+ reportSwallowed('server.compact-inject.sdk', err);
3312
+ finishFail('error');
3313
+ return;
3314
+ }
3315
+ if (p && typeof p.catch === 'function') {
3316
+ p.catch((err) => {
3317
+ reportSwallowed('server.compact-inject.sdk', err);
3318
+ if (err && err.code === 'not-delivered') {
3319
+ // Early routing failure: revoke the optimistic ack from just now (close the bar with a failure hint + roll back the dedup window).
3320
+ compactInjectGuard.rollback(scopeKey);
3321
+ reply({ reqId, ok: false, reason: 'not-delivered' });
3322
+ }
3323
+ });
3324
+ }
3325
+ finishOk();
3326
+ } else {
3327
+ // 960K forced compaction (PTY): enqueue + sendNow — write focus-in+ESC to interrupt the current generation,
3328
+ // poll for idle, then bracketed-paste /compact. Never a blind write (on failure requeue; frontend ack failure is retryable).
3329
+ if (isForce) {
3330
+ try {
3331
+ const ptyAnchor = { project: resolvedProject || undefined, instanceKey: resolvedInstance || undefined };
3332
+ const item = chatQueue.enqueue(text, ptyAnchor);
3333
+ if (!item) { finishFail('error'); return; }
3334
+ const started = chatQueue.sendNow(item.id, ptyAnchor);
3335
+ if (started) { finishOk(); return; }
3336
+ // sendNow did not start (slot occupied/external injection): remove the just-enqueued /compact from the queue — otherwise it would be
3337
+ // auto-injected as an ordinary message during a later rescue/drain, chaining duplicate compactions with the frontend's busy retry (ghost item).
3338
+ try { chatQueue.remove(item.id, ptyAnchor); } catch (e) { reportSwallowed('server.compact-inject.pty-force.remove', e); }
3339
+ finishFail('busy'); // retryable, the frontend forces again next turn
3340
+ } catch (err) { reportSwallowed('server.compact-inject.pty-force', err); finishFail('error'); }
3341
+ return;
3342
+ }
3343
+ chatQueue.injectCommand(text, { project: resolvedProject || undefined, instanceKey: resolvedInstance || undefined })
3344
+ .then((r) => { if (r && r.ok) finishOk(); else finishFail((r && r.reason) || 'error'); })
3345
+ .catch((err) => { reportSwallowed('server.compact-inject.pty', err); finishFail('error'); });
3346
+ }
3347
+ return;
3170
3348
  } else if (msg.type === 'sdk-interrupt') {
3171
3349
  // Stop button in SDK mode — interrupt current turn, keep session alive.
3172
3350
  // Streaming-state reconciliation comes from the wire path (proxy →
@@ -3522,6 +3700,15 @@ function _emitTurnEnd(sessionId, ts, transcriptPath = null, scope = null) {
3522
3700
  // _scheduleTurnEndBroadcast entry. chatQueue no-ops internally when uninitialized
3523
3701
  // (SDK mode / tests that never ran startViewer).
3524
3702
  try { chatQueue.onTurnEnd(sid, t); } catch { /* best-effort */ }
3703
+ // Compaction dedup window: after a turn ends, the dedup window of the last successful injection can be released (allowing the next confirmation).
3704
+ // This covers PTY; the SDK side is cleared separately by the sdk-compact broadcast. The production-side scope is already normalized (instances folded),
3705
+ // while the injecting guard's key carries the instance stamp, so clear all instance keys by project (clearProject) rather than a single clearSuccess (review P2-2).
3706
+ try {
3707
+ const proj = sc.project || (_projectName || '');
3708
+ // minAgeMs=success window: a window younger than 60s since the last successful injection is kept — it belongs to the interrupted round's result;
3709
+ // clearing immediately would let multiple tabs chain forced compactions through the gap while compaction is still running (review P1-3). Old windows (≥60s) release normally.
3710
+ if (proj) compactInjectGuard.clearProject(proj, { minAgeMs: 60000 });
3711
+ } catch (e) { reportSwallowed('server.compact-inject.guard-clear', e); }
3525
3712
  if (typeof _onTurnEndBroadcastForTests === 'function') {
3526
3713
  try { _onTurnEndBroadcastForTests({ sessionId: sid, ts: t }); }
3527
3714
  catch (e) { if (process.env.NODE_ENV === 'test') throw e; /* prod 不让测试桩污染 */ }
@@ -4115,6 +4302,15 @@ function isIdAddressedApprovalClear(msg) {
4115
4302
  }
4116
4303
 
4117
4304
  export function broadcastWsMessage(msg) { if (terminalWss) {
4305
+ // A real SDK compaction happened (compact_boundary) → release that scope's injection dedup window (allowing the next confirmation).
4306
+ // Clear it on the way before broadcasting; frame dispatch is unaffected; sdk-compact carries its own cwd + instanceKey.
4307
+ if (msg && typeof msg === 'object' && msg.type === 'sdk-compact') {
4308
+ try {
4309
+ const cp = msg.cwd ? projectKeyForCwd(msg.cwd) : null;
4310
+ const gk = scopeKeyOf(cp || (_projectName || ''), msg.instanceKey || null);
4311
+ if (gk) compactInjectGuard.clearSuccess(gk);
4312
+ } catch (e) { reportSwallowed('server.compact-inject.guard-clear-sdk', e); }
4313
+ }
4118
4314
  // SDK multi-session (2026-10-12): a cwd-tagged frame belongs to one workspace's session.
4119
4315
  // Route it only to clients viewing that workspace (or the bound view with no ?project=),
4120
4316
  // so a background workspace's approval/queue/spinner never bleeds into the foreground.
@@ -4218,6 +4414,10 @@ export function setSdkCancelApproval(fn) { _sdkCancelApproval = fn; }
4218
4414
  let _sdkSendUserMessage = null;
4219
4415
  export function setSdkSendUserMessage(fn) { _sdkSendUserMessage = fn; }
4220
4416
 
4417
+ /** Reference to sdk-manager's forceSendUserMessage (set by cli.js after import) — 960K forced compaction. */
4418
+ let _sdkForceSendUserMessage = null;
4419
+ export function setSdkForceSendUserMessage(fn) { _sdkForceSendUserMessage = fn; }
4420
+
4221
4421
  /** Reference to sdk-manager's interruptTurn (set by cli.js after import). */
4222
4422
  let _sdkInterruptTurn = null;
4223
4423
  export function setSdkInterruptTurn(fn) { _sdkInterruptTurn = fn; }
@@ -4248,6 +4448,13 @@ export function setSdkGetMcpStatusSnapshot(fn) { _sdkGetMcpStatusSnapshot = fn;
4248
4448
  let _sdkGetSessionStateSnapshot = null;
4249
4449
  export function setSdkGetSessionStateSnapshot(fn) { _sdkGetSessionStateSnapshot = fn; }
4250
4450
 
4451
+ /** sdk-manager's getTurnGate (atomic can-start-turn gate) for context-compaction inject. */
4452
+ let _sdkGetTurnGate = null;
4453
+ export function setSdkGetTurnGate(fn) { _sdkGetTurnGate = fn; }
4454
+
4455
+ /** Per-scope dedupe for context-compaction injects (one confirm → one `/compact`). */
4456
+ const compactInjectGuard = createCompactInjectGuard();
4457
+
4251
4458
  /** Reference to sdk-manager's getSdkTaskSnapshot (set by cli.js after import). */
4252
4459
  let _sdkGetSdkTaskSnapshot = null;
4253
4460
  export function setSdkGetSdkTaskSnapshot(fn) { _sdkGetSdkTaskSnapshot = fn; }