@twinsearth/timemachine-dsh-plugin 0.0.0-stage → 0.1.0

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/lib/index.js ADDED
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Node entry for Cordis. The implementation lives in `src/` so the package
3
+ * remains readable when installed under a DSH profile.
4
+ */
5
+ export { apply, default, inject, name, registerRoutes, ROUTE_PATHS, ROUTE_PREFIX, RESTORE_CONFIRM } from '../src/plugin.mjs';
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@twinsearth/timemachine-dsh-plugin",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "DSH 一键还原点:手动/自动双还原点、会话与工作区完整备份、第三方插件 latest 重装、配置迁移与一键还原。",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./lib/index.js",
8
+ "./client": "./lib/client.js",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "main": "lib/index.js",
12
+ "files": [
13
+ "lib",
14
+ "src",
15
+ "plugin.json",
16
+ "cordis.patch.yml",
17
+ "README.md",
18
+ "CHANGELOG.md",
19
+ "docs",
20
+ "scripts/host-menu-patch.mjs",
21
+ "LICENSE"
22
+ ],
23
+ "dsh": {
24
+ "plugin": true,
25
+ "kind": "server",
26
+ "bundle": {
27
+ "patch": "cordis.patch.yml"
28
+ },
29
+ "client": {
30
+ "platform": "web"
31
+ }
32
+ },
33
+ "scripts": {
34
+ "test": "node --test test/*.test.mjs",
35
+ "check": "node scripts/check.mjs",
36
+ "pack-check": "node scripts/pack-check.mjs"
37
+ },
38
+ "engines": {
39
+ "node": ">=22",
40
+ "dsh": ">=0.2.0 <0.3.0"
41
+ },
42
+ "keywords": [
43
+ "dsh",
44
+ "dsh-plugin",
45
+ "backup",
46
+ "restore",
47
+ "timemachine"
48
+ ],
49
+ "license": "MIT"
50
+ }
package/plugin.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "id": "timemachine",
3
+ "name": "DSH 一键还原点",
4
+ "version": "0.1.0",
5
+ "description": "手动/自动还原点、会话与工作区备份、第三方插件 latest 重装、DSH 配置迁移。",
6
+ "entry": "lib/index.js",
7
+ "client": "lib/client.js",
8
+ "bundle": "cordis.patch.yml"
9
+ }
@@ -0,0 +1,274 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * DSH native application-menu integration.
4
+ *
5
+ * DSH 0.2.x builds the Windows/macOS application menu inside
6
+ * `resources/app.asar/lib/main.js`. Plugins cannot append to that menu through
7
+ * Cordis slots, so this opt-in host patch inserts one item directly after
8
+ * "Developer tools" and points it at the plugin's `window` hook.
9
+ *
10
+ * The patcher is deliberately conservative:
11
+ * - it only replaces one exact, version-known menu block;
12
+ * - it refuses while a DSH desktop process is running unless --force;
13
+ * - it keeps a byte-for-byte backup next to app.asar;
14
+ * - it rebuilds the asar data section and updates the affected integrity hash;
15
+ * - --restore puts the backup back.
16
+ *
17
+ * Usage:
18
+ * node scripts/host-menu-patch.mjs --app-asar "D:\DSH\resources\app.asar"
19
+ * node scripts/host-menu-patch.mjs --app-asar ... --dry-run
20
+ * node scripts/host-menu-patch.mjs --app-asar ... --restore
21
+ */
22
+
23
+ import { createHash } from 'node:crypto';
24
+ import { execFileSync } from 'node:child_process';
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ const LABEL = 'DSH一键还原点';
29
+ const MARKER = 'twinsearth-timemachine-menu-v1';
30
+ const ORIGINAL_BLOCK = `\t\t{
31
+ \t\t\trole: "toggleDevTools",
32
+ \t\t\tlabel: currentDesktopLocale().messages.toggleDevToolsMenu
33
+ \t\t},`;
34
+ const PATCHED_BLOCK = `\t\t{
35
+ \t\t\trole: "toggleDevTools",
36
+ \t\t\tlabel: currentDesktopLocale().messages.toggleDevToolsMenu
37
+ \t\t},
38
+ \t\t{
39
+ \t\t\tid: "${MARKER}",
40
+ \t\t\tlabel: "${LABEL}",
41
+ \t\t\tclick: () => {
42
+ \t\t\t\tconst window = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find((candidate) => !candidate.isDestroyed());
43
+ \t\t\t\tif (window === void 0) return;
44
+ \t\t\t\twindow.show();
45
+ \t\t\t\twindow.focus();
46
+ \t\t\t\twindow.webContents.executeJavaScript("window.__DSH_TIMEMACHINE_OPEN__?.()").catch((error) => {
47
+ \t\t\t\t\tconsole.error("timemachine menu:", error);
48
+ \t\t\t\t});
49
+ \t\t\t}
50
+ \t\t},`;
51
+
52
+ function usage(message) {
53
+ if (message) console.error(message);
54
+ console.error('usage: node scripts/host-menu-patch.mjs --app-asar <path> [--dry-run] [--force] [--restore] [--check]');
55
+ process.exit(2);
56
+ }
57
+
58
+ function parseArgs(argv) {
59
+ const args = { appAsar: '', dryRun: false, force: false, restore: false, check: false };
60
+ for (let index = 0; index < argv.length; index += 1) {
61
+ const value = argv[index];
62
+ if (value === '--app-asar') args.appAsar = argv[++index] ?? '';
63
+ else if (value === '--dry-run') args.dryRun = true;
64
+ else if (value === '--force') args.force = true;
65
+ else if (value === '--restore') args.restore = true;
66
+ else if (value === '--check') args.check = true;
67
+ else if (value === '--help' || value === '-h') usage();
68
+ else usage(`unknown argument: ${value}`);
69
+ }
70
+ if (args.appAsar === '') usage('--app-asar is required');
71
+ return args;
72
+ }
73
+
74
+ function align8(value) {
75
+ return Math.ceil(value / 8) * 8;
76
+ }
77
+
78
+ function walkFiles(node, prefix = '', out = []) {
79
+ if (node?.files && typeof node.files === 'object') {
80
+ for (const [name, child] of Object.entries(node.files)) walkFiles(child, `${prefix}/${name}`, out);
81
+ } else {
82
+ out.push({ path: prefix, entry: node });
83
+ }
84
+ return out;
85
+ }
86
+
87
+ function readAsar(file) {
88
+ const buffer = fs.readFileSync(file);
89
+ if (buffer.length < 16 || buffer.readUInt32LE(0) !== 4) throw new Error('not an asar archive');
90
+ const headerSize = buffer.readUInt32LE(4);
91
+ const jsonSize = buffer.readUInt32LE(12);
92
+ if (headerSize < 4 || jsonSize < 2 || 16 + jsonSize > buffer.length) throw new Error('invalid asar header');
93
+ const header = JSON.parse(buffer.subarray(16, 16 + jsonSize).toString('utf8'));
94
+ const dataStart = 8 + headerSize;
95
+ const files = walkFiles(header);
96
+ return { buffer, header, headerSize, jsonSize, dataStart, files };
97
+ }
98
+
99
+ function sha256(buffer) {
100
+ return createHash('sha256').update(buffer).digest('hex');
101
+ }
102
+
103
+ function fileData(archive, row) {
104
+ const offset = Number(row.entry.offset);
105
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new Error(`invalid offset for ${row.path}`);
106
+ return archive.buffer.subarray(archive.dataStart + offset, archive.dataStart + offset + row.entry.size);
107
+ }
108
+
109
+ function createHeaderBuffer(header) {
110
+ const json = Buffer.from(JSON.stringify(header), 'utf8');
111
+ const headerSize = align8(4 + json.length);
112
+ const buffer = Buffer.alloc(8 + headerSize);
113
+ buffer.writeUInt32LE(4, 0);
114
+ buffer.writeUInt32LE(headerSize, 4);
115
+ buffer.writeUInt32LE(headerSize - 4, 8);
116
+ buffer.writeUInt32LE(json.length, 12);
117
+ json.copy(buffer, 16);
118
+ return buffer;
119
+ }
120
+
121
+ function detectRunningDsh() {
122
+ if (process.platform !== 'win32') {
123
+ try {
124
+ const output = execFileSync('pgrep', ['-fl', 'DSH'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
125
+ return output.trim().split(/\r?\n/u).filter(Boolean);
126
+ } catch {
127
+ return [];
128
+ }
129
+ }
130
+ try {
131
+ const output = execFileSync('tasklist', ['/FI', 'IMAGENAME eq DeepSeek Harness.exe', '/FO', 'CSV', '/NH'], {
132
+ encoding: 'utf8',
133
+ stdio: ['ignore', 'pipe', 'ignore'],
134
+ });
135
+ return output.trim().split(/\r?\n/u).filter((line) => line.toLowerCase().includes('deepseek harness.exe'));
136
+ } catch {
137
+ return [];
138
+ }
139
+ }
140
+
141
+ function patchMainSource(source) {
142
+ if (source.includes(`id: "${MARKER}"`)) return { source, changed: false };
143
+ const first = source.indexOf(ORIGINAL_BLOCK);
144
+ if (first < 0) {
145
+ throw new Error('the Developer-tools menu block was not found; this DSH build is not supported by the patch');
146
+ }
147
+ if (source.indexOf(ORIGINAL_BLOCK, first + ORIGINAL_BLOCK.length) >= 0) {
148
+ throw new Error('the Developer-tools menu block is not unique; refusing to patch');
149
+ }
150
+ return { source: source.replace(ORIGINAL_BLOCK, PATCHED_BLOCK), changed: true };
151
+ }
152
+
153
+ function buildPatchedAsar(archive, patchedMain) {
154
+ const mainRows = archive.files.filter((row) => row.path === '/lib/main.js');
155
+ if (mainRows.length !== 1) throw new Error('app.asar has no unique /lib/main.js');
156
+ const mainRow = mainRows[0];
157
+ if (mainRow.entry.unpacked === true) throw new Error('/lib/main.js is unpacked; this patcher only supports packed main.js');
158
+
159
+ const oldMain = fileData(archive, mainRow);
160
+ if (oldMain.length !== mainRow.entry.size) throw new Error('main.js is truncated');
161
+ mainRow.entry.size = patchedMain.length;
162
+ mainRow.entry.integrity = {
163
+ algorithm: 'SHA256',
164
+ hash: sha256(patchedMain),
165
+ blockSize: 4194304,
166
+ blocks: [sha256(patchedMain)],
167
+ };
168
+
169
+ const packed = archive.files
170
+ .filter((row) => row.entry.unpacked !== true)
171
+ .sort((left, right) => Number(left.entry.offset) - Number(right.entry.offset));
172
+ const originalData = new Map();
173
+ for (const row of packed) originalData.set(row.path, fileData(archive, row));
174
+ let cursor = 0;
175
+ for (const row of packed) {
176
+ row.entry.offset = String(cursor);
177
+ cursor += row.entry.size;
178
+ }
179
+
180
+ const header = createHeaderBuffer(archive.header);
181
+ const out = Buffer.alloc(header.length + cursor);
182
+ header.copy(out, 0);
183
+ let writeAt = header.length;
184
+ for (const row of packed) {
185
+ const data = row.path === '/lib/main.js' ? patchedMain : originalData.get(row.path);
186
+ if (data.length !== row.entry.size) throw new Error(`size mismatch for ${row.path}`);
187
+ data.copy(out, writeAt);
188
+ writeAt += data.length;
189
+ }
190
+ if (writeAt !== out.length) throw new Error('asar rebuild size mismatch');
191
+ return out;
192
+ }
193
+
194
+ function main() {
195
+ const args = parseArgs(process.argv.slice(2));
196
+ const appAsar = path.resolve(args.appAsar);
197
+ if (!fs.existsSync(appAsar)) throw new Error(`app.asar not found: ${appAsar}`);
198
+ const backup = `${appAsar}.timemachine-backup`;
199
+
200
+ if (args.restore) {
201
+ if (!fs.existsSync(backup)) throw new Error(`backup not found: ${backup}`);
202
+ if (args.dryRun) {
203
+ console.log(`[dry-run] would restore ${appAsar} from ${backup}`);
204
+ return;
205
+ }
206
+ if (!args.force && detectRunningDsh().length > 0) {
207
+ throw new Error('DSH is running. Close it completely before restoring app.asar, or pass --force.');
208
+ }
209
+ fs.copyFileSync(backup, appAsar);
210
+ console.log(`restored ${appAsar}`);
211
+ return;
212
+ }
213
+
214
+ const archive = readAsar(appAsar);
215
+ const mainRow = archive.files.find((row) => row.path === '/lib/main.js');
216
+ if (mainRow === undefined) throw new Error('/lib/main.js is missing from app.asar');
217
+ const originalSource = fileData(archive, mainRow).toString('utf8');
218
+ const { source: patchedSource, changed } = patchMainSource(originalSource);
219
+ const already = !changed;
220
+
221
+ if (args.check) {
222
+ console.log(JSON.stringify({
223
+ app_asar: appAsar,
224
+ version: (() => {
225
+ try {
226
+ const pkg = archive.files.find((row) => row.path === '/package.json');
227
+ return pkg === undefined ? null : JSON.parse(fileData(archive, pkg).toString('utf8')).version;
228
+ } catch { return null; }
229
+ })(),
230
+ patched: already,
231
+ running: detectRunningDsh(),
232
+ backup_exists: fs.existsSync(backup),
233
+ }, null, 2));
234
+ return;
235
+ }
236
+
237
+ if (already) {
238
+ console.log(`already patched: ${appAsar}`);
239
+ return;
240
+ }
241
+ const running = detectRunningDsh();
242
+ if (running.length > 0 && !args.force) {
243
+ throw new Error(`DSH is running (${running.length} process(es)). Close it completely, then retry; or pass --force.`);
244
+ }
245
+
246
+ const patched = buildPatchedAsar(archive, Buffer.from(patchedSource, 'utf8'));
247
+ const output = args.dryRun ? null : `${appAsar}.timemachine-new`;
248
+ if (args.dryRun) {
249
+ console.log(`[dry-run] would patch ${appAsar}: ${archive.buffer.length} -> ${patched.length} bytes, main.js ${mainRow.entry.size} bytes`);
250
+ return;
251
+ }
252
+ if (!fs.existsSync(backup)) fs.copyFileSync(appAsar, backup);
253
+ fs.writeFileSync(output, patched);
254
+ try {
255
+ fs.renameSync(output, appAsar);
256
+ } catch (error) {
257
+ try { fs.rmSync(output, { force: true }); } catch { /* ignore */ }
258
+ throw new Error(`could not replace app.asar: ${error instanceof Error ? error.message : String(error)}. The original was not changed; backup: ${backup}`);
259
+ }
260
+ const verify = readAsar(appAsar);
261
+ const verifyMain = verify.files.find((row) => row.path === '/lib/main.js');
262
+ const verifySource = verifyMain === undefined ? '' : fileData(verify, verifyMain).toString('utf8');
263
+ if (!verifySource.includes(`id: "${MARKER}"`)) throw new Error('patched app.asar did not verify; restore the backup');
264
+ console.log(`patched ${appAsar}`);
265
+ console.log(`backup ${backup}`);
266
+ console.log('Restart DSH once. The menu item appears under Application → Developer tools.');
267
+ }
268
+
269
+ try {
270
+ main();
271
+ } catch (error) {
272
+ console.error(`host-menu-patch: ${error instanceof Error ? error.message : String(error)}`);
273
+ process.exit(1);
274
+ }
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Minimal ustar reader/writer.
3
+ *
4
+ * The archive needs exactly two operations: write regular-file entries and
5
+ * read them back. ustar is a 512-byte header format, so this file replaces a
6
+ * dependency. GNU long-name (`L`) entries are written and read for paths that
7
+ * do not fit the 100+155 byte split; PAX, symlinks and sparse files are not
8
+ * supported and are rejected instead of silently misread.
9
+ */
10
+
11
+ const BLOCK = 512;
12
+ const REGULAR = '0';
13
+
14
+ function octal(number, length) {
15
+ const text = Math.max(0, Math.floor(number)).toString(8);
16
+ if (text.length > length - 1) throw new Error(`tar field overflow: ${number} does not fit in ${length - 1} octal digits`);
17
+ return `${text.padStart(length - 1, '0')}\0`;
18
+ }
19
+
20
+ function writeString(target, offset, value, length) {
21
+ const bytes = Buffer.from(String(value), 'utf8');
22
+ if (bytes.length > length) throw new Error(`tar field overflow: ${JSON.stringify(String(value))} is longer than ${length}`);
23
+ bytes.copy(target, offset, 0, bytes.length);
24
+ }
25
+
26
+ function splitName(name) {
27
+ if (name.length <= 100) return { name, prefix: '' };
28
+ for (let index = name.length - 100; index <= name.length; index += 1) {
29
+ if (name[index] === '/') {
30
+ const prefix = name.slice(0, index);
31
+ const rest = name.slice(index + 1);
32
+ if (prefix.length <= 155 && rest.length <= 100) return { name: rest, prefix };
33
+ }
34
+ }
35
+ throw new Error(`tar path too long: ${name}`);
36
+ }
37
+
38
+ function headerFor(name, prefix, dataLength, mode, mtimeMs, typeFlag) {
39
+ const header = Buffer.alloc(BLOCK, 0);
40
+ writeString(header, 0, name, 100);
41
+ writeString(header, 100, octal(mode, 8), 8);
42
+ writeString(header, 108, octal(0, 8), 8);
43
+ writeString(header, 116, octal(0, 8), 8);
44
+ writeString(header, 124, octal(dataLength, 12), 12);
45
+ writeString(header, 136, octal(Math.floor(mtimeMs / 1000), 12), 12);
46
+ writeString(header, 148, ' ', 8);
47
+ writeString(header, 156, typeFlag, 1);
48
+ writeString(header, 257, 'ustar\0', 6);
49
+ writeString(header, 263, '00', 2);
50
+ writeString(header, 345, prefix, 155);
51
+ let checksum = 0;
52
+ for (const byte of header) checksum += byte;
53
+ writeString(header, 148, `${checksum.toString(8).padStart(6, '0')}\0 `, 8);
54
+ return header;
55
+ }
56
+
57
+ /**
58
+ * Build a tar archive from regular-file entries.
59
+ * @param {Array<{name: string, data: Buffer|string, mode?: number, mtimeMs?: number}>} entries
60
+ * @returns {Buffer}
61
+ */
62
+ export function writeTar(entries) {
63
+ const blocks = [];
64
+ let total = 0;
65
+ for (const entry of entries) {
66
+ const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(String(entry.data), 'utf8');
67
+ let name;
68
+ let prefix = '';
69
+ let longName = null;
70
+ try {
71
+ ({ name, prefix } = splitName(entry.name));
72
+ } catch {
73
+ longName = entry.name;
74
+ name = '././@LongLink';
75
+ }
76
+ if (longName !== null) {
77
+ const payload = Buffer.from(`${longName}\0`, 'utf8');
78
+ blocks.push(headerFor('././@LongLink', '', payload.length, 0o644, entry.mtimeMs ?? 0, 'L'));
79
+ blocks.push(payload);
80
+ const longPad = (BLOCK - (payload.length % BLOCK)) % BLOCK;
81
+ if (longPad > 0) blocks.push(Buffer.alloc(longPad, 0));
82
+ total += BLOCK + payload.length + longPad;
83
+ }
84
+ blocks.push(headerFor(name, prefix, data.length, entry.mode ?? 0o644, entry.mtimeMs ?? 0, REGULAR));
85
+ blocks.push(data);
86
+ const padding = (BLOCK - (data.length % BLOCK)) % BLOCK;
87
+ if (padding > 0) blocks.push(Buffer.alloc(padding, 0));
88
+ total += BLOCK + data.length + padding;
89
+ }
90
+ blocks.push(Buffer.alloc(BLOCK * 2, 0));
91
+ return Buffer.concat(blocks, total + BLOCK * 2);
92
+ }
93
+
94
+ function readString(buffer, offset, length) {
95
+ const slice = buffer.subarray(offset, offset + length);
96
+ const end = slice.indexOf(0);
97
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf8');
98
+ }
99
+
100
+ function readOctal(buffer, offset, length) {
101
+ const text = readString(buffer, offset, length).trim();
102
+ return text === '' ? 0 : Number.parseInt(text, 8);
103
+ }
104
+
105
+ /**
106
+ * Read a ustar archive of regular files.
107
+ * @param {Buffer} buffer
108
+ * @returns {Array<{name: string, data: Buffer, mode: number, mtimeMs: number}>}
109
+ */
110
+ export function readTar(buffer) {
111
+ const entries = [];
112
+ let offset = 0;
113
+ let longName = null;
114
+ while (offset + BLOCK <= buffer.length) {
115
+ const header = buffer.subarray(offset, offset + BLOCK);
116
+ if (header.every((byte) => byte === 0)) break;
117
+ const name = readString(header, 0, 100);
118
+ const prefix = readString(header, 345, 155);
119
+ const size = readOctal(header, 124, 12);
120
+ const mode = readOctal(header, 100, 8);
121
+ const mtimeMs = readOctal(header, 136, 12) * 1000;
122
+ const typeFlag = readString(header, 156, 1) || REGULAR;
123
+ const full = prefix === '' ? name : `${prefix}/${name}`;
124
+ const start = offset + BLOCK;
125
+ const end = start + size;
126
+ if (end > buffer.length) throw new Error(`tar entry ${full} claims ${size} bytes past the end of the archive`);
127
+ if (typeFlag === 'L') {
128
+ longName = buffer.subarray(start, end).toString('utf8').replace(/\0+$/u, '');
129
+ offset = end + ((BLOCK - (size % BLOCK)) % BLOCK);
130
+ continue;
131
+ }
132
+ if (typeFlag !== REGULAR) throw new Error(`unsupported tar entry type ${JSON.stringify(typeFlag)} for ${full}`);
133
+ entries.push({ name: longName ?? full, data: buffer.subarray(start, end), mode, mtimeMs });
134
+ longName = null;
135
+ offset = end + ((BLOCK - (size % BLOCK)) % BLOCK);
136
+ }
137
+ return entries;
138
+ }
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Zstandard frame primitives (RFC 8878) for DSH session logs.
3
+ *
4
+ * A DSH session log is a sequence of independent, checksummed zstd frames.
5
+ * `zlib.zstdDecompressSync` only decodes the first frame, so reading a whole
6
+ * log needs a frame walker. This module walks frame headers without reading
7
+ * payload bytes, decompresses one frame at a time, and can rewrite the first
8
+ * frame (the session header) while preserving every later frame byte-for-byte.
9
+ */
10
+
11
+ import fs from 'node:fs';
12
+ import zlib from 'node:zlib';
13
+
14
+ export const ZSTD_MAGIC = 0xfd2fb528;
15
+ export const CHECKSUM_OPTIONS = {
16
+ params: { [zlib.constants.ZSTD_c_checksumFlag]: 1 },
17
+ };
18
+
19
+ /** Whether this Node exposes the synchronous Zstandard API. */
20
+ export function hasZstd() {
21
+ return typeof zlib.zstdCompressSync === 'function' && typeof zlib.zstdDecompressSync === 'function';
22
+ }
23
+
24
+ function scanFramesWith(reader, maxFrames = Number.POSITIVE_INFINITY) {
25
+ const length = reader.length;
26
+ const frames = [];
27
+ let offset = 0;
28
+ while (offset < length) {
29
+ const start = offset;
30
+ if (length - offset < 4) return { frames, tornStart: start };
31
+ if (reader.readUInt32LE(offset) !== ZSTD_MAGIC) throw new Error(`invalid frame magic at byte ${offset}`);
32
+ offset += 4;
33
+ if (offset === length) return { frames, tornStart: start };
34
+
35
+ const descriptor = reader.readUInt8(offset);
36
+ offset += 1;
37
+ if ((descriptor & 24) !== 0) throw new Error(`reserved frame-header bit set at byte ${offset - 1}`);
38
+ const contentSizeFlag = descriptor >>> 6;
39
+ const singleSegment = (descriptor & 32) !== 0;
40
+ const hasChecksum = (descriptor & 4) !== 0;
41
+ const dictionaryFlag = descriptor & 3;
42
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
43
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
44
+
45
+ const rest = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
46
+ if (length - offset < rest) return { frames, tornStart: start };
47
+ offset += rest;
48
+
49
+ for (;;) {
50
+ if (length - offset < 3) return { frames, tornStart: start };
51
+ const blockHeader = reader.readUIntLE(offset, 3);
52
+ offset += 3;
53
+ const lastBlock = (blockHeader & 1) !== 0;
54
+ const blockType = (blockHeader >>> 1) & 3;
55
+ const blockSize = blockHeader >>> 3;
56
+ if (blockType === 3) throw new Error(`reserved block type at byte ${offset - 3}`);
57
+ const payloadBytes = blockType === 1 ? 1 : blockSize;
58
+ if (length - offset < payloadBytes) return { frames, tornStart: start };
59
+ offset += payloadBytes;
60
+ if (lastBlock) break;
61
+ }
62
+ if (hasChecksum) {
63
+ if (length - offset < 4) return { frames, tornStart: start };
64
+ offset += 4;
65
+ }
66
+ frames.push({ start, end: offset, hasChecksum });
67
+ if (frames.length === maxFrames) return { frames };
68
+ }
69
+ return { frames };
70
+ }
71
+
72
+ /**
73
+ * Walk the byte range of every complete frame in a buffer.
74
+ * @param {Buffer} buf
75
+ * @param {number} [maxFrames]
76
+ * @returns {{frames: Array<{start: number, end: number, hasChecksum: boolean}>, tornStart?: number}}
77
+ */
78
+ export function scanFrames(buf, maxFrames = Number.POSITIVE_INFINITY) {
79
+ return scanFramesWith({
80
+ length: buf.length,
81
+ readUInt32LE: (offset) => buf.readUInt32LE(offset),
82
+ readUInt8: (offset) => buf.readUInt8(offset),
83
+ readUIntLE: (offset, bytes) => buf.readUIntLE(offset, bytes),
84
+ }, maxFrames);
85
+ }
86
+
87
+ /**
88
+ * Walk frames from a file without reading payloads into memory.
89
+ * @param {string} file
90
+ * @param {{windowBytes?: number}} [options]
91
+ */
92
+ export function scanFramesFromFile(file, options = {}) {
93
+ const windowBytes = Number.isSafeInteger(options.windowBytes) && options.windowBytes >= 4096
94
+ ? options.windowBytes
95
+ : 256 * 1024;
96
+ const fd = fs.openSync(file, 'r');
97
+ try {
98
+ const size = fs.fstatSync(fd).size;
99
+ let windowStart = -1;
100
+ let window = null;
101
+ const ensure = (pos, need) => {
102
+ if (window !== null && pos >= windowStart && pos + need <= windowStart + window.length) return true;
103
+ const length = Math.min(windowBytes, size - pos);
104
+ if (length < need) return false;
105
+ const buffer = Buffer.allocUnsafe(length);
106
+ const read = fs.readSync(fd, buffer, 0, length, pos);
107
+ window = read === length ? buffer : buffer.subarray(0, read);
108
+ windowStart = pos;
109
+ return window.length >= need;
110
+ };
111
+ const reader = {
112
+ length: size,
113
+ readUInt32LE(pos) {
114
+ if (!ensure(pos, 4)) throw new Error(`short read at byte ${pos}`);
115
+ return window.readUInt32LE(pos - windowStart);
116
+ },
117
+ readUInt8(pos) {
118
+ if (!ensure(pos, 1)) throw new Error(`short read at byte ${pos}`);
119
+ return window.readUInt8(pos - windowStart);
120
+ },
121
+ readUIntLE(pos, bytes) {
122
+ if (!ensure(pos, bytes)) throw new Error(`short read at byte ${pos}`);
123
+ return window.readUIntLE(pos - windowStart, bytes);
124
+ },
125
+ };
126
+ return { ...scanFramesWith(reader), file_bytes: size };
127
+ } finally {
128
+ fs.closeSync(fd);
129
+ }
130
+ }
131
+
132
+ /** Compress one independently decodable, checksummed frame; verifies the round trip. */
133
+ export function compressFrame(payload) {
134
+ const frame = zlib.zstdCompressSync(payload, CHECKSUM_OPTIONS);
135
+ if (frame.readUInt32LE(0) !== ZSTD_MAGIC) throw new Error('compressed frame has wrong magic');
136
+ if ((frame.readUInt8(4) & 4) === 0) throw new Error('compressed frame lacks the checksum flag');
137
+ const back = zlib.zstdDecompressSync(frame).toString('utf8');
138
+ if (back !== payload.toString('utf8')) throw new Error('compressed frame failed roundtrip');
139
+ return frame;
140
+ }
141
+
142
+ /** Decompress exactly one complete frame. */
143
+ export function decompressFrame(slice) {
144
+ return zlib.zstdDecompressSync(slice).toString('utf8');
145
+ }
146
+
147
+ /**
148
+ * Decode every complete frame of a session log.
149
+ * @param {Buffer} buffer
150
+ * @returns {{header: object|null, events: string[], frameCount: number, tornStart: number|null, bytes: number}}
151
+ */
152
+ export function decodeSessionLog(buffer) {
153
+ const walked = scanFrames(buffer);
154
+ const lines = [];
155
+ for (const frame of walked.frames) {
156
+ const text = decompressFrame(buffer.subarray(frame.start, frame.end));
157
+ for (const line of text.split(/\r?\n/u)) {
158
+ if (line.trim() !== '') lines.push(line);
159
+ }
160
+ }
161
+ let header = null;
162
+ if (lines.length > 0) {
163
+ try {
164
+ const parsed = JSON.parse(lines[0]);
165
+ if (parsed?.type === 'session') header = parsed;
166
+ } catch { /* the first line is not the header */ }
167
+ }
168
+ return {
169
+ header,
170
+ events: lines.slice(header === null ? 0 : 1),
171
+ frameCount: walked.frames.length,
172
+ tornStart: walked.tornStart ?? null,
173
+ bytes: buffer.length,
174
+ };
175
+ }
176
+
177
+ /**
178
+ * Rewrite the first frame (the session header) and keep every subsequent frame.
179
+ * Used when a restore maps `cwd` to a different path.
180
+ * @param {Buffer} buffer
181
+ * @param {(header: object) => object} change
182
+ * @returns {{buffer: Buffer, changed: boolean}}
183
+ */
184
+ export function rewriteSessionHeader(buffer, change) {
185
+ const walked = scanFrames(buffer);
186
+ if (walked.frames.length === 0) throw new Error('session log has no complete frame');
187
+ const first = walked.frames[0];
188
+ const text = decompressFrame(buffer.subarray(first.start, first.end));
189
+ const newline = text.indexOf('\n');
190
+ const firstLine = newline === -1 ? text : text.slice(0, newline);
191
+ const rest = newline === -1 ? '' : text.slice(newline);
192
+ let header;
193
+ try {
194
+ header = JSON.parse(firstLine);
195
+ } catch {
196
+ throw new Error('session log first line is not JSON');
197
+ }
198
+ if (header?.type !== 'session') throw new Error('session log first line is not a session header');
199
+ const next = change(header);
200
+ if (next === null || typeof next !== 'object') throw new Error('header rewrite returned no object');
201
+ const encoded = `${JSON.stringify(next)}${rest}`;
202
+ if (encoded === text) return { buffer, changed: false };
203
+ const frame = compressFrame(Buffer.from(encoded, 'utf8'));
204
+ const tailStart = first.end;
205
+ return { buffer: Buffer.concat([frame, buffer.subarray(tailStart)]), changed: true };
206
+ }