cc-viewer 1.9.24 → 1.9.26
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.
- package/README.md +1 -1
- package/cli.js +14 -0
- package/dist/assets/App-CjP88gbM.css +1 -0
- package/dist/assets/App-CkbwkH74.js +2 -0
- package/dist/assets/ArchivePreview-1XAr8LvB.js +1 -0
- package/dist/assets/AudioPreview-7zCADwCz.css +1 -0
- package/dist/assets/AudioPreview-DGcbrJjl.js +1 -0
- package/dist/assets/{MdxEditorPanel-CT6w8hjl.js → MdxEditorPanel-DFGSL5OM.js} +1 -1
- package/dist/assets/Mobile-DFu8Kn5W.js +1 -0
- package/dist/assets/ProxyStatsModal-BU9liIIO.js +1 -0
- package/dist/assets/SubtitlePreview-BGW9y2LI.css +1 -0
- package/dist/assets/SubtitlePreview-Ca_dpMFL.js +1 -0
- package/dist/assets/{_baseUniq-BGBEhBne.js → _baseUniq-9PjtCZvX.js} +1 -1
- package/dist/assets/{arc-4pbWOEmh.js → arc-C7i0W-3s.js} +1 -1
- package/dist/assets/{architectureDiagram-Q4EWVU46-BHZPDnby.js → architectureDiagram-Q4EWVU46-B0-9CMiF.js} +1 -1
- package/dist/assets/{blockDiagram-DXYQGD6D-DszLU7Pg.js → blockDiagram-DXYQGD6D-v3Zg9ooQ.js} +1 -1
- package/dist/assets/{c4Diagram-AHTNJAMY-DbDJNYxl.js → c4Diagram-AHTNJAMY-BngN_7qF.js} +1 -1
- package/dist/assets/{channel-BpIsxDHj.js → channel-IbZhDvnM.js} +1 -1
- package/dist/assets/{chunk-4BX2VUAB-ChcBwBh2.js → chunk-4BX2VUAB-8cHviTVA.js} +1 -1
- package/dist/assets/{chunk-4TB4RGXK-DzBEAck_.js → chunk-4TB4RGXK-C3CP4doN.js} +1 -1
- package/dist/assets/{chunk-55IACEB6-9UDvmw07.js → chunk-55IACEB6-FUVA-xfN.js} +1 -1
- package/dist/assets/{chunk-EDXVE4YY-DHEU2DKg.js → chunk-EDXVE4YY-BL4ddY7-.js} +1 -1
- package/dist/assets/{chunk-FMBD7UC4-sysT0Sy2.js → chunk-FMBD7UC4-fgqPq6Tx.js} +1 -1
- package/dist/assets/{chunk-OYMX7WX6-DLXt2vYo.js → chunk-OYMX7WX6-BGnPcd9h.js} +1 -1
- package/dist/assets/{chunk-QZHKN3VN-CDIkC7QK.js → chunk-QZHKN3VN-Cs6WjmqO.js} +1 -1
- package/dist/assets/{chunk-YZCP3GAM-D9b_INz7.js → chunk-YZCP3GAM-qq4Q4j7H.js} +1 -1
- package/dist/assets/classDiagram-6PBFFD2Q-Bszndikj.js +1 -0
- package/dist/assets/classDiagram-v2-HSJHXN6E-Bszndikj.js +1 -0
- package/dist/assets/clone-MC_fW61A.js +1 -0
- package/dist/assets/{cose-bilkent-S5V4N54A-DJQwV_Dp.js → cose-bilkent-S5V4N54A-D-uK3RSk.js} +1 -1
- package/dist/assets/{dagre-KV5264BT-bl9Pq21t.js → dagre-KV5264BT-BulmeCnQ.js} +1 -1
- package/dist/assets/{diagram-5BDNPKRD-BA8CJxzI.js → diagram-5BDNPKRD-DI7Q04yx.js} +1 -1
- package/dist/assets/{diagram-G4DWMVQ6-DzSQULuz.js → diagram-G4DWMVQ6-B7zYIZac.js} +1 -1
- package/dist/assets/{diagram-MMDJMWI5-DhfHWnT4.js → diagram-MMDJMWI5-D_f5k-GJ.js} +1 -1
- package/dist/assets/{diagram-TYMM5635-BbAoFfGS.js → diagram-TYMM5635-DQ-vW7nJ.js} +1 -1
- package/dist/assets/{erDiagram-SMLLAGMA-CMjA2eBk.js → erDiagram-SMLLAGMA-BgubHrDi.js} +1 -1
- package/dist/assets/{flowDiagram-DWJPFMVM-bOubqgJ6.js → flowDiagram-DWJPFMVM-fPYA9wmX.js} +1 -1
- package/dist/assets/{ganttDiagram-T4ZO3ILL-BUIu7WwI.js → ganttDiagram-T4ZO3ILL-hNsatnIF.js} +1 -1
- package/dist/assets/{gitGraphDiagram-UUTBAWPF-B_vrztDU.js → gitGraphDiagram-UUTBAWPF-1GijxkLh.js} +1 -1
- package/dist/assets/{graph-BR3YGx52.js → graph-sNq_HPra.js} +1 -1
- package/dist/assets/{index-BMpUfdYI.js → index-BnWh6jkG.js} +1 -1
- package/dist/assets/{index-DtZAmvwJ.js → index-CmwhODrM.js} +1 -1
- package/dist/assets/{index-B88yR2TU.js → index-D6mBgqj7.js} +1 -1
- package/dist/assets/{index-mvm_Pxcf.js → index-DggrqRzx.js} +1 -1
- package/dist/assets/{index-BQx5MOpr.js → index-DiVw76Ih.js} +1 -1
- package/dist/assets/index-Dn7twftJ.js +2 -0
- package/dist/assets/{index-DwMyfQJq.js → index-ijWns1Ex.js} +1 -1
- package/dist/assets/{index-ClTuiPoz.js → index-ng96S3Hy.js} +1 -1
- package/dist/assets/{infoDiagram-42DDH7IO-Co9Db2ir.js → infoDiagram-42DDH7IO-C9HYi6HU.js} +1 -1
- package/dist/assets/{ishikawaDiagram-UXIWVN3A-4z7EydCd.js → ishikawaDiagram-UXIWVN3A-D3Ae6xRc.js} +1 -1
- package/dist/assets/{journeyDiagram-VCZTEJTY-CtLfbhYE.js → journeyDiagram-VCZTEJTY-BMPDBa6W.js} +1 -1
- package/dist/assets/{jszip.min-DtbrAiWv.js → jszip.min-D6JfNfcl.js} +1 -1
- package/dist/assets/{kanban-definition-6JOO6SKY-9ZrhOvdX.js → kanban-definition-6JOO6SKY-BXEtzhr-.js} +1 -1
- package/dist/assets/{layout-Ddo06NJO.js → layout-CbMMhBh2.js} +1 -1
- package/dist/assets/{linear-BZUsBSwS.js → linear-DivVFiS7.js} +1 -1
- package/dist/assets/{mermaid.core-O-x0KuTp.js → mermaid.core-Dq-d8oPN.js} +2 -2
- package/dist/assets/{min-PzJh19JL.js → min-CXI1r_lz.js} +1 -1
- package/dist/assets/{mindmap-definition-QFDTVHPH-C3MVo-7p.js → mindmap-definition-QFDTVHPH-CONBMUxc.js} +1 -1
- package/dist/assets/{pieDiagram-DEJITSTG-CMn9-kQc.js → pieDiagram-DEJITSTG-C0rsPXdi.js} +1 -1
- package/dist/assets/{quadrantDiagram-34T5L4WZ-9eyqTdkj.js → quadrantDiagram-34T5L4WZ-DA2PNu4u.js} +1 -1
- package/dist/assets/{requirementDiagram-MS252O5E-BJbuDOpR.js → requirementDiagram-MS252O5E-DjsBvm40.js} +1 -1
- package/dist/assets/{sankeyDiagram-XADWPNL6-CzQ1KxD3.js → sankeyDiagram-XADWPNL6-Drl_Kmzt.js} +1 -1
- package/dist/assets/{seqResourceLoaders-DH-Nl0yh.css → seqResourceLoaders-CjAnOisT.css} +1 -1
- package/dist/assets/seqResourceLoaders-L-Fzax-z.js +2 -0
- package/dist/assets/{sequenceDiagram-FGHM5R23-CfmSEAYp.js → sequenceDiagram-FGHM5R23-Dcz5NXKY.js} +1 -1
- package/dist/assets/{stateDiagram-FHFEXIEX-Brw2ZXQC.js → stateDiagram-FHFEXIEX-7P3czdgX.js} +1 -1
- package/dist/assets/{stateDiagram-v2-QKLJ7IA2-Dnyo23Rp.js → stateDiagram-v2-QKLJ7IA2-C3xgfAOE.js} +1 -1
- package/dist/assets/{timeline-definition-GMOUNBTQ-DNi7GnlG.js → timeline-definition-GMOUNBTQ-BVe-eF-9.js} +1 -1
- package/dist/assets/util-DUb-88OI.js +1 -0
- package/dist/assets/{vendor-antd-DWLgSkPo.js → vendor-antd-VJVAjRBJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-CKsm_iG4.js → vendor-codemirror-D2yaEhu3.js} +1 -1
- package/dist/assets/{vendor-mdxeditor-Dah6NK0y.js → vendor-mdxeditor-DKI8QSRd.js} +2 -2
- package/dist/assets/{vendor-qrcode-CDcb8weP.js → vendor-qrcode-CDB9Y_Vp.js} +1 -1
- package/dist/assets/{vendor-virtuoso-DKUobZpA.js → vendor-virtuoso-DEFa9UCG.js} +1 -1
- package/dist/assets/{vennDiagram-DHZGUBPP-Cdkdx7gB.js → vennDiagram-DHZGUBPP-C8KL2OR8.js} +1 -1
- package/dist/assets/{wardley-RL74JXVD-YKzsVN4U.js → wardley-RL74JXVD-Dm4mxyoW.js} +1 -1
- package/dist/assets/{wardleyDiagram-NUSXRM2D-gBsb6aut.js → wardleyDiagram-NUSXRM2D-BoA34gDh.js} +1 -1
- package/dist/assets/{xychartDiagram-5P7HB3ND-Bh63NWof.js → xychartDiagram-5P7HB3ND-66ynIBzj.js} +1 -1
- package/dist/index.html +4 -4
- package/package.json +1 -1
- package/server/lib/approval-policy.js +5 -2
- package/server/lib/ask/perm-bridge.js +4 -0
- package/server/lib/ask/perm-request-bridge.js +1 -1
- package/server/lib/audio-stream.js +267 -0
- package/server/lib/auto-approve.js +26 -5
- package/server/lib/restart-helper.js +65 -0
- package/server/lib/restart.js +83 -0
- package/server/lib/sdk-manager.js +19 -10
- package/server/lib/terminal-ws-ping.js +42 -0
- package/server/lib/update-instances.js +42 -0
- package/server/lib/update-job.js +260 -0
- package/server/lib/updater.js +37 -220
- package/server/proxy.js +16 -9
- package/server/pty-manager.js +1 -0
- package/server/routes/ask-perm.js +17 -13
- package/server/routes/files-content.js +65 -0
- package/server/routes/project-meta.js +11 -7
- package/server/routes/update.js +58 -0
- package/server/server.js +67 -11
- package/dist/assets/App-BwRRqrP5.css +0 -1
- package/dist/assets/App-Cfmm41z0.js +0 -2
- package/dist/assets/ArchivePreview-dKWXN9Zp.js +0 -1
- package/dist/assets/Mobile-noWViQpL.js +0 -1
- package/dist/assets/ProxyStatsModal-BeCRPqaC.js +0 -1
- package/dist/assets/classDiagram-6PBFFD2Q-4Lh0SB4X.js +0 -1
- package/dist/assets/classDiagram-v2-HSJHXN6E-4Lh0SB4X.js +0 -1
- package/dist/assets/clone-cWiXtXrO.js +0 -1
- package/dist/assets/index-Ca3a2tOc.js +0 -2
- package/dist/assets/seqResourceLoaders-DeqzMajS.js +0 -2
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Audio Stream — dedicated streaming response module for audio preview.
|
|
3
|
+
*
|
|
4
|
+
* Backs /api/audio-stream with single-range HTTP Range support. Unlike fileRaw
|
|
5
|
+
* (full buffer, 10MB cap), this streams via createReadStream and supports
|
|
6
|
+
* 206/416/304/If-Range, satisfying Safari/WebKit's byte-range requirement (it
|
|
7
|
+
* probes with `Range: bytes=0-1`).
|
|
8
|
+
*
|
|
9
|
+
* Design boundaries:
|
|
10
|
+
* - The sniffer only ever overrides to an audio/* MIME, never video/* (the ftyp
|
|
11
|
+
* brand cannot reliably tell audio m4a from video mp4); the extension MIME is
|
|
12
|
+
* the fallback.
|
|
13
|
+
* - parseByteRange supports suffix ranges and clamping, per RFC 9110 §14.
|
|
14
|
+
* - serveAudioStream wraps everything in a top-level try/catch with a
|
|
15
|
+
* res.headersSent guard so no sync fs error becomes an unhandled rejection
|
|
16
|
+
* that kills the process (see server.js:985).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { openSync, readSync, closeSync, createReadStream } from 'node:fs';
|
|
20
|
+
import { reportSwallowed } from './error-report.js';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Extension → audio/* MIME. `.opus` is an Ogg container (RFC 7845 §9); `.m4a`
|
|
24
|
+
* uses audio/mp4 (RFC 4337); `.flac` uses audio/flac (RFC 9639).
|
|
25
|
+
*/
|
|
26
|
+
const AUDIO_MIME = {
|
|
27
|
+
'.mp3': 'audio/mpeg',
|
|
28
|
+
'.wav': 'audio/wav',
|
|
29
|
+
'.ogg': 'audio/ogg',
|
|
30
|
+
'.oga': 'audio/ogg',
|
|
31
|
+
'.opus': 'audio/ogg',
|
|
32
|
+
'.m4a': 'audio/mp4',
|
|
33
|
+
'.aac': 'audio/aac',
|
|
34
|
+
'.flac': 'audio/flac',
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Supported audio extensions (lowercase, leading dot). */
|
|
38
|
+
const AUDIO_EXTENSIONS = new Set(Object.keys(AUDIO_MIME));
|
|
39
|
+
|
|
40
|
+
/** How many head bytes readHead reads; large enough to span a typical ID3v2 tag. */
|
|
41
|
+
const SNIFF_BYTES = 4096;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Derive the lowercased extension from a real file path, cross-platform
|
|
45
|
+
* (basename via split(/[\\/]/), last dot).
|
|
46
|
+
* @param {string} filePath
|
|
47
|
+
* @returns {string} lowercase extension with leading dot, or ''
|
|
48
|
+
*/
|
|
49
|
+
function audioExtOf(filePath) {
|
|
50
|
+
const base = String(filePath || '').split(/[\\/]/).pop() || '';
|
|
51
|
+
const dot = base.lastIndexOf('.');
|
|
52
|
+
return dot > 0 ? base.slice(dot).toLowerCase() : '';
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Read the first SNIFF_BYTES for container sniffing. Uses
|
|
57
|
+
* openSync/readSync/finally closeSync and never readFileSync (a multi-GB audio
|
|
58
|
+
* file would blow up memory). Short reads / failures are non-fatal.
|
|
59
|
+
* @param {string} filePath
|
|
60
|
+
* @param {number} [size] file size (avoids over-reading a small file)
|
|
61
|
+
* @returns {Buffer|null} first N bytes, or null on failure
|
|
62
|
+
*/
|
|
63
|
+
function readHead(filePath, size) {
|
|
64
|
+
let fd;
|
|
65
|
+
try {
|
|
66
|
+
fd = openSync(filePath, 'r');
|
|
67
|
+
const len = Math.min(SNIFF_BYTES, typeof size === 'number' && size >= 0 ? size : SNIFF_BYTES);
|
|
68
|
+
if (len <= 0) return null;
|
|
69
|
+
const buf = Buffer.alloc(len);
|
|
70
|
+
const n = readSync(fd, buf, 0, len, 0);
|
|
71
|
+
return n > 0 ? buf.subarray(0, n) : null;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
reportSwallowed('audioStream.readHead', err);
|
|
74
|
+
return null;
|
|
75
|
+
} finally {
|
|
76
|
+
if (fd !== undefined) {
|
|
77
|
+
try { closeSync(fd); } catch (err) { reportSwallowed('audioStream.closeHead', err); }
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Sniff the real audio MIME from magic bytes; only ever returns audio/*, never
|
|
84
|
+
* video/*. Order: ADTS before the generic MP3 frame sync (both use a 0xFF sync,
|
|
85
|
+
* and ID3 can also prefix ADTS).
|
|
86
|
+
* @param {Buffer|null} buf head bytes
|
|
87
|
+
* @param {string} ext lowercase extension with leading dot (fallback)
|
|
88
|
+
* @returns {string} an audio/* MIME
|
|
89
|
+
*/
|
|
90
|
+
function sniffAudioMime(buf, ext) {
|
|
91
|
+
const fallback = AUDIO_MIME[ext] || 'application/octet-stream';
|
|
92
|
+
if (!buf || buf.length < 2) return fallback;
|
|
93
|
+
|
|
94
|
+
// Ogg container: OggS; the first packet (~offset 28) distinguishes
|
|
95
|
+
// Opus/Vorbis/FLAC, but all already map to audio/ogg.
|
|
96
|
+
if (buf.length >= 4 && buf[0] === 0x4f && buf[1] === 0x67 && buf[2] === 0x67 && buf[3] === 0x53) {
|
|
97
|
+
return 'audio/ogg';
|
|
98
|
+
}
|
|
99
|
+
// Native FLAC: fLaC.
|
|
100
|
+
if (buf.length >= 4 && buf[0] === 0x66 && buf[1] === 0x4c && buf[2] === 0x61 && buf[3] === 0x43) {
|
|
101
|
+
return 'audio/flac';
|
|
102
|
+
}
|
|
103
|
+
// WAV: RIFF....WAVE.
|
|
104
|
+
if (buf.length >= 12 &&
|
|
105
|
+
buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 &&
|
|
106
|
+
buf[8] === 0x57 && buf[9] === 0x41 && buf[10] === 0x56 && buf[11] === 0x45) {
|
|
107
|
+
return 'audio/wav';
|
|
108
|
+
}
|
|
109
|
+
// MP4/M4A: ftyp at offset 4; the brand cannot reliably split audio from video,
|
|
110
|
+
// so this audio-only route always serves audio/mp4.
|
|
111
|
+
if (buf.length >= 8 && buf[4] === 0x66 && buf[5] === 0x74 && buf[6] === 0x79 && buf[7] === 0x70) {
|
|
112
|
+
return 'audio/mp4';
|
|
113
|
+
}
|
|
114
|
+
// ID3v2 tag: may prefix MP3 or ADTS AAC, so look past the tag for the frame sync.
|
|
115
|
+
if (buf.length >= 3 && buf[0] === 0x49 && buf[1] === 0x44 && buf[2] === 0x33) {
|
|
116
|
+
// ID3v2 size is syncsafe at offset 6-9; skip the tag to find the frame.
|
|
117
|
+
if (buf.length >= 10) {
|
|
118
|
+
const tagSize = ((buf[6] & 0x7f) << 21) | ((buf[7] & 0x7f) << 14) | ((buf[8] & 0x7f) << 7) | (buf[9] & 0x7f);
|
|
119
|
+
const frameAt = 10 + tagSize;
|
|
120
|
+
if (frameAt + 1 < buf.length) {
|
|
121
|
+
const b0 = buf[frameAt]; const b1 = buf[frameAt + 1];
|
|
122
|
+
if (b0 === 0xff && (b1 & 0xf6) === 0xf0) return 'audio/aac'; // ADTS (MPEG-2/4)
|
|
123
|
+
if (b0 === 0xff && (b1 & 0xe0) === 0xe0 && (b1 & 0x06) !== 0) return 'audio/mpeg'; // MP3, layer bits≠00
|
|
124
|
+
return 'audio/mpeg'; // ID3 with a non-ADTS frame defaults to MP3
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
// Tag larger than the sniff window: trust the extension rather than guess.
|
|
128
|
+
return fallback;
|
|
129
|
+
}
|
|
130
|
+
// ADTS AAC: FF F1/F9 (MPEG-4) or FF F0/F8 (MPEG-2), 12-bit sync, layer bits 00.
|
|
131
|
+
if (buf[0] === 0xff && (buf[1] & 0xf6) === 0xf0) {
|
|
132
|
+
return 'audio/aac';
|
|
133
|
+
}
|
|
134
|
+
// Bare MP3 frame: FF Ex/Fx with layer bits≠00.
|
|
135
|
+
if (buf[0] === 0xff && (buf[1] & 0xe0) === 0xe0 && (buf[1] & 0x06) !== 0) {
|
|
136
|
+
return 'audio/mpeg';
|
|
137
|
+
}
|
|
138
|
+
return fallback;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Parse a single-range Range header. Multi-range / malformed returns null (the
|
|
143
|
+
* caller ignores it and serves 200).
|
|
144
|
+
* @param {string|undefined} header Range header value
|
|
145
|
+
* @param {number} size total file bytes
|
|
146
|
+
* @returns {{start:number,end:number}|'unsatisfiable'|null}
|
|
147
|
+
*/
|
|
148
|
+
function parseByteRange(header, size) {
|
|
149
|
+
if (!header || typeof header !== 'string') return null;
|
|
150
|
+
if (!Number.isSafeInteger(size) || size <= 0) return 'unsatisfiable'; // any range on an empty file is 416
|
|
151
|
+
const m = /^bytes=(\d*)-(\d*)$/i.exec(header.trim());
|
|
152
|
+
if (!m || (m[1] === '' && m[2] === '')) return null; // malformed / multi-range → ignore (200)
|
|
153
|
+
|
|
154
|
+
if (m[1] === '') {
|
|
155
|
+
// Suffix: bytes=-N
|
|
156
|
+
const n = Number(m[2]);
|
|
157
|
+
if (!Number.isSafeInteger(n) || n <= 0) return 'unsatisfiable';
|
|
158
|
+
return { start: Math.max(0, size - n), end: size - 1 };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const start = Number(m[1]);
|
|
162
|
+
if (!Number.isSafeInteger(start) || start >= size) return 'unsatisfiable';
|
|
163
|
+
const end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1);
|
|
164
|
+
if (!Number.isSafeInteger(end) || end < start) return null; // invalid → ignore (200)
|
|
165
|
+
return { start, end };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Stream an audio response. Order: 304 (If-None-Match) → If-Range →
|
|
170
|
+
* Range (206) / 200. HEAD ignores Range and returns 200 headers only (and also
|
|
171
|
+
* sniffs, so its Content-Type matches GET).
|
|
172
|
+
* @param {import('node:http').IncomingMessage} req
|
|
173
|
+
* @param {import('node:http').ServerResponse} res
|
|
174
|
+
* @param {{filePath:string, stat:import('node:fs').Stats, ext:string}} ctx
|
|
175
|
+
*/
|
|
176
|
+
function serveAudioStream(req, res, ctx) {
|
|
177
|
+
const { filePath, stat, ext } = ctx;
|
|
178
|
+
const size = stat.size;
|
|
179
|
+
const name = String(filePath || '').split(/[\\/]/).pop() || 'audio';
|
|
180
|
+
const etag = `"${size.toString(16)}-${Math.floor(stat.mtimeMs).toString(16)}"`;
|
|
181
|
+
|
|
182
|
+
// 304 takes priority over Range and needs no body or sniffed Content-Type.
|
|
183
|
+
if (req.headers['if-none-match'] && req.headers['if-none-match'] === etag) {
|
|
184
|
+
res.writeHead(304, { 'Cache-Control': 'private', 'ETag': etag });
|
|
185
|
+
res.end();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const base = {
|
|
190
|
+
'Content-Type': sniffAudioMime(readHead(filePath, size), ext),
|
|
191
|
+
'Accept-Ranges': 'bytes',
|
|
192
|
+
'Cache-Control': 'private',
|
|
193
|
+
'ETag': etag,
|
|
194
|
+
'Content-Disposition': `inline; filename*=UTF-8''${encodeURIComponent(name)}`,
|
|
195
|
+
'X-Content-Type-Options': 'nosniff',
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
// HEAD: no stream, 200 headers (Range is GET-only and ignored).
|
|
199
|
+
if (req.method === 'HEAD') {
|
|
200
|
+
res.writeHead(200, { ...base, 'Content-Length': size });
|
|
201
|
+
res.end();
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Empty file: serve a clean 200 with Content-Length 0; a 0-length
|
|
206
|
+
// createReadStream range (end=-1) would throw after headers are sent.
|
|
207
|
+
if (size === 0) {
|
|
208
|
+
res.writeHead(200, { ...base, 'Content-Length': 0 });
|
|
209
|
+
res.end();
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// If-Range: only an exact strong-ETag match continues with Range, else ignore it → 200.
|
|
214
|
+
const ifRange = req.headers['if-range'];
|
|
215
|
+
const rangeOk = !ifRange || ifRange === etag;
|
|
216
|
+
const range = rangeOk ? parseByteRange(req.headers.range, size) : null;
|
|
217
|
+
|
|
218
|
+
// 416: valid-but-unsatisfiable.
|
|
219
|
+
if (range === 'unsatisfiable') {
|
|
220
|
+
res.writeHead(416, {
|
|
221
|
+
'Content-Range': `bytes */${size}`,
|
|
222
|
+
'Content-Length': 0,
|
|
223
|
+
'Accept-Ranges': 'bytes',
|
|
224
|
+
});
|
|
225
|
+
res.end();
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
let status; let headers; let start; let end;
|
|
230
|
+
if (range) {
|
|
231
|
+
// 206: must carry Content-Range (Safari seek depends on it).
|
|
232
|
+
({ start, end } = range);
|
|
233
|
+
status = 206;
|
|
234
|
+
headers = {
|
|
235
|
+
...base,
|
|
236
|
+
'Content-Range': `bytes ${start}-${end}/${size}`,
|
|
237
|
+
'Content-Length': end - start + 1,
|
|
238
|
+
};
|
|
239
|
+
} else {
|
|
240
|
+
// 200: never carries Content-Range; the explicit end bound prevents a file
|
|
241
|
+
// that grows mid-request from exceeding Content-Length.
|
|
242
|
+
start = 0; end = size - 1;
|
|
243
|
+
status = 200;
|
|
244
|
+
headers = { ...base, 'Content-Length': size };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
res.writeHead(status, headers);
|
|
248
|
+
const stream = createReadStream(filePath, { start, end });
|
|
249
|
+
// Headers are already sent by the time a read error can fire, so we can only
|
|
250
|
+
// abort the response mid-stream; report it for diagnosis.
|
|
251
|
+
stream.on('error', (err) => { reportSwallowed('audioStream.stream', err); res.destroy(); });
|
|
252
|
+
// Stop reading from disk if the client aborts (e.g. skips the preview).
|
|
253
|
+
res.on('close', () => { stream.destroy(); });
|
|
254
|
+
// If the socket was already destroyed before these listeners attached, the
|
|
255
|
+
// 'close' event already fired and never will again — destroy the stream now.
|
|
256
|
+
if (res.destroyed) { stream.destroy(); return; }
|
|
257
|
+
stream.pipe(res);
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export {
|
|
261
|
+
AUDIO_MIME,
|
|
262
|
+
AUDIO_EXTENSIONS,
|
|
263
|
+
audioExtOf,
|
|
264
|
+
sniffAudioMime,
|
|
265
|
+
parseByteRange,
|
|
266
|
+
serveAudioStream,
|
|
267
|
+
};
|
|
@@ -18,7 +18,10 @@
|
|
|
18
18
|
// Semantics of the settings (shared with the client):
|
|
19
19
|
// plan: prefs.approvalModal.planAutoApproveSeconds (default 0 = off)
|
|
20
20
|
// perm: prefs.autoApproveSeconds (default 3 when unset)
|
|
21
|
-
// 0/off, N>0 = N seconds, -1 = instant (resolve immediately, no buffer)
|
|
21
|
+
// 0/off, N>0 = N seconds, -1 = instant (resolve immediately, no buffer),
|
|
22
|
+
// -2 = full auto-approve (完全免审批): instant like -1, and the npm-publish
|
|
23
|
+
// hard gate (approval-policy.js isPublishCommand) is lifted — perm only;
|
|
24
|
+
// a hand-edited plan -2 is treated as off.
|
|
22
25
|
// AskUserQuestion hosting ("问答题自动托管") is a separate feature with minute
|
|
23
26
|
// semantics and lives in ./ask-auto-answer.js — it is not routed through this module
|
|
24
27
|
// (the 300s cap would silently disable its 10/20/30-minute tiers).
|
|
@@ -30,6 +33,10 @@ import { reportSwallowed } from './error-report.js';
|
|
|
30
33
|
export const AUTO_APPROVE_BUFFER_MS = 1000;
|
|
31
34
|
export const DEFAULT_PERM_AUTO_APPROVE_SECONDS = 3;
|
|
32
35
|
export const AUTO_APPROVE_INSTANT = -1;
|
|
36
|
+
// 完全免审批 (full auto-approve): instant like -1, and additionally lifts the
|
|
37
|
+
// npm-publish hard gate (approval-policy.js isPublishCommand). Deliberately
|
|
38
|
+
// permission-only — a hand-edited planAutoApproveSeconds: -2 is treated as off.
|
|
39
|
+
export const AUTO_APPROVE_FULL = -2;
|
|
33
40
|
// A hand-edited preferences.json can hold an absurdly large value. Besides being
|
|
34
41
|
// pointless, a value above the 5-minute hard approval timeout would advertise an
|
|
35
42
|
// autoApproveAt the deny timeout always beats (a lying countdown); and beyond
|
|
@@ -39,8 +46,8 @@ export const MAX_AUTO_APPROVE_SECONDS = 300;
|
|
|
39
46
|
|
|
40
47
|
/**
|
|
41
48
|
* Extract the configured seconds for a kind ('plan' | 'perm') from an effective
|
|
42
|
-
* prefs object. Returns null when disabled (0 / invalid / negative other than
|
|
43
|
-
* absurdly large).
|
|
49
|
+
* prefs object. Returns null when disabled (0 / invalid / negative other than
|
|
50
|
+
* -1 (and -2 for perm) / absurdly large).
|
|
44
51
|
*/
|
|
45
52
|
export function effectiveAutoApproveSeconds(kind, prefs) {
|
|
46
53
|
const raw = kind === 'plan'
|
|
@@ -49,11 +56,25 @@ export function effectiveAutoApproveSeconds(kind, prefs) {
|
|
|
49
56
|
const seconds = Number(raw);
|
|
50
57
|
if (!Number.isFinite(seconds)) return null;
|
|
51
58
|
if (seconds === AUTO_APPROVE_INSTANT) return AUTO_APPROVE_INSTANT;
|
|
59
|
+
if (kind === 'perm' && seconds === AUTO_APPROVE_FULL) return AUTO_APPROVE_FULL;
|
|
52
60
|
if (seconds <= 0) return null;
|
|
53
61
|
if (seconds > MAX_AUTO_APPROVE_SECONDS) return null;
|
|
54
62
|
return seconds;
|
|
55
63
|
}
|
|
56
64
|
|
|
65
|
+
/**
|
|
66
|
+
* Whether a raw prefs value opts into automatic approval at all (instant tiers
|
|
67
|
+
* -1/-2, or a positive countdown). Used where only the opt-in matters, not the
|
|
68
|
+
* tier: the Read/Glob/Grep outside-cwd directory-grant paths and the
|
|
69
|
+
* PermissionRequest hook's silent-allow decision. Number()-normalizes so a
|
|
70
|
+
* hand-edited string value ("-1") keeps working like before.
|
|
71
|
+
*/
|
|
72
|
+
export function isAutoApproveEnabledValue(raw) {
|
|
73
|
+
const seconds = Number(raw);
|
|
74
|
+
if (!Number.isFinite(seconds)) return false;
|
|
75
|
+
return seconds === AUTO_APPROVE_INSTANT || seconds === AUTO_APPROVE_FULL || seconds > 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
57
78
|
/**
|
|
58
79
|
* Read prefs (project-fork aware) and compute the auto-approve deadline for a
|
|
59
80
|
* pending approval. `projectKey` is the session cwd (SDK) or hook-reported cwd
|
|
@@ -75,7 +96,7 @@ export function computeAutoApprove(kind, projectKey, { now = Date.now(), readPre
|
|
|
75
96
|
const effective = hasFork(prefs, key) ? resolveScoped(prefs, prefs.prefsByProject[key]) : prefs;
|
|
76
97
|
const seconds = effectiveAutoApproveSeconds(kind, effective);
|
|
77
98
|
if (seconds === null) return { enabled: false };
|
|
78
|
-
const instant = seconds === AUTO_APPROVE_INSTANT;
|
|
99
|
+
const instant = seconds === AUTO_APPROVE_INSTANT || seconds === AUTO_APPROVE_FULL;
|
|
79
100
|
return {
|
|
80
101
|
enabled: true,
|
|
81
102
|
instant,
|
|
@@ -99,7 +120,7 @@ export function autoApproveFireDelayMs(computed, now = Date.now()) {
|
|
|
99
120
|
* pending entry: { autoApproveAt, seconds, cancelled, timer }.
|
|
100
121
|
* `onFire` is invoked once when the deadline (+buffer) passes; callers must
|
|
101
122
|
* re-check the entry is still pending and not cancelled inside onFire.
|
|
102
|
-
* Instant (-1) fires SYNCHRONOUSLY — the caller MUST register the pending entry
|
|
123
|
+
* Instant (-1/-2) fires SYNCHRONOUSLY — the caller MUST register the pending entry
|
|
103
124
|
* (and emit the pending frame) before calling this.
|
|
104
125
|
*/
|
|
105
126
|
export function createAutoApproveState(computed, onFire) {
|
|
@@ -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
|
+
}
|
|
@@ -42,6 +42,8 @@ import {
|
|
|
42
42
|
createAutoApproveState,
|
|
43
43
|
cancelAutoApproveState,
|
|
44
44
|
replayAutoApproveFields,
|
|
45
|
+
isAutoApproveEnabledValue,
|
|
46
|
+
AUTO_APPROVE_FULL,
|
|
45
47
|
} from './auto-approve.js';
|
|
46
48
|
import {
|
|
47
49
|
computeAskAutoAnswer,
|
|
@@ -939,7 +941,8 @@ function _createSession(key, cwd) {
|
|
|
939
941
|
// canUseTool is mounted in EVERY mode (including bypassPermissions) so the
|
|
940
942
|
// npm-publish hard gate survives --d, mirroring perm-bridge.js's bypass
|
|
941
943
|
// exemption. In bypass mode the callback early-allows everything except
|
|
942
|
-
// publish commands and the two interactive tools (see _handleCanUseTool)
|
|
944
|
+
// publish commands and the two interactive tools (see _handleCanUseTool);
|
|
945
|
+
// the only publish exemption is the explicit full auto-approve tier (-2).
|
|
943
946
|
canUseTool: _handleCanUseTool,
|
|
944
947
|
..._permissionMode === 'bypassPermissions' && { allowDangerouslySkipPermissions: true },
|
|
945
948
|
};
|
|
@@ -2067,7 +2070,9 @@ function _createSession(key, cwd) {
|
|
|
2067
2070
|
}
|
|
2068
2071
|
}
|
|
2069
2072
|
|
|
2070
|
-
// 2. npm publish is
|
|
2073
|
+
// 2. npm publish is not auto-allowed by default, even under --d (safety floor) —
|
|
2074
|
+
// the only exception is the explicit full auto-approve tier (-2) resolved in the
|
|
2075
|
+
// perm branch below.
|
|
2071
2076
|
const isPublish = isPublishCommand(toolName, input);
|
|
2072
2077
|
|
|
2073
2078
|
// 3. Bypass mode auto-approves everything except publish and the two
|
|
@@ -2180,8 +2185,7 @@ function _createSession(key, cwd) {
|
|
|
2180
2185
|
// directory is not trusted for subsequent calls.
|
|
2181
2186
|
if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') {
|
|
2182
2187
|
const prefs = readPrefsRaw();
|
|
2183
|
-
const
|
|
2184
|
-
const shouldGrantDir = autoApproveSeconds === -1 || autoApproveSeconds > 0;
|
|
2188
|
+
const shouldGrantDir = isAutoApproveEnabledValue(prefs.autoApproveSeconds);
|
|
2185
2189
|
const sessionCwd = _cwd || process.env.CCV_PROJECT_DIR;
|
|
2186
2190
|
if (sessionCwd && shouldGrantDir) {
|
|
2187
2191
|
let targetDir = null;
|
|
@@ -2227,10 +2231,15 @@ function _createSession(key, cwd) {
|
|
|
2227
2231
|
// unknown decision → fall through to normal approval flow
|
|
2228
2232
|
} catch (err) { reportSwallowed('sdk-manager.waterfall.perm', err); }
|
|
2229
2233
|
}
|
|
2230
|
-
// npm publish is a hard safety floor: it must
|
|
2231
|
-
//
|
|
2232
|
-
//
|
|
2233
|
-
|
|
2234
|
+
// npm publish is a hard safety floor: it must wait for a HUMAN decision at
|
|
2235
|
+
// every tier EXCEPT the explicit full auto-approve (-2, 完全免审批), which
|
|
2236
|
+
// opts into letting high-risk commands through (intended for isolated
|
|
2237
|
+
// containers). Same exemption for unattended scheduled-task runs (ctx != null)
|
|
2238
|
+
// — those never auto-approve at any tier.
|
|
2239
|
+
const permComputed = computeAutoApprove('perm', _cwd);
|
|
2240
|
+
const permAuto = (ctx || (isPublish && permComputed.seconds !== AUTO_APPROVE_FULL))
|
|
2241
|
+
? { enabled: false }
|
|
2242
|
+
: permComputed;
|
|
2234
2243
|
const permPayload = { type: 'perm-hook-pending', id, toolName, input, cwd: _cwd, sessionId: effSessionId(), instanceKey, ...origin,
|
|
2235
2244
|
autoApproveSeconds: permAuto.enabled ? permAuto.seconds : 0,
|
|
2236
2245
|
...(permAuto.enabled ? { autoApproveAt: permAuto.autoApproveAt } : {}) };
|
|
@@ -2316,8 +2325,8 @@ function _createSession(key, cwd) {
|
|
|
2316
2325
|
};
|
|
2317
2326
|
_pendingApprovals.set(id, entry);
|
|
2318
2327
|
// Arm the server-side fallback AFTER the entry is in the map: instant (-1 for
|
|
2319
|
-
// plan
|
|
2320
|
-
// the same first-wins wrapper. Ask hosting arms its own state factory (minute
|
|
2328
|
+
// plan, -1/-2 for perm, 0 minutes for ask hosting) fires synchronously and resolves
|
|
2329
|
+
// through the same first-wins wrapper. Ask hosting arms its own state factory (minute
|
|
2321
2330
|
// semantics) and resolves the pre-picked answers map; plan/perm keep the generic
|
|
2322
2331
|
// auto-approve state. A null autoValue (no selectable option) never reaches here —
|
|
2323
2332
|
// the ask caller passes autoMeta only when answers were actually picked, otherwise
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* App-level keepalive loop for /ws/terminal connections.
|
|
3
|
+
*
|
|
4
|
+
* Browsers cannot send WS control-frame pings, and a NAT/proxy can silently
|
|
5
|
+
* half-open this socket: the client watchdog (TerminalWsContext) uses these frames
|
|
6
|
+
* as its liveness signal, and without them a dead socket never fires onclose,
|
|
7
|
+
* freezing every push-only consumer on this channel (sdk-context-usage blood bar,
|
|
8
|
+
* approvals, queue state) until a page refresh.
|
|
9
|
+
*
|
|
10
|
+
* Extracted as its own module so the test seam (server-terminal-ws-ping.test.js)
|
|
11
|
+
* loads ONLY this helper — a full server.js import in the shared test process
|
|
12
|
+
* leaks module state into sibling server tests (same pattern as
|
|
13
|
+
* setTerminalWssForTests, which ws-instance-isolation.test.js drives the same way).
|
|
14
|
+
*
|
|
15
|
+
* Send-only on purpose: a dead connection is skipped (readyState gate) and the
|
|
16
|
+
* client-side watchdog owns close+reconnect, keeping the historical broadcast
|
|
17
|
+
* semantics (skip non-OPEN, heal on reconnect) unchanged.
|
|
18
|
+
*/
|
|
19
|
+
import { reportSwallowed } from './error-report.js';
|
|
20
|
+
|
|
21
|
+
export const TERMINAL_WS_PING_MS = 25_000;
|
|
22
|
+
|
|
23
|
+
export function attachTerminalWsPing(ws, { setI = setInterval, clearI = clearInterval } = {}) {
|
|
24
|
+
// Send the FIRST ping immediately on connect, not after one full interval. The
|
|
25
|
+
// client resets its ping-seen evidence on every (re)connect; if the socket goes
|
|
26
|
+
// half-open during the first 25s window before any ping arrives, the watchdog
|
|
27
|
+
// would have no evidence and stay passive forever — a permanent freeze. An
|
|
28
|
+
// immediate first frame closes that window.
|
|
29
|
+
const sendPing = () => {
|
|
30
|
+
if (ws.readyState !== 1) return;
|
|
31
|
+
// A failed keepalive send is the server's only liveness signal for this socket —
|
|
32
|
+
// report it (dedup-capped per tag, so a dead socket does not flood every 25s).
|
|
33
|
+
try { ws.send(JSON.stringify({ type: 'ping', ts: Date.now() })); }
|
|
34
|
+
catch (err) { reportSwallowed('ws.terminal-ping', err); }
|
|
35
|
+
};
|
|
36
|
+
sendPing();
|
|
37
|
+
const pingTimer = setI(sendPing, TERMINAL_WS_PING_MS);
|
|
38
|
+
pingTimer.unref?.();
|
|
39
|
+
ws.on('close', () => clearI(pingTimer));
|
|
40
|
+
return pingTimer;
|
|
41
|
+
}
|
|
42
|
+
|
|
@@ -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
|
+
}
|