cc-viewer 1.9.22 → 1.9.24

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 (107) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +2 -2
  3. package/cli.js +25 -1
  4. package/dist/assets/App-BwRRqrP5.css +1 -0
  5. package/dist/assets/App-Cfmm41z0.js +2 -0
  6. package/dist/assets/ArchivePreview-BKXTsPsN.css +1 -0
  7. package/dist/assets/ArchivePreview-dKWXN9Zp.js +1 -0
  8. package/dist/assets/{MdxEditorPanel-CmHF9Mz1.js → MdxEditorPanel-CT6w8hjl.js} +1 -1
  9. package/dist/assets/Mobile-noWViQpL.js +1 -0
  10. package/dist/assets/{ProxyStatsModal-Ogrx3mxS.js → ProxyStatsModal-BeCRPqaC.js} +1 -1
  11. package/dist/assets/{_baseUniq-CsF04anE.js → _baseUniq-BGBEhBne.js} +1 -1
  12. package/dist/assets/{arc-BOacYe6N.js → arc-4pbWOEmh.js} +1 -1
  13. package/dist/assets/{architectureDiagram-Q4EWVU46-BSUEfjC_.js → architectureDiagram-Q4EWVU46-BHZPDnby.js} +1 -1
  14. package/dist/assets/{blockDiagram-DXYQGD6D-CC37UGtW.js → blockDiagram-DXYQGD6D-DszLU7Pg.js} +1 -1
  15. package/dist/assets/{c4Diagram-AHTNJAMY-IzgRD4uO.js → c4Diagram-AHTNJAMY-DbDJNYxl.js} +1 -1
  16. package/dist/assets/{channel-C6PxyQUn.js → channel-BpIsxDHj.js} +1 -1
  17. package/dist/assets/{chunk-4BX2VUAB-cdQt_dcU.js → chunk-4BX2VUAB-ChcBwBh2.js} +1 -1
  18. package/dist/assets/{chunk-4TB4RGXK-BpTDA_Pb.js → chunk-4TB4RGXK-DzBEAck_.js} +1 -1
  19. package/dist/assets/{chunk-55IACEB6-CcitNo0P.js → chunk-55IACEB6-9UDvmw07.js} +1 -1
  20. package/dist/assets/{chunk-EDXVE4YY-BjKwZ9I7.js → chunk-EDXVE4YY-DHEU2DKg.js} +1 -1
  21. package/dist/assets/{chunk-FMBD7UC4-vZDVX3tI.js → chunk-FMBD7UC4-sysT0Sy2.js} +1 -1
  22. package/dist/assets/{chunk-OYMX7WX6-DGkYahGo.js → chunk-OYMX7WX6-DLXt2vYo.js} +1 -1
  23. package/dist/assets/{chunk-QZHKN3VN-C9065hSE.js → chunk-QZHKN3VN-CDIkC7QK.js} +1 -1
  24. package/dist/assets/{chunk-YZCP3GAM-D_pcTg6_.js → chunk-YZCP3GAM-D9b_INz7.js} +1 -1
  25. package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +1 -0
  26. package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +1 -0
  27. package/dist/assets/clone-cWiXtXrO.js +1 -0
  28. package/dist/assets/{cose-bilkent-S5V4N54A-BPPFMIGv.js → cose-bilkent-S5V4N54A-DJQwV_Dp.js} +1 -1
  29. package/dist/assets/{dagre-KV5264BT-fjzhKO5o.js → dagre-KV5264BT-bl9Pq21t.js} +1 -1
  30. package/dist/assets/{diagram-5BDNPKRD-5L6FzTry.js → diagram-5BDNPKRD-BA8CJxzI.js} +1 -1
  31. package/dist/assets/{diagram-G4DWMVQ6-GOwcGpff.js → diagram-G4DWMVQ6-DzSQULuz.js} +1 -1
  32. package/dist/assets/{diagram-MMDJMWI5-BDsFE25W.js → diagram-MMDJMWI5-DhfHWnT4.js} +1 -1
  33. package/dist/assets/{diagram-TYMM5635-BqjpbSGH.js → diagram-TYMM5635-BbAoFfGS.js} +1 -1
  34. package/dist/assets/{erDiagram-SMLLAGMA-DWO3Dk1v.js → erDiagram-SMLLAGMA-CMjA2eBk.js} +1 -1
  35. package/dist/assets/{flowDiagram-DWJPFMVM-Br4nNBVd.js → flowDiagram-DWJPFMVM-bOubqgJ6.js} +1 -1
  36. package/dist/assets/{ganttDiagram-T4ZO3ILL-9sN-VOhw.js → ganttDiagram-T4ZO3ILL-BUIu7WwI.js} +1 -1
  37. package/dist/assets/{gitGraphDiagram-UUTBAWPF-BsPcTAKr.js → gitGraphDiagram-UUTBAWPF-B_vrztDU.js} +1 -1
  38. package/dist/assets/{graph-o31GzaB6.js → graph-BR3YGx52.js} +1 -1
  39. package/dist/assets/{index-DAjx9lT3.js → index-B88yR2TU.js} +1 -1
  40. package/dist/assets/{index-PDvAAbti.js → index-BMpUfdYI.js} +1 -1
  41. package/dist/assets/{index-DyV81jSF.js → index-BQx5MOpr.js} +1 -1
  42. package/dist/assets/index-Ca3a2tOc.js +2 -0
  43. package/dist/assets/{index-CuvDJTY7.js → index-ClTuiPoz.js} +1 -1
  44. package/dist/assets/{index-tZqiJJGq.js → index-DtZAmvwJ.js} +1 -1
  45. package/dist/assets/{index-B3b0lRUB.js → index-DwMyfQJq.js} +1 -1
  46. package/dist/assets/{index-CXMr3tiK.js → index-mvm_Pxcf.js} +1 -1
  47. package/dist/assets/{infoDiagram-42DDH7IO-VUMzEo4o.js → infoDiagram-42DDH7IO-Co9Db2ir.js} +1 -1
  48. package/dist/assets/{ishikawaDiagram-UXIWVN3A-BuzrU3sx.js → ishikawaDiagram-UXIWVN3A-4z7EydCd.js} +1 -1
  49. package/dist/assets/{journeyDiagram-VCZTEJTY-BZtR5BAF.js → journeyDiagram-VCZTEJTY-CtLfbhYE.js} +1 -1
  50. package/dist/assets/{jszip.min-CtodH5MV.js → jszip.min-DtbrAiWv.js} +1 -1
  51. package/dist/assets/{kanban-definition-6JOO6SKY-Cj_97xXb.js → kanban-definition-6JOO6SKY-9ZrhOvdX.js} +1 -1
  52. package/dist/assets/{layout-Du0I-tlh.js → layout-Ddo06NJO.js} +1 -1
  53. package/dist/assets/{linear-BJtxCASI.js → linear-BZUsBSwS.js} +1 -1
  54. package/dist/assets/{mermaid.core-QlorX0Yw.js → mermaid.core-O-x0KuTp.js} +2 -2
  55. package/dist/assets/{min-BVnQfunZ.js → min-PzJh19JL.js} +1 -1
  56. package/dist/assets/{mindmap-definition-QFDTVHPH-Bh_KL4qU.js → mindmap-definition-QFDTVHPH-C3MVo-7p.js} +1 -1
  57. package/dist/assets/{pieDiagram-DEJITSTG-Bvv0rC_q.js → pieDiagram-DEJITSTG-CMn9-kQc.js} +1 -1
  58. package/dist/assets/{quadrantDiagram-34T5L4WZ-Bw8cGCRU.js → quadrantDiagram-34T5L4WZ-9eyqTdkj.js} +1 -1
  59. package/dist/assets/{requirementDiagram-MS252O5E-Cg9jQ71h.js → requirementDiagram-MS252O5E-BJbuDOpR.js} +1 -1
  60. package/dist/assets/{sankeyDiagram-XADWPNL6-BXJo6-CD.js → sankeyDiagram-XADWPNL6-CzQ1KxD3.js} +1 -1
  61. package/dist/assets/seqResourceLoaders-DH-Nl0yh.css +41 -0
  62. package/dist/assets/seqResourceLoaders-DeqzMajS.js +2 -0
  63. package/dist/assets/{sequenceDiagram-FGHM5R23-D7zpGxwq.js → sequenceDiagram-FGHM5R23-CfmSEAYp.js} +1 -1
  64. package/dist/assets/{stateDiagram-FHFEXIEX-Der2CqR1.js → stateDiagram-FHFEXIEX-Brw2ZXQC.js} +1 -1
  65. package/dist/assets/{stateDiagram-v2-QKLJ7IA2-DetvG_Lc.js → stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js} +1 -1
  66. package/dist/assets/{timeline-definition-GMOUNBTQ-0UenzEZ6.js → timeline-definition-GMOUNBTQ-DNi7GnlG.js} +1 -1
  67. package/dist/assets/{vendor-antd-I6I2F7Rv.js → vendor-antd-DWLgSkPo.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-Zkm6UHQg.js → vendor-codemirror-CKsm_iG4.js} +1 -1
  69. package/dist/assets/{vendor-mdxeditor-CC09MDyZ.js → vendor-mdxeditor-Dah6NK0y.js} +2 -2
  70. package/dist/assets/{vendor-qrcode-gZpmSeeh.js → vendor-qrcode-CDcb8weP.js} +1 -1
  71. package/dist/assets/{vendor-virtuoso-BGwznQ5y.js → vendor-virtuoso-DKUobZpA.js} +1 -1
  72. package/dist/assets/{vennDiagram-DHZGUBPP-COzYyZ5h.js → vennDiagram-DHZGUBPP-Cdkdx7gB.js} +1 -1
  73. package/dist/assets/{wardley-RL74JXVD-VZdOtN8t.js → wardley-RL74JXVD-YKzsVN4U.js} +1 -1
  74. package/dist/assets/{wardleyDiagram-NUSXRM2D-CVkL75Qy.js → wardleyDiagram-NUSXRM2D-gBsb6aut.js} +1 -1
  75. package/dist/assets/{xychartDiagram-5P7HB3ND-6CHBAYyF.js → xychartDiagram-5P7HB3ND-Bh63NWof.js} +1 -1
  76. package/dist/index.html +4 -4
  77. package/findcc.js +4 -4
  78. package/node_modules/@ccv/core/src/ask-auto-answer.js +122 -0
  79. package/node_modules/@ccv/core/src/contentFilter.js +4 -1
  80. package/node_modules/@ccv/core/src/ultraplanTemplates.js +199 -0
  81. package/package.json +1 -1
  82. package/server/i18n.js +4 -20
  83. package/server/lib/ask/ask-bridge.js +4 -1
  84. package/server/lib/ask/ask-reaper.js +1 -0
  85. package/server/lib/ask-auto-answer.js +153 -0
  86. package/server/lib/auto-approve.js +3 -1
  87. package/server/lib/binary-sniff.js +35 -0
  88. package/server/lib/ensure-hooks.js +134 -2
  89. package/server/lib/im/im-bridge-core.js +16 -0
  90. package/server/lib/scheduled-task-executor.js +14 -2
  91. package/server/lib/scheduled-task-store.js +129 -18
  92. package/server/lib/sdk-manager.js +178 -30
  93. package/server/pty-manager.js +103 -4
  94. package/server/routes/ask-perm.js +87 -6
  95. package/server/routes/files-content.js +46 -8
  96. package/server/routes/scheduled-tasks.js +13 -0
  97. package/server/server.js +100 -0
  98. package/server/system-prompt-templates/presets/kimi-k3.md +8 -0
  99. package/dist/assets/App-BN3viVRq.js +0 -2
  100. package/dist/assets/App-BvVdj099.css +0 -1
  101. package/dist/assets/Mobile-nbI6IeX_.js +0 -1
  102. package/dist/assets/classDiagram-6PBFFD2Q-BUmU_G-i.js +0 -1
  103. package/dist/assets/classDiagram-v2-HSJHXN6E-BUmU_G-i.js +0 -1
  104. package/dist/assets/clone-CvoOne2K.js +0 -1
  105. package/dist/assets/index-DoFyHmPM.js +0 -2
  106. package/dist/assets/seqResourceLoaders-DbccWwKz.css +0 -41
  107. package/dist/assets/seqResourceLoaders-n9iXZRHx.js +0 -2
@@ -0,0 +1,122 @@
1
+ // CLIENT-SAFE: no node deps. Home: @ccv/core (ask-auto-answer.js) — consumed by packages/app
2
+ // (server auto-answer timers) and importable by apps/web. Do not add fs/process/node: imports.
3
+ // AskUserQuestion auto-answer ("managed answering") picker logic.
4
+ //
5
+ // When the hosting setting (approvalModal.askAutoAnswerMinutes) is enabled, the server
6
+ // answers a pending AskUserQuestion itself at a wall-clock deadline. This module decides
7
+ // WHICH option to pick, pure and locale-aware:
8
+ // 1. first option (array order) whose label contains a "Recommended" marker in any
9
+ // supported UI language — Claude Code localizes the "(Recommended)" suffix;
10
+ // 2. otherwise the first selectable option.
11
+ // The synthetic "Other" option is never auto-picked.
12
+
13
+ // Lower-cased marker vocabulary covering the 18 supported locales
14
+ // (zh, en, zh-TW, ko, ja, de, es, fr, it, da, pl, ru, ar, no, pt-BR, th, tr, uk).
15
+ // Matching is a case-insensitive substring test, so surrounding decorations like
16
+ // "(推荐)", "(推荐)", "- Recommended" all match without extra normalization.
17
+ export const RECOMMENDED_MARKERS = Object.freeze([
18
+ '推荐', // zh
19
+ '推薦', // zh-TW
20
+ 'recommended', // en
21
+ '推奨', // ja
22
+ '추천', // ko
23
+ 'empfohlen', // de
24
+ 'recomendado', // es + pt-BR
25
+ 'recommandé', // fr
26
+ 'consigliato', // it
27
+ 'anbefalet', // da
28
+ 'anbefalt', // no
29
+ 'zalecane', // pl
30
+ 'рекомендуется', // ru
31
+ 'рекомендовано', // uk
32
+ 'موصى به', // ar
33
+ 'แนะนำ', // th
34
+ 'önerilen', // tr
35
+ ]);
36
+
37
+ // The form's synthetic free-text option — recognized case-insensitively, same as
38
+ // AskQuestionForm (/^other$/i). Never a valid auto-pick target.
39
+ const OTHER_LABEL_RE = /^other$/i;
40
+
41
+ // Negation prefixes that immediately precede a marker and turn it into a
42
+ // DIScouragement ("不推荐", "Not recommended", "Nicht empfohlen", …). A label whose
43
+ // only marker occurrence is negated must NOT be treated as recommended — otherwise
44
+ // the picker would auto-confirm the exact option the model advised against.
45
+ // Multi-language, lower-cased, matched against the lower-cased label.
46
+ const NEGATION_PREFIXES = Object.freeze([
47
+ '不', '非', '未', '勿', // zh / zh-TW
48
+ 'not ', 'no ', "isn't ", "aren't ", 'never ', // en
49
+ 'nicht ', 'kein ', // de
50
+ 'não ', // pt-BR (es uses 'no ', shared with en above)
51
+ 'pas ', // fr
52
+ 'non ', // it
53
+ 'ikke ', // da + no
54
+ 'nie ', // pl
55
+ 'не ', // ru + uk
56
+ '비', '추천하지', // ko
57
+ '非推奨', '推奨しない', // ja (非推奨 is itself a full negated form)
58
+ 'لا ', // ar
59
+ 'ไม่', // th
60
+ 'değil', 'önerilmez', // tr
61
+ ]);
62
+
63
+ /**
64
+ * @param {unknown} label
65
+ * @returns {boolean} true when the label contains a Recommended marker (any locale)
66
+ * that is NOT negated (e.g. "Not recommended" / "不推荐" are excluded).
67
+ */
68
+ export function isRecommendedLabel(label) {
69
+ if (typeof label !== 'string' || label.length === 0) return false;
70
+ const hay = label.toLowerCase();
71
+ for (const marker of RECOMMENDED_MARKERS) {
72
+ let idx = hay.indexOf(marker);
73
+ while (idx !== -1) {
74
+ const before = hay.slice(0, idx);
75
+ const negated = NEGATION_PREFIXES.some((neg) => before.endsWith(neg));
76
+ if (!negated) return true;
77
+ idx = hay.indexOf(marker, idx + 1);
78
+ }
79
+ }
80
+ return false;
81
+ }
82
+
83
+ /**
84
+ * A selectable option: an object with a non-empty string label that is not the
85
+ * synthetic "Other" option.
86
+ */
87
+ function _isSelectableOption(opt) {
88
+ return !!opt
89
+ && typeof opt === 'object'
90
+ && typeof opt.label === 'string'
91
+ && opt.label.length > 0
92
+ && !OTHER_LABEL_RE.test(opt.label);
93
+ }
94
+
95
+ /**
96
+ * Build the auto-answer payload for an AskUserQuestion questions array.
97
+ *
98
+ * All-or-nothing: the answers map must cover every question (the upstream tool
99
+ * expects an answer per question), so if ANY question has no selectable option
100
+ * the whole ask is left for a human and this returns null.
101
+ *
102
+ * @param {unknown} questions - array of { question, options, multiSelect? }
103
+ * @returns {Object<string, string>|null} { [questionText]: label } or null
104
+ */
105
+ export function pickAutoAnswers(questions) {
106
+ if (!Array.isArray(questions) || questions.length === 0) return null;
107
+ const answers = {};
108
+ for (const q of questions) {
109
+ if (!q || typeof q !== 'object') return null;
110
+ const questionText = q.question;
111
+ if (typeof questionText !== 'string' || questionText.length === 0) return null;
112
+ const options = Array.isArray(q.options) ? q.options : [];
113
+ const selectable = options.filter(_isSelectableOption);
114
+ if (selectable.length === 0) return null;
115
+ const recommended = selectable.find((opt) => isRecommendedLabel(opt.label));
116
+ // First recommended match wins; without any marker the first option wins.
117
+ // multiSelect degenerates to the single picked label (the client-side ", "
118
+ // join of one label is just that label).
119
+ answers[questionText] = (recommended || selectable[0]).label;
120
+ }
121
+ return answers;
122
+ }
@@ -610,7 +610,10 @@ let _registryScanned = new WeakSet();
610
610
  // Identify the session by the first request's timestamp; auto-reset on switch
611
611
  let _registrySessionKey = null;
612
612
 
613
- const PROMPT_PREFIX_LEN = 60;
613
+ export const PROMPT_PREFIX_LEN = 60;
614
+ // Shared cap on the retained prompt snippet for agent tasks — the web tracker and
615
+ // the server replay table must truncate identically for prompt-prefix joins.
616
+ export const AGENT_PROMPT_SNIPPET_LEN = 1024;
614
617
  const TM_TAG_RE = /<teammate-message[^>]*>/;
615
618
 
616
619
  /**
@@ -0,0 +1,199 @@
1
+ // Ultraplan prompt templates for local Claude Code execution.
2
+ // Shared isomorphic module (@ccv/core): the web hosts (TerminalPanel / ChatView) assemble
3
+ // at send time, and the scheduled-task executor (packages/app) assembles at fire time —
4
+ // one source of truth so the wrapper can never drift between the two.
5
+ //
6
+ // Two expert roles:
7
+ // - codeExpert: Multi-agent code planning & implementation (from subagents template)
8
+ // - researchExpert: Multi-agent research & analysis
9
+ // Plus the 'none' variant: no template wrapper, the user input is sent as-is.
10
+ //
11
+ // Assembly logic mirrors ~/claude-code/commands/ultraplan.tsx:63-73
12
+ // buildUltraplanPrompt(blurb, seedPlan?)
13
+
14
+ export const ULTRAPLAN_VARIANTS = {
15
+
16
+ codeExpert: `<system-reminder>
17
+ [SCOPED INSTRUCTION] The following instructions apply only to the next 1–3 interactions. Once the task is complete, these instructions should gradually decrease in priority and no longer affect subsequent interactions. You should be adept at utilizing tools such as \`AskUserQuestion\` and \`EnterPlanMode\`, rather than relying solely on plain text processing. Before execution, you must ensure that the \`EnterPlanMode\`, \`ExitPlanMode\`, \`SendMessage\`, \`TaskCreate\`, \`TaskUpdate\`, \`TaskStop\`, \`TaskGet\`, \`TaskOutput\` and \`TaskList\` tools are loaded.
18
+
19
+ Pre-requisite: Use \`AskUserQuestion\` to clarify user intent whenever the request is ambiguous (target element, interaction style, scope of platforms, etc.). Skip only if the intent is unambiguous.
20
+
21
+ Leverage a multi-agent exploration mechanism to formulate a highly detailed implementation plan.
22
+
23
+ Instructions:
24
+ 1. Use the \`Agent\` tool to spawn parallel agents that simultaneously explore different aspects of the codebase:
25
+ - If necessary, assign a preliminary researcher to use the \`webSearch\` tool to first investigate cutting-edge solutions in the relevant industry domain;
26
+ - One agent responsible for understanding the relevant existing code and architecture;
27
+ - One agent responsible for identifying all files that need to be modified;
28
+ - One agent responsible for identifying potential risks, edge cases, and dependencies;
29
+ - You may add other roles or deploy additional agents beyond the three listed above; the maximum number of concurrently dispatched agents is 5.
30
+
31
+ 2. Synthesize the findings from all agents into a detailed, step-by-step implementation plan.
32
+
33
+ 3. Use the \`Agent\` tool to spawn 2-3 review agents that examine the plan from different perspectives, checking for missing steps, potential risks, or corresponding mitigation strategies.
34
+
35
+ 4. Integrate the feedback gathered during the review process, then call \`ExitPlanMode\` to submit your final plan.
36
+
37
+ 5. Once \`ExitPlanMode\` returns a result:
38
+ - If approved: proceed to execute the plan within this session.
39
+ - If rejected: revise the plan based on the feedback provided and call \`ExitPlanMode\` again.
40
+ - If an error occurs (including receiving a "Not in Plan Mode" message): do **not** follow the suggestions provided in the error message; instead, prompt the user for further instructions.
41
+
42
+ Your final plan must include the following elements:
43
+ - A clear summary of the implementation strategy;
44
+ - An ordered list of files to be created or modified, with precise details of the required changes for each file;
45
+ - A step-by-step execution sequence;
46
+ - Testing and validation procedures;
47
+ - Potential risks and their corresponding mitigation strategies;
48
+
49
+ 6. After the final plan has been successfully executed:
50
+ First run \`git diff --quiet && git diff --cached --quiet\` (or equivalent) to detect whether the working tree actually has non-trivial changes; if there are no real changes (or only whitespace/comment-only edits), skip the UltraReview step.
51
+ Otherwise, if the project is managed with Git:
52
+ Use the \`Agent\` tool to build a team, dynamically allocating the number of teammates based on task complexity (5+ recommended);
53
+ Note: spawn teammates (which have a \`name\`), not plain subagents (which have no name);
54
+ Task: Conduct a Code Review of the current git changes from multiple roles and perspectives;
55
+ Pre-requisites:
56
+ - The git repository may be located in a subdirectory of the current directory; recursively locate the \`.git\` directory first before proceeding;
57
+ - In the case of multiple repositories, review tasks may be executed separately per repository;
58
+ Review dimensions (a reference framework — each role covers them as its perspective requires, aiming to be as comprehensive as possible):
59
+ - Whether requirements/objectives have been met and functionality is complete;
60
+ - Whether newly added code introduces side effects, breaks existing functionality, or poses potential risks;
61
+ - Code quality: naming, readability, complexity, technical debt, maintainability;
62
+ - Testing and documentation: whether there is adequate test coverage, and whether critical logic has necessary comments or documentation;
63
+ - Dependencies and compatibility: whether new dependencies or version compatibility issues have been introduced;
64
+ - Any other dimensions you see fit;
65
+ Workflow:
66
+ - Each teammate, according to their own role, covers the review dimensions one by one and independently outputs a report;
67
+ - After consolidating the reports, perform a cross-review to identify conflicts or shared concerns;
68
+ - Distill specific, actionable modification suggestions and annotate them with priority levels (P0/P1/P2/P3);
69
+ - Upon completion, fix all P0 and P1 items; evaluate P2 items dialectically (use \`AskUserQuestion\` to consult the user when any item needs a special decision);
70
+ - After execution is complete, close the team: notify each teammate to exit individually;
71
+ </system-reminder>`,
72
+
73
+ researchExpert: `<system-reminder>
74
+ [SCOPED INSTRUCTION] The following instructions are intended for the next 1–3 interactions. Once the task is complete, these instructions should be gradually deprioritized and no longer influence subsequent interactions.You should be adept at utilizing tools such as \`AskUserQuestion\`, \`EnterPlanMode\` and \`WebSearch\`, rather than relying solely on plain text processing. Before execution, you must ensure that the \`EnterPlanMode\`, \`ExitPlanMode\`, \`TaskCreate\`, \`TaskUpdate\`, \`TaskStop\`, \`TaskGet\`, \`TaskOutput\` and \`TaskList\` tools are loaded.
75
+
76
+ Pre-requisite: Use \`AskUserQuestion\` to clarify the research scope, target audience, and deliverable format whenever the user's intent is ambiguous. Skip only if the intent is unambiguous.
77
+
78
+ Leverage a multi-agent exploration mechanism to formulate an exceptionally detailed implementation plan.
79
+
80
+ Instructions:
81
+ 1. Utilize the Agent tool to spawn parallel agents that simultaneously explore various facets of the requirements:
82
+ - If necessary, deploy a preliminary investigator to conduct an initial survey of industry-specific solutions using \`webSearch\`;
83
+ - If necessary, deploy a specialized investigator to research authoritative sources—such as academic papers, news articles, and research reports—using \`webSearch\`;
84
+ - Assign an agent to synthesize the target solution, while simultaneously verifying the rigor and credibility of the gathered papers, news, and research reports;
85
+ - If necessary, assign an agent to analyze competitor data to provide supplementary analytical perspectives;
86
+ - If necessary, assign an agent to handle the implementation of a product demo (generating outputs such as HTML, Markdown, etc.);
87
+ - If the task is sufficiently complex, you may assign additional teammates to the roles defined above, or introduce other specialized roles; you are permitted to schedule up to 5 teammates concurrently.
88
+
89
+ 2. Synthesize the findings from the aforementioned agents into a comprehensive, step-by-step implementation plan.
90
+
91
+ 3. Utilize the Agent tool to spawn a set of parallel review agents; these agents shall scrutinize the plan from multiple roles and perspectives to identify any omitted steps and to propose reasonable additions or optimizations.
92
+
93
+ 4. Consolidate the feedback received from the review agents, then invoke \`ExitPlanMode\` to submit your final plan.
94
+
95
+ 5. Upon receiving the result from \`ExitPlanMode\`:
96
+ - If Approved: Proceed to execute the plan within this current session.
97
+ - If Rejected: Revise the plan based on the provided feedback, and then invoke \`ExitPlanMode\` once again.
98
+ - If an Error Occurs (including the message "Not in Plan Mode"): Do *not* follow the suggestions provided by the error message; instead, prompt the user for further instructions.
99
+
100
+ Your final plan must include the following elements:
101
+ - A clear summary of the proposed implementation strategy;
102
+ - An ordered list of files to be created or modified, specifying the exact changes required for each;
103
+ - A step-by-step sequence for executing the implementation;
104
+ - Identification of potential risks and corresponding mitigation strategies;
105
+ - Creative ideation and suggestions for advanced enhancements;
106
+ - If a product demo was generated, place the corresponding demo output in an appropriate location and notify the user.
107
+ </system-reminder>`,
108
+
109
+ };
110
+
111
+ /**
112
+ * Wrap user-authored custom instruction body with the same scoped-instruction
113
+ * preamble used by the built-in variants. Produces a full <system-reminder>
114
+ * block ready to be inlined into a Claude Code prompt.
115
+ */
116
+ export function buildCustomTemplate(content) {
117
+ const body = (content || '').trim();
118
+ if (!body) return '';
119
+ // A body that already carries the wrapper shell (the prefilled skeleton or a
120
+ // hand-written one) must not be wrapped again; startsWith (not includes) so a
121
+ // body that merely *mentions* the tag in prose still gets the scope preamble.
122
+ if (body.startsWith('<system-reminder>')) return body;
123
+ return `<system-reminder>
124
+ [SCOPED INSTRUCTION] The following instructions apply only to the next 1–3 interactions. Once the task is complete, these instructions should gradually decrease in priority and no longer affect subsequent interactions. You should be adept at utilizing tools such as \`AskUserQuestion\` and \`EnterPlanMode\`, rather than relying solely on plain text processing.
125
+
126
+ ${body}
127
+ </system-reminder>`;
128
+ }
129
+
130
+ /**
131
+ * Assemble a local ultraplan prompt.
132
+ * Mirrors ~/claude-code/commands/ultraplan.tsx:63-73 buildUltraplanPrompt()
133
+ *
134
+ * @param {string} userPrompt - User's task description
135
+ * @param {'none'|'codeExpert'|'researchExpert'|'custom'} variant - Template variant;
136
+ * 'none' returns the user prompt as-is (no wrapper).
137
+ * @param {string} [seedPlan] - Optional draft plan to refine
138
+ * @param {string} [customContent] - Required when variant === 'custom': the user-authored body
139
+ * @returns {string} Assembled prompt ready to send to Claude Code
140
+ */
141
+ export function buildLocalUltraplan(userPrompt, variant = 'codeExpert', seedPlan, customContent) {
142
+ // 'none' is the empty template: send the user input verbatim. seedPlan only
143
+ // makes sense together with a wrapper, so it is ignored here.
144
+ if (variant === 'none') return userPrompt || '';
145
+ let template;
146
+ if (variant === 'custom') {
147
+ template = buildCustomTemplate(customContent);
148
+ if (!template) return '';
149
+ } else {
150
+ template = ULTRAPLAN_VARIANTS[variant] || ULTRAPLAN_VARIANTS.codeExpert;
151
+ }
152
+ const parts = [];
153
+ if (seedPlan) {
154
+ parts.push('Here is a draft plan to refine:', '', seedPlan, '');
155
+ }
156
+ parts.push(template);
157
+ if (userPrompt) {
158
+ parts.push('', userPrompt);
159
+ }
160
+ return parts.join('\n');
161
+ }
162
+
163
+ /**
164
+ * Assemble the text a scheduled task actually dispatches (executor-side).
165
+ * The task stores the RAW user input (task.prompt) plus the template selection
166
+ * and attachment paths; the wrapper and the quoted-path prefix are injected here
167
+ * at fire time so the stored prompt stays editable and summaries stay human-readable.
168
+ *
169
+ * @param {object} task
170
+ * @param {string} task.prompt raw user text (never pre-wrapped)
171
+ * @param {string} [task.template] 'none' | builtin key | 'custom:<id>'; absent → 'none'
172
+ * @param {string} [task.templateContent] snapshot of the custom expert body (custom:* only)
173
+ * @param {Array<{name:string, path:string}>} [task.attachments]
174
+ * @returns {string} the prompt to dispatch (empty string when there is nothing to send)
175
+ */
176
+ export function assembleScheduledPrompt(task) {
177
+ const raw = (task && task.prompt != null) ? String(task.prompt).trim() : '';
178
+ const attachments = Array.isArray(task?.attachments) ? task.attachments : [];
179
+ const filePaths = attachments
180
+ .map(f => (f && typeof f.path === 'string') ? `"${f.path.replace(/"/g, '')}"` : '')
181
+ .filter(Boolean)
182
+ .join(' ');
183
+ const userInput = filePaths ? (raw ? `${filePaths} ${raw}` : filePaths) : raw;
184
+
185
+ const template = typeof task?.template === 'string' ? task.template : 'none';
186
+ if (template.startsWith('custom:')) {
187
+ // The snapshot rides with the task so later edits/deletions of the custom
188
+ // expert do not change what fires. A missing/empty snapshot degrades to the
189
+ // raw input rather than silently dropping the task.
190
+ const wrapped = buildCustomTemplate(task.templateContent);
191
+ if (!wrapped) return userInput;
192
+ return `${wrapped}\n\n${userInput}`.trim();
193
+ }
194
+ if (template === 'codeExpert' || template === 'researchExpert') {
195
+ return buildLocalUltraplan(userInput, template);
196
+ }
197
+ // 'none' or anything unknown: verbatim.
198
+ return userInput;
199
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cc-viewer",
3
- "version": "1.9.22",
3
+ "version": "1.9.24",
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
@@ -841,6 +841,7 @@ const i18nData = {
841
841
  "server.dingtalk.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
842
842
  "server.dingtalk.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
843
843
  "server.dingtalk.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
844
+ "server.dingtalk.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
844
845
  "server.feishu.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
845
846
  "server.feishu.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
846
847
  "server.feishu.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -855,6 +856,7 @@ const i18nData = {
855
856
  "server.feishu.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
856
857
  "server.feishu.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
857
858
  "server.feishu.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
859
+ "server.feishu.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
858
860
  "server.wecom.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
859
861
  "server.wecom.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
860
862
  "server.wecom.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -869,6 +871,7 @@ const i18nData = {
869
871
  "server.wecom.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
870
872
  "server.wecom.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
871
873
  "server.wecom.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
874
+ "server.wecom.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
872
875
  "server.discord.replyChunkTitle": { "zh": "Claude", "en": "Claude" },
873
876
  "server.discord.truncated": { "zh": "(回复过长已截断,完整内容请见 Web 界面)", "en": "(reply truncated — see the web UI for the full content)" },
874
877
  "server.discord.noTextReply": { "zh": "(本轮无文本回复)", "en": "(no text reply this turn)" },
@@ -883,6 +886,7 @@ const i18nData = {
883
886
  "server.discord.queueFull": { "zh": "消息队列已满({max}),已丢弃该消息,请稍后再发。", "en": "Message queue is full ({max}); this message was dropped. Try again later." },
884
887
  "server.discord.ackProcessing": { "zh": "收到,正在思考…", "en": "Got it, thinking…" },
885
888
  "server.discord.ackTimeout": { "zh": "处理超时,请重试。", "en": "Processing timed out, please try again." },
889
+ "server.discord.startupError": { "zh": "Claude 启动未完成(目录信任待处理),请检查配置后重试。", "en": "Claude startup incomplete (directory trust pending) — check configuration and retry." },
886
890
  "update.updating": {
887
891
  "zh": "正在更新到 v{version}...",
888
892
  "en": "Updating to v{version}...",
@@ -1163,26 +1167,6 @@ const i18nData = {
1163
1167
  "tr": "Mevcut günlüğü indir",
1164
1168
  "uk": "Завантажити поточний лог"
1165
1169
  },
1166
- "ui.exportPrompts": {
1167
- "zh": "查看用户 Prompt",
1168
- "en": "Export user prompts",
1169
- "zh-TW": "匯出用戶 Prompt",
1170
- "ko": "사용자 Prompt 내보내기",
1171
- "ja": "ユーザー Prompt をエクスポート",
1172
- "de": "Benutzer-Prompts exportieren",
1173
- "es": "Exportar prompts de usuario",
1174
- "fr": "Exporter les prompts utilisateur",
1175
- "it": "Esporta prompt utente",
1176
- "da": "Eksportér bruger-prompts",
1177
- "pl": "Eksportuj prompty użytkownika",
1178
- "ru": "Экспорт пользовательских Prompt",
1179
- "ar": "تصدير Prompt المستخدم",
1180
- "no": "Eksporter bruker-prompts",
1181
- "pt-BR": "Exportar prompts do usuário",
1182
- "th": "ส่งออก Prompt ผู้ใช้",
1183
- "tr": "Kullanıcı Prompt'larını dışa aktar",
1184
- "uk": "Експорт Prompt користувача"
1185
- },
1186
1170
  "ui.exportPromptsTxt": {
1187
1171
  "zh": "导出到本地 .txt",
1188
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
+ }