cc-viewer 1.9.23 → 1.9.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +1 -1
  3. package/cli.js +14 -0
  4. package/dist/assets/App-BUIwNK3C.js +2 -0
  5. package/dist/assets/App-C5xq-7nS.css +1 -0
  6. package/dist/assets/ArchivePreview-BKXTsPsN.css +1 -0
  7. package/dist/assets/ArchivePreview-BuFE-N7z.js +1 -0
  8. package/dist/assets/{MdxEditorPanel-CTAS2DJv.js → MdxEditorPanel-BiKPuJGb.js} +1 -1
  9. package/dist/assets/Mobile-D2UvqCIN.js +1 -0
  10. package/dist/assets/{ProxyStatsModal-C4sl-cuB.js → ProxyStatsModal-CBdBgS9_.js} +1 -1
  11. package/dist/assets/{_baseUniq-CsF04anE.js → _baseUniq-h4hafO2D.js} +1 -1
  12. package/dist/assets/{arc-BOacYe6N.js → arc-CN5nAVn-.js} +1 -1
  13. package/dist/assets/{architectureDiagram-Q4EWVU46-BSUEfjC_.js → architectureDiagram-Q4EWVU46-NTnIUsWP.js} +1 -1
  14. package/dist/assets/{blockDiagram-DXYQGD6D-CC37UGtW.js → blockDiagram-DXYQGD6D-BPFMPOwn.js} +1 -1
  15. package/dist/assets/{c4Diagram-AHTNJAMY-IzgRD4uO.js → c4Diagram-AHTNJAMY-CAPyXRVj.js} +1 -1
  16. package/dist/assets/{channel-C6PxyQUn.js → channel-BULnUStk.js} +1 -1
  17. package/dist/assets/{chunk-4BX2VUAB-cdQt_dcU.js → chunk-4BX2VUAB-BeSOU8fB.js} +1 -1
  18. package/dist/assets/{chunk-4TB4RGXK-BpTDA_Pb.js → chunk-4TB4RGXK-BVCrVLA0.js} +1 -1
  19. package/dist/assets/{chunk-55IACEB6-CcitNo0P.js → chunk-55IACEB6-D0XHzdzo.js} +1 -1
  20. package/dist/assets/{chunk-EDXVE4YY-BjKwZ9I7.js → chunk-EDXVE4YY-DizHN_m_.js} +1 -1
  21. package/dist/assets/{chunk-FMBD7UC4-vZDVX3tI.js → chunk-FMBD7UC4-3r0oXmep.js} +1 -1
  22. package/dist/assets/{chunk-OYMX7WX6-DGkYahGo.js → chunk-OYMX7WX6-C701FNEA.js} +1 -1
  23. package/dist/assets/{chunk-QZHKN3VN-C9065hSE.js → chunk-QZHKN3VN-KAdMyJai.js} +1 -1
  24. package/dist/assets/{chunk-YZCP3GAM-D_pcTg6_.js → chunk-YZCP3GAM-Cn2gaRZ3.js} +1 -1
  25. package/dist/assets/classDiagram-6PBFFD2Q-7MJg98xK.js +1 -0
  26. package/dist/assets/classDiagram-v2-HSJHXN6E-7MJg98xK.js +1 -0
  27. package/dist/assets/clone-Bddq99Xt.js +1 -0
  28. package/dist/assets/{cose-bilkent-S5V4N54A-BPPFMIGv.js → cose-bilkent-S5V4N54A-URab8isi.js} +1 -1
  29. package/dist/assets/{dagre-KV5264BT-fjzhKO5o.js → dagre-KV5264BT-Cq24tJ6h.js} +1 -1
  30. package/dist/assets/{diagram-5BDNPKRD-5L6FzTry.js → diagram-5BDNPKRD-D4KEpJ0T.js} +1 -1
  31. package/dist/assets/{diagram-G4DWMVQ6-GOwcGpff.js → diagram-G4DWMVQ6-DZLa6S7S.js} +1 -1
  32. package/dist/assets/{diagram-MMDJMWI5-BDsFE25W.js → diagram-MMDJMWI5-BBhsOBKy.js} +1 -1
  33. package/dist/assets/{diagram-TYMM5635-BqjpbSGH.js → diagram-TYMM5635-ClWpYbD-.js} +1 -1
  34. package/dist/assets/{erDiagram-SMLLAGMA-DWO3Dk1v.js → erDiagram-SMLLAGMA-5RXRgGvh.js} +1 -1
  35. package/dist/assets/{flowDiagram-DWJPFMVM-Br4nNBVd.js → flowDiagram-DWJPFMVM-DXiHDbOU.js} +1 -1
  36. package/dist/assets/{ganttDiagram-T4ZO3ILL-9sN-VOhw.js → ganttDiagram-T4ZO3ILL-Db5oVw9h.js} +1 -1
  37. package/dist/assets/{gitGraphDiagram-UUTBAWPF-BsPcTAKr.js → gitGraphDiagram-UUTBAWPF-CCPK1X9H.js} +1 -1
  38. package/dist/assets/{graph-o31GzaB6.js → graph-DNxO4J9w.js} +1 -1
  39. package/dist/assets/{index-tZqiJJGq.js → index-Bc_IaWe7.js} +1 -1
  40. package/dist/assets/{index-CXMr3tiK.js → index-CXW8X8EW.js} +1 -1
  41. package/dist/assets/{index-B3b0lRUB.js → index-DDo6Z3Ov.js} +1 -1
  42. package/dist/assets/{index-CuvDJTY7.js → index-DR_FOzBM.js} +1 -1
  43. package/dist/assets/{index-PDvAAbti.js → index-DaP3fzs1.js} +1 -1
  44. package/dist/assets/{index-DAjx9lT3.js → index-Do02L044.js} +1 -1
  45. package/dist/assets/{index-DyV81jSF.js → index-HLRCpKmY.js} +1 -1
  46. package/dist/assets/index-ev1Hmm1O.js +2 -0
  47. package/dist/assets/{infoDiagram-42DDH7IO-VUMzEo4o.js → infoDiagram-42DDH7IO-CzPZsFEc.js} +1 -1
  48. package/dist/assets/{ishikawaDiagram-UXIWVN3A-BuzrU3sx.js → ishikawaDiagram-UXIWVN3A-eEVseuO_.js} +1 -1
  49. package/dist/assets/{journeyDiagram-VCZTEJTY-BZtR5BAF.js → journeyDiagram-VCZTEJTY-CmMKnKhj.js} +1 -1
  50. package/dist/assets/{jszip.min-CtodH5MV.js → jszip.min-JnHXMwa-.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-Cj_97xXb.js → kanban-definition-6JOO6SKY-CZMggR3M.js} +1 -1
  52. package/dist/assets/{layout-Du0I-tlh.js → layout-DVqRDfNO.js} +1 -1
  53. package/dist/assets/{linear-BJtxCASI.js → linear-BHB3KNeC.js} +1 -1
  54. package/dist/assets/{mermaid.core-QlorX0Yw.js → mermaid.core-DOjmjAg3.js} +2 -2
  55. package/dist/assets/{min-BVnQfunZ.js → min-DxJCEK6c.js} +1 -1
  56. package/dist/assets/{mindmap-definition-QFDTVHPH-Bh_KL4qU.js → mindmap-definition-QFDTVHPH-B6W3RjCJ.js} +1 -1
  57. package/dist/assets/{pieDiagram-DEJITSTG-Bvv0rC_q.js → pieDiagram-DEJITSTG-BRNQVuFX.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-34T5L4WZ-Bw8cGCRU.js → quadrantDiagram-34T5L4WZ-CUCnCkJJ.js} +1 -1
  59. package/dist/assets/{requirementDiagram-MS252O5E-Cg9jQ71h.js → requirementDiagram-MS252O5E-Ds-5hLni.js} +1 -1
  60. package/dist/assets/{sankeyDiagram-XADWPNL6-BXJo6-CD.js → sankeyDiagram-XADWPNL6-Cxi30RZc.js} +1 -1
  61. package/dist/assets/seqResourceLoaders-B8ZIXCeg.js +2 -0
  62. package/dist/assets/seqResourceLoaders-DH-Nl0yh.css +41 -0
  63. package/dist/assets/{sequenceDiagram-FGHM5R23-D7zpGxwq.js → sequenceDiagram-FGHM5R23-C6CukZv8.js} +1 -1
  64. package/dist/assets/{stateDiagram-FHFEXIEX-Der2CqR1.js → stateDiagram-FHFEXIEX-iPJCU2Ja.js} +1 -1
  65. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DetvG_Lc.js → stateDiagram-v2-QKLJ7IA2-DMFhwtNH.js} +1 -1
  66. package/dist/assets/{timeline-definition-GMOUNBTQ-0UenzEZ6.js → timeline-definition-GMOUNBTQ-Dqd-tCUs.js} +1 -1
  67. package/dist/assets/{vendor-antd-I6I2F7Rv.js → vendor-antd-D1L_UwKJ.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-Zkm6UHQg.js → vendor-codemirror-DOZOjrWx.js} +1 -1
  69. package/dist/assets/{vendor-mdxeditor-CC09MDyZ.js → vendor-mdxeditor-8ZUcYZ6G.js} +2 -2
  70. package/dist/assets/{vendor-qrcode-gZpmSeeh.js → vendor-qrcode-Pw_LHfBZ.js} +1 -1
  71. package/dist/assets/{vendor-virtuoso-BGwznQ5y.js → vendor-virtuoso-AhfR22q5.js} +1 -1
  72. package/dist/assets/{vennDiagram-DHZGUBPP-COzYyZ5h.js → vennDiagram-DHZGUBPP-CrOJisSD.js} +1 -1
  73. package/dist/assets/{wardley-RL74JXVD-VZdOtN8t.js → wardley-RL74JXVD-By8Ltw9G.js} +1 -1
  74. package/dist/assets/{wardleyDiagram-NUSXRM2D-CVkL75Qy.js → wardleyDiagram-NUSXRM2D-5SnzlvF9.js} +1 -1
  75. package/dist/assets/{xychartDiagram-5P7HB3ND-6CHBAYyF.js → xychartDiagram-5P7HB3ND-CJ4uNjoK.js} +1 -1
  76. package/dist/index.html +4 -4
  77. package/node_modules/@ccv/core/src/ask-auto-answer.js +122 -0
  78. package/package.json +1 -1
  79. package/server/i18n.js +0 -20
  80. package/server/lib/ask/ask-bridge.js +4 -1
  81. package/server/lib/ask/ask-reaper.js +1 -0
  82. package/server/lib/ask-auto-answer.js +153 -0
  83. package/server/lib/auto-approve.js +3 -1
  84. package/server/lib/binary-sniff.js +35 -0
  85. package/server/lib/restart-helper.js +65 -0
  86. package/server/lib/restart.js +83 -0
  87. package/server/lib/sdk-manager.js +65 -19
  88. package/server/lib/update-instances.js +42 -0
  89. package/server/lib/update-job.js +260 -0
  90. package/server/lib/updater.js +37 -220
  91. package/server/pty-manager.js +1 -0
  92. package/server/routes/ask-perm.js +87 -6
  93. package/server/routes/files-content.js +46 -8
  94. package/server/routes/project-meta.js +11 -7
  95. package/server/routes/update.js +58 -0
  96. package/server/server.js +69 -5
  97. package/server/system-prompt-templates/presets/kimi-k3.md +8 -0
  98. package/dist/assets/App-BvVdj099.css +0 -1
  99. package/dist/assets/App-DEA3HoZr.js +0 -2
  100. package/dist/assets/Mobile-CgVpXvs2.js +0 -1
  101. package/dist/assets/classDiagram-6PBFFD2Q-BUmU_G-i.js +0 -1
  102. package/dist/assets/classDiagram-v2-HSJHXN6E-BUmU_G-i.js +0 -1
  103. package/dist/assets/clone-CvoOne2K.js +0 -1
  104. package/dist/assets/index-CS47d9oh.js +0 -2
  105. package/dist/assets/seqResourceLoaders-CORH46PN.js +0 -2
  106. package/dist/assets/seqResourceLoaders-v4YzKhTS.css +0 -41
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.23",
3
+ "version": "1.9.25",
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
@@ -1167,26 +1167,6 @@ const i18nData = {
1167
1167
  "tr": "Mevcut günlüğü indir",
1168
1168
  "uk": "Завантажити поточний лог"
1169
1169
  },
1170
- "ui.exportPrompts": {
1171
- "zh": "查看用户 Prompt",
1172
- "en": "Export user prompts",
1173
- "zh-TW": "匯出用戶 Prompt",
1174
- "ko": "사용자 Prompt 내보내기",
1175
- "ja": "ユーザー Prompt をエクスポート",
1176
- "de": "Benutzer-Prompts exportieren",
1177
- "es": "Exportar prompts de usuario",
1178
- "fr": "Exporter les prompts utilisateur",
1179
- "it": "Esporta prompt utente",
1180
- "da": "Eksportér bruger-prompts",
1181
- "pl": "Eksportuj prompty użytkownika",
1182
- "ru": "Экспорт пользовательских Prompt",
1183
- "ar": "تصدير Prompt المستخدم",
1184
- "no": "Eksporter bruker-prompts",
1185
- "pt-BR": "Exportar prompts do usuário",
1186
- "th": "ส่งออก Prompt ผู้ใช้",
1187
- "tr": "Kullanıcı Prompt'larını dışa aktar",
1188
- "uk": "Експорт Prompt користувача"
1189
- },
1190
1170
  "ui.exportPromptsTxt": {
1191
1171
  "zh": "导出到本地 .txt",
1192
1172
  "en": "Export to local .txt",
@@ -126,7 +126,10 @@ function sleep(ms) { return new Promise(r => setTimeout(r, ms)); }
126
126
 
127
127
  function postToViewer() {
128
128
  return new Promise((resolve, reject) => {
129
- const body = JSON.stringify({ questions, toolUseId });
129
+ // Hook runs in the session's cwd — report it so the server can resolve the
130
+ // project-forked askAutoAnswerMinutes pref for THIS session's project, not the
131
+ // server's currently-bound one (workspace mode hosts several projects).
132
+ const body = JSON.stringify({ questions, toolUseId, cwd: process.cwd() });
130
133
  const req = httpClient.request({
131
134
  hostname: '127.0.0.1',
132
135
  port: Number(port),
@@ -96,6 +96,7 @@ export async function reapDeadAskWaiters(deps, state, { now = Date.now() } = {})
96
96
  // row means another instance's answer consumed it — do not fabricate a
97
97
  // cancelled placeholder or grey out a real answer).
98
98
  if (entry.timer) clearTimeout(entry.timer);
99
+ if (entry.auto?.timer) clearTimeout(entry.auto.timer); // hosting timer must not outlive the reaped entry
99
100
  deps.pendingAskHooks.delete(id);
100
101
  lastPoll.delete(id);
101
102
  const diskRow = deps.loadAskStore()[id];
@@ -0,0 +1,153 @@
1
+ // Server-side auto-answer ("managed answering") countdown for AskUserQuestion.
2
+ //
3
+ // Mirrors auto-approve.js (plan/permission) but with MINUTE semantics and a
4
+ // different value contract, because the feature spec differs in two ways:
5
+ // - 0 minutes means "answer immediately" (unattended flows), not "off";
6
+ // - "off" is the ABSENCE of a value (null/undefined), not 0.
7
+ // Do NOT route this through computeAutoApprove: its 300s cap would silently
8
+ // disable the 10/20/30-minute tiers, and its Number() coercion would turn the
9
+ // persisted "off" (null) into 0 = instant — the most dangerous trap here.
10
+ //
11
+ // Deadline model is identical to auto-approve.js: armed at ask arrival
12
+ // (wall-clock), fires at deadline + ASK_AUTO_ANSWER_BUFFER_MS so a connected
13
+ // client's exact-deadline answer can still win the first-write race.
14
+ //
15
+ // Semantics of the setting (shared with the client):
16
+ // prefs.approvalModal.askAutoAnswerMinutes
17
+ // null/undefined/absent = off (default), 0 = instant, N>0 = N minutes.
18
+
19
+ import { readPrefsRaw } from './prefs-store.js';
20
+ import { getCurrentProjectKey, hasFork, resolveScoped } from './project-prefs.js';
21
+ import { reportSwallowed } from './error-report.js';
22
+
23
+ export { pickAutoAnswers } from '@ccv/core/ask-auto-answer';
24
+
25
+ export const ASK_AUTO_ANSWER_BUFFER_MS = 1000;
26
+ // A hand-edited preferences.json can hold an absurdly large value; beyond
27
+ // 2^31-1 ms Node's setTimeout clamps the delay to 1ms (instant answer). Cap below
28
+ // the 24h ask timeout so the advertised deadline is always reachable: the ask's own
29
+ // 24h timeout is armed first, so the max tier must leave room for the fire buffer.
30
+ // 1439 min = 24h - 1min, comfortably under ASK_TIMEOUT_MS.
31
+ export const MAX_ASK_AUTO_ANSWER_MINUTES = 1439;
32
+
33
+ /**
34
+ * Extract the configured minutes from an effective prefs object.
35
+ * Strict typing on purpose: null/undefined/strings/'10'/NaN are all OFF; only a
36
+ * real finite number in [0, MAX] enables hosting. Returns null when disabled.
37
+ */
38
+ export function effectiveAskAutoAnswerMinutes(prefs) {
39
+ const raw = prefs?.approvalModal?.askAutoAnswerMinutes;
40
+ if (typeof raw !== 'number' || !Number.isFinite(raw)) return null;
41
+ if (raw < 0 || raw > MAX_ASK_AUTO_ANSWER_MINUTES) return null;
42
+ return raw;
43
+ }
44
+
45
+ /**
46
+ * Read prefs (project-fork aware) and compute the auto-answer deadline for a
47
+ * pending AskUserQuestion. `projectKey` is the session cwd (SDK) or
48
+ * hook-reported cwd (PTY hook); falls back to the server's current project key.
49
+ *
50
+ * Returns:
51
+ * { enabled:false } — no hosting
52
+ * { enabled:true, instant, minutes, seconds, autoAnswerAt } — absolute epoch ms deadline
53
+ */
54
+ export function computeAskAutoAnswer(projectKey, { now = Date.now(), readPrefs = readPrefsRaw, file } = {}) {
55
+ let prefs = {};
56
+ try {
57
+ prefs = readPrefs(file) || {};
58
+ } catch (err) {
59
+ reportSwallowed('ask-auto-answer.read-prefs', err);
60
+ return { enabled: false };
61
+ }
62
+ const key = typeof projectKey === 'string' && projectKey ? projectKey : getCurrentProjectKey();
63
+ const effective = hasFork(prefs, key) ? resolveScoped(prefs, prefs.prefsByProject[key]) : prefs;
64
+ const minutes = effectiveAskAutoAnswerMinutes(effective);
65
+ if (minutes === null) return { enabled: false };
66
+ const instant = minutes === 0;
67
+ const seconds = minutes * 60;
68
+ return {
69
+ enabled: true,
70
+ instant,
71
+ minutes,
72
+ seconds,
73
+ autoAnswerAt: instant ? now : now + seconds * 1000,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * Delay for the server-side timer: the user-visible deadline plus the request
79
+ * buffer, never negative. Instant (0 minutes) fires on the same tick (0).
80
+ */
81
+ export function askAutoAnswerFireDelayMs(computed, now = Date.now()) {
82
+ if (!computed?.enabled) return null;
83
+ if (computed.instant) return 0;
84
+ return Math.max(0, computed.autoAnswerAt - now) + ASK_AUTO_ANSWER_BUFFER_MS;
85
+ }
86
+
87
+ /**
88
+ * Arm the server-side timer. Returns the auto state stored on the pending
89
+ * entry: { autoAnswerAt, seconds, minutes, cancelled, timer }.
90
+ * `onFire` is invoked once when the deadline (+buffer) passes; callers must
91
+ * re-check the entry is still pending and not cancelled inside onFire.
92
+ * Instant fires SYNCHRONOUSLY — the caller MUST register the pending entry
93
+ * (and emit the pending frame) before calling this.
94
+ */
95
+ export function createAskAutoAnswerState(computed, onFire) {
96
+ const delay = askAutoAnswerFireDelayMs(computed);
97
+ if (delay === null) return null; // disabled — never arm
98
+ const state = {
99
+ autoAnswerAt: computed.autoAnswerAt,
100
+ seconds: computed.seconds,
101
+ minutes: computed.minutes,
102
+ cancelled: false,
103
+ timer: null,
104
+ };
105
+ if (delay === 0) {
106
+ onFire();
107
+ return state;
108
+ }
109
+ state.timer = setTimeout(onFire, delay);
110
+ return state;
111
+ }
112
+
113
+ /**
114
+ * Cancel an armed auto-answer state: clears the timer and marks it cancelled.
115
+ * Accepts either the auto state itself or the whole pending entry ({ auto,
116
+ * autoCancelled }) — the entry form also stamps the durable entry-level flag so
117
+ * replays never re-arm. Returns true only on the first cancellation (so callers
118
+ * broadcast once).
119
+ */
120
+ export function cancelAskAutoAnswerState(autoOrEntry) {
121
+ if (!autoOrEntry) return false;
122
+ // Entry form: { auto, autoCancelled }
123
+ if (Object.prototype.hasOwnProperty.call(autoOrEntry, 'autoCancelled')) {
124
+ const entry = autoOrEntry;
125
+ if (entry.autoCancelled) return false;
126
+ entry.autoCancelled = true;
127
+ if (entry.auto) {
128
+ entry.auto.cancelled = true;
129
+ if (entry.auto.timer) {
130
+ clearTimeout(entry.auto.timer);
131
+ entry.auto.timer = null;
132
+ }
133
+ }
134
+ return true;
135
+ }
136
+ const auto = autoOrEntry;
137
+ if (auto.cancelled) return false;
138
+ auto.cancelled = true;
139
+ if (auto.timer) {
140
+ clearTimeout(auto.timer);
141
+ auto.timer = null;
142
+ }
143
+ return true;
144
+ }
145
+
146
+ /** Fields merged into pending/replay frames for the client countdown UI. */
147
+ export function replayAskAutoAnswerFields(auto, autoCancelled) {
148
+ return {
149
+ autoAnswerAt: autoCancelled ? null : (auto?.autoAnswerAt ?? null),
150
+ autoAnswerSeconds: auto?.seconds ?? null,
151
+ autoCancelled: autoCancelled === true,
152
+ };
153
+ }
@@ -19,7 +19,9 @@
19
19
  // plan: prefs.approvalModal.planAutoApproveSeconds (default 0 = off)
20
20
  // perm: prefs.autoApproveSeconds (default 3 when unset)
21
21
  // 0/off, N>0 = N seconds, -1 = instant (resolve immediately, no buffer).
22
- // AskUserQuestion approvals are never auto-approved.
22
+ // AskUserQuestion hosting ("问答题自动托管") is a separate feature with minute
23
+ // semantics and lives in ./ask-auto-answer.js — it is not routed through this module
24
+ // (the 300s cap would silently disable its 10/20/30-minute tiers).
23
25
 
24
26
  import { readPrefsRaw } from './prefs-store.js';
25
27
  import { getCurrentProjectKey, hasFork, resolveScoped } from './project-prefs.js';
@@ -0,0 +1,35 @@
1
+ import { isUtf8 } from 'node:buffer';
2
+
3
+ export function getUtf16Encoding(input) {
4
+ const littleEndian = input[0] === 0xff && input[1] === 0xfe;
5
+ const bigEndian = input[0] === 0xfe && input[1] === 0xff;
6
+ if (!littleEndian && !bigEndian) return null;
7
+ // A UTF-32LE BOM starts with the UTF-16LE prefix. Never guess through it.
8
+ if (littleEndian && input[2] === 0 && input[3] === 0) return null;
9
+ const payload = input.subarray(2);
10
+ if (payload.length % 2 !== 0) return null;
11
+ const text = bigEndian ? Buffer.from(payload).swap16().toString('utf16le') : payload.toString('utf16le');
12
+ for (let index = 0; index < text.length; index++) {
13
+ const code = text.charCodeAt(index);
14
+ if (code === 0 || code === 0xfffd) return null;
15
+ if (code >= 0xd800 && code <= 0xdbff) {
16
+ const next = text.charCodeAt(++index);
17
+ if (!(next >= 0xdc00 && next <= 0xdfff)) return null;
18
+ } else if (code >= 0xdc00 && code <= 0xdfff) return null;
19
+ }
20
+ return bigEndian ? 'utf16be' : 'utf16le';
21
+ }
22
+
23
+ // Inspect the entire already-bounded buffer before it can become editable text.
24
+ // Legacy encodings without a reliable BOM intentionally fall back to download
25
+ // rather than being decoded into corruptible replacement characters. ESC and
26
+ // backspace are accepted for ANSI logs and terminal progress output.
27
+ export function isBinaryBuffer(input) {
28
+ if (input.length === 0 || getUtf16Encoding(input)) return false;
29
+ let controls = 0;
30
+ for (const byte of input) {
31
+ if (byte === 0) return true;
32
+ if (byte < 0x08 || (byte > 0x0d && byte < 0x20 && byte !== 0x1b) || byte === 0x7f) controls++;
33
+ }
34
+ return controls / input.length > 0.02 || !isUtf8(input);
35
+ }
@@ -0,0 +1,65 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs';
3
+ import { dirname } from 'node:path';
4
+ import { pathToFileURL } from 'node:url';
5
+ import { restartFromHelper, waitForExit } from './restart.js';
6
+ import { installStagedUpdate, readRestartConfig, RESTART_READY_FILE } from './update-job.js';
7
+
8
+ for (const signal of ['SIGINT', 'SIGHUP', 'SIGTERM']) process.on(signal, () => { /* The replacement must survive the old terminal job. */ });
9
+ process.stdout.on('error', () => {});
10
+ process.stderr.on('error', () => {});
11
+
12
+
13
+ export async function runRestartHelper({ stateFile = process.argv[2], configFile = process.argv[3], config, install = installStagedUpdate, restart = restartFromHelper, log = console.error } = {}) {
14
+ let staged;
15
+ try {
16
+ config ||= readRestartConfig(configFile);
17
+ if (!Number.isInteger(config.pid) || config.pid <= 0 || !Array.isArray(config.args) || typeof config.cwd !== 'string' || typeof config.cliPath !== 'string' || !/^\d+\.\d+\.\d+$/.test(config.version)) throw new Error('Invalid arguments');
18
+ staged = JSON.parse(readFileSync(stateFile, 'utf8'));
19
+ if (staged.version !== config.version) throw new Error('Staged update does not match the requested version');
20
+ mkdirSync(dirname(RESTART_READY_FILE), { recursive: true, mode: 0o700 });
21
+ writeFileSync(RESTART_READY_FILE, JSON.stringify({ token: config.token }), { mode: 0o600 });
22
+ await waitForExit(config.pid);
23
+ writeFileSync(stateFile, JSON.stringify({ ...staged, status: 'installing' }), { mode: 0o600 });
24
+ log('[CC Viewer] Installing the downloaded update...');
25
+ await install(staged, { stateFile, ownerPid: config.pid, cliPath: config.cliPath });
26
+ writeFileSync(stateFile, JSON.stringify({ ...staged, status: 'completed' }), { mode: 0o600 });
27
+ const { rm } = await import('node:fs/promises');
28
+ await rm(staged.tarballPath, { force: true });
29
+ await rm(stateFile, { force: true });
30
+ return await restart(config, { wait: async () => {} });
31
+ } catch (err) {
32
+ try {
33
+ if (!staged) staged = JSON.parse(readFileSync(stateFile, 'utf8'));
34
+ writeFileSync(stateFile, JSON.stringify({ ...staged, status: 'failed', error: err.message, updatedAt: Date.now() }), { mode: 0o600 });
35
+ if (staged?.tarballPath) {
36
+ const { rm } = await import('node:fs/promises');
37
+ await rm(staged.tarballPath, { force: true }).catch(rmErr => log(`[CC Viewer] Failed to remove staged package: ${rmErr.message}`));
38
+ }
39
+ } catch (writeErr) { log(`[CC Viewer] Failed to record update failure: ${writeErr.message}`); }
40
+ log(`[CC Viewer] Restart failed: ${err.message}`);
41
+ if (config?.cliPath && Number.isInteger(config.pid)) {
42
+ try {
43
+ const { waitForExit } = await import('./restart.js');
44
+ await waitForExit(config.pid);
45
+ return await restart(config, { wait: async () => {} });
46
+ } catch (restoreErr) {
47
+ log(`[CC Viewer] Restore failed: ${restoreErr.message}`);
48
+ return 1;
49
+ }
50
+ }
51
+ return 1;
52
+ } finally {
53
+ if (configFile) {
54
+ const { rm } = await import('node:fs/promises');
55
+ await rm(configFile, { force: true }).catch(() => {});
56
+ }
57
+ }
58
+ }
59
+
60
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
61
+ for (const signal of ['SIGINT', 'SIGHUP', 'SIGTERM']) process.on(signal, () => { /* The replacement must survive the old terminal job. */ });
62
+ process.stdout.on('error', () => {});
63
+ process.stderr.on('error', () => {});
64
+ process.exitCode = await runRestartHelper();
65
+ }
@@ -0,0 +1,83 @@
1
+ import { fileURLToPath } from 'node:url';
2
+ import { spawn } from 'node:child_process';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
5
+ import { dirname } from 'node:path';
6
+ import { isPidAlive } from './pid-alive.js';
7
+ import { UPDATE_STATE_FILE, RESTART_CONFIG_FILE, RESTART_READY_FILE } from './update-job.js';
8
+
9
+ export const RESTART_HELPER_PATH = fileURLToPath(new URL('./restart-helper.js', import.meta.url));
10
+
11
+ export async function launchRestart({ pid = process.pid, args, cwd, version, cliPath, spawnImpl = spawn, timeoutMs = 5000 } = {}) {
12
+ if (!Number.isInteger(pid) || pid <= 0 || !Array.isArray(args) || typeof cwd !== 'string' || typeof version !== 'string' || !/^\d+\.\d+\.\d+$/.test(version) || typeof cliPath !== 'string') {
13
+ throw new Error('Invalid restart configuration');
14
+ }
15
+ const token = randomUUID();
16
+ await mkdir(dirname(RESTART_CONFIG_FILE), { recursive: true, mode: 0o700 });
17
+ await writeFile(RESTART_CONFIG_FILE, JSON.stringify({ pid, args, cwd, version, cliPath, token }), { mode: 0o600 });
18
+ await rm(RESTART_READY_FILE, { force: true });
19
+ let child;
20
+ try {
21
+ child = spawnImpl(process.execPath, [RESTART_HELPER_PATH, UPDATE_STATE_FILE, RESTART_CONFIG_FILE], {
22
+ detached: true, stdio: 'inherit', windowsHide: true, env: process.env,
23
+ });
24
+ } catch (err) {
25
+ await rm(RESTART_CONFIG_FILE, { force: true });
26
+ throw err;
27
+ }
28
+ return new Promise((resolve, reject) => {
29
+ let settled = false;
30
+ const finish = (err) => {
31
+ if (settled) return;
32
+ settled = true;
33
+ clearTimeout(timer);
34
+ clearInterval(poll);
35
+ child.off('error', onError);
36
+ child.off('exit', onExit);
37
+ if (err) {
38
+ try { child.kill('SIGKILL'); } catch { }
39
+ Promise.all([rm(RESTART_CONFIG_FILE, { force: true }), rm(RESTART_READY_FILE, { force: true })])
40
+ .catch(() => {})
41
+ .finally(() => reject(err));
42
+ } else {
43
+ child.unref();
44
+ resolve(child);
45
+ }
46
+ };
47
+ const onError = (err) => finish(err);
48
+ const onExit = (code) => { checkReady().then(ok => { if (!ok) finish(new Error(`Restart helper exited before it was ready (${code})`)); }); };
49
+ child.once('error', onError);
50
+ child.once('exit', onExit);
51
+ const checkReady = async () => {
52
+ try {
53
+ const ready = JSON.parse(await readFile(RESTART_READY_FILE, 'utf8'));
54
+ if (ready.token === token) { finish(); return true; }
55
+ } catch { /* Wait for the helper's bounded readiness signal. */ }
56
+ return false;
57
+ };
58
+ const poll = setInterval(checkReady, 50);
59
+ checkReady();
60
+ const timer = setTimeout(() => finish(new Error('Restart helper readiness timed out')), timeoutMs);
61
+ timer.unref?.();
62
+ });
63
+ }
64
+
65
+ export async function waitForExit(pid, { alive = isPidAlive, sleep = (ms) => new Promise(r => setTimeout(r, ms)), timeoutMs = 15000 } = {}) {
66
+ const deadline = Date.now() + timeoutMs;
67
+ while (alive(pid)) {
68
+ if (Date.now() >= deadline) throw new Error('Timed out waiting for the old ccv process to stop');
69
+ await sleep(100);
70
+ }
71
+ }
72
+
73
+ export async function restartFromHelper(config, { spawnImpl = spawn, wait = waitForExit } = {}) {
74
+ await wait(config.pid);
75
+ const child = spawnImpl(process.execPath, [config.cliPath, ...config.args], { cwd: config.cwd, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: false, env: { ...process.env, CCV_NO_OPEN: '1' } });
76
+ child.stdout?.on('data', (chunk) => { try { process.stdout.write(chunk); } catch { } });
77
+ child.stderr?.on('data', (chunk) => { try { process.stderr.write(chunk); } catch { } });
78
+ console.error(`[CC Viewer] Restarted in the background with PID ${child.pid}. Stop it with: kill ${child.pid}`);
79
+ return new Promise((resolve, reject) => {
80
+ child.once('error', reject);
81
+ child.once('exit', (code, signal) => resolve(code ?? (signal ? 1 : 0)));
82
+ });
83
+ }
@@ -43,6 +43,13 @@ import {
43
43
  cancelAutoApproveState,
44
44
  replayAutoApproveFields,
45
45
  } from './auto-approve.js';
46
+ import {
47
+ computeAskAutoAnswer,
48
+ createAskAutoAnswerState,
49
+ cancelAskAutoAnswerState,
50
+ replayAskAutoAnswerFields,
51
+ pickAutoAnswers,
52
+ } from './ask-auto-answer.js';
46
53
 
47
54
  let _query;
48
55
  try {
@@ -2130,11 +2137,25 @@ function _createSession(key, cwd) {
2130
2137
  // server/lib/ask/ask-constants.js.
2131
2138
  const askTimeoutMs = ASK_TIMEOUT_MS;
2132
2139
  const askStartedAt = Date.now();
2133
- const askPayload = { type: 'sdk-ask-pending', id, questions: input.questions, startedAt: askStartedAt, timeoutMs: askTimeoutMs, cwd: _cwd, sessionId: effSessionId(), instanceKey, ...origin };
2140
+ // Server-side hosting ("问答题自动托管"): approvalModal.askAutoAnswerMinutes
2141
+ // (0 = instant, N = N minutes) answers the ask at the wall-clock deadline even
2142
+ // with no browser connected. Unlike plan/perm this deliberately applies to
2143
+ // unattended scheduled-task runs (ctx != null): hosting is opt-in (default off)
2144
+ // and the 0-minute tier exists precisely for those flows — without it an
2145
+ // ephemeral run would hang the full 24h. The pick prefers the first option
2146
+ // carrying a localized "Recommended" marker, else the first option.
2147
+ const askAuto = computeAskAutoAnswer(_cwd);
2148
+ const askAutoAnswers = askAuto.enabled ? pickAutoAnswers(input.questions) : null;
2149
+ const askHosting = askAuto.enabled && !!askAutoAnswers;
2150
+ const askPayload = { type: 'sdk-ask-pending', id, questions: input.questions, startedAt: askStartedAt, timeoutMs: askTimeoutMs, cwd: _cwd, sessionId: effSessionId(), instanceKey, ...origin,
2151
+ // Always stamp the hosting fields (null when off) so a client whose global pref
2152
+ // disagrees with the fork-resolved server value never re-arms locally.
2153
+ ...replayAskAutoAnswerFields(askHosting ? askAuto : null, false) };
2134
2154
  if (_broadcastWs) {
2135
2155
  _broadcastWs(askPayload);
2136
2156
  }
2137
- const answers = await _waitForApproval(id, askTimeoutMs, 'ask', askPayload, options?.signal, ctx);
2157
+ const answers = await _waitForApproval(id, askTimeoutMs, 'ask', askPayload, options?.signal, ctx,
2158
+ askHosting ? askAuto : null, askHosting ? askAutoAnswers : undefined);
2138
2159
  if (answers === null) {
2139
2160
  return { behavior: 'deny', message: 'Timeout waiting for user answer' };
2140
2161
  }
@@ -2258,7 +2279,7 @@ function _createSession(key, cwd) {
2258
2279
  } catch (err) { console.warn('[sdk-manager] approval-dismiss broadcast threw:', err?.message); }
2259
2280
  }
2260
2281
 
2261
- function _waitForApproval(id, timeoutMs, kind, replay = null, signal = null, ctx = null, autoMeta = null) {
2282
+ function _waitForApproval(id, timeoutMs, kind, replay = null, signal = null, ctx = null, autoMeta = null, autoValue = undefined) {
2262
2283
  // Record the id on the ephemeral run's ctx ONLY when it actually parks (the three
2263
2284
  // callers below sit after every auto-allow/hard-deny early-return, so an auto-allowed
2264
2285
  // tool never lands here) — keeps ctx.approvalIds bounded (review P3: no unbounded growth).
@@ -2294,15 +2315,25 @@ function _createSession(key, cwd) {
2294
2315
  },
2295
2316
  };
2296
2317
  _pendingApprovals.set(id, entry);
2297
- // Arm the server-side fallback AFTER the entry is in the map: instant (-1) fires
2298
- // synchronously and resolves through the same first-wins wrapper.
2318
+ // Arm the server-side fallback AFTER the entry is in the map: instant (-1 for
2319
+ // plan/perm, 0 minutes for ask hosting) fires synchronously and resolves through
2320
+ // the same first-wins wrapper. Ask hosting arms its own state factory (minute
2321
+ // semantics) and resolves the pre-picked answers map; plan/perm keep the generic
2322
+ // auto-approve state. A null autoValue (no selectable option) never reaches here —
2323
+ // the ask caller passes autoMeta only when answers were actually picked, otherwise
2324
+ // resolve(null) would be misread as the timeout/deny path.
2299
2325
  if (autoMeta?.enabled) {
2300
- entry.auto = createAutoApproveState(autoMeta, () => {
2326
+ const fireResolveValue = autoValue !== undefined
2327
+ ? autoValue
2328
+ : (kind === 'plan' ? { approve: true, feedback: '' } : { decision: 'allow' });
2329
+ const fireResolvedType = kind === 'ask' ? 'sdk-ask-resolved' : (kind === 'plan' ? 'sdk-plan-resolved' : 'perm-hook-resolved');
2330
+ const fireReason = kind === 'ask' ? 'auto-answered' : 'auto-approved';
2331
+ entry.auto = (kind === 'ask' ? createAskAutoAnswerState : createAutoApproveState)(autoMeta, () => {
2301
2332
  const p = _pendingApprovals.get(id);
2302
2333
  if (!p || p.autoCancelled) return;
2303
- p.resolve(kind === 'plan' ? { approve: true, feedback: '' } : { decision: 'allow' });
2334
+ p.resolve(fireResolveValue);
2304
2335
  try {
2305
- _broadcastWs?.({ type: kind === 'plan' ? 'sdk-plan-resolved' : 'perm-hook-resolved', id, reason: 'auto-approved', cwd: _cwd, sessionId: _sessionId || null, instanceKey });
2336
+ _broadcastWs?.({ type: fireResolvedType, id, reason: fireReason, cwd: _cwd, sessionId: (ctx && ctx.sessionId) || _sessionId || null, instanceKey });
2306
2337
  } catch (err) { reportSwallowed('sdk-manager.auto-approve-broadcast', err); }
2307
2338
  });
2308
2339
  }
@@ -2350,30 +2381,44 @@ function _createSession(key, cwd) {
2350
2381
  if (remaining <= 0) continue;
2351
2382
  out.push({
2352
2383
  id, kind: p.kind || null, replay: p.replay || null, remainingMs: remaining,
2353
- ...replayAutoApproveFields(p.auto, p.autoCancelled),
2384
+ // Ask hosting replays under its own field names (autoAnswerAt/…) — an ask
2385
+ // entry must never advertise autoApproveAt (plan/perm-only contract, pinned
2386
+ // by sdk-manager-auto-approve.test.js).
2387
+ ...(p.kind === 'ask'
2388
+ ? replayAskAutoAnswerFields(p.auto, p.autoCancelled)
2389
+ : replayAutoApproveFields(p.auto, p.autoCancelled)),
2354
2390
  });
2355
2391
  }
2356
2392
  return out;
2357
2393
  }
2358
2394
 
2359
2395
  /**
2360
- * Cancel the SERVER-SIDE auto-approve countdown for a pending plan/perm approval
2361
- * (client clicked the countdown-cancel button). Unlike cancelApproval this does NOT
2396
+ * Cancel the SERVER-SIDE auto-approve / hosting countdown for a pending plan/perm/ask
2397
+ * approval (client clicked the countdown-cancel button). Unlike cancelApproval this does NOT
2362
2398
  * resolve the approval — it stays pending for a manual decision; only the fallback
2363
2399
  * timer is destroyed and the cancelled flag is replayed to fresh clients so they
2364
2400
  * never re-arm. Returns true when the id matched a pending approval of that kind
2365
2401
  * (even on a repeat cancel — the state change is durable while pending); false when
2366
2402
  * nothing matched (caller falls back to the legacy relay-only behavior).
2403
+ * For ask specifically, false is also returned when no hosting timer was armed
2404
+ * (hosting off / no selectable option) so the caller can fall through to the
2405
+ * PTY-hook entry.
2367
2406
  */
2368
2407
  function _autoCancelApproval(id, kind) {
2369
- // plan/perm only — ask approvals never arm a server auto-approve timer.
2370
- if (kind !== 'plan' && kind !== 'perm') return false;
2408
+ if (kind !== 'plan' && kind !== 'perm' && kind !== 'ask') return false;
2371
2409
  const pending = _pendingApprovals.get(id);
2410
+ // A kind-collision (the id belongs to a plan/perm pending) must NOT be treated as
2411
+ // handled: return false so the caller falls through to the PTY-hook entry, which may
2412
+ // legitimately own that ask id. Without this the hosting cancel is silently dropped.
2372
2413
  if (!pending || pending.kind !== kind) return false;
2373
- const first = cancelAutoApproveState(pending);
2414
+ // Ask with no armed hosting timer: nothing to cancel, but the durable latch is still
2415
+ // stamped (harmless) and the caller falls through to relay the broadcast so sibling
2416
+ // tabs stop their countdown.
2417
+ if (kind === 'ask' && !pending.auto) return false;
2418
+ const first = kind === 'ask' ? cancelAskAutoAnswerState(pending) : cancelAutoApproveState(pending);
2374
2419
  if (first && _broadcastWs) {
2375
2420
  try {
2376
- _broadcastWs({ type: kind === 'plan' ? 'sdk-plan-auto-cancel' : 'perm-hook-auto-cancel', id, cwd: _cwd, sessionId: _sessionId || null, instanceKey });
2421
+ _broadcastWs({ type: kind === 'plan' ? 'sdk-plan-auto-cancel' : (kind === 'ask' ? 'ask-auto-cancel' : 'perm-hook-auto-cancel'), id, cwd: _cwd, sessionId: _sessionId || null, instanceKey });
2377
2422
  } catch (err) { reportSwallowed('sdk-manager.auto-cancel-broadcast', err); }
2378
2423
  }
2379
2424
  return true;
@@ -3046,10 +3091,11 @@ export function cancelApproval(id, reason) {
3046
3091
  }
3047
3092
 
3048
3093
  /**
3049
- * Cancel the server-side auto-approve countdown for a plan/perm approval,
3050
- * scanning EVERY session (auto-cancel WS handlers). The approval stays pending
3051
- * for a manual decision. Returns false when no pending approval matched, so the
3052
- * caller can fall back to the legacy relay-only broadcast.
3094
+ * Cancel the server-side auto-approve countdown for a plan/perm approval, or the
3095
+ * hosting ("问答题自动托管") timer for an AskUserQuestion approval, scanning EVERY
3096
+ * session (auto-cancel WS handlers). The approval stays pending for a manual
3097
+ * decision. Returns false when no pending approval matched, so the caller can fall
3098
+ * back to the legacy relay-only broadcast.
3053
3099
  */
3054
3100
  export function autoCancelApproval(id, kind) {
3055
3101
  for (const sess of new Set([..._sessions.values(), ..._ephemeralHosts])) {
@@ -0,0 +1,42 @@
1
+ import { request } from 'node:http';
2
+
3
+ const DEFAULT_START_PORT = 7008;
4
+ const DEFAULT_MAX_PORT = 7049;
5
+
6
+ export function normalInstancePortRange(env = process.env) {
7
+ if (env.CCV_IM_PLATFORM || env.CCV_WORKSPACE_MODE) return [];
8
+ const start = Number(env.CCV_START_PORT) || DEFAULT_START_PORT;
9
+ const end = Number(env.CCV_MAX_PORT) || DEFAULT_MAX_PORT;
10
+ return start >= DEFAULT_START_PORT && end <= DEFAULT_MAX_PORT && start <= end ? [start, end] : [];
11
+ }
12
+
13
+ export function probeInstance(port, { requestImpl = request, timeoutMs = 300 } = {}) {
14
+ return new Promise((resolve) => {
15
+ let settled = false;
16
+ const done = (value) => { if (!settled) { settled = true; resolve(value); } };
17
+ let req;
18
+ try {
19
+ req = requestImpl({ hostname: '127.0.0.1', port, path: '/api/version-info', timeout: timeoutMs }, (res) => {
20
+ let body = '';
21
+ res.setEncoding('utf8');
22
+ res.on('data', chunk => { body += chunk; });
23
+ res.on('end', () => {
24
+ try {
25
+ const data = JSON.parse(body);
26
+ done(res.statusCode === 200 && /^\d+\.\d+\.\d+$/.test(data.version || '') && data.instanceKind === 'normal' && data.instancePort === port);
27
+ } catch { done(false); }
28
+ });
29
+ });
30
+ req.on('error', () => done(false));
31
+ req.on('timeout', () => { req.destroy(); done(false); });
32
+ req.end();
33
+ } catch { done(false); }
34
+ });
35
+ }
36
+
37
+ export async function hasOtherNormalInstance({ portRange = normalInstancePortRange(), currentPort, probe = probeInstance } = {}) {
38
+ if (!Array.isArray(portRange) || portRange.length !== 2) return false;
39
+ const ports = Array.from({ length: portRange[1] - portRange[0] + 1 }, (_, i) => portRange[0] + i).filter(port => port !== currentPort);
40
+ const results = await Promise.all(ports.map(port => probe(port)));
41
+ return results.some(Boolean);
42
+ }