UNPKG

@phren/cli

Version:

Knowledge layer for AI agents - CLI, MCP server, and data layer

184 lines (183 loc) • 8.94 kB
import { createHmac, randomBytes } from "node:crypto"; import { lstat, realpath } from "node:fs/promises"; import { homedir } from "node:os"; import path from "node:path"; import { normalizeFileReference, resolveFilePath, resolveRepositoryFile } from "./file-resolve.js"; import { readFileRange } from "./file-range.js"; import { wslDriveReference } from "./home-media.js"; import { git, gitRoot } from "./projects.js"; import { BridgeError } from "./protocol.js"; const MAX_MATCHES = 20; const MAX_FOLDERS = 16; const MAX_REPOS = 8; function absent(error) { return error instanceof BridgeError && [400, 403, 404].includes(error.status); } /** A terminal-observed directory may authorize its checkout only if every * component is real. realpath comparison catches symlinked parents as well. */ export async function observedChatDirectory(value) { if (typeof value !== "string" || !path.isAbsolute(value) || Buffer.byteLength(value) > 4096 || value.split(/[\\/]/).some(part => part === "." || part === "..")) return undefined; const local = path.resolve(value); try { const info = await lstat(local); if (info.isSymbolicLink() || !info.isDirectory()) return undefined; const canonical = await realpath(local); const sameDriveSpelling = (name) => process.platform === "win32" ? name.replace(/^[a-z]:/i, drive => drive.toUpperCase()) : name; return sameDriveSpelling(canonical) === sameDriveSpelling(local) ? canonical : undefined; } catch { return undefined; } } export async function recentChatCheckouts(recent, current) { const home = await realpath(homedir()).catch(() => homedir()); const directories = [...new Set(recent)].slice(0, MAX_FOLDERS); const found = new Map(); if (current) found.set(current.root, current); for (const batch of Array.from({ length: Math.ceil(directories.length / 4) }, (_, i) => directories.slice(i * 4, i * 4 + 4))) { const resolved = await Promise.all(batch.map(async (value) => { try { const folder = await observedChatDirectory(value); if (!folder || folder === home || path.dirname(folder) === folder) return undefined; const repo = await gitRoot(folder); if (!repo || repo === home || home.startsWith(repo + path.sep) || path.dirname(repo) === repo) return undefined; return { repo, folder }; } catch (error) { if (error instanceof BridgeError && error.status === 504) throw error; return undefined; } })); for (const item of resolved) { if (!item) continue; const existing = found.get(item.repo); if (existing) { if (!existing.folders.includes(item.folder)) existing.folders.push(item.folder); } else if (found.size < MAX_REPOS) found.set(item.repo, { root: item.repo, folders: [item.folder] }); } if (found.size >= MAX_REPOS) break; } return [...found.values()]; } /** Range access is scoped to a concrete result from this live session. * The phone never supplies a filesystem root. */ export class ChatFiles { secret = randomBytes(32); selections = new Map(); select(target, root, file, checkout) { const owner = JSON.stringify(target); const fileToken = createHmac("sha256", this.secret).update(JSON.stringify([owner, root, file.path, file.version])).digest("hex"); this.selections.delete(fileToken); if (this.selections.size >= 1024) this.selections.delete(this.selections.keys().next().value); this.selections.set(fileToken, { target: owner, root, file }); return { ...file, fileToken, checkout }; } async read(target, fileToken, requested, offset, length, version) { const selected = this.selections.get(fileToken); if (!selected || selected.target !== JSON.stringify(target) || selected.file.path !== requested || await realpath(selected.root).catch(() => undefined) !== selected.root) { throw new BridgeError(404, "This file selection has expired. Open the link again."); } if (version !== undefined && version !== selected.file.version) throw new BridgeError(409, "The file changed. Open it again."); return readFileRange(selected.root, requested, offset, length, selected.file.version); } async resolve(target, root, cwd, input, search, recent) { const drive = await wslDriveReference(input); if (drive?.includes(":")) throw new BridgeError(400, "Invalid file path."); input = drive ?? input; const requested = normalizeFileReference(input); const absolute = path.isAbsolute(requested); const basename = requested.replace(/^\.\//, ""); const bare = !basename.includes("/") && basename !== "." && basename !== ".."; if (search && (!bare || requested.length > 256 || requested.includes(":"))) throw new BridgeError(400, "Search by filename."); if (!search) { try { const file = await resolveFilePath(root, cwd, input); return { files: [file], truncated: false }; } catch (error) { if (!(error instanceof BridgeError) || (error.status !== 404 && error.status !== 409 && !(absolute && error.status === 403 && error.message === "This file is outside the repository."))) throw error; } } if (!bare && !absolute) return { files: [], truncated: false }; const repos = await recentChatCheckouts(await recent(), root ? { root, folders: [cwd] } : undefined); const files = []; let truncated = false; const labelPart = (dir) => Array.from(path.basename(dir).replace(/[\x00-\x1f\x7f\\]/g, "�")).slice(0, 100).join(""); const labels = repos.map(repo => labelPart(repo.root)); const distinguish = new Set(labels.map(label => label.toLowerCase())).size !== labels.length; for (const [index, repo] of repos.entries()) { const checkout = distinguish ? `${index + 1}. ${labels[index]} · ${labelPart(path.dirname(repo.root))}` : labels[index]; const matches = new Map(); const offer = (file) => { if (file && !file.path.includes(":")) matches.set(file.path, file); }; if (!search && repo.root !== root) { for (const folder of absolute ? repo.folders.slice(0, 1) : repo.folders) { try { offer(await resolveRepositoryFile(repo.root, folder, requested)); } catch (error) { if (!absent(error)) throw error; } } } if (bare) { const escaped = basename.replace(/[\\*?\[\]]/g, "\\$&"); const name = search ? `*${escaped}*` : escaped; const listing = await git(repo.root, "ls-files", "--cached", "--others", "--exclude-standard", "-z", "--", `:(glob,icase)**/${name}`) .catch(error => { if (!(error instanceof BridgeError) || error.status === 504) throw error; truncated = true; return ""; }); const names = [...new Set(listing.split("\0").filter(Boolean))]; if (names.length > 100) truncated = true; for (const file of names.slice(0, 100)) { if (files.length + matches.size > MAX_MATCHES) break; if (matches.has(file) || file.includes(":") || Buffer.byteLength(file) > 2048) continue; try { const info = await readFileRange(repo.root, file, 0, 0); offer({ path: file, size: info.total, contentType: info.contentType, version: info.version }); } catch (error) { if (!absent(error)) throw error; } } } for (const file of matches.values()) { if (files.length === MAX_MATCHES) return { files, truncated: true }; files.push(repo.root === root ? { ...file, checkout } : this.select(target, repo.root, file, checkout)); } } return { files, truncated }; } }