@lornatang/dsh-caveman 0.1.4 → 0.1.6
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/CHANGELOG.md +13 -0
- package/README.md +1 -1
- package/README.zh.md +1 -1
- package/lib/compression.js +14 -5
- package/lib/native.js +24 -4
- package/package.json +5 -1
- package/scripts/caveman-cli.mjs +30 -30
- package/scripts/learn-binary.mjs +82 -82
- package/scripts/learn-checksums.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.1.6 - 2026-11-19
|
|
4
|
+
|
|
5
|
+
- Compare endpoint host names instead of URL substrings when detecting provider hosts, so a crafted URL cannot satisfy a provider check by embedding a domain in its path (clears the js/incomplete-url-substring-sanitization findings).
|
|
6
|
+
- Override undici to 8.12.4 and @modelcontextprotocol/client to 2.4.0, clearing six Dependabot advisories.
|
|
7
|
+
- Keep the verified analyzer binaries attached to this release under the new version.
|
|
8
|
+
|
|
9
|
+
## 0.1.5 - 2026-11-19
|
|
10
|
+
|
|
11
|
+
- Cache the verified local runtime identity for one second per endpoint, so a tool call performs one health check instead of two while a runtime restart still invalidates sessions.
|
|
12
|
+
- Skip the second read-and-hash of a read tool input when the runtime response carries no ccr:// recovery context.
|
|
13
|
+
- Cache per-session surface manifests by content generation and node count, so unchanged surfaces are not re-hashed on every agent step.
|
|
14
|
+
- Keep the verified analyzer binaries attached to this release under the new version.
|
|
15
|
+
|
|
3
16
|
## 0.1.4 - 2026-11-19
|
|
4
17
|
|
|
5
18
|
- Restore the POSIX native-socket retry: a socket the runtime has not created yet is retried instead of disabling the call, while a replaced or foreign-owned path is still refused before any request is sent.
|
package/README.md
CHANGED
|
@@ -43,7 +43,7 @@ git clone https://github.com/Lornatang/dsh-caveman.git
|
|
|
43
43
|
cd dsh-caveman
|
|
44
44
|
npm ci
|
|
45
45
|
npm pack
|
|
46
|
-
dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.
|
|
46
|
+
dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.5.tgz
|
|
47
47
|
```
|
|
48
48
|
|
|
49
49
|
The `add` command composes the bundle into the profile. Its patches insert the `caveman` row, three Cavecrew presets, and their delegation tools. Restart DSH after `add` or `remove` so the profile reloads its composition.
|
package/README.zh.md
CHANGED
|
@@ -43,7 +43,7 @@ git clone https://github.com/Lornatang/dsh-caveman.git
|
|
|
43
43
|
cd dsh-caveman
|
|
44
44
|
npm ci
|
|
45
45
|
npm pack
|
|
46
|
-
dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.
|
|
46
|
+
dsh plugin --profile <name> add ./lornatang-dsh-caveman-0.1.5.tgz
|
|
47
47
|
```
|
|
48
48
|
|
|
49
49
|
`add` 命令把 bundle 组合进 profile。patch 会插入 `caveman` 行、三个 Cavecrew 预设及其委派工具。`add` 或 `remove` 后重启 DSH,使 profile 重新加载配置。
|
package/lib/compression.js
CHANGED
|
@@ -151,14 +151,23 @@ export function resolveOriginalResult(session, event) {
|
|
|
151
151
|
cache.set(item, current);
|
|
152
152
|
return current;
|
|
153
153
|
}
|
|
154
|
+
const manifests = new WeakMap();
|
|
154
155
|
function manifestFor(session) {
|
|
155
|
-
|
|
156
|
+
const generation = session.surface.contentGeneration;
|
|
157
|
+
const count = session.surface.nodes.length;
|
|
158
|
+
const cached = manifests.get(session);
|
|
159
|
+
if (cached && cached.generation === generation && cached.count === count)
|
|
160
|
+
return cached.value;
|
|
161
|
+
const entries = session.surface.nodes.map(seq => {
|
|
156
162
|
let event = session.eventAt(seq);
|
|
157
163
|
if (event.type === 'tool/result')
|
|
158
164
|
event = resolveOriginalResult(session, event);
|
|
159
165
|
const data = event.type === 'user/message' ? event.data : 'message' in event.data ? event.data.message : event.data;
|
|
160
166
|
return { id: `seq-${event.seq}`, sha256: createHash('sha256').update(JSON.stringify(data)).digest('hex') };
|
|
161
167
|
});
|
|
168
|
+
const value = { entries, bytes: Buffer.byteLength(JSON.stringify(entries), 'utf8') };
|
|
169
|
+
manifests.set(session, { generation, count, value });
|
|
170
|
+
return value;
|
|
162
171
|
}
|
|
163
172
|
function surfaceMatchesManifest(session, manifest) {
|
|
164
173
|
if (session.surface.nodes.length !== manifest.length)
|
|
@@ -372,7 +381,7 @@ export function registerCompression(ctx, endpoint, automatic) {
|
|
|
372
381
|
}
|
|
373
382
|
const manifest = manifestFor(session);
|
|
374
383
|
const maxSegments = capabilities.limits.max_segments ?? 256;
|
|
375
|
-
const byteBudget = Math.max(0, capabilities.limits.request_bytes -
|
|
384
|
+
const byteBudget = Math.max(0, capabilities.limits.request_bytes - manifest.bytes - 16_384);
|
|
376
385
|
const prepared = eligible.map(candidate => {
|
|
377
386
|
const sourceId = `seq-${resolveOriginalResult(session, candidate.event).seq}`;
|
|
378
387
|
const segments = candidate.blocks.map(block => ({
|
|
@@ -385,7 +394,7 @@ export function registerCompression(ctx, endpoint, automatic) {
|
|
|
385
394
|
try {
|
|
386
395
|
for (const group of batches) {
|
|
387
396
|
signal.throwIfAborted();
|
|
388
|
-
if (!surfaceMatchesManifest(session, manifest)) {
|
|
397
|
+
if (!surfaceMatchesManifest(session, manifest.entries)) {
|
|
389
398
|
restore(session);
|
|
390
399
|
return decision;
|
|
391
400
|
}
|
|
@@ -394,13 +403,13 @@ export function registerCompression(ctx, endpoint, automatic) {
|
|
|
394
403
|
continue;
|
|
395
404
|
const segments = candidates.flatMap(candidate => candidate.segments);
|
|
396
405
|
const optimization = await runtime.optimize({
|
|
397
|
-
scope, binding, adapter: ADAPTER, manifest,
|
|
406
|
+
scope, binding, adapter: ADAPTER, manifest: manifest.entries,
|
|
398
407
|
candidates: segments,
|
|
399
408
|
model: { provider: modelSelection.provider, id: modelSelection.model, protocol: 'dsh' },
|
|
400
409
|
recoveryOverheadText: JSON.stringify(published), signal,
|
|
401
410
|
});
|
|
402
411
|
signal.throwIfAborted();
|
|
403
|
-
if (!surfaceMatchesManifest(session, manifest) || ctx.tools.get(tool.name, agent, toolSet) !== tool) {
|
|
412
|
+
if (!surfaceMatchesManifest(session, manifest.entries) || ctx.tools.get(tool.name, agent, toolSet) !== tool) {
|
|
404
413
|
restore(session);
|
|
405
414
|
return decision;
|
|
406
415
|
}
|
package/lib/native.js
CHANGED
|
@@ -204,15 +204,32 @@ async function inputState(ctx, cwd, input, signal) {
|
|
|
204
204
|
return undefined;
|
|
205
205
|
}
|
|
206
206
|
}
|
|
207
|
+
const RUNTIME_VERIFICATION_TTL_MS = 1_000;
|
|
208
|
+
const verifiedInstances = new Map();
|
|
207
209
|
async function runtimeInstance(endpoint, home, signal) {
|
|
208
|
-
|
|
210
|
+
signal?.throwIfAborted();
|
|
211
|
+
const key = `${endpoint}\u0000${home}`;
|
|
212
|
+
const cached = verifiedInstances.get(key);
|
|
213
|
+
if (cached && cached.expires > Date.now())
|
|
214
|
+
return cached.token;
|
|
215
|
+
if (!await verifiedRuntime(endpoint, process.env, signal)) {
|
|
216
|
+
verifiedInstances.delete(key);
|
|
209
217
|
return undefined;
|
|
218
|
+
}
|
|
210
219
|
try {
|
|
211
220
|
const port = Number(new URL(endpoint).port || 80);
|
|
212
221
|
const token = JSON.parse(readFileSync(join(home, 'run', `${port}.json`), 'utf8')).instance_token;
|
|
213
|
-
|
|
222
|
+
if (typeof token !== 'string' || !token) {
|
|
223
|
+
verifiedInstances.delete(key);
|
|
224
|
+
return undefined;
|
|
225
|
+
}
|
|
226
|
+
if (verifiedInstances.size >= 32)
|
|
227
|
+
verifiedInstances.delete(verifiedInstances.keys().next().value);
|
|
228
|
+
verifiedInstances.set(key, { token, expires: Date.now() + RUNTIME_VERIFICATION_TTL_MS });
|
|
229
|
+
return token;
|
|
214
230
|
}
|
|
215
231
|
catch {
|
|
232
|
+
verifiedInstances.delete(key);
|
|
216
233
|
return undefined;
|
|
217
234
|
}
|
|
218
235
|
}
|
|
@@ -346,16 +363,19 @@ export function registerNative(ctx, endpoint, policy) {
|
|
|
346
363
|
const before = await nativeCall(home, { ...base, event: { type: 'tool.before', timestamp_ms: Date.now() },
|
|
347
364
|
tool: { name: exec.name, input: exec.arguments, ...(beforeState ? { input_state: beforeState } : {}) } }, exec.signal);
|
|
348
365
|
const result = await next();
|
|
366
|
+
const recoveryContext = before?.context?.includes('ccr://') ?? false;
|
|
349
367
|
let afterState;
|
|
350
368
|
if (!exec.signal.aborted && await runtimeInstance(endpoint, home, exec.signal) === state.instance) {
|
|
351
|
-
|
|
369
|
+
// The comparison only gates a ccr:// reminder, so skip the second full
|
|
370
|
+
// read-and-hash when the before response carries no recovery context.
|
|
371
|
+
afterState = exec.name === 'read' && recoveryContext ? await inputState(ctx, state.session.cwd, exec.arguments, exec.signal) : undefined;
|
|
352
372
|
const textOnly = result.content.every(block => block.type === 'text') && result.content.reduce((sum, block) => sum + (block.type === 'text' ? Buffer.byteLength(block.text, 'utf8') : 0), 0) <= 1_500_000;
|
|
353
373
|
const content = textOnly ? result.content.map(block => block.type === 'text' ? block.text : '').join('\n') : '';
|
|
354
374
|
await nativeCall(home, { ...base, event: { type: result.isError ? 'tool.failure' : 'tool.after', timestamp_ms: Date.now() },
|
|
355
375
|
tool: { name: exec.name, input: exec.arguments, ...(afterState ? { input_state: afterState } : {}), ...(content ? { output: Buffer.from(content).toString('base64') } : {}) } }, exec.signal);
|
|
356
376
|
}
|
|
357
377
|
const canRecover = exec.toolSet && ctx.tools.get('mcp__caveman__caveman_retrieve', exec.agent, exec.toolSet);
|
|
358
|
-
if (!policy.core || state.specialized || !before?.context || (
|
|
378
|
+
if (!policy.core || state.specialized || !before?.context || (recoveryContext && (!canRecover || !beforeState || beforeState !== afterState)) || exec.signal.aborted)
|
|
359
379
|
return result;
|
|
360
380
|
const reminder = createUserMessage({ source: { kind: 'dsh-caveman-native', form: 'notice' }, content: [{ type: 'text', text: before.context }] });
|
|
361
381
|
return { ...result, additionalContexts: [...result.additionalContexts ?? [], reminder] };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lornatang/dsh-caveman",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"description": "Caveman integration for DeepSeek Harness.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -81,6 +81,10 @@
|
|
|
81
81
|
"undici": "^8.12.4",
|
|
82
82
|
"yaml": "^2.8.1"
|
|
83
83
|
},
|
|
84
|
+
"overrides": {
|
|
85
|
+
"undici": "$undici",
|
|
86
|
+
"@modelcontextprotocol/client": "^2.4.0"
|
|
87
|
+
},
|
|
84
88
|
"peerDependencies": {
|
|
85
89
|
"@deepseek-ai/cordis": "~4.1.0",
|
|
86
90
|
"@deepseek-ai/dsh-llm": "*"
|
package/scripts/caveman-cli.mjs
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { spawn } from 'node:child_process'
|
|
3
|
-
import { constants } from 'node:os'
|
|
4
|
-
import { createRequire } from 'node:module'
|
|
5
|
-
import { dirname, join } from 'node:path'
|
|
6
|
-
|
|
7
|
-
const require = createRequire(import.meta.url)
|
|
8
|
-
const cli = join(dirname(require.resolve('@caveman-ai/cli/package.json')), 'dist', 'index.js')
|
|
9
|
-
const args = process.argv.slice(2)
|
|
10
|
-
let learnBinary
|
|
11
|
-
if (args[0] === 'learn' && !['--help', '-h', 'help'].includes(args[1])) {
|
|
12
|
-
try { learnBinary = await (await import('./learn-binary.mjs')).resolveLearnBinary() }
|
|
13
|
-
catch (error) { console.error(`dsh-caveman: ${error.message}`); process.exit(1) }
|
|
14
|
-
}
|
|
15
|
-
const direct = learnBinary && args[1] === 'locate'
|
|
16
|
-
const child = spawn(direct ? learnBinary : process.execPath, direct ? args : [cli, ...args], {
|
|
17
|
-
stdio: 'inherit', windowsHide: true,
|
|
18
|
-
env: learnBinary ? { ...process.env, CAVEMAN_PROXY_BIN: learnBinary } : process.env,
|
|
19
|
-
})
|
|
20
|
-
|
|
21
|
-
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
22
|
-
process.on(signal, () => { if (child.exitCode === null && child.signalCode === null) child.kill(signal) })
|
|
23
|
-
}
|
|
24
|
-
child.once('error', error => {
|
|
25
|
-
console.error(`dsh-caveman: could not start the CLI: ${error.message}`)
|
|
26
|
-
process.exitCode = 1
|
|
27
|
-
})
|
|
28
|
-
child.once('exit', (code, signal) => {
|
|
29
|
-
process.exitCode = code ?? (signal ? 128 + (constants.signals[signal] ?? 0) : 1)
|
|
30
|
-
})
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { constants } from 'node:os'
|
|
4
|
+
import { createRequire } from 'node:module'
|
|
5
|
+
import { dirname, join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const require = createRequire(import.meta.url)
|
|
8
|
+
const cli = join(dirname(require.resolve('@caveman-ai/cli/package.json')), 'dist', 'index.js')
|
|
9
|
+
const args = process.argv.slice(2)
|
|
10
|
+
let learnBinary
|
|
11
|
+
if (args[0] === 'learn' && !['--help', '-h', 'help'].includes(args[1])) {
|
|
12
|
+
try { learnBinary = await (await import('./learn-binary.mjs')).resolveLearnBinary() }
|
|
13
|
+
catch (error) { console.error(`dsh-caveman: ${error.message}`); process.exit(1) }
|
|
14
|
+
}
|
|
15
|
+
const direct = learnBinary && args[1] === 'locate'
|
|
16
|
+
const child = spawn(direct ? learnBinary : process.execPath, direct ? args : [cli, ...args], {
|
|
17
|
+
stdio: 'inherit', windowsHide: true,
|
|
18
|
+
env: learnBinary ? { ...process.env, CAVEMAN_PROXY_BIN: learnBinary } : process.env,
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
for (const signal of ['SIGINT', 'SIGTERM']) {
|
|
22
|
+
process.on(signal, () => { if (child.exitCode === null && child.signalCode === null) child.kill(signal) })
|
|
23
|
+
}
|
|
24
|
+
child.once('error', error => {
|
|
25
|
+
console.error(`dsh-caveman: could not start the CLI: ${error.message}`)
|
|
26
|
+
process.exitCode = 1
|
|
27
|
+
})
|
|
28
|
+
child.once('exit', (code, signal) => {
|
|
29
|
+
process.exitCode = code ?? (signal ? 128 + (constants.signals[signal] ?? 0) : 1)
|
|
30
|
+
})
|
package/scripts/learn-binary.mjs
CHANGED
|
@@ -1,82 +1,82 @@
|
|
|
1
|
-
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
-
import { createReadStream } from 'node:fs'
|
|
3
|
-
import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises'
|
|
4
|
-
import { homedir } from 'node:os'
|
|
5
|
-
import { join } from 'node:path'
|
|
6
|
-
|
|
7
|
-
const MAX_BINARY_BYTES = 120 * 1024 * 1024
|
|
8
|
-
const manifestUrl = new URL('./learn-checksums.json', import.meta.url)
|
|
9
|
-
const packageUrl = new URL('../package.json', import.meta.url)
|
|
10
|
-
|
|
11
|
-
async function fileDigest(path) {
|
|
12
|
-
try {
|
|
13
|
-
const hash = createHash('sha256')
|
|
14
|
-
for await (const chunk of createReadStream(path)) hash.update(chunk)
|
|
15
|
-
return hash.digest('hex')
|
|
16
|
-
} catch (error) {
|
|
17
|
-
if (error?.code === 'ENOENT') return undefined
|
|
18
|
-
throw error
|
|
19
|
-
}
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Download and verify the executable once for the current platform and version. */
|
|
23
|
-
export async function resolveLearnBinary(options = {}) {
|
|
24
|
-
const { env = process.env, platform = process.platform, arch = process.arch } = options
|
|
25
|
-
if (env.DSH_CAVEMAN_LEARN_BINARY) return env.DSH_CAVEMAN_LEARN_BINARY
|
|
26
|
-
const manifest = options.manifest ?? JSON.parse(await readFile(manifestUrl, 'utf8'))
|
|
27
|
-
const version = JSON.parse(await readFile(packageUrl, 'utf8')).version
|
|
28
|
-
if (manifest.version !== version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) throw new Error('Invalid analyzer version manifest')
|
|
29
|
-
const os = { linux: 'linux', darwin: 'darwin', win32: 'win32' }[platform]
|
|
30
|
-
const cpu = { x64: 'amd64', arm64: 'arm64' }[arch]
|
|
31
|
-
const entry = manifest.binaries?.[`${platform}-${arch}`]
|
|
32
|
-
const expectedName = os && cpu ? `dsh-caveman-learn_${os}_${cpu}` : undefined
|
|
33
|
-
if (!expectedName || entry?.name !== expectedName || !/^[a-f0-9]{64}$/u.test(entry.sha256 ?? '')) {
|
|
34
|
-
throw new Error(`No verified analyzer is available for ${platform}/${arch}`)
|
|
35
|
-
}
|
|
36
|
-
const directory = join(options.cacheRoot ?? join(homedir(), '.dsh', 'cache', 'dsh-caveman', 'learn'), version)
|
|
37
|
-
const target = join(directory, `${expectedName}${platform === 'win32' ? '.exe' : ''}`)
|
|
38
|
-
if (await fileDigest(target) === entry.sha256) return target
|
|
39
|
-
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
40
|
-
const temporary = join(directory, `.${expectedName}.${randomBytes(12).toString('hex')}.tmp`)
|
|
41
|
-
let handle
|
|
42
|
-
let dispatcher
|
|
43
|
-
try {
|
|
44
|
-
const url = `https://github.com/Lornatang/dsh-caveman/releases/download/v${version}/${expectedName}`
|
|
45
|
-
let fetcher = options.fetcher ?? fetch
|
|
46
|
-
if (!options.fetcher && (env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY)) {
|
|
47
|
-
const { EnvHttpProxyAgent, fetch: proxyFetch } = await import('undici')
|
|
48
|
-
dispatcher = new EnvHttpProxyAgent({
|
|
49
|
-
httpProxy: env.http_proxy ?? env.HTTP_PROXY ?? '',
|
|
50
|
-
httpsProxy: env.https_proxy ?? env.HTTPS_PROXY ?? '',
|
|
51
|
-
noProxy: env.no_proxy ?? env.NO_PROXY ?? '',
|
|
52
|
-
})
|
|
53
|
-
fetcher = (input, init) => proxyFetch(input, { ...init, dispatcher })
|
|
54
|
-
}
|
|
55
|
-
const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) })
|
|
56
|
-
if (!response.ok || !response.body) throw new Error(`Analyzer download failed (HTTP ${response.status})`)
|
|
57
|
-
const advertised = Number(response.headers.get('content-length'))
|
|
58
|
-
if (advertised > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
|
|
59
|
-
handle = await open(temporary, 'wx', 0o700)
|
|
60
|
-
const hash = createHash('sha256')
|
|
61
|
-
let size = 0
|
|
62
|
-
for await (const chunk of response.body) {
|
|
63
|
-
size += chunk.length
|
|
64
|
-
if (size > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
|
|
65
|
-
hash.update(chunk)
|
|
66
|
-
await handle.writeFile(chunk)
|
|
67
|
-
}
|
|
68
|
-
await handle.close()
|
|
69
|
-
handle = undefined
|
|
70
|
-
if (hash.digest('hex') !== entry.sha256) throw new Error('Analyzer checksum mismatch')
|
|
71
|
-
await chmod(temporary, 0o700)
|
|
72
|
-
try { await rename(temporary, target) } catch (error) {
|
|
73
|
-
// Another invocation may have finished the same verified download.
|
|
74
|
-
if (await fileDigest(target) !== entry.sha256) throw error
|
|
75
|
-
}
|
|
76
|
-
return target
|
|
77
|
-
} finally {
|
|
78
|
-
await handle?.close().catch(() => {})
|
|
79
|
-
await rm(temporary, { force: true }).catch(() => {})
|
|
80
|
-
await dispatcher?.destroy().catch(() => {})
|
|
81
|
-
}
|
|
82
|
-
}
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
2
|
+
import { createReadStream } from 'node:fs'
|
|
3
|
+
import { chmod, mkdir, open, readFile, rename, rm } from 'node:fs/promises'
|
|
4
|
+
import { homedir } from 'node:os'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
|
|
7
|
+
const MAX_BINARY_BYTES = 120 * 1024 * 1024
|
|
8
|
+
const manifestUrl = new URL('./learn-checksums.json', import.meta.url)
|
|
9
|
+
const packageUrl = new URL('../package.json', import.meta.url)
|
|
10
|
+
|
|
11
|
+
async function fileDigest(path) {
|
|
12
|
+
try {
|
|
13
|
+
const hash = createHash('sha256')
|
|
14
|
+
for await (const chunk of createReadStream(path)) hash.update(chunk)
|
|
15
|
+
return hash.digest('hex')
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error?.code === 'ENOENT') return undefined
|
|
18
|
+
throw error
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Download and verify the executable once for the current platform and version. */
|
|
23
|
+
export async function resolveLearnBinary(options = {}) {
|
|
24
|
+
const { env = process.env, platform = process.platform, arch = process.arch } = options
|
|
25
|
+
if (env.DSH_CAVEMAN_LEARN_BINARY) return env.DSH_CAVEMAN_LEARN_BINARY
|
|
26
|
+
const manifest = options.manifest ?? JSON.parse(await readFile(manifestUrl, 'utf8'))
|
|
27
|
+
const version = JSON.parse(await readFile(packageUrl, 'utf8')).version
|
|
28
|
+
if (manifest.version !== version || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) throw new Error('Invalid analyzer version manifest')
|
|
29
|
+
const os = { linux: 'linux', darwin: 'darwin', win32: 'win32' }[platform]
|
|
30
|
+
const cpu = { x64: 'amd64', arm64: 'arm64' }[arch]
|
|
31
|
+
const entry = manifest.binaries?.[`${platform}-${arch}`]
|
|
32
|
+
const expectedName = os && cpu ? `dsh-caveman-learn_${os}_${cpu}` : undefined
|
|
33
|
+
if (!expectedName || entry?.name !== expectedName || !/^[a-f0-9]{64}$/u.test(entry.sha256 ?? '')) {
|
|
34
|
+
throw new Error(`No verified analyzer is available for ${platform}/${arch}`)
|
|
35
|
+
}
|
|
36
|
+
const directory = join(options.cacheRoot ?? join(homedir(), '.dsh', 'cache', 'dsh-caveman', 'learn'), version)
|
|
37
|
+
const target = join(directory, `${expectedName}${platform === 'win32' ? '.exe' : ''}`)
|
|
38
|
+
if (await fileDigest(target) === entry.sha256) return target
|
|
39
|
+
await mkdir(directory, { recursive: true, mode: 0o700 })
|
|
40
|
+
const temporary = join(directory, `.${expectedName}.${randomBytes(12).toString('hex')}.tmp`)
|
|
41
|
+
let handle
|
|
42
|
+
let dispatcher
|
|
43
|
+
try {
|
|
44
|
+
const url = `https://github.com/Lornatang/dsh-caveman/releases/download/v${version}/${expectedName}`
|
|
45
|
+
let fetcher = options.fetcher ?? fetch
|
|
46
|
+
if (!options.fetcher && (env.https_proxy || env.HTTPS_PROXY || env.http_proxy || env.HTTP_PROXY)) {
|
|
47
|
+
const { EnvHttpProxyAgent, fetch: proxyFetch } = await import('undici')
|
|
48
|
+
dispatcher = new EnvHttpProxyAgent({
|
|
49
|
+
httpProxy: env.http_proxy ?? env.HTTP_PROXY ?? '',
|
|
50
|
+
httpsProxy: env.https_proxy ?? env.HTTPS_PROXY ?? '',
|
|
51
|
+
noProxy: env.no_proxy ?? env.NO_PROXY ?? '',
|
|
52
|
+
})
|
|
53
|
+
fetcher = (input, init) => proxyFetch(input, { ...init, dispatcher })
|
|
54
|
+
}
|
|
55
|
+
const response = await fetcher(url, { signal: AbortSignal.timeout(120_000) })
|
|
56
|
+
if (!response.ok || !response.body) throw new Error(`Analyzer download failed (HTTP ${response.status})`)
|
|
57
|
+
const advertised = Number(response.headers.get('content-length'))
|
|
58
|
+
if (advertised > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
|
|
59
|
+
handle = await open(temporary, 'wx', 0o700)
|
|
60
|
+
const hash = createHash('sha256')
|
|
61
|
+
let size = 0
|
|
62
|
+
for await (const chunk of response.body) {
|
|
63
|
+
size += chunk.length
|
|
64
|
+
if (size > MAX_BINARY_BYTES) throw new Error('Analyzer download exceeds the size limit')
|
|
65
|
+
hash.update(chunk)
|
|
66
|
+
await handle.writeFile(chunk)
|
|
67
|
+
}
|
|
68
|
+
await handle.close()
|
|
69
|
+
handle = undefined
|
|
70
|
+
if (hash.digest('hex') !== entry.sha256) throw new Error('Analyzer checksum mismatch')
|
|
71
|
+
await chmod(temporary, 0o700)
|
|
72
|
+
try { await rename(temporary, target) } catch (error) {
|
|
73
|
+
// Another invocation may have finished the same verified download.
|
|
74
|
+
if (await fileDigest(target) !== entry.sha256) throw error
|
|
75
|
+
}
|
|
76
|
+
return target
|
|
77
|
+
} finally {
|
|
78
|
+
await handle?.close().catch(() => {})
|
|
79
|
+
await rm(temporary, { force: true }).catch(() => {})
|
|
80
|
+
await dispatcher?.destroy().catch(() => {})
|
|
81
|
+
}
|
|
82
|
+
}
|