import { readFile, stat } from 'node:fs/promises'; import { isAbsolute, relative, resolve, sep } from 'node:path'; import { z } from 'zod'; import { sha256 } from './codec.js'; export const dependencySchema = z.object({ root: z.string(), platform: z.string(), arch: z.string(), files: z.array(z.object({ path: z.string(), hash: z.string() })), unavailable: z.array(z.string()).optional(), }); export type Dependencies = z.infer; const manifests = [ 'package.json', 'bun.lock', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'Cargo.lock', 'pyproject.toml', 'uv.lock', ]; const hashCache = new Map< string, { size: number; mtimeMs: number; hash: string } >(); async function fingerprint(path: string): Promise { try { const info = await stat(path); if (!info.isFile() || info.size > 8 * 1024 * 1024) return 'unavailable'; const cached = hashCache.get(path); if (cached && cached.size === info.size && cached.mtimeMs === info.mtimeMs) return cached.hash; const hash = sha256(await readFile(path)); hashCache.set(path, { size: info.size, mtimeMs: info.mtimeMs, hash }); if (hashCache.size > 2048) hashCache.delete(hashCache.keys().next().value!); return hash; } catch (error) { return (error as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unavailable'; } } /** Bindings captured on Windows before paths were stored in portable form. */ export function portableDependencyPath(path: string, platform: string): string { return platform === 'win32' ? path.replaceAll('\\', '/') : path; } export async function captureDependencies( cwd: string, paths: string[], ): Promise { const root = resolve(cwd); const files: Dependencies['files'] = []; const unavailable: string[] = []; for (const input of [...new Set([...paths.slice(0, 24), ...manifests])]) { const native = relative(root, resolve(root, input)); if (!native || native.startsWith('..') || isAbsolute(native)) continue; // Stored in portable form: Windows `relative()` yields backslashes, which // broke comparisons against `/`-joined tool paths and data moved between // machines (portable MINIMAL_AGENT_HOME). resolve() accepts both on Windows. const path = native.split(sep).join('/'); const hash = await fingerprint(resolve(root, path)); if (hash === 'unavailable') unavailable.push(path); else files.push({ path, hash }); } return { root, files, platform: process.platform, arch: process.arch, unavailable, }; } /** Read only on recall/adoption. Changes are uncertainty, not proof of failure. */ export async function checkDependencies( binding: Dependencies, ): Promise { const changed: string[] = []; if (binding.platform !== process.platform || binding.arch !== process.arch) changed.push('平台/架构'); for (const file of binding.files) { if ((await fingerprint(resolve(binding.root, file.path))) !== file.hash) changed.push(file.path); } if (binding.unavailable?.length) changed.push(...binding.unavailable.map((path) => `${path}(未绑定)`)); return changed; }