@ddtcorex/dsh-maestro-core 0.10.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/LICENSE +21 -0
- package/README.md +209 -0
- package/cordis.patch.yml +43 -0
- package/lib/bin.d.ts +2 -0
- package/lib/bin.js +3 -0
- package/lib/boot-guard.d.ts +33 -0
- package/lib/boot-guard.js +68 -0
- package/lib/boot-lock.d.ts +56 -0
- package/lib/boot-lock.js +155 -0
- package/lib/cli.d.ts +31 -0
- package/lib/cli.js +336 -0
- package/lib/client.js +2901 -0
- package/lib/config/index.d.ts +34 -0
- package/lib/config/index.js +62 -0
- package/lib/config/service.d.ts +18 -0
- package/lib/config/service.js +28 -0
- package/lib/config.d.ts +1 -0
- package/lib/config.js +19 -0
- package/lib/daemon-freshness.d.ts +48 -0
- package/lib/daemon-freshness.js +122 -0
- package/lib/debug-agent.d.ts +17 -0
- package/lib/debug-agent.js +144 -0
- package/lib/dsh-session.d.ts +26 -0
- package/lib/dsh-session.js +45 -0
- package/lib/guard/config.d.ts +82 -0
- package/lib/guard/config.js +211 -0
- package/lib/guard/decide.d.ts +30 -0
- package/lib/guard/decide.js +38 -0
- package/lib/guard/full-scan-tool.d.ts +6 -0
- package/lib/guard/full-scan-tool.js +65 -0
- package/lib/guard/index.d.ts +85 -0
- package/lib/guard/index.js +254 -0
- package/lib/guard/journal.d.ts +146 -0
- package/lib/guard/journal.js +398 -0
- package/lib/guard/migrate.d.ts +15 -0
- package/lib/guard/migrate.js +42 -0
- package/lib/guard/parse.d.ts +193 -0
- package/lib/guard/parse.js +1103 -0
- package/lib/guard/paths.d.ts +104 -0
- package/lib/guard/paths.js +254 -0
- package/lib/guard/permission-policy.d.ts +10 -0
- package/lib/guard/permission-policy.js +21 -0
- package/lib/guard/redact.d.ts +25 -0
- package/lib/guard/redact.js +52 -0
- package/lib/guard/rules.d.ts +65 -0
- package/lib/guard/rules.js +832 -0
- package/lib/guard/status-tool.d.ts +54 -0
- package/lib/guard/status-tool.js +195 -0
- package/lib/guard/tiers.d.ts +2 -0
- package/lib/guard/tiers.js +1 -0
- package/lib/guard/validators.d.ts +4 -0
- package/lib/guard/validators.js +45 -0
- package/lib/health-poller.d.ts +90 -0
- package/lib/health-poller.js +430 -0
- package/lib/index.d.ts +7 -0
- package/lib/index.js +7 -0
- package/lib/intents.d.ts +32 -0
- package/lib/intents.js +49 -0
- package/lib/notifier.d.ts +12 -0
- package/lib/notifier.js +62 -0
- package/lib/paths.d.ts +13 -0
- package/lib/paths.js +70 -0
- package/lib/plugin.d.ts +250 -0
- package/lib/plugin.js +1126 -0
- package/lib/preset.d.ts +73 -0
- package/lib/preset.js +158 -0
- package/lib/report.d.ts +11 -0
- package/lib/report.js +58 -0
- package/lib/restart-exec.d.ts +35 -0
- package/lib/restart-exec.js +60 -0
- package/lib/restart-guards.d.ts +39 -0
- package/lib/restart-guards.js +150 -0
- package/lib/restart-tool.d.ts +124 -0
- package/lib/restart-tool.js +539 -0
- package/lib/restart-web.d.ts +26 -0
- package/lib/restart-web.js +58 -0
- package/lib/resume-log.d.ts +24 -0
- package/lib/resume-log.js +18 -0
- package/lib/resume-tools.d.ts +131 -0
- package/lib/resume-tools.js +337 -0
- package/lib/resume.d.ts +33 -0
- package/lib/resume.js +221 -0
- package/lib/scan.d.ts +20 -0
- package/lib/scan.js +71 -0
- package/lib/self-kill-guard.d.ts +81 -0
- package/lib/self-kill-guard.js +208 -0
- package/lib/session-health.d.ts +89 -0
- package/lib/session-health.js +274 -0
- package/lib/session-log-file.d.ts +22 -0
- package/lib/session-log-file.js +74 -0
- package/lib/skill-provider.d.ts +6 -0
- package/lib/skill-provider.js +73 -0
- package/lib/snapshot.d.ts +59 -0
- package/lib/snapshot.js +358 -0
- package/lib/source.d.ts +19 -0
- package/lib/source.js +19 -0
- package/lib/store/index.d.ts +42 -0
- package/lib/store/index.js +340 -0
- package/lib/store/legacy.d.ts +17 -0
- package/lib/store/legacy.js +85 -0
- package/lib/supervisor.d.ts +119 -0
- package/lib/supervisor.js +741 -0
- package/lib/sync/backup-config.d.ts +55 -0
- package/lib/sync/backup-config.js +119 -0
- package/lib/sync/backup-service.d.ts +110 -0
- package/lib/sync/backup-service.js +440 -0
- package/lib/sync/bidirectional.d.ts +39 -0
- package/lib/sync/bidirectional.js +25 -0
- package/lib/sync/cli.d.ts +38 -0
- package/lib/sync/cli.js +536 -0
- package/lib/sync/config.d.ts +77 -0
- package/lib/sync/config.js +90 -0
- package/lib/sync/fingerprint.d.ts +29 -0
- package/lib/sync/fingerprint.js +65 -0
- package/lib/sync/hashing.d.ts +9 -0
- package/lib/sync/hashing.js +47 -0
- package/lib/sync/index.d.ts +6 -0
- package/lib/sync/index.js +634 -0
- package/lib/sync/machine-id.d.ts +29 -0
- package/lib/sync/machine-id.js +66 -0
- package/lib/sync/merge.d.ts +33 -0
- package/lib/sync/merge.js +88 -0
- package/lib/sync/peer-host.d.ts +22 -0
- package/lib/sync/peer-host.js +62 -0
- package/lib/sync/process-runner.d.ts +31 -0
- package/lib/sync/process-runner.js +161 -0
- package/lib/sync/remote-agent.d.ts +42 -0
- package/lib/sync/remote-agent.js +217 -0
- package/lib/sync/remote-cache.d.ts +18 -0
- package/lib/sync/remote-cache.js +60 -0
- package/lib/sync/remote-manifest.d.ts +8 -0
- package/lib/sync/remote-manifest.js +64 -0
- package/lib/sync/s3-object-store.d.ts +38 -0
- package/lib/sync/s3-object-store.js +126 -0
- package/lib/sync/session-merge.d.ts +18 -0
- package/lib/sync/session-merge.js +191 -0
- package/lib/sync/session-plan.d.ts +29 -0
- package/lib/sync/session-plan.js +213 -0
- package/lib/sync/sigv4.d.ts +20 -0
- package/lib/sync/sigv4.js +57 -0
- package/lib/sync/snapshot.d.ts +21 -0
- package/lib/sync/snapshot.js +176 -0
- package/lib/sync/ssh-mux.d.ts +12 -0
- package/lib/sync/ssh-mux.js +48 -0
- package/lib/sync/sync-plan.d.ts +24 -0
- package/lib/sync/sync-plan.js +366 -0
- package/lib/sync/sync-service.d.ts +177 -0
- package/lib/sync/sync-service.js +819 -0
- package/lib/sync/sync-types.d.ts +87 -0
- package/lib/sync/sync-types.js +1 -0
- package/lib/sync/transport.d.ts +75 -0
- package/lib/sync/transport.js +200 -0
- package/lib/sync/tunnel-restore.d.ts +77 -0
- package/lib/sync/tunnel-restore.js +142 -0
- package/lib/sync/validation.d.ts +10 -0
- package/lib/sync/validation.js +83 -0
- package/lib/tool-view.d.ts +62 -0
- package/lib/tool-view.js +70 -0
- package/lib/types/client/auto-reload.d.ts +8 -0
- package/lib/types/client/auto-reload.d.ts.map +1 -0
- package/lib/types/client/config/MaestroSettings.d.ts +25 -0
- package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
- package/lib/types/client/config/components/BrandMark.d.ts +50 -0
- package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
- package/lib/types/client/config/guard-view.d.ts +83 -0
- package/lib/types/client/config/guard-view.d.ts.map +1 -0
- package/lib/types/client/config/index.d.ts +20 -0
- package/lib/types/client/config/index.d.ts.map +1 -0
- package/lib/types/client/config/maestro-mark.d.ts +29 -0
- package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
- package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
- package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
- package/lib/types/client/index.d.ts +16 -0
- package/lib/types/client/index.d.ts.map +1 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
- package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/SyncPanel.d.ts +12 -0
- package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
- package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
- package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
- package/lib/types/client/sync/index.d.ts +10 -0
- package/lib/types/client/sync/index.d.ts.map +1 -0
- package/lib/types/client/sync/ui.d.ts +79 -0
- package/lib/types/client/sync/ui.d.ts.map +1 -0
- package/lib/types/client/sync/use-backup.d.ts +50 -0
- package/lib/types/client/sync/use-backup.d.ts.map +1 -0
- package/lib/types/client/sync/use-sync.d.ts +88 -0
- package/lib/types/client/sync/use-sync.d.ts.map +1 -0
- package/package.json +89 -0
- package/skills/dsh-safe-restart/SKILL.md +206 -0
- package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
- package/src/client/auto-reload.ts +104 -0
- package/src/client/config/MaestroSettings.tsx +892 -0
- package/src/client/config/components/BrandMark.tsx +94 -0
- package/src/client/config/guard-view.ts +187 -0
- package/src/client/config/index.tsx +109 -0
- package/src/client/config/maestro-mark.ts +37 -0
- package/src/client/config/settings-nav-icon.ts +68 -0
- package/src/client/index.tsx +33 -0
- package/src/client/sync/R2SyncPanel.tsx +260 -0
- package/src/client/sync/SyncPanel.tsx +422 -0
- package/src/client/sync/confirm-dialog.tsx +202 -0
- package/src/client/sync/index.tsx +336 -0
- package/src/client/sync/ui.tsx +313 -0
- package/src/client/sync/use-backup.ts +207 -0
- package/src/client/sync/use-sync.ts +502 -0
- package/src/host/bin.ts +3 -0
- package/src/host/boot-guard.ts +76 -0
- package/src/host/boot-lock.ts +155 -0
- package/src/host/cli.ts +288 -0
- package/src/host/config/index.ts +78 -0
- package/src/host/config/service.ts +40 -0
- package/src/host/config.ts +18 -0
- package/src/host/daemon-freshness.ts +143 -0
- package/src/host/debug-agent.ts +145 -0
- package/src/host/dsh-session.ts +56 -0
- package/src/host/dsh-skill.d.ts +44 -0
- package/src/host/guard/augment.d.ts +33 -0
- package/src/host/guard/config.ts +244 -0
- package/src/host/guard/decide.ts +40 -0
- package/src/host/guard/full-scan-tool.ts +61 -0
- package/src/host/guard/index.ts +281 -0
- package/src/host/guard/journal.ts +440 -0
- package/src/host/guard/migrate.ts +41 -0
- package/src/host/guard/parse.ts +1150 -0
- package/src/host/guard/paths.ts +239 -0
- package/src/host/guard/permission-policy.ts +15 -0
- package/src/host/guard/redact.ts +64 -0
- package/src/host/guard/rules.ts +891 -0
- package/src/host/guard/status-tool.ts +229 -0
- package/src/host/guard/tiers.ts +2 -0
- package/src/host/guard/validators.ts +29 -0
- package/src/host/health-poller.ts +446 -0
- package/src/host/index.ts +7 -0
- package/src/host/intents.ts +67 -0
- package/src/host/notifier.ts +71 -0
- package/src/host/paths.ts +70 -0
- package/src/host/plugin.ts +1097 -0
- package/src/host/preset.ts +170 -0
- package/src/host/report.ts +71 -0
- package/src/host/restart-exec.ts +81 -0
- package/src/host/restart-guards.ts +150 -0
- package/src/host/restart-tool.ts +483 -0
- package/src/host/restart-web.ts +72 -0
- package/src/host/resume-log.ts +39 -0
- package/src/host/resume-tools.ts +385 -0
- package/src/host/resume.ts +204 -0
- package/src/host/scan.ts +61 -0
- package/src/host/self-kill-guard.ts +216 -0
- package/src/host/session-health.ts +236 -0
- package/src/host/session-log-file.ts +77 -0
- package/src/host/skill-provider.ts +69 -0
- package/src/host/snapshot.ts +337 -0
- package/src/host/source.ts +19 -0
- package/src/host/store/index.ts +348 -0
- package/src/host/store/legacy.ts +96 -0
- package/src/host/supervisor.ts +720 -0
- package/src/host/sync/backup-config.ts +159 -0
- package/src/host/sync/backup-service.ts +453 -0
- package/src/host/sync/bidirectional.ts +66 -0
- package/src/host/sync/cli.ts +539 -0
- package/src/host/sync/config.ts +119 -0
- package/src/host/sync/fingerprint.ts +83 -0
- package/src/host/sync/hashing.ts +58 -0
- package/src/host/sync/index.ts +737 -0
- package/src/host/sync/machine-id.ts +81 -0
- package/src/host/sync/merge.ts +102 -0
- package/src/host/sync/peer-host.ts +65 -0
- package/src/host/sync/process-runner.ts +177 -0
- package/src/host/sync/remote-agent.ts +213 -0
- package/src/host/sync/remote-cache.ts +68 -0
- package/src/host/sync/remote-manifest.ts +70 -0
- package/src/host/sync/s3-object-store.ts +144 -0
- package/src/host/sync/session-merge.ts +220 -0
- package/src/host/sync/session-plan.ts +237 -0
- package/src/host/sync/sigv4.ts +81 -0
- package/src/host/sync/snapshot.ts +162 -0
- package/src/host/sync/ssh-mux.ts +56 -0
- package/src/host/sync/sync-plan.ts +366 -0
- package/src/host/sync/sync-service.ts +855 -0
- package/src/host/sync/sync-types.ts +102 -0
- package/src/host/sync/transport.ts +261 -0
- package/src/host/sync/tunnel-restore.ts +160 -0
- package/src/host/sync/validation.ts +91 -0
- package/src/host/tool-view.ts +98 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session Zstandard line union. DSH session artifacts require the first
|
|
3
|
+
* checksummed Zstandard frame to contain exactly their JSONL header line.
|
|
4
|
+
* Binary-safe: .jsonl.zstd is staged and merged only through validated Zstd artifact API.
|
|
5
|
+
* Zstd bytes remain Buffer and are never converted to UTF-8 string; only decompressed
|
|
6
|
+
* plaintext is stringified for line union. The standalone checksummed header frame is preserved.
|
|
7
|
+
*/
|
|
8
|
+
import { copyFile, open, readFile, rename, unlink } from 'node:fs/promises';
|
|
9
|
+
import { existsSync } from 'node:fs';
|
|
10
|
+
import { randomBytes } from 'node:crypto';
|
|
11
|
+
import { dirname } from 'node:path';
|
|
12
|
+
import { constants, zstdCompress, zstdDecompress } from 'node:zlib';
|
|
13
|
+
import { promisify } from 'node:util';
|
|
14
|
+
const ZSTD_MAGIC = 0xFD2FB528;
|
|
15
|
+
const compressZstd = promisify(zstdCompress);
|
|
16
|
+
const decompressZstd = promisify(zstdDecompress);
|
|
17
|
+
const ZSTD_CHECKSUM_OPTIONS = {
|
|
18
|
+
params: { [constants.ZSTD_c_checksumFlag]: 1 },
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Union JSONL lines (or any line-delimited text) by exact line equality.
|
|
22
|
+
* Preserves local order then appends remote-only lines.
|
|
23
|
+
* Ensures trailing newline when result is non-empty.
|
|
24
|
+
*/
|
|
25
|
+
export function mergeZstdLines(localText, remoteText) {
|
|
26
|
+
const localLines = String(localText ?? '')
|
|
27
|
+
.split('\n')
|
|
28
|
+
.filter((line) => line.length > 0);
|
|
29
|
+
const remoteLines = String(remoteText ?? '')
|
|
30
|
+
.split('\n')
|
|
31
|
+
.filter((line) => line.length > 0);
|
|
32
|
+
const seen = new Set(localLines);
|
|
33
|
+
const mergedArr = [...localLines];
|
|
34
|
+
let added = 0;
|
|
35
|
+
for (const line of remoteLines) {
|
|
36
|
+
if (!seen.has(line)) {
|
|
37
|
+
seen.add(line);
|
|
38
|
+
mergedArr.push(line);
|
|
39
|
+
added++;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const merged = mergedArr.length > 0 ? mergedArr.join('\n') + '\n' : '';
|
|
43
|
+
return { merged, added };
|
|
44
|
+
}
|
|
45
|
+
/** Locate complete normal Zstandard frames in a concatenated DSH artifact. */
|
|
46
|
+
function scanZstdFrames(source) {
|
|
47
|
+
const frames = [];
|
|
48
|
+
let offset = 0;
|
|
49
|
+
while (offset < source.length) {
|
|
50
|
+
const start = offset;
|
|
51
|
+
if (source.length - offset < 5 || source.readUInt32LE(offset) !== ZSTD_MAGIC) {
|
|
52
|
+
throw new Error('corrupt Zstandard session artifact');
|
|
53
|
+
}
|
|
54
|
+
offset += 4;
|
|
55
|
+
const descriptor = source.readUInt8(offset++);
|
|
56
|
+
if ((descriptor & 0x18) !== 0)
|
|
57
|
+
throw new Error('corrupt Zstandard frame descriptor');
|
|
58
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
59
|
+
const singleSegment = (descriptor & 0x20) !== 0;
|
|
60
|
+
const dictionaryFlag = descriptor & 0x03;
|
|
61
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
62
|
+
const contentSizeBytes = contentSizeFlag === 0
|
|
63
|
+
? (singleSegment ? 1 : 0)
|
|
64
|
+
: 1 << contentSizeFlag;
|
|
65
|
+
const frameHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
66
|
+
if (source.length - offset < frameHeaderBytes)
|
|
67
|
+
throw new Error('incomplete Zstandard frame header');
|
|
68
|
+
offset += frameHeaderBytes;
|
|
69
|
+
for (;;) {
|
|
70
|
+
if (source.length - offset < 3)
|
|
71
|
+
throw new Error('incomplete Zstandard frame block');
|
|
72
|
+
const blockHeader = source.readUIntLE(offset, 3);
|
|
73
|
+
offset += 3;
|
|
74
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
75
|
+
const blockType = (blockHeader >>> 1) & 0x03;
|
|
76
|
+
const blockSize = blockHeader >>> 3;
|
|
77
|
+
if (blockType === 3)
|
|
78
|
+
throw new Error('corrupt Zstandard frame block');
|
|
79
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
80
|
+
if (source.length - offset < payloadBytes)
|
|
81
|
+
throw new Error('incomplete Zstandard frame payload');
|
|
82
|
+
offset += payloadBytes;
|
|
83
|
+
if (lastBlock)
|
|
84
|
+
break;
|
|
85
|
+
}
|
|
86
|
+
if ((descriptor & 0x04) !== 0) {
|
|
87
|
+
if (source.length - offset < 4)
|
|
88
|
+
throw new Error('incomplete Zstandard frame checksum');
|
|
89
|
+
offset += 4;
|
|
90
|
+
}
|
|
91
|
+
frames.push({ start, end: offset });
|
|
92
|
+
}
|
|
93
|
+
return frames;
|
|
94
|
+
}
|
|
95
|
+
function parseSessionHeader(header, label) {
|
|
96
|
+
if (header.length === 0 || header.indexOf(0x0A) !== header.length - 1) {
|
|
97
|
+
throw new Error(`${label} session artifact has no standalone header frame`);
|
|
98
|
+
}
|
|
99
|
+
const line = header.subarray(0, -1).toString('utf8');
|
|
100
|
+
let value;
|
|
101
|
+
try {
|
|
102
|
+
value = JSON.parse(line);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
106
|
+
}
|
|
107
|
+
const record = value;
|
|
108
|
+
const hasValidInteger = (field) => {
|
|
109
|
+
const value = record?.[field];
|
|
110
|
+
return typeof value === 'number'
|
|
111
|
+
&& Number.isSafeInteger(value)
|
|
112
|
+
&& value >= 0
|
|
113
|
+
&& !Object.is(value, -0);
|
|
114
|
+
};
|
|
115
|
+
if (record === null
|
|
116
|
+
|| typeof record !== 'object'
|
|
117
|
+
|| record.type !== 'session'
|
|
118
|
+
|| typeof record.version !== 'number'
|
|
119
|
+
|| typeof record.id !== 'string'
|
|
120
|
+
|| !hasValidInteger('createdAt')
|
|
121
|
+
|| !hasValidInteger('delegationDepth')
|
|
122
|
+
|| (record.origin !== undefined && record.origin !== 'subagent')
|
|
123
|
+
|| (record.agentPreset !== undefined && typeof record.agentPreset !== 'string')) {
|
|
124
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
125
|
+
}
|
|
126
|
+
return line;
|
|
127
|
+
}
|
|
128
|
+
async function readSessionArtifact(filePath, label) {
|
|
129
|
+
if (!existsSync(filePath))
|
|
130
|
+
throw new Error(`${label} session artifact does not exist`);
|
|
131
|
+
const source = await readFile(filePath);
|
|
132
|
+
const frames = scanZstdFrames(source);
|
|
133
|
+
if (frames.length === 0)
|
|
134
|
+
throw new Error(`${label} session artifact has no Zstandard frames`);
|
|
135
|
+
const headerBytes = await decompressZstd(source.subarray(frames[0].start, frames[0].end));
|
|
136
|
+
const header = parseSessionHeader(headerBytes, label);
|
|
137
|
+
const plaintext = await Promise.all(frames.map(async ({ start, end }) => decompressZstd(source.subarray(start, end))));
|
|
138
|
+
return { header, text: Buffer.concat(plaintext).toString('utf8') };
|
|
139
|
+
}
|
|
140
|
+
async function writeAtomically(filePath, content) {
|
|
141
|
+
const temporaryPath = `${filePath}.${randomBytes(12).toString('hex')}.tmp`;
|
|
142
|
+
const handle = await open(temporaryPath, 'wx', 0o600);
|
|
143
|
+
try {
|
|
144
|
+
await handle.writeFile(content);
|
|
145
|
+
await handle.sync();
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
await handle.close();
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
await rename(temporaryPath, filePath);
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
await unlink(temporaryPath).catch(() => undefined);
|
|
155
|
+
throw error;
|
|
156
|
+
}
|
|
157
|
+
const directory = await open(dirname(filePath), 'r');
|
|
158
|
+
try {
|
|
159
|
+
await directory.sync();
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
await directory.close();
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* Merge two valid DSH Zstandard session artifacts into the local artifact.
|
|
167
|
+
* The original local bytes are copied to a timestamped backup before the
|
|
168
|
+
* atomic publish. Invalid, missing, plaintext, or mismatched input never
|
|
169
|
+
* replaces the local file.
|
|
170
|
+
*/
|
|
171
|
+
export async function mergeZstdFiles(localPath, remotePath) {
|
|
172
|
+
const local = await readSessionArtifact(localPath, 'local');
|
|
173
|
+
const remote = await readSessionArtifact(remotePath, 'remote');
|
|
174
|
+
if (local.header !== remote.header) {
|
|
175
|
+
throw new Error('cannot merge session artifacts with different headers');
|
|
176
|
+
}
|
|
177
|
+
const { merged, added } = mergeZstdLines(local.text, remote.text);
|
|
178
|
+
if (added === 0)
|
|
179
|
+
return { added: 0 };
|
|
180
|
+
if (!merged.startsWith(local.header + '\n')) {
|
|
181
|
+
throw new Error('merged session artifact lost its header');
|
|
182
|
+
}
|
|
183
|
+
const body = merged.slice(local.header.length + 1);
|
|
184
|
+
const frames = [await compressZstd(local.header + '\n', ZSTD_CHECKSUM_OPTIONS)];
|
|
185
|
+
if (body.length > 0)
|
|
186
|
+
frames.push(await compressZstd(body, ZSTD_CHECKSUM_OPTIONS));
|
|
187
|
+
const backupPath = `${localPath}.bak.${Date.now()}.${randomBytes(6).toString('hex')}`;
|
|
188
|
+
await copyFile(localPath, backupPath);
|
|
189
|
+
await writeAtomically(localPath, Buffer.concat(frames));
|
|
190
|
+
return { added };
|
|
191
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export interface SessionIdentity {
|
|
2
|
+
/** decompressed header line Buffer (UTF-8 without trailing newline) */
|
|
3
|
+
header: Buffer;
|
|
4
|
+
sessionId: string;
|
|
5
|
+
cwd: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Validates Zstd header frame and extracts identity.
|
|
9
|
+
* - Validates Zstd magic and frame structure via checksum-aware decompression.
|
|
10
|
+
* - Decompresses only the first frame (standalone header) and validates JSONL header.
|
|
11
|
+
* - Never converts raw Zstd bytes to UTF-8 string.
|
|
12
|
+
*/
|
|
13
|
+
export declare function parseSessionIdentity(buffer: Buffer): SessionIdentity;
|
|
14
|
+
/**
|
|
15
|
+
* Compare header identity, not just path.
|
|
16
|
+
* Returns true if both buffers represent the same session (same id, cwd, and header line).
|
|
17
|
+
*/
|
|
18
|
+
export declare function isSameSession(a: Buffer, b: Buffer): boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Merge two valid session buffers via binary path and return merged Buffer with added count.
|
|
21
|
+
* - Validates both buffers via validated Zstd artifact API (checksum, header frame).
|
|
22
|
+
* - Preserves DSH standalone checksummed Zstd header frame (first frame is header alone).
|
|
23
|
+
* - Never converts Zstd bytes to UTF-8 string; only decompressed plaintext is stringified for line union.
|
|
24
|
+
* - Throws if headers differ (conflict) or either buffer is invalid/truncated.
|
|
25
|
+
*/
|
|
26
|
+
export declare function mergeSessionBuffers(local: Buffer, remote: Buffer): {
|
|
27
|
+
merged: Buffer;
|
|
28
|
+
added: number;
|
|
29
|
+
};
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Binary-safe session planning for DSH Zstd artifacts.
|
|
3
|
+
* Bytes remain bytes: .jsonl.zstd is staged and merged only through validated Zstd artifact API.
|
|
4
|
+
* Session handling is Buffer/path-only and preserves DSH standalone checksummed Zstd header frame.
|
|
5
|
+
*/
|
|
6
|
+
import { constants, zstdCompressSync, zstdDecompressSync } from 'node:zlib';
|
|
7
|
+
const ZSTD_MAGIC = 0xFD2FB528;
|
|
8
|
+
const ZSTD_CHECKSUM_OPTIONS = {
|
|
9
|
+
params: { [constants.ZSTD_c_checksumFlag]: 1 },
|
|
10
|
+
};
|
|
11
|
+
/** Locate complete Zstd frames, throwing on corrupt/truncated structure. Never converts Zstd bytes to string. */
|
|
12
|
+
function scanZstdFrames(source) {
|
|
13
|
+
const frames = [];
|
|
14
|
+
let offset = 0;
|
|
15
|
+
while (offset < source.length) {
|
|
16
|
+
const start = offset;
|
|
17
|
+
if (source.length - offset < 4 || source.readUInt32LE(offset) !== ZSTD_MAGIC) {
|
|
18
|
+
throw new Error('corrupt Zstandard session artifact');
|
|
19
|
+
}
|
|
20
|
+
if (source.length - offset < 5) {
|
|
21
|
+
throw new Error('incomplete Zstandard frame header');
|
|
22
|
+
}
|
|
23
|
+
offset += 4;
|
|
24
|
+
const descriptor = source.readUInt8(offset++);
|
|
25
|
+
if ((descriptor & 0x18) !== 0)
|
|
26
|
+
throw new Error('corrupt Zstandard frame descriptor');
|
|
27
|
+
const contentSizeFlag = descriptor >>> 6;
|
|
28
|
+
const singleSegment = (descriptor & 0x20) !== 0;
|
|
29
|
+
const dictionaryFlag = descriptor & 0x03;
|
|
30
|
+
const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag;
|
|
31
|
+
const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag;
|
|
32
|
+
const frameHeaderBytes = (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes;
|
|
33
|
+
if (source.length - offset < frameHeaderBytes)
|
|
34
|
+
throw new Error('incomplete Zstandard frame header');
|
|
35
|
+
offset += frameHeaderBytes;
|
|
36
|
+
for (;;) {
|
|
37
|
+
if (source.length - offset < 3)
|
|
38
|
+
throw new Error('incomplete Zstandard frame block');
|
|
39
|
+
const blockHeader = source.readUIntLE(offset, 3);
|
|
40
|
+
offset += 3;
|
|
41
|
+
const lastBlock = (blockHeader & 1) !== 0;
|
|
42
|
+
const blockType = (blockHeader >>> 1) & 0x03;
|
|
43
|
+
const blockSize = blockHeader >>> 3;
|
|
44
|
+
if (blockType === 3)
|
|
45
|
+
throw new Error('corrupt Zstandard frame block');
|
|
46
|
+
const payloadBytes = blockType === 1 ? 1 : blockSize;
|
|
47
|
+
if (source.length - offset < payloadBytes)
|
|
48
|
+
throw new Error('incomplete Zstandard frame payload');
|
|
49
|
+
offset += payloadBytes;
|
|
50
|
+
if (lastBlock)
|
|
51
|
+
break;
|
|
52
|
+
}
|
|
53
|
+
if ((descriptor & 0x04) !== 0) {
|
|
54
|
+
if (source.length - offset < 4)
|
|
55
|
+
throw new Error('incomplete Zstandard frame checksum');
|
|
56
|
+
offset += 4;
|
|
57
|
+
}
|
|
58
|
+
frames.push({ start, end: offset });
|
|
59
|
+
}
|
|
60
|
+
return frames;
|
|
61
|
+
}
|
|
62
|
+
function parseHeaderLine(headerBytes, label) {
|
|
63
|
+
if (headerBytes.length === 0 || headerBytes[headerBytes.length - 1] !== 0x0A) {
|
|
64
|
+
throw new Error(`${label} session artifact has no standalone header frame`);
|
|
65
|
+
}
|
|
66
|
+
if (headerBytes.indexOf(0x0A) !== headerBytes.length - 1) {
|
|
67
|
+
throw new Error(`${label} session artifact header frame not standalone`);
|
|
68
|
+
}
|
|
69
|
+
const line = headerBytes.subarray(0, -1).toString('utf8');
|
|
70
|
+
let value;
|
|
71
|
+
try {
|
|
72
|
+
value = JSON.parse(line);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
76
|
+
}
|
|
77
|
+
const record = value;
|
|
78
|
+
const hasValidInteger = (field) => {
|
|
79
|
+
const v = record?.[field];
|
|
80
|
+
return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0 && !Object.is(v, -0);
|
|
81
|
+
};
|
|
82
|
+
if (record === null ||
|
|
83
|
+
typeof record !== 'object' ||
|
|
84
|
+
record.type !== 'session' ||
|
|
85
|
+
typeof record.version !== 'number' ||
|
|
86
|
+
typeof record.id !== 'string' ||
|
|
87
|
+
!hasValidInteger('createdAt') ||
|
|
88
|
+
!hasValidInteger('delegationDepth') ||
|
|
89
|
+
(record.origin !== undefined && record.origin !== 'subagent') ||
|
|
90
|
+
(record.agentPreset !== undefined && typeof record.agentPreset !== 'string')) {
|
|
91
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
92
|
+
}
|
|
93
|
+
if (record.cwd !== undefined && typeof record.cwd !== 'string') {
|
|
94
|
+
throw new Error(`${label} session artifact has an invalid session header`);
|
|
95
|
+
}
|
|
96
|
+
return { line, record: record };
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Validates Zstd header frame and extracts identity.
|
|
100
|
+
* - Validates Zstd magic and frame structure via checksum-aware decompression.
|
|
101
|
+
* - Decompresses only the first frame (standalone header) and validates JSONL header.
|
|
102
|
+
* - Never converts raw Zstd bytes to UTF-8 string.
|
|
103
|
+
*/
|
|
104
|
+
export function parseSessionIdentity(buffer) {
|
|
105
|
+
if (!Buffer.isBuffer(buffer))
|
|
106
|
+
throw new Error('session buffer must be Buffer');
|
|
107
|
+
if (buffer.length === 0)
|
|
108
|
+
throw new Error('empty session buffer');
|
|
109
|
+
if (buffer.length < 4)
|
|
110
|
+
throw new Error('corrupt Zstandard session artifact');
|
|
111
|
+
if (buffer.readUInt32LE(0) !== ZSTD_MAGIC)
|
|
112
|
+
throw new Error('corrupt Zstandard session artifact');
|
|
113
|
+
const frames = scanZstdFrames(buffer);
|
|
114
|
+
if (frames.length === 0)
|
|
115
|
+
throw new Error('session artifact has no Zstandard frames');
|
|
116
|
+
let headerBytes;
|
|
117
|
+
try {
|
|
118
|
+
headerBytes = zstdDecompressSync(buffer.subarray(frames[0].start, frames[0].end));
|
|
119
|
+
}
|
|
120
|
+
catch (e) {
|
|
121
|
+
throw new Error(`invalid Zstd header frame: ${e?.message ?? String(e)}`);
|
|
122
|
+
}
|
|
123
|
+
const { line, record } = parseHeaderLine(headerBytes, 'session');
|
|
124
|
+
const sessionId = String(record.id);
|
|
125
|
+
const cwd = typeof record.cwd === 'string' ? String(record.cwd) : '';
|
|
126
|
+
const header = Buffer.from(line, 'utf8');
|
|
127
|
+
return { header, sessionId, cwd };
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Compare header identity, not just path.
|
|
131
|
+
* Returns true if both buffers represent the same session (same id, cwd, and header line).
|
|
132
|
+
*/
|
|
133
|
+
export function isSameSession(a, b) {
|
|
134
|
+
try {
|
|
135
|
+
const idA = parseSessionIdentity(a);
|
|
136
|
+
const idB = parseSessionIdentity(b);
|
|
137
|
+
return idA.sessionId === idB.sessionId && idA.cwd === idB.cwd && idA.header.equals(idB.header);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function mergePlaintextLines(localText, remoteText) {
|
|
144
|
+
const localLines = String(localText ?? '')
|
|
145
|
+
.split('\n')
|
|
146
|
+
.filter((line) => line.length > 0);
|
|
147
|
+
const remoteLines = String(remoteText ?? '')
|
|
148
|
+
.split('\n')
|
|
149
|
+
.filter((line) => line.length > 0);
|
|
150
|
+
const seen = new Set(localLines);
|
|
151
|
+
const mergedArr = [...localLines];
|
|
152
|
+
let added = 0;
|
|
153
|
+
for (const line of remoteLines) {
|
|
154
|
+
if (!seen.has(line)) {
|
|
155
|
+
seen.add(line);
|
|
156
|
+
mergedArr.push(line);
|
|
157
|
+
added++;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
const merged = mergedArr.length > 0 ? mergedArr.join('\n') + '\n' : '';
|
|
161
|
+
return { merged, added };
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Merge two valid session buffers via binary path and return merged Buffer with added count.
|
|
165
|
+
* - Validates both buffers via validated Zstd artifact API (checksum, header frame).
|
|
166
|
+
* - Preserves DSH standalone checksummed Zstd header frame (first frame is header alone).
|
|
167
|
+
* - Never converts Zstd bytes to UTF-8 string; only decompressed plaintext is stringified for line union.
|
|
168
|
+
* - Throws if headers differ (conflict) or either buffer is invalid/truncated.
|
|
169
|
+
*/
|
|
170
|
+
export function mergeSessionBuffers(local, remote) {
|
|
171
|
+
const localId = parseSessionIdentity(local);
|
|
172
|
+
const remoteId = parseSessionIdentity(remote);
|
|
173
|
+
if (localId.sessionId !== remoteId.sessionId || localId.cwd !== remoteId.cwd || !localId.header.equals(remoteId.header)) {
|
|
174
|
+
throw new Error('cannot merge session buffers with different headers');
|
|
175
|
+
}
|
|
176
|
+
const localFrames = scanZstdFrames(local);
|
|
177
|
+
const remoteFrames = scanZstdFrames(remote);
|
|
178
|
+
const localPlainBufs = [];
|
|
179
|
+
for (const f of localFrames) {
|
|
180
|
+
try {
|
|
181
|
+
localPlainBufs.push(zstdDecompressSync(local.subarray(f.start, f.end)));
|
|
182
|
+
}
|
|
183
|
+
catch (e) {
|
|
184
|
+
throw new Error(`local session decompress failed: ${e?.message ?? String(e)}`);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const remotePlainBufs = [];
|
|
188
|
+
for (const f of remoteFrames) {
|
|
189
|
+
try {
|
|
190
|
+
remotePlainBufs.push(zstdDecompressSync(remote.subarray(f.start, f.end)));
|
|
191
|
+
}
|
|
192
|
+
catch (e) {
|
|
193
|
+
throw new Error(`remote session decompress failed: ${e?.message ?? String(e)}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const localText = Buffer.concat(localPlainBufs).toString('utf8');
|
|
197
|
+
const remoteText = Buffer.concat(remotePlainBufs).toString('utf8');
|
|
198
|
+
const { merged, added } = mergePlaintextLines(localText, remoteText);
|
|
199
|
+
if (added === 0) {
|
|
200
|
+
return { merged: local, added: 0 };
|
|
201
|
+
}
|
|
202
|
+
const headerLine = localId.header.toString('utf8');
|
|
203
|
+
if (!merged.startsWith(headerLine + '\n')) {
|
|
204
|
+
throw new Error('merged session artifact lost its header');
|
|
205
|
+
}
|
|
206
|
+
const body = merged.slice(headerLine.length + 1);
|
|
207
|
+
const frames = [zstdCompressSync(headerLine + '\n', ZSTD_CHECKSUM_OPTIONS)];
|
|
208
|
+
if (body.length > 0) {
|
|
209
|
+
frames.push(zstdCompressSync(body, ZSTD_CHECKSUM_OPTIONS));
|
|
210
|
+
}
|
|
211
|
+
const mergedBuf = Buffer.concat(frames);
|
|
212
|
+
return { merged: mergedBuf, added };
|
|
213
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export declare function sha256Hex(data: string | Buffer): string;
|
|
2
|
+
export interface SignRequestOpts {
|
|
3
|
+
method: string;
|
|
4
|
+
host: string;
|
|
5
|
+
path: string;
|
|
6
|
+
query?: string;
|
|
7
|
+
headers: Record<string, string>;
|
|
8
|
+
bodySha256: string;
|
|
9
|
+
region: string;
|
|
10
|
+
service: string;
|
|
11
|
+
accessKeyId: string;
|
|
12
|
+
secretAccessKey: string;
|
|
13
|
+
now: Date;
|
|
14
|
+
}
|
|
15
|
+
export interface SignedRequest {
|
|
16
|
+
authorization: string;
|
|
17
|
+
amzDate: string;
|
|
18
|
+
xAmzContentSha256: string;
|
|
19
|
+
}
|
|
20
|
+
export declare function signRequest(opts: SignRequestOpts): SignedRequest;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// src/host/sigv4.ts — AWS Signature Version 4 (S3 service) with zero deps.
|
|
2
|
+
//
|
|
3
|
+
// Computes the canonical request, the string-to-sign, and the signing key
|
|
4
|
+
// chain exactly per the AWS docs; the pinned known-answer test keeps it honest.
|
|
5
|
+
// ETag is a CAS/version token, never a content checksum — our content
|
|
6
|
+
// integrity lives in SHA-256 (blob keys + manifest metadata).
|
|
7
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
8
|
+
export function sha256Hex(data) {
|
|
9
|
+
return createHash('sha256').update(data).digest('hex');
|
|
10
|
+
}
|
|
11
|
+
function hmac(key, data) {
|
|
12
|
+
return createHmac('sha256', key).update(data).digest();
|
|
13
|
+
}
|
|
14
|
+
function isoDate(d) {
|
|
15
|
+
return d.toISOString().replace(/[-:]/g, '').replace(/\.\d{3}Z$/, 'Z'); // YYYYMMDDTHHMMSSZ
|
|
16
|
+
}
|
|
17
|
+
function scopeDate(d) {
|
|
18
|
+
return isoDate(d).slice(0, 8);
|
|
19
|
+
}
|
|
20
|
+
export function signRequest(opts) {
|
|
21
|
+
const amzDate = isoDate(opts.now);
|
|
22
|
+
const date = scopeDate(opts.now);
|
|
23
|
+
const raw = {
|
|
24
|
+
host: opts.host,
|
|
25
|
+
'x-amz-content-sha256': opts.bodySha256,
|
|
26
|
+
'x-amz-date': amzDate,
|
|
27
|
+
...opts.headers,
|
|
28
|
+
};
|
|
29
|
+
// Signed headers are lower-cased; look up through a normalized map so mixed
|
|
30
|
+
// case (e.g. 'Content-Length') never hits an undefined value.
|
|
31
|
+
const headers = {};
|
|
32
|
+
for (const [k, v] of Object.entries(raw))
|
|
33
|
+
headers[k.toLowerCase()] = v;
|
|
34
|
+
const signedKeys = Object.keys(headers).sort();
|
|
35
|
+
const canonicalHeaders = signedKeys.map((k) => `${k}:${headers[k].trim().replace(/\s+/g, ' ')}\n`).join('');
|
|
36
|
+
const canonicalQuery = (opts.query ?? '').split('&').filter(Boolean).sort().join('&');
|
|
37
|
+
const canonicalRequest = [
|
|
38
|
+
opts.method.toUpperCase(),
|
|
39
|
+
opts.path,
|
|
40
|
+
canonicalQuery,
|
|
41
|
+
canonicalHeaders,
|
|
42
|
+
signedKeys.join(';'),
|
|
43
|
+
opts.bodySha256,
|
|
44
|
+
].join('\n');
|
|
45
|
+
const scope = `${date}/${opts.region}/${opts.service}/aws4_request`;
|
|
46
|
+
const stringToSign = ['AWS4-HMAC-SHA256', amzDate, scope, sha256Hex(canonicalRequest)].join('\n');
|
|
47
|
+
const kDate = hmac(Buffer.from(`AWS4${opts.secretAccessKey}`, 'utf8'), date);
|
|
48
|
+
const kRegion = hmac(kDate, opts.region);
|
|
49
|
+
const kService = hmac(kRegion, opts.service);
|
|
50
|
+
const kSigning = hmac(kService, 'aws4_request');
|
|
51
|
+
const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex');
|
|
52
|
+
return {
|
|
53
|
+
authorization: `AWS4-HMAC-SHA256 Credential=${opts.accessKeyId}/${scope}, SignedHeaders=${signedKeys.join(';')}, Signature=${signature}`,
|
|
54
|
+
amzDate,
|
|
55
|
+
xAmzContentSha256: opts.bodySha256,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { FileSnapshot } from './sync-types.js';
|
|
2
|
+
export declare function hashBuffer(buf: Buffer): string;
|
|
3
|
+
export declare function kindForPath(p: string): FileSnapshot['kind'];
|
|
4
|
+
export declare function snapshotFile(validatedPath: string, content: Buffer): FileSnapshot;
|
|
5
|
+
/**
|
|
6
|
+
* Collect snapshots for all eligible files under root using the provided fs.
|
|
7
|
+
* - Walks recursively via fs.readdirSync/statSync/readFileSync when available.
|
|
8
|
+
* - Validates each discovered relative path via normalizeEligiblePath.
|
|
9
|
+
* - Hashes file bytes with SHA-256 and records kind.
|
|
10
|
+
* Returns sorted snapshots by path for determinism.
|
|
11
|
+
*/
|
|
12
|
+
export declare function collectSnapshots(root: string, fs: any): FileSnapshot[];
|
|
13
|
+
/**
|
|
14
|
+
* Snapshot a specific list of validated eligible paths under root.
|
|
15
|
+
* Useful for hashing staged remote files where we already know the manifest.
|
|
16
|
+
*/
|
|
17
|
+
export declare function snapshotPaths(root: string, paths: string[], fs: any): FileSnapshot[];
|
|
18
|
+
/**
|
|
19
|
+
* Snapshot from an in-memory map of path -> Buffer (useful for testing staged remote).
|
|
20
|
+
*/
|
|
21
|
+
export declare function snapshotFromMap(contents: Map<string, Buffer>): FileSnapshot[];
|