UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

216 lines • 10.7 kB
import { createHash } from "node:crypto"; import { createReadStream } from "node:fs"; import { readFile } from "node:fs/promises"; import { join, posix, win32 } from "node:path"; import { parseRepositoryIdentity } from "../repository-identity.js"; export const MOVE_BUNDLE_FORMAT = 1; export const MANIFEST_FILE = "manifest.json"; export const SESSION_BUNDLE_PATH = "files/session.jsonl"; export class MoveBundleInvalidError extends Error { constructor(detail) { super(`The moved session could not be verified (${detail}); it was not imported. The original device keeps it.`); this.code = "move_bundle_invalid"; this.name = "MoveBundleInvalidError"; } } /** Streams the file through the hash, so a large blob never blocks the host's event loop. */ export async function sha256File(path) { const hash = createHash("sha256"); for await (const chunk of createReadStream(path)) hash.update(chunk); return hash.digest("hex"); } const isString = (value) => typeof value === "string"; /** Both separators count: a bundle written on one OS is read on another. */ export function leavesBundle(path) { return posix.isAbsolute(path) || win32.isAbsolute(path) || path.split(/[\\/]/).includes(".."); } /** * The most segments a path in a bundle may have (senpi#6469). The engine's own paths are at most four deep * (`files/extensions/<extension>/<id>.json`, `files/resident-blobs/<session>/<id>.blob`); extension state under * `state/` is as deep as its extension makes it, and this leaves eight times the engine's depth for it. With no cap a * path of 1,024 bytes names about 500 folders, and an import creates every folder of every listed path. */ export const MAX_BUNDLE_PATH_SEGMENTS = 32; /** Both separators count, as in `leavesBundle`. */ export function nestsTooDeep(path) { return path.split(/[\\/]/).length > MAX_BUNDLE_PATH_SEGMENTS; } /** A path as an error may show it: quoted, and cut short only when it is long. */ export const shown = (path) => JSON.stringify(path.length > 120 ? `${path.slice(0, 120)}...` : path); /** * A file the move would carry sits deeper than a bundle path may be, so a receiver would refuse the bundle. The * sender refuses first: before it seals the session where it still can, and before it writes a bundle where the * session was sealed already (by a version that did not look). */ export class MovePathTooDeepError extends Error { constructor(path, sealedAlready) { super(`A file of this session is nested deeper than a move can carry (${MAX_BUNDLE_PATH_SEGMENTS} path segments): ${shown(path)}. ${sealedAlready ? "No bundle was written. The session is sealed for this move: finish the move as declined to take it back." : "The session was not sealed for the move and nothing was written."}`); this.code = "move_path_too_deep"; this.name = "MovePathTooDeepError"; } } function parseFile(value) { const file = value; if (typeof file !== "object" || file === null || !isString(file.path) || !isString(file.sha256)) throw new MoveBundleInvalidError("a listed file is malformed"); if (leavesBundle(file.path)) throw new MoveBundleInvalidError(`a listed path leaves the bundle: ${file.path}`); if (nestsTooDeep(file.path)) throw new MoveBundleInvalidError(`a listed path is nested deeper than ${MAX_BUNDLE_PATH_SEGMENTS} segments: ${shown(file.path)}`); return { path: file.path, sha256: file.sha256 }; } /** * Move ids and session ids become folder and file names (staging folder, ledger record, resident blobs), so they * must be plain ids: a letter or digit first (never `.` or `..`), then letters, digits, `.`, `_`, `-`, at most 128. */ const PLAIN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/; export function isPlainId(value) { return typeof value === "string" && PLAIN_ID.test(value); } export function isMoveId(value) { return isPlainId(value); } export function parsePlainId(value, what) { if (typeof value !== "string" || !PLAIN_ID.test(value)) throw new MoveBundleInvalidError(`the ${what} is not a plain id: ${JSON.stringify(value)}`); return value; } export function parseMoveId(value) { return parsePlainId(value, "move id"); } /** The importer joins this name onto its session folder, so it must be a plain session file name and nothing else. */ const SESSION_FILE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/; /** Whether `value` is a name a session can land under: what a manifest may carry and what a `status` may name. */ export const isSessionFileName = (value) => typeof value === "string" && SESSION_FILE_NAME.test(value) && !value.includes(".."); function parseSessionFileName(value) { if (!isSessionFileName(value)) throw new MoveBundleInvalidError(`the session file name is not a plain file name: ${value}`); return value; } /** Payload kinds this version imports; any other kind refuses the bundle. */ export const KNOWN_PAYLOAD_KINDS = new Set(["extension-state"]); /** Where `extension-state` payload files sit inside the bundle. */ export const EXTENSION_STATE_PREFIX = "state/"; function parsePayload(value) { const payload = value; if (typeof payload !== "object" || payload === null || !isString(payload.kind) || !Array.isArray(payload.files)) throw new MoveBundleInvalidError("a payload is malformed"); if (!KNOWN_PAYLOAD_KINDS.has(payload.kind)) throw new MoveBundleInvalidError("it carries a payload this version cannot import"); const files = payload.files.map(parseFile); // The importer unpacks extension state by stripping this prefix; a file anywhere else is not extension state. const outside = files.find((file) => !file.path.startsWith(EXTENSION_STATE_PREFIX)); if (outside !== undefined) throw new MoveBundleInvalidError(`an extension-state file is listed outside state/: ${outside.path}`); return { kind: payload.kind, files }; } const unreadable = (error) => new MoveBundleInvalidError(`manifest unreadable: ${error instanceof Error ? error.message : String(error)}`); export async function readManifest(bundleDir) { let text; try { text = await readFile(join(bundleDir, MANIFEST_FILE), "utf8"); } catch (error) { throw unreadable(error); } return parseManifest(text); } /** * What a sender reads back from the bundle it kept: the move it is for, and the queued input the release took out, * in a format this version knows. Nothing else is checked. The bundle is the sender's own, and a rule about its paths that is newer than the bundle * (the depth cap) must not stop the sender from finishing its move. */ export async function readKeptBundle(bundleDir) { let raw; try { raw = JSON.parse(await readFile(join(bundleDir, MANIFEST_FILE), "utf8")); } catch (error) { throw unreadable(error); } if (typeof raw !== "object" || raw === null) throw new MoveBundleInvalidError("the manifest is not an object"); // The format says what the two fields read below mean: a bundle of another format is left for a version that knows it. const format = Reflect.get(raw, "format"); if (format !== MOVE_BUNDLE_FORMAT) throw new MoveBundleInvalidError(`unknown bundle format ${String(format)}`); const queued = Reflect.get(raw, "droppedUserMessages"); const droppedUserMessages = Array.isArray(queued) ? queued : []; if (!droppedUserMessages.every(isString)) throw new MoveBundleInvalidError("malformed queued input"); return { moveId: parseMoveId(Reflect.get(raw, "moveId")), droppedUserMessages }; } /** The manifest from its own text: an inline bundle's manifest is read before any of its files is written. */ export function parseManifest(text) { let raw; try { raw = JSON.parse(text); } catch (error) { throw unreadable(error); } if (typeof raw !== "object" || raw === null) throw new MoveBundleInvalidError("the manifest is not an object"); const m = raw; if (m.format !== MOVE_BUNDLE_FORMAT) throw new MoveBundleInvalidError(`unknown bundle format ${String(m.format)}`); for (const key of ["moveId", "sessionId", "sessionFileName", "sourceCwd"]) { if (!isString(m[key])) throw new MoveBundleInvalidError(`missing ${key}`); } const payloads = (Array.isArray(m.payloads) ? m.payloads : []).map(parsePayload); const dropped = Array.isArray(m.droppedUserMessages) ? m.droppedUserMessages : []; if (!dropped.every(isString)) throw new MoveBundleInvalidError("malformed queued input"); return { format: MOVE_BUNDLE_FORMAT, moveId: parseMoveId(m.moveId), sessionId: parsePlainId(m.sessionId, "session id"), sessionFileName: parseSessionFileName(m.sessionFileName), sourceCwd: m.sourceCwd, repository: parseRepositoryIdentity(m.repository), session: parseFile(m.session), sidecars: (Array.isArray(m.sidecars) ? m.sidecars : []).map(parseFile), droppedUserMessages: dropped, payloads, }; } /** Every file a manifest lists besides itself: the session, its sidecars and the payload files. */ export const listedFiles = (manifest) => [ manifest.session, ...manifest.sidecars, ...manifest.payloads.flatMap((payload) => payload.files), ]; /** * Checks every listed file against the manifest. `sent` is the sha256 each file of an inline bundle arrived with * (senpi#6267): a file must match that too, so an entry that contradicts its own bytes is refused like a changed file. */ export async function verifyBundle(bundleDir, manifest, sent) { for (const file of listedFiles(manifest)) { let actual; try { actual = await sha256File(join(bundleDir, file.path)); } catch { throw new MoveBundleInvalidError(`missing ${file.path}`); } if (actual !== file.sha256) throw new MoveBundleInvalidError(`${file.path} changed in transit`); if (sent !== undefined && sent.get(file.path) !== actual) throw new MoveBundleInvalidError(`${file.path} was sent with a sha256 that is not its bytes'`); } const header = (await readFile(join(bundleDir, manifest.session.path), "utf8")).split("\n", 1)[0] ?? ""; let id; try { id = JSON.parse(header).id; } catch { id = undefined; } if (id !== manifest.sessionId) throw new MoveBundleInvalidError("the session file's own id does not match the bundle's session id"); } //# sourceMappingURL=bundle.js.map