@mulmoclaude/core 7.8.0 → 7.9.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.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["hasStringProp","isRecord","existsSync","path","rmSync","writeFileSync","mkdirSync","execFileSync","renameSync","mkdtempSync","realpathSyncOrNull","isInsideRoot","readdirSync","path","isRecord","path","readFileSync","isPluginFactory","pathToFileURL","isWithinRoot","READ_CHUNK_BYTES","READ_FLAGS","constants","readSync","readPackageFile","openSync","fstatSync","closeSync","existsSync","createHash","refuse","path","isRecord","readFile","writeJsonAtomic","isRecord","open","rm","readFile","timingSafeEqual","randomUUID","mkdir","path","createHash","ONE_MIB","isRecord","createHash","constants","open","createGunzip","readFileSync","path","existsSync","statSync","mkdtemp","writeFile","rm","mkdir","createHash","path","existsSync","readFile","writeFileAtomic","rm"],"sources":["../../src/runtime-plugins/ledger.ts","../../src/runtime-plugins/packageJson.ts","../../src/runtime-plugins/extract.ts","../../src/runtime-plugins/containment.ts","../../src/runtime-plugins/load.ts","../../src/runtime-plugins/npmBuiltinNames.ts","../../src/runtime-plugins/installSource.ts","../../src/runtime-plugins/ledgerWrite.ts","../../src/runtime-plugins/ledgerLock.ts","../../src/runtime-plugins/download.ts","../../src/runtime-plugins/fetchPackage.ts","../../src/runtime-plugins/inspect.ts","../../src/runtime-plugins/install.ts"],"sourcesContent":["// The runtime-plugin install ledger (`plugins/plugins.json` in the workspace). Shared by every host\n// that reads the same workspace, so they agree on which entries count.\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\nexport interface LedgerEntry {\n /** npm package name, e.g. `@gui-chat-plugin/weather`. */\n name: string;\n /** Semver string from the tgz's `package.json`, e.g. `0.1.0`. */\n version: string;\n /** Basename of the tgz inside `plugins/`. Joined with the plugins\n * root to read. */\n tgz: string;\n /** ISO 8601 timestamp of the install. */\n installedAt: string;\n /** Where it was installed from — `npm:<name>@<version>`, `github:<owner>/<repo>#<tag>` or `file:<absolute path>`.\n * Optional: entries written by hand or by an older host have none. */\n source?: string;\n}\n\n// `source` is optional, but when present it must be a string, so the type above tells the truth.\n// No ledger written before the field existed carries one, so this rejects nothing that used to load.\nconst hasValidSource = (value: Record<string, unknown>): boolean => !Object.hasOwn(value, \"source\") || typeof value.source === \"string\";\n\nexport const isLedgerEntry = (value: unknown): value is LedgerEntry =>\n hasStringProp(value, \"name\") &&\n hasStringProp(value, \"version\") &&\n hasStringProp(value, \"tgz\") &&\n hasStringProp(value, \"installedAt\") &&\n hasValidSource(value);\n\n/** The well-formed entries of a parsed ledger; anything that is not an array reads as empty. */\nexport const parseLedger = (raw: unknown): LedgerEntry[] => {\n if (!Array.isArray(raw)) return [];\n return raw.filter(isLedgerEntry);\n};\n","// Reading a runtime plugin's `package.json`: the fields the loader uses, and the entry point it imports.\nimport { isRecord } from \"@mulmoclaude/common\";\n\nexport interface PackageJson {\n name?: string | undefined;\n version?: string | undefined;\n /** Left unnarrowed because every legal Node.js `exports` value is\n * accepted here — string sugar, array fallback chain, condition or\n * subpath map. `pickExportsTarget` is what discriminates them. */\n exports?: unknown | undefined;\n main?: string | undefined;\n module?: string | undefined;\n}\n\nconst optionalString = (value: unknown): string | undefined => (typeof value === \"string\" ? value : undefined);\n\n/** Rebuild the fields the loader reads from arbitrary parsed JSON.\n * Field-by-field rather than a predicate, so a plugin shipping a\n * non-string `main` can't reach `path.join` as if it were one.\n * Returns null when the parsed value isn't an object at all. */\nexport function toPackageJson(value: unknown): PackageJson | null {\n if (!isRecord(value)) return null;\n return {\n name: optionalString(value.name),\n version: optionalString(value.version),\n exports: value.exports,\n main: optionalString(value.main),\n module: optionalString(value.module),\n };\n}\n\n/** Resolve the entry-point path from a plugin's `package.json`. Covers\n * the four legal `exports` shapes per the Node.js spec, then falls\n * through to `module` / `main` for legacy packages.\n *\n * Legal `exports` forms (Node.js docs):\n * 1. String sugar: `\"exports\": \"./index.js\"`\n * 2. Conditional root: `\"exports\": { \"import\": \"./esm.js\", … }`\n * 3. Subpath map: `\"exports\": { \".\": \"./index.js\", \"./util\": \"./util.js\", … }`\n * 4. Subpath + cond.: `\"exports\": { \".\": { \"import\": \"./esm.js\", \"require\": \"./cjs.js\" } }`\n *\n * Earlier the loader only matched form (4) and fell straight through\n * to `module` / `main`. Real npm packages using forms (1)-(3) failed\n * to load (#1077 review). */\nexport function resolveEntrySpecifier(pkg: PackageJson): string | null {\n const fromExports = resolveExportsField(pkg.exports);\n if (fromExports) return fromExports;\n if (typeof pkg.module === \"string\") return pkg.module;\n if (typeof pkg.main === \"string\") return pkg.main;\n return null;\n}\n\nfunction resolveExportsField(exportsField: unknown): string | null {\n // Form 1: top-level string sugar.\n // Form A: array fallback chain (e.g. [\"./dist/index.js\", \"./fallback.js\"]).\n // Form 2: conditional root (e.g. `{ import, require, default }`).\n // Form 3 / 4: subpath map keyed by `.` — value can be a string,\n // array, or condition object (Codex review iter-2 on #1116).\n const root = pickExportsTarget(exportsField);\n if (root) return root;\n if (isRecord(exportsField)) {\n return pickExportsTarget(exportsField[\".\"]);\n }\n return null;\n}\n\n/** Walk a Node.js `exports` value and return the first string entry\n * point this ESM loader can use. Handles every legal target shape:\n *\n * - string: return it directly.\n * - array: try each element in order; first resolvable wins.\n * Per the spec arrays are a fallback chain — Node tries each\n * until one resolves on disk. We don't probe disk here, so\n * \"first string-or-resolvable-condition\" approximates that.\n * - condition object: prefer `import` (ESM-specific), then\n * `default` (universal fallback).\n * - everything else (e.g. only `require`, only nested arrays of\n * condition objects with no string targets): null. */\nfunction pickExportsTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n for (const entry of value) {\n const resolved = pickExportsTarget(entry);\n if (resolved) return resolved;\n }\n return null;\n }\n if (!isRecord(value)) return null;\n // Condition object — `import` first (the ESM-specific condition\n // match), then `default` (the universal fallback that \"always\n // matches\" per the Node.js spec).\n const fromImport = pickExportsTarget(value.import);\n if (fromImport) return fromImport;\n return pickExportsTarget(value.default);\n}\n","// Extracting a runtime plugin's tgz into its version-keyed cache slot.\nimport { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { execFileSync } from \"node:child_process\";\nimport path from \"node:path\";\n\n/** Sentinel file written at the end of a successful extract. The\n * loader uses its presence (not just `existsSync(cachePath)`) as the\n * cache-validity check, so a partial extract (interrupted tar, ENOSPC\n * half-write) is detected and re-extracted on the next boot instead\n * of becoming a permanent broken state. */\nexport const EXTRACT_MARKER = \".extract-complete\";\n\nexport function isCacheValid(cachePath: string): boolean {\n return existsSync(path.join(cachePath, EXTRACT_MARKER));\n}\n\n// The archive can ship its own `.extract-complete` — as a symlink, writing through which would empty\n// whatever it points at outside the folder. Whatever is there is removed (a link is removed, never its\n// target), and the marker is created only if nothing is in its place (`wx`), so it is never followed.\nfunction writeMarker(markerPath: string): void {\n rmSync(markerPath, { recursive: true, force: true });\n writeFileSync(markerPath, \"\", { flag: \"wx\" });\n}\n\n/** Run `tar xzf` to extract a tgz into the version-keyed cache slot.\n * `--strip-components=1` drops the `package/` prefix that npm packs\n * add. `execFileSync` (not `execSync`) so paths bypass shell parsing\n * and never trip on metacharacters in workspace paths. Synchronous\n * because boot is single-threaded and the alternative (a stream\n * pipeline) adds dependencies for no benefit.\n *\n * On failure, the partial directory is removed so the next boot\n * re-extracts cleanly (no sticky broken state). The completion\n * marker is written ONLY after tar exits 0 — readers should test\n * `isCacheValid()`, not `existsSync(cachePath)`. */\nexport function extractTgz(tgzAbs: string, destDir: string): void {\n // Wipe any leftover from a previous failed extract before writing.\n if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });\n mkdirSync(destDir, { recursive: true });\n try {\n execFileSync(\"tar\", [\"-xzf\", tgzAbs, \"-C\", destDir, \"--strip-components=1\"], { stdio: \"pipe\" });\n writeMarker(path.join(destDir, EXTRACT_MARKER));\n } catch (err) {\n // Tear down the partial tree so isCacheValid() stays false next boot.\n try {\n rmSync(destDir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n\nconst removeQuietly = (dir: string): void => {\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n};\n\n// Moves a complete staging folder into place, and never removes what is there: a folder at the\n// destination may be a complete one another process published a moment ago (same key, so the same\n// bytes), which a running host may be reading. Since every folder is completed before it is renamed in,\n// the destination is never partial in this layout; if it exists without its marker anyway, this refuses\n// rather than guessing, and the caller logs it.\nexport function publishStaged(staging: string, destDir: string): void {\n try {\n renameSync(staging, destDir);\n } catch (err) {\n removeQuietly(staging);\n if (!isCacheValid(destDir)) throw err;\n }\n}\n\n/** Unpack `bytes` (a gzipped npm tarball) to `destDir` so that no reader ever sees a partial tree, even\n * with two processes (MulmoClaude and MulmoTerminal on one workspace) unpacking the same folder at once:\n * into a unique sibling folder, completed with the marker, then renamed into place. The bytes are the\n * ones the caller already read and keyed the folder by, so what is unpacked is what the key names. */\nexport function extractBytesAtomically(bytes: Buffer, destDir: string): void {\n if (isCacheValid(destDir)) return;\n const parent = path.dirname(destDir);\n mkdirSync(parent, { recursive: true });\n const staging = mkdtempSync(path.join(parent, `.${path.basename(destDir)}-`));\n try {\n execFileSync(\"tar\", [\"-xzf\", \"-\", \"-C\", staging, \"--strip-components=1\"], { input: bytes, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n writeMarker(path.join(staging, EXTRACT_MARKER));\n publishStaged(staging, destDir);\n } catch (err) {\n removeQuietly(staging);\n throw err;\n }\n}\n","// Whether what an extracted package holds stays inside it once links are followed. `tar` refuses to\n// WRITE outside the folder (absolute and `..` members, writes through a link), but it keeps a symlink\n// member as a link, so a file inside can point anywhere; these checks follow it.\nimport { readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { isInsideRoot, realpathSyncOrNull } from \"../files/containment.js\";\n\n/** True when `file` exists and, with every link followed, is inside `root`. */\nexport function resolvesInside(file: string, root: string): boolean {\n const rootReal = realpathSyncOrNull(root);\n const fileReal = realpathSyncOrNull(file);\n return rootReal !== null && fileReal !== null && isInsideRoot(rootReal, fileReal);\n}\n\n/** The first symlink under `root` that leads outside it (or nowhere), relative to `root`; null when\n * every link stays inside. */\nexport function linkLeadingOut(root: string, dir: string = root): string | null {\n for (const item of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, item.name);\n if (item.isSymbolicLink() && !resolvesInside(full, root)) return path.relative(root, full);\n const nested = item.isDirectory() ? linkLeadingOut(root, full) : null;\n if (nested !== null) return nested;\n }\n return null;\n}\n","// Loading one runtime plugin: from an extracted cache directory to its TOOL_DEFINITION and handler.\n// The host injects what is its own — the runtime a factory plugin is built with, and the logger —\n// so every host that reads the same ledger loads a plugin the same way.\nimport { createHash } from \"node:crypto\";\nimport { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { PluginRuntime, ToolDefinition } from \"gui-chat-protocol\";\nimport { isPluginFactory } from \"gui-chat-protocol\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { isWithinRoot } from \"../files/containment.js\";\nimport { resolvesInside } from \"./containment.js\";\nimport { extractBytesAtomically, isCacheValid } from \"./extract.js\";\nimport type { LedgerEntry } from \"./ledger.js\";\nimport { resolveEntrySpecifier, toPackageJson, type PackageJson } from \"./packageJson.js\";\n\nexport interface RuntimePlugin {\n /** npm package name, e.g. `@gui-chat-plugin/weather`. */\n name: string;\n /** Semver string from the tgz's `package.json`. */\n version: string;\n /** Absolute path to the extracted plugin directory, `plugins/.cache/<name>/<version>/<content key>/`\n * for a ledger entry (the full sha256 of the package file's bytes, in hex). */\n cachePath: string;\n /** TOOL_DEFINITION export from the plugin's `dist/index.js`. The\n * shape matches static plugins, so the same MCP merge / dispatch\n * path applies. */\n definition: ToolDefinition;\n /** Server-side handler the dispatch route calls. The convention\n * across @gui-chat-plugin packages is to export it under the same\n * key as `TOOL_DEFINITION.name` (e.g. weather → `fetchWeather`,\n * browse → `browse`); we capture it at load time so the dispatch\n * route doesn't have to re-resolve. The signature follows\n * gui-chat-protocol's `ToolPluginCore.execute`:\n * `(context: ToolContext, args) => Promise<ToolResult>` — context\n * first, args second. `null` means the module shipped a\n * TOOL_DEFINITION but no matching handler — the dispatch will 500\n * with a useful message. */\n execute: ((context: unknown, args: unknown) => unknown) | null;\n /** Optional short, URL-safe alias for the OAuth callback route\n * (#1162). When the plugin's module exports\n * `OAUTH_CALLBACK_ALIAS = \"<alias>\"`, the host registers\n * `/api/plugins/runtime/oauth-callback/<alias>` and forwards\n * `kind: \"oauthCallback\"` dispatch args to this plugin. The\n * package-name-in-path shape was rejected by Spotify Dashboard\n * because of the percent-encoded `@` / `/` characters, so OAuth\n * plugins declare a short alias (e.g. `\"spotify\"`) instead. Null\n * for non-OAuth plugins. */\n oauthCallbackAlias: string | null;\n}\n\n/** The host's logger. Every call carries a data object, so a host can prefix and forward it as is. */\nexport interface RuntimePluginLogger {\n info: (message: string, data: Record<string, unknown>) => void;\n warn: (message: string, data: Record<string, unknown>) => void;\n error: (message: string, data: Record<string, unknown>) => void;\n}\n\nexport interface LoadDeps {\n /** The runtime a FACTORY plugin (`export default definePlugin(...)`) is built with. Called only\n * for a factory module, once per load. */\n runtimeFor: (pkgName: string) => PluginRuntime;\n log: RuntimePluginLogger;\n}\n\n/** Where a ledger's tgz files live, and where they are extracted. */\nexport interface RuntimePluginRoots {\n pluginsDir: string;\n cacheDir: string;\n}\n\nconst isToolDefinition = (value: unknown): value is ToolDefinition => {\n if (!isRecord(value)) return false;\n return typeof value.name === \"string\" && typeof value.description === \"string\";\n};\n\nfunction readPackageJson(cachePath: string, log: RuntimePluginLogger): PackageJson | null {\n const pkgPath = path.join(cachePath, \"package.json\");\n try {\n const parsed: unknown = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n const pkg = toPackageJson(parsed);\n if (!pkg) log.warn(\"package.json is not an object — skipping\", { path: pkgPath });\n return pkg;\n } catch (err) {\n log.warn(\"package.json read/parse failed\", { path: pkgPath, error: String(err) });\n return null;\n }\n}\n\n/** Two carrier shapes (#1110 backward compatibility):\n *\n * 1. **Factory** (`export default definePlugin(setup)`) — `mod.default`\n * is a function. Call it with the plugin's runtime; the return\n * value carries `TOOL_DEFINITION` and the handler keyed by\n * `TOOL_DEFINITION.name`. Closure over runtime gives the handler\n * access to scoped pubsub / files / log without per-call context\n * threading.\n * 2. **Legacy** (`export const TOOL_DEFINITION = ...; export async\n * function <name>(context, args) ...`) — `mod.TOOL_DEFINITION` and\n * `mod[<name>]` directly. Continues to work; existing\n * @gui-chat-plugin packages don't need to migrate.\n */\nfunction resolveCarrier(name: string, mod: Record<string, unknown>, deps: LoadDeps): { carrier: Record<string, unknown>; usingFactory: boolean } {\n const defaultExport = mod.default;\n if (isPluginFactory(defaultExport)) {\n return { carrier: defaultExport(deps.runtimeFor(name)), usingFactory: true };\n }\n return { carrier: mod, usingFactory: false };\n}\n\n/** Callability is the whole of what a dynamically imported export can be\n * proved to have, so parameters and result stay `unknown` — the loader\n * never inspects either. */\nconst isPluginHandler = (value: unknown): value is (...args: unknown[]) => unknown => typeof value === \"function\";\n\n/** Pull the executable from a carrier. Factory-shape handlers take\n * `(args)` only (runtime is closed over) so we wrap to discard the\n * legacy `context` arg the dispatch route passes. Legacy-shape\n * handlers keep the `(context, args)` signature unchanged. Returns\n * null when no function is exported under `definition.name` — the\n * plugin still appears in `tools/list` but dispatch logs + 500s. */\nexport function resolveExecute(\n carrier: Record<string, unknown>,\n definitionName: string,\n usingFactory: boolean,\n): ((context: unknown, args: unknown) => unknown) | null {\n // Own-property guard: a bare `carrier[definitionName]` for a plugin naming its\n // tool `constructor` / `toString` resolves to an Object.prototype function,\n // defeating the `typeof … !== \"function\"` gate below (#2319).\n const handler = Object.hasOwn(carrier, definitionName) ? carrier[definitionName] : undefined;\n if (!isPluginHandler(handler)) return null;\n if (usingFactory) return (_context, args) => handler(args);\n return handler;\n}\n\n/** Read the optional `OAUTH_CALLBACK_ALIAS` named export. Validated\n * against `^[a-z0-9][a-z0-9-]{0,30}$` — short, lowercase,\n * URL-friendly, can't be `..` or contain `/`. A bad alias is logged\n * and ignored (the plugin still loads; just skips the OAuth route\n * registration). */\nconst OAUTH_CALLBACK_ALIAS_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;\nfunction resolveOauthCallbackAlias(name: string, mod: Record<string, unknown>, log: RuntimePluginLogger): string | null {\n const raw = mod.OAUTH_CALLBACK_ALIAS;\n if (raw === undefined) return null;\n if (typeof raw !== \"string\" || !OAUTH_CALLBACK_ALIAS_RE.test(raw)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- this branch exists BECAUSE `raw` is the wrong shape; echoing whatever it stringifies to is the diagnostic.\n log.warn(\"OAUTH_CALLBACK_ALIAS export is not a valid alias — ignoring\", { name, raw: String(raw) });\n return null;\n }\n return raw;\n}\n\n/** Load a plugin from an already-extracted cache directory. Accepts\n * paths explicitly, so tests don't need a real workspace. Returns\n * null on any structural failure (missing package.json, missing\n * TOOL_DEFINITION, broken import); the caller treats nulls as \"skip\". */\nexport async function loadPluginFromCacheDir(name: string, version: string, cachePath: string, deps: LoadDeps): Promise<RuntimePlugin | null> {\n const { log } = deps;\n const pkg = readPackageJson(cachePath, log);\n if (!pkg) return null;\n const entrySpec = resolveEntrySpecifier(pkg);\n if (!entrySpec) {\n log.warn(\"no entry specifier in package.json — skipping\", { name });\n return null;\n }\n const entryAbs = path.join(cachePath, entrySpec);\n if (!resolvesInside(entryAbs, cachePath)) {\n log.warn(\"plugin entry is missing or leads outside its folder — skipping\", { name, entrySpec });\n return null;\n }\n try {\n const mod: unknown = await import(pathToFileURL(entryAbs).href);\n if (!isRecord(mod)) {\n log.warn(\"plugin module namespace is not an object — skipping\", { name, entrySpec });\n return null;\n }\n const { carrier, usingFactory } = resolveCarrier(name, mod, deps);\n const definition = carrier.TOOL_DEFINITION;\n if (!isToolDefinition(definition)) {\n log.warn(\"no TOOL_DEFINITION export — skipping\", { name, entrySpec, shape: usingFactory ? \"factory\" : \"legacy\" });\n return null;\n }\n const execute = resolveExecute(carrier, definition.name, usingFactory);\n if (!execute) {\n log.warn(\"no execute handler matching TOOL_DEFINITION.name — dispatch will fail\", {\n name,\n expectedExport: definition.name,\n shape: usingFactory ? \"factory\" : \"legacy\",\n });\n }\n const oauthCallbackAlias = resolveOauthCallbackAlias(name, mod, log);\n return { name, version, cachePath, definition, execute, oauthCallbackAlias };\n } catch (err) {\n log.error(\"import failed\", { name, entrySpec, error: String(err) });\n return null;\n }\n}\n\n/** Lexical anchor: confirm `candidate` resolves inside `base`. Catches\n * malformed ledger entries (`name` containing `../../etc`) before we\n * touch the disk. The asset route trusts registry membership, so a\n * registered cachePath that escaped the base would expose arbitrary\n * files via the unauthenticated GET — this check is the first\n * line of defence; `loadPluginFromCacheDir` checks the entry's realpath\n * after extraction as the symlink-escape backstop. */\nexport function ensureInsideBase(candidate: string, base: string): boolean {\n return isWithinRoot(path.resolve(base), path.resolve(candidate));\n}\n\n/** Make a ledger entry's cache directory ready to load: both of its paths anchored inside their\n * roots, its tgz present, and the tgz extracted unless a complete extract is already there.\n * Returns the cache directory, or null (logged) when the entry cannot be loaded. */\n// The unpacked copy is keyed by the BYTES of the package file as well as the name and version: a\n// host that loads while running would otherwise be handed the module it imported before (an ESM\n// import is cached by its URL), and the file name alone is no key — two ledger paths can share a\n// basename, and a hand-written entry can have its file's bytes replaced in place. Different bytes\n// therefore unpack to a different folder, and a reinstall never has to delete a folder a running host\n// may still be serving from. The file is read ONCE, from one handle and to at most the install's limit,\n// and that same read is both hashed and unpacked, so what is unpacked is what the key names.\nconst MAX_PACKAGE_FILE_BYTES = 50 * 1024 * 1024;\nconst READ_CHUNK_BYTES = 64 * 1024;\n// Non-blocking, so a FIFO named in the ledger is refused at open instead of waiting for a writer.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\n\nfunction readChunks(fileHandle: number, maxBytes: number): Buffer | null {\n const chunks: Buffer[] = [];\n let received = 0;\n for (;;) {\n const chunk = Buffer.alloc(READ_CHUNK_BYTES);\n const bytesRead = readSync(fileHandle, chunk, 0, READ_CHUNK_BYTES, null);\n if (bytesRead === 0) return Buffer.concat(chunks, received);\n received += bytesRead;\n if (received > maxBytes) return null;\n chunks.push(chunk.subarray(0, bytesRead));\n }\n}\n\n/** The package file's bytes, or null when it is not a regular file or grows past the limit while read. */\nfunction readPackageFile(tgzAbs: string): Buffer | null {\n const fileHandle = openSync(tgzAbs, READ_FLAGS);\n try {\n return fstatSync(fileHandle).isFile() ? readChunks(fileHandle, MAX_PACKAGE_FILE_BYTES) : null;\n } finally {\n closeSync(fileHandle);\n }\n}\n\nfunction loggedPackageBytes(tgzAbs: string, entry: LedgerEntry, log: RuntimePluginLogger): Buffer | null {\n try {\n const bytes = readPackageFile(tgzAbs);\n if (bytes === null) log.warn(\"tgz is not a package file within the size limit — skipping\", { name: entry.name, tgz: entry.tgz });\n return bytes;\n } catch (err) {\n log.error(\"tgz unreadable — skipping\", { name: entry.name, tgz: entry.tgz, error: String(err) });\n return null;\n }\n}\n\nexport function prepareLedgerEntry(entry: LedgerEntry, roots: RuntimePluginRoots, log: RuntimePluginLogger): string | null {\n const tgzAbs = path.join(roots.pluginsDir, entry.tgz);\n const versionDir = path.join(roots.cacheDir, entry.name, entry.version);\n // Anchor checks BEFORE any disk probe (`existsSync` / `realpath`).\n // The ledger has two separate user-controlled fields — `tgz` and\n // (`name`, `version`) — and each joins against a different base.\n // Both must stay inside their respective bases; otherwise even a\n // stat-only probe would touch a path outside the intended roots.\n if (!ensureInsideBase(tgzAbs, roots.pluginsDir)) {\n log.warn(\"ledger entry tgz escapes plugins root — skipping\", { name: entry.name, tgz: entry.tgz });\n return null;\n }\n if (!ensureInsideBase(versionDir, roots.cacheDir)) {\n log.warn(\"ledger entry escapes plugin cache root — skipping\", {\n name: entry.name,\n version: entry.version,\n });\n return null;\n }\n if (!existsSync(tgzAbs)) {\n log.warn(\"tgz missing — skipping\", { name: entry.name, tgz: entry.tgz });\n return null;\n }\n const bytes = loggedPackageBytes(tgzAbs, entry, log);\n if (bytes === null) return null;\n const cachePath = path.join(versionDir, createHash(\"sha256\").update(bytes).digest(\"hex\"));\n if (!isCacheValid(cachePath)) {\n try {\n extractBytesAtomically(bytes, cachePath);\n log.info(\"extracted\", { name: entry.name, version: entry.version });\n } catch (err) {\n log.error(\"extract failed\", { name: entry.name, error: String(err) });\n return null;\n }\n }\n return cachePath;\n}\n","// The names validate-npm-package-name 7.0.1 refuses for a new package because Node ships a module\n// by that name (lib/builtin-modules.json there). A fixed copy rather than node:module builtinModules,\n// which differs between Node versions, so every host refuses the same names.\nexport const NPM_BUILTIN_MODULE_NAMES: ReadonlySet<string> = new Set([\n \"_http_agent\",\n \"_http_client\",\n \"_http_common\",\n \"_http_incoming\",\n \"_http_outgoing\",\n \"_http_server\",\n \"_stream_duplex\",\n \"_stream_passthrough\",\n \"_stream_readable\",\n \"_stream_transform\",\n \"_stream_wrap\",\n \"_stream_writable\",\n \"_tls_common\",\n \"_tls_wrap\",\n \"assert\",\n \"assert/strict\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"dns/promises\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"inspector/promises\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"path/posix\",\n \"path/win32\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"readline/promises\",\n \"repl\",\n \"stream\",\n \"stream/consumers\",\n \"stream/promises\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"timers/promises\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"util/types\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n \"node:sea\",\n \"node:sqlite\",\n \"node:test\",\n \"node:test/reporters\",\n]);\n","// Where a runtime plugin is installed from, as a user types it: `<npm name>[@<version or dist-tag>]`,\n// `github:<owner>/<repo>[#<tag>]`, or `file:<absolute path>.tgz`. Parsing only — nothing here reaches\n// the network or the disk.\n\nimport path from \"node:path\";\nimport { NPM_BUILTIN_MODULE_NAMES } from \"./npmBuiltinNames.js\";\n\nexport type InstallSource =\n { kind: \"npm\"; name: string; spec: string | null } | { kind: \"github\"; owner: string; repo: string; tag: string | null } | { kind: \"file\"; path: string };\n\nexport type ParsedInstallSource = { ok: true; source: InstallSource } | { ok: false; error: string };\n\nconst MAX_NPM_NAME_LENGTH = 214;\nconst MAX_TAG_LENGTH = 255;\n// npm's rule for a NEW package name (validate-npm-package-name 7.0.1), one segment at a time: lower\n// case, URL-safe, no `~'!()*`. Its leading `.`, `-` and `_` checks apply to the WHOLE name, so inside\n// a scoped name a segment may start with `-` or `_` (`@_scope/-pkg`). A leading `.` is refused in every\n// segment here: it is what would let one read as `.` or `..` in a path. Split rather than one pattern,\n// so no quantifier nests.\nconst NPM_UNSCOPED_NAME = /^[a-z0-9][a-z0-9\\-._]*$/;\nconst NPM_SCOPED_SEGMENT = /^[a-z0-9\\-_][a-z0-9\\-._]*$/;\n// semver 2.0.0: a numeric identifier has no leading zero; an identifier is never empty.\nconst NUMERIC_IDENTIFIER = /^(?:0|[1-9]\\d*)$/;\nconst ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/;\nconst ALL_DIGITS = /^\\d+$/;\n// A dist-tag cannot parse as a version or a range, so one that starts with a letter is unambiguous.\nconst DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]*$/;\nconst GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;\nconst GITHUB_REPO = /^[A-Za-z0-9._-]{1,100}$/;\nconst GITHUB_TAG = /^[A-Za-z0-9._+/-]+$/;\nconst GITHUB_PREFIX = \"github:\";\nconst FILE_PREFIX = \"file:\";\nconst PACKAGE_FILE_SUFFIX = \".tgz\";\n\nconst refuse = (error: string): ParsedInstallSource => ({ ok: false, error });\n\nfunction isNpmNameShape(name: string): boolean {\n if (!name.startsWith(\"@\")) return NPM_UNSCOPED_NAME.test(name);\n const slash = name.indexOf(\"/\");\n return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1));\n}\n\n// npm refuses these whole names for a new package. npm compares them lower-cased; a name reaching here\n// is already lower case, so an exact match is the same test.\nconst NPM_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\"node_modules\", \"favicon.ico\"]);\n\nconst isNpmReservedName = (name: string): boolean => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name);\n\nexport const isNpmPackageName = (name: string): boolean => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name);\n\nconst isVersionCore = (core: string): boolean => {\n const parts = core.split(\".\");\n return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part));\n};\n\n// A prerelease identifier that is all digits is numeric, so no leading zero; a build identifier may have one.\nconst isLabel = (label: string, prerelease: boolean): boolean =>\n label.split(\".\").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part)));\n\n/** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */\nfunction isSemverShape(version: string): boolean {\n const plus = version.indexOf(\"+\");\n const build = plus === -1 ? null : version.slice(plus + 1);\n const withoutBuild = plus === -1 ? version : version.slice(0, plus);\n const dash = withoutBuild.indexOf(\"-\");\n const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash);\n const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1);\n return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false));\n}\n\n/** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because\n * what it resolves to would change between the confirmation and the next install. */\nexport const isNpmVersionSpec = (spec: string): boolean => isSemverShape(spec) || DIST_TAG.test(spec);\n\n/** An exact version — what a package's own `version` must be, since it becomes part of a file name\n * and a cache folder. */\nexport const isExactVersion = (version: string): boolean => isSemverShape(version);\n\nfunction parseNpm(input: string): ParsedInstallSource {\n const specAt = input.lastIndexOf(\"@\");\n const hasSpec = specAt > 0;\n const name = hasSpec ? input.slice(0, specAt) : input;\n const spec = hasSpec ? input.slice(specAt + 1) : null;\n if (!isNpmPackageName(name)) return refuse(`not an npm package name: ${JSON.stringify(name)}`);\n if (spec !== null && !isNpmVersionSpec(spec)) return refuse(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`);\n return { ok: true, source: { kind: \"npm\", name, spec } };\n}\n\nconst isGithubTag = (tag: string): boolean =>\n tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\");\n\nfunction parseGithub(rest: string): ParsedInstallSource {\n const hash = rest.indexOf(\"#\");\n const ownerRepo = hash === -1 ? rest : rest.slice(0, hash);\n const tag = hash === -1 ? null : rest.slice(hash + 1);\n const [owner = \"\", repo = \"\", ...extra] = ownerRepo.split(\"/\");\n if (extra.length > 0 || !GITHUB_OWNER.test(owner)) return refuse(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`);\n if (!GITHUB_REPO.test(repo) || repo === \".\" || repo === \"..\") return refuse(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`);\n if (tag !== null && !isGithubTag(tag)) return refuse(`not a release tag: ${JSON.stringify(tag)}`);\n return { ok: true, source: { kind: \"github\", owner, repo, tag } };\n}\n\n// A package file already on disk. Absolute only: core has no working directory of its own, so the host\n// resolves a relative path against its own before calling. A folder is not a source — packing one\n// runs its lifecycle scripts, and installing never runs plugin code.\nfunction parseFile(rest: string): ParsedInstallSource {\n if (rest === \"\") return refuse(\"a file: source names no file\");\n if (rest.includes(\"\\0\")) return refuse(\"a file: source contains a NUL byte\");\n if (!path.isAbsolute(rest)) return refuse(`a file: source must be an absolute path: ${JSON.stringify(rest)}`);\n if (!rest.endsWith(PACKAGE_FILE_SUFFIX)) return refuse(`a file: source must name a ${PACKAGE_FILE_SUFFIX} package file: ${JSON.stringify(rest)}`);\n return { ok: true, source: { kind: \"file\", path: path.normalize(rest) } };\n}\n\nexport function parseInstallSource(input: unknown): ParsedInstallSource {\n if (typeof input !== \"string\") return refuse(\"an install source is a string\");\n const trimmed = input.trim();\n if (trimmed === \"\") return refuse(\"an install source is empty\");\n if (trimmed.startsWith(GITHUB_PREFIX)) return parseGithub(trimmed.slice(GITHUB_PREFIX.length));\n if (trimmed.startsWith(FILE_PREFIX)) return parseFile(trimmed.slice(FILE_PREFIX.length));\n return parseNpm(trimmed);\n}\n\n/** The ledger's `source` field for what was actually installed: the resolved version or tag. */\nexport function sourceLabel(source: InstallSource, resolved: string): string {\n if (source.kind === \"npm\") return `npm:${source.name}@${resolved}`;\n if (source.kind === \"github\") return `github:${source.owner}/${source.repo}#${resolved}`;\n return `${FILE_PREFIX}${source.path}`;\n}\n\n/** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */\nexport const packageFileName = (name: string, version: string): string => `${name.replace(/^@/, \"\").replaceAll(\"/\", \"-\")}-${version}.tgz`;\n\nconst CONTENT_ID_LENGTH = 12;\n\n/** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`.\n * Two different packages with one name and version (a GitHub tag published again) then get different\n * files. The hash is short, so the install also refuses to write over an existing file whose bytes\n * differ: that is what keeps a file an entry points at from changing. */\nexport const installedFileName = (name: string, version: string, sha256Hex: string): string =>\n packageFileName(name, version).replace(/\\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);\n","// Writing the runtime-plugin ledger. The edits work on the RAW parsed value rather than on\n// `parseLedger`'s output: an entry the parser skips (hand-written, missing a field) is still the\n// user's, and an install must not delete it by rewriting the file from the entries it understood.\n// The one exception is a value carrying the name being installed or removed: the name gets exactly\n// one entry, so such a value is replaced or removed even when the parser would have skipped it.\nimport { readFile } from \"node:fs/promises\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { writeJsonAtomic } from \"../files/json.js\";\nimport type { LedgerEntry } from \"./ledger.js\";\n\nconst isEntryNamed = (value: unknown, name: string): boolean => isRecord(value) && Object.hasOwn(value, \"name\") && value.name === name;\n\n/** The ledger with `entry` in it, exactly once: it takes the place of the first entry of the same\n * name, any further ones are dropped (each would load another copy), and with none it is appended. */\nexport function withLedgerEntry(raw: readonly unknown[], entry: LedgerEntry): unknown[] {\n const first = raw.findIndex((value) => isEntryNamed(value, entry.name));\n if (first === -1) return [...raw, entry];\n return raw.flatMap((value, index) => {\n if (index === first) return [entry];\n return isEntryNamed(value, entry.name) ? [] : [value];\n });\n}\n\n/** The ledger without any entry named `name`; everything else is kept as it was. */\nexport const withoutLedgerEntry = (raw: readonly unknown[], name: string): unknown[] => raw.filter((value) => !isEntryNamed(value, name));\n\nexport type ReadLedgerResult = { ok: true; raw: unknown[] } | { ok: false; error: string };\n\nasync function readLedgerText(ledgerPath: string): Promise<{ ok: true; text: string | null } | { ok: false; error: string }> {\n try {\n return { ok: true, text: await readFile(ledgerPath, \"utf-8\") };\n } catch (err) {\n if (isRecord(err) && err.code === \"ENOENT\") return { ok: true, text: null };\n return { ok: false, error: `cannot read the plugin ledger ${ledgerPath}: ${String(err)}` };\n }\n}\n\nfunction parseLedgerText(ledgerPath: string, text: string): ReadLedgerResult {\n try {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed)\n ? { ok: true, raw: parsed }\n : { ok: false, error: `the plugin ledger ${ledgerPath} is not a JSON array; fix it before installing` };\n } catch (err) {\n return { ok: false, error: `the plugin ledger ${ledgerPath} is not valid JSON; fix it before installing: ${String(err)}` };\n }\n}\n\n/** The ledger as an array to edit: a missing file is an empty ledger; a file that is not a JSON\n * array is refused rather than overwritten, since writing over it would lose what the user wrote. */\nexport async function readLedgerForWrite(ledgerPath: string): Promise<ReadLedgerResult> {\n const read = await readLedgerText(ledgerPath);\n if (!read.ok) return read;\n return read.text === null ? { ok: true, raw: [] } : parseLedgerText(ledgerPath, read.text);\n}\n\nexport const writeLedger = (ledgerPath: string, raw: readonly unknown[]): Promise<void> => writeJsonAtomic(ledgerPath, raw);\n","// One writer of a workspace's plugin ledger at a time, across processes: MulmoClaude's server, its\n// `plugin` command and MulmoTerminal all edit the same plugins.json. The lock is a file beside the\n// ledger created with O_EXCL, holding the holder's pid and a token.\n//\n// Nothing ever removes another writer's lock. Taking over a lock that looks abandoned cannot be made\n// safe with files alone — every scheme tried let a third writer in while the first still worked — and\n// an edit holds the lock for milliseconds, so a lock left behind means a writer crashed mid-edit. A\n// writer that waits past the limit fails instead, and when the pid in the lock is not running, it says\n// which file to remove.\nimport { randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { mkdir, open, readFile, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n/** How long a writer waits for another to finish before giving up. */\nexport const LEDGER_LOCK_WAIT_MS = 10_000;\nconst LEDGER_LOCK_RETRY_MS = 50;\n\nexport class LedgerBusyError extends Error {}\n\nexport interface LedgerLockDeps {\n now?: () => number;\n sleep?: (delayMs: number) => Promise<void>;\n waitMs?: number;\n /** Whether a process with this pid is running; injectable for tests. */\n isRunning?: (pid: number) => boolean;\n}\n\nexport const ledgerLockPath = (ledgerPath: string): string => `${ledgerPath}.lock`;\n\nconst hasCode = (err: unknown, code: string): boolean => isRecord(err) && err.code === code;\n\n/** Creates the lock holding `token`; false when another writer holds it. A failed write leaves no lock. */\nasync function tryCreate(lockPath: string, token: string): Promise<boolean> {\n const opened = await open(lockPath, \"wx\").catch((err: unknown) => {\n if (hasCode(err, \"EEXIST\")) return null;\n throw err;\n });\n if (opened === null) return false;\n try {\n await opened.writeFile(token);\n } catch (err) {\n await opened.close().catch(() => undefined);\n await rm(lockPath, { force: true });\n throw err;\n }\n await opened.close();\n return true;\n}\n\n/** Removes the lock only while it still carries `token`: if someone removed it by hand, it is not ours. */\nasync function release(lockPath: string, token: string): Promise<void> {\n const held = await readFile(lockPath).catch(() => null);\n const ours = Buffer.from(token);\n if (held !== null && held.length === ours.length && timingSafeEqual(held, ours)) await rm(lockPath, { force: true });\n}\n\n/** `kill(pid, 0)` sends nothing: ESRCH means no such process, EPERM means one we may not signal. */\nexport function processIsRunning(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return hasCode(err, \"EPERM\");\n }\n}\n\nconst PID_PREFIX = /^(\\d+) /;\n\nasync function busyError(lockPath: string, ledgerPath: string, isRunning: (pid: number) => boolean): Promise<LedgerBusyError> {\n const held = await readFile(lockPath, \"utf-8\").catch(() => \"\");\n const pid = Number(PID_PREFIX.exec(held)?.[1] ?? Number.NaN);\n if (Number.isInteger(pid) && pid > 0 && !isRunning(pid)) {\n return new LedgerBusyError(`${lockPath} was left by a writer that is no longer running (pid ${pid}); remove it and try again`);\n }\n return new LedgerBusyError(`another install or removal is editing ${ledgerPath}; try again when it finishes`);\n}\n\nconst defaultSleep = (delayMs: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, delayMs));\n\n/** Runs `work` holding the ledger's lock; throws LedgerBusyError when another writer keeps it past the wait. */\nexport async function withLedgerLock<T>(ledgerPath: string, work: () => Promise<T>, deps: LedgerLockDeps = {}): Promise<T> {\n const now = deps.now ?? Date.now;\n const sleep = deps.sleep ?? defaultSleep;\n const lockPath = ledgerLockPath(ledgerPath);\n const token = `${process.pid} ${randomUUID()}\\n`;\n await mkdir(path.dirname(lockPath), { recursive: true });\n const deadline = now() + (deps.waitMs ?? LEDGER_LOCK_WAIT_MS);\n while (!(await tryCreate(lockPath, token))) {\n if (now() >= deadline) throw await busyError(lockPath, ledgerPath, deps.isRunning ?? processIsRunning);\n await sleep(LEDGER_LOCK_RETRY_MS);\n }\n try {\n return await work();\n } finally {\n await release(lockPath, token);\n }\n}\n","// Downloading a runtime plugin's metadata and package file. The deadline covers the whole transfer —\n// headers AND body — because a server that sends headers and then stalls would otherwise hold the\n// install forever, and the size cap is enforced while reading, so a lying Content-Length cannot\n// make the host buffer more than it agreed to.\nimport { createHash } from \"node:crypto\";\n\nexport type FetchFn = typeof fetch;\n\nexport interface DownloadLimits {\n timeoutMs: number;\n maxBytes: number;\n}\n\nexport class DownloadError extends Error {}\n\n// A pending read is ended when the deadline passes: cancelling the reader settles it at once (the\n// streams spec closes the reader whatever the source's own cancel does), and the abort reason is thrown.\n// Never awaited, so a body whose cancel never settles cannot hold the install.\nasync function readCapped(body: ReadableStream<Uint8Array>, url: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const reader = body.getReader();\n const onAbort = (): void => {\n reader.cancel(signal.reason).catch(() => undefined);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n return await collectChunks(reader, url, maxBytes, signal);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nasync function collectChunks(reader: ReadableStreamDefaultReader<Uint8Array>, url: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const chunks: Uint8Array[] = [];\n let received = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw signal.reason;\n if (done) return Buffer.concat(chunks);\n received += value.byteLength;\n if (received > maxBytes) {\n reader.cancel().catch(() => undefined);\n throw new DownloadError(`${url} is larger than ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n}\n\n/** The response's body once it is known to be a success within the cap. */\n// A refused response's body is cancelled, so the connection behind it is released rather than left\n// streaming whatever the server keeps sending.\nfunction refuseResponse(res: Response, message: string): never {\n res.body?.cancel().catch(() => undefined);\n throw new DownloadError(message);\n}\n\nfunction acceptedBody(res: Response, url: string, maxBytes: number): ReadableStream<Uint8Array> {\n if (!res.ok) refuseResponse(res, `${url} answered HTTP ${res.status}`);\n const declared = Number(res.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) refuseResponse(res, `${url} is ${declared} bytes, more than ${maxBytes}`);\n if (!res.body) throw new DownloadError(`${url} answered with no body`);\n return res.body;\n}\n\n// A fetch implementation is meant to reject once its signal aborts, but one that does not would hold\n// the install forever; the request is raced against the signal so the deadline holds either way.\nfunction settlesByDeadline<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n const onAbort = (): void => reject(signal.reason);\n if (signal.aborted) onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\nexport async function downloadBytes(fetchFn: FetchFn, url: string, headers: Record<string, string>, limits: DownloadLimits): Promise<Buffer> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(new DownloadError(`${url} did not finish within ${limits.timeoutMs}ms`)), limits.timeoutMs);\n try {\n const res = await settlesByDeadline(fetchFn(url, { headers, signal: controller.signal, redirect: \"follow\" }), controller.signal);\n return await readCapped(acceptedBody(res, url, limits.maxBytes), url, limits.maxBytes, controller.signal);\n } catch (err) {\n if (err instanceof DownloadError) throw err;\n const reason: unknown = controller.signal.aborted ? controller.signal.reason : err;\n throw reason instanceof DownloadError ? reason : new DownloadError(`${url} could not be downloaded: ${String(reason)}`);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport async function downloadJson(fetchFn: FetchFn, url: string, headers: Record<string, string>, limits: DownloadLimits): Promise<unknown> {\n const bytes = await downloadBytes(fetchFn, url, headers, limits);\n try {\n return JSON.parse(bytes.toString(\"utf-8\"));\n } catch {\n throw new DownloadError(`${url} did not answer with JSON`);\n }\n}\n\n// sha1 is not accepted: it is too weak to stand for \"these are the bytes the registry published\",\n// and every version published since 2017 carries a sha512.\nconst SRI = /^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/;\n\n/** Whether `bytes` match an npm `dist.integrity` (Subresource Integrity, possibly several space-\n * separated hashes) — the strongest algorithm present must match. False when none is recognised. */\nexport function matchesIntegrity(bytes: Uint8Array, integrity: string): boolean {\n const hashes = integrity\n .split(/\\s+/)\n .map((part) => SRI.exec(part))\n .filter((match): match is RegExpExecArray => match !== null);\n const order = [\"sha512\", \"sha384\", \"sha256\"];\n const strongest = order.find((algorithm) => hashes.some((match) => match[1] === algorithm));\n if (strongest === undefined) return false;\n const actual = createHash(strongest).update(bytes).digest(\"base64\");\n return hashes.some((match) => match[1] === strongest && match[2] === actual);\n}\n","// Fetching a runtime plugin's package file from npm, a GitHub release, or a file on disk. Which version\n// / asset to take is decided by pure functions over the registry's answer, so the choice is testable\n// without a network; the fetches around them only move bytes.\nimport { createHash } from \"node:crypto\";\nimport { constants, open, type FileHandle } from \"node:fs/promises\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { DownloadError, downloadBytes, downloadJson, matchesIntegrity, type FetchFn } from \"./download.js\";\nimport type { InstallSource } from \"./installSource.js\";\n\nexport const NPM_REGISTRY = \"https://registry.npmjs.org\";\nexport const GITHUB_API = \"https://api.github.com\";\nconst ONE_SECOND_MS = 1000;\nconst ONE_MIB = 1024 * 1024;\nconst METADATA_LIMITS = { timeoutMs: 30 * ONE_SECOND_MS, maxBytes: 32 * ONE_MIB };\nconst PACKAGE_LIMITS = { timeoutMs: 120 * ONE_SECOND_MS, maxBytes: 50 * ONE_MIB };\n// GitHub's API refuses a request without a User-Agent; a generic one names no user or host.\nconst USER_AGENT = \"mulmo-runtime-plugins\";\n\nexport interface FetchedPackage {\n bytes: Buffer;\n /** The npm version, GitHub tag or file path that was resolved, for the ledger's `source`. */\n resolved: string;\n}\n\nexport interface NpmRelease {\n version: string;\n tarball: string;\n integrity: string | null;\n}\n\n/** A decision that either holds a value or says why there is none. */\nexport type Resolved<T> = { ok: true; value: T } | { ok: false; error: string };\n\nconst stringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\nconst fail = <T>(error: string): Resolved<T> => ({ ok: false, error });\nconst isHttpsUrl = (value: string): boolean => value.startsWith(\"https://\");\n\nfunction resolveNpmVersion(packument: Record<string, unknown>, versions: Record<string, unknown>, spec: string | null): Resolved<string> {\n const tags = isRecord(packument[\"dist-tags\"]) ? packument[\"dist-tags\"] : {};\n if (spec !== null && Object.hasOwn(versions, spec)) return { ok: true, value: spec };\n const tag = spec ?? \"latest\";\n const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null;\n if (fromTag !== null) return { ok: true, value: fromTag };\n return fail(spec === null ? \"the package has no latest version\" : `no version or dist-tag ${JSON.stringify(spec)}`);\n}\n\nfunction releaseOf(versions: Record<string, unknown>, version: string): Resolved<NpmRelease> {\n const entry = Object.hasOwn(versions, version) ? versions[version] : undefined;\n const dist = isRecord(entry) && isRecord(entry.dist) ? entry.dist : null;\n const tarball = dist ? stringOrNull(dist.tarball) : null;\n if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`);\n return { ok: true, value: { version, tarball, integrity: stringOrNull(dist.integrity) } };\n}\n\n/** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */\nexport function resolveNpmRelease(packument: unknown, spec: string | null): Resolved<NpmRelease> {\n if (!isRecord(packument) || !isRecord(packument.versions)) return fail(\"the registry did not answer with a package\");\n const version = resolveNpmVersion(packument, packument.versions, spec);\n return version.ok ? releaseOf(packument.versions, version.value) : version;\n}\n\n/** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */\nexport function verifyNpmBytes(bytes: Uint8Array, release: NpmRelease): string | null {\n if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`;\n return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`;\n}\n\nexport interface GithubAsset {\n tag: string;\n name: string;\n /** The browser download URL, for an unauthenticated download. */\n downloadUrl: string;\n /** The API URL of the asset, for a download with a token (private repositories). */\n apiUrl: string;\n /** GitHub's own `sha256:<hex>` for the asset, when the API gives one (assets uploaded before GitHub\n * started recording digests have none). */\n digest: string | null;\n}\n\nconst assetsOf = (release: Record<string, unknown>): Record<string, unknown>[] => (Array.isArray(release.assets) ? release.assets.filter(isRecord) : []);\n\n/** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin\n * is exactly what a user should not have to trust. */\nexport function resolveGithubAsset(release: unknown): Resolved<GithubAsset> {\n if (!isRecord(release) || typeof release.tag_name !== \"string\") return fail(\"GitHub did not answer with a release\");\n const assets = assetsOf(release);\n const tgz = assets.filter((asset) => typeof asset.name === \"string\" && asset.name.endsWith(\".tgz\"));\n const names = assets.map((asset) => String(asset.name)).join(\", \") || \"none\";\n if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`);\n const [asset] = tgz;\n const downloadUrl = stringOrNull(asset?.browser_download_url);\n const apiUrl = stringOrNull(asset?.url);\n if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl))\n return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`);\n return { ok: true, value: { tag: release.tag_name, name: String(asset?.name), downloadUrl, apiUrl, digest: stringOrNull(asset?.digest) } };\n}\n\nconst SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/;\n\n/** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older\n * uploads carry none, and the bytes still came over https from GitHub — but a digest that is present\n * must be a sha256 and must match. */\nexport function verifyGithubBytes(bytes: Uint8Array, asset: GithubAsset): string | null {\n if (asset.digest === null) return null;\n const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1];\n if (expected === undefined) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`;\n return createHash(\"sha256\").update(bytes).digest(\"hex\") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`;\n}\n\nexport interface FetchDeps {\n fetch: FetchFn;\n /** Sent to GitHub when present: raises the rate limit and reaches private repositories. */\n githubToken?: string | undefined;\n npmRegistry?: string | undefined;\n githubApi?: string | undefined;\n}\n\n// The metadata a base serves decides which bytes are trusted (npm's integrity, GitHub's asset URL),\n// and a GitHub token is sent to it, so a base reached over plain http is refused outright.\nfunction httpsBase(base: string, what: string): string {\n if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`);\n return base.endsWith(\"/\") ? base.slice(0, -1) : base;\n}\n\n// A scoped name keeps its `@` and has its `/` encoded, which is the form the registry routes.\nconst packumentUrl = (registry: string, name: string): string => `${registry}/${name.replaceAll(\"/\", \"%2f\")}`;\n\nasync function fetchNpm(source: Extract<InstallSource, { kind: \"npm\" }>, deps: FetchDeps): Promise<FetchedPackage> {\n const accept = { accept: \"application/vnd.npm.install-v1+json\", \"user-agent\": USER_AGENT };\n const packument = await downloadJson(\n deps.fetch,\n packumentUrl(httpsBase(deps.npmRegistry ?? NPM_REGISTRY, \"the npm registry\"), source.name),\n accept,\n METADATA_LIMITS,\n );\n const resolved = resolveNpmRelease(packument, source.spec);\n if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`);\n const release = resolved.value;\n const bytes = await downloadBytes(deps.fetch, release.tarball, { \"user-agent\": USER_AGENT }, PACKAGE_LIMITS);\n const mismatch = verifyNpmBytes(bytes, release);\n if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`);\n return { bytes, resolved: release.version };\n}\n\nfunction githubHeaders(deps: FetchDeps, accept: string): Record<string, string> {\n const headers: Record<string, string> = { accept, \"user-agent\": USER_AGENT };\n if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`;\n return headers;\n}\n\n// The token goes only to the API it was given for: an asset URL in the release's answer that names\n// another host is refused rather than handed the token, whatever scheme it uses.\nfunction assetUrl(asset: GithubAsset, deps: FetchDeps, apiBase: string): string {\n if (!deps.githubToken) return asset.downloadUrl;\n if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`);\n return asset.apiUrl;\n}\n\nasync function fetchGithub(source: Extract<InstallSource, { kind: \"github\" }>, deps: FetchDeps): Promise<FetchedPackage> {\n const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`;\n const which = source.tag === null ? \"latest\" : `tags/${encodeURIComponent(source.tag)}`;\n const apiBase = httpsBase(deps.githubApi ?? GITHUB_API, \"the GitHub API\");\n const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`;\n const release = await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, \"application/vnd.github+json\"), METADATA_LIMITS);\n const resolved = resolveGithubAsset(release);\n if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`);\n const asset = resolved.value;\n const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, \"application/octet-stream\"), PACKAGE_LIMITS);\n const mismatch = verifyGithubBytes(bytes, asset);\n if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`);\n return { bytes, resolved: asset.tag };\n}\n\nconst errorCode = (err: unknown): string => (err instanceof Error && \"code\" in err && typeof err.code === \"string\" ? err.code : String(err));\n\n// Non-blocking, so opening a FIFO that ends in .tgz returns at once instead of waiting for a writer;\n// it has no effect on reading a regular file. Windows has no such flag, and no FIFOs to open this way.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\nconst READ_CHUNK_BYTES = 64 * 1024;\n\n/** Something to read from in chunks: a FileHandle, or a stand-in in tests. */\nexport interface ChunkReader {\n read: (buffer: Buffer, offset: number, length: number, position: null) => Promise<{ bytesRead: number }>;\n}\n\n/** Reads to the end, refusing as soon as more than `maxBytes` arrive: never holds more than one chunk past it.\n * Once `signal` aborts, no further read is started. */\nexport async function readAtMost(reader: ChunkReader, maxBytes: number, what: string, signal?: AbortSignal): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let received = 0;\n for (;;) {\n if (signal?.aborted) throw new DownloadError(`${what}: reading stopped at the deadline`);\n const chunk = Buffer.alloc(READ_CHUNK_BYTES);\n const { bytesRead } = await reader.read(chunk, 0, READ_CHUNK_BYTES, null);\n if (bytesRead === 0) return Buffer.concat(chunks, received);\n received += bytesRead;\n if (received > maxBytes) throw new DownloadError(`${what} is larger than ${maxBytes} bytes`);\n chunks.push(chunk.subarray(0, bytesRead));\n }\n}\n\n/** Rejects with a DownloadError once `timeoutMs` pass, and aborts the signal `work` was given so it starts\n * nothing more. A read already stuck in the kernel cannot be cancelled from Node — closing its handle waits\n * for it — so at most that one read stays in flight, and its handle closes once it returns. */\nexport function withDeadline<T>(work: (signal: AbortSignal) => Promise<T>, timeoutMs: number, what: string): Promise<T> {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new DownloadError(`${what} took longer than ${timeoutMs} ms to read`));\n }, timeoutMs);\n });\n return Promise.race([work(controller.signal), late]).finally(() => clearTimeout(timer));\n}\n\n// Opened once, and the kind and size come from that handle: checking the path and then reading it\n// again would read whatever replaced it in between.\nasync function readPackageFile(file: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const handle: FileHandle = await open(file, READ_FLAGS).catch((err: unknown) => {\n throw new DownloadError(`${file} could not be read (${errorCode(err)})`);\n });\n try {\n const info = await handle.stat();\n if (!info.isFile()) throw new DownloadError(`${file} is not a file`);\n if (info.size > maxBytes) throw new DownloadError(`${file} is larger than ${maxBytes} bytes`);\n return await readAtMost(handle, maxBytes, file, signal);\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\n// Held to a download's byte limit and deadline.\nasync function fetchFile(source: Extract<InstallSource, { kind: \"file\" }>): Promise<FetchedPackage> {\n const bytes = await withDeadline((signal) => readPackageFile(source.path, PACKAGE_LIMITS.maxBytes, signal), PACKAGE_LIMITS.timeoutMs, source.path);\n return { bytes, resolved: source.path };\n}\n\nexport function fetchPackage(source: InstallSource, deps: FetchDeps): Promise<FetchedPackage> {\n if (source.kind === \"npm\") return fetchNpm(source, deps);\n if (source.kind === \"github\") return fetchGithub(source, deps);\n return fetchFile(source);\n}\n","// Reading what a package file says it is — before it is put in the ledger, and without running any of\n// its code. The file is unpacked into a temporary folder beside the plugins folder (a temporary file\n// belongs next to its destination, not in the OS temp dir), read, and removed.\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createGunzip } from \"node:zlib\";\nimport { linkLeadingOut, resolvesInside } from \"./containment.js\";\nimport { extractTgz } from \"./extract.js\";\nimport { ensureInsideBase } from \"./load.js\";\nimport { resolveEntrySpecifier, toPackageJson } from \"./packageJson.js\";\n\nexport interface InspectedPackage {\n name: string;\n version: string;\n entrySpec: string;\n}\n\nconst TEMP_PREFIX = \".inspect-\";\nconst ONE_MIB = 1024 * 1024;\n// What a package may expand to. The download is capped compressed; this caps what unpacking it can\n// cost in disk and time. It also bounds the member count, since every tar member is at least 512 bytes.\nexport const MAX_UNPACKED_BYTES = 256 * ONE_MIB;\n\n/** Whether the gzip stream expands to at most `maxBytes`, counted while it is inflated so a hostile\n * archive is stopped at the limit rather than after it has been written out. */\nexport function inflatesWithin(bytes: Uint8Array, maxBytes: number): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const gunzip = createGunzip();\n let inflated = 0;\n gunzip.on(\"data\", (chunk: Buffer) => {\n inflated += chunk.length;\n if (inflated <= maxBytes) return;\n gunzip.destroy();\n resolve(false);\n });\n gunzip.on(\"end\", () => resolve(true));\n gunzip.on(\"error\", reject);\n gunzip.end(bytes);\n });\n}\n\nconst UNPARSABLE = Symbol(\"unparsable\");\n\nfunction parseJsonFile(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return UNPARSABLE;\n }\n}\n\nexport type Inspected = { ok: true; value: InspectedPackage } | { ok: false; error: string };\n\nconst refuse = (error: string): Inspected => ({ ok: false, error });\n\nfunction readPackage(dir: string): Inspected {\n const outward = linkLeadingOut(dir);\n if (outward !== null) return refuse(`the package holds a link that leads outside it: ${outward}`);\n const pkgPath = path.join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return refuse(\"the package has no package.json\");\n const parsed = parseJsonFile(pkgPath);\n if (parsed === UNPARSABLE) return refuse(\"the package's package.json is not valid JSON\");\n const pkg = toPackageJson(parsed);\n if (pkg?.name === undefined || pkg.version === undefined) return refuse(\"the package's package.json has no name or version\");\n const entrySpec = resolveEntrySpecifier(pkg);\n if (entrySpec === null) return refuse(\"the package's package.json names no server entry (exports, module or main)\");\n const entryAbs = path.join(dir, entrySpec);\n if (!ensureInsideBase(entryAbs, dir) || !resolvesInside(entryAbs, dir)) return refuse(`the package's server entry ${entrySpec} is not in it`);\n // A folder passes the checks above, and `import()` of one fails at load, where the plugin would be skipped.\n if (!statSync(entryAbs).isFile()) return refuse(`the package's server entry ${entrySpec} is not a file`);\n return { ok: true, value: { name: pkg.name, version: pkg.version, entrySpec } };\n}\n\n/** What the package file says it is, or why it is not a package this loader can use. */\nexport async function inspectPackage(bytes: Uint8Array, pluginsDir: string): Promise<Inspected> {\n const withinLimit = await inflatesWithin(bytes, MAX_UNPACKED_BYTES).catch(() => null);\n if (withinLimit === null) return refuse(\"the file is not a gzip package\");\n if (!withinLimit) return refuse(`the package expands to more than ${MAX_UNPACKED_BYTES} bytes`);\n const work = await mkdtemp(path.join(pluginsDir, TEMP_PREFIX));\n try {\n const tgz = path.join(work, \"package.tgz\");\n await writeFile(tgz, bytes);\n const unpacked = path.join(work, \"unpacked\");\n try {\n extractTgz(tgz, unpacked);\n } catch (err) {\n return refuse(`the file could not be unpacked as a package: ${String(err)}`);\n }\n return readPackage(unpacked);\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n}\n","// Installing a runtime plugin into the workspace ledger, the same way in every host: parse what the\n// user typed, fetch the package file, read what it says it is, let the host ask the user, then put\n// the file in `plugins/` and the entry in the ledger. Nothing here runs the plugin's code — the host\n// loads it at its next start, which is where a tool-name collision is refused, as it is today.\nimport { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { writeFileAtomic } from \"../files/atomic.js\";\nimport { DownloadError } from \"./download.js\";\nimport { fetchPackage, type FetchDeps } from \"./fetchPackage.js\";\nimport { inspectPackage } from \"./inspect.js\";\nimport { installedFileName, isExactVersion, isNpmPackageName, parseInstallSource, sourceLabel, type InstallSource } from \"./installSource.js\";\nimport { parseLedger, type LedgerEntry } from \"./ledger.js\";\nimport { LedgerBusyError, withLedgerLock } from \"./ledgerLock.js\";\nimport { readLedgerForWrite, withLedgerEntry, withoutLedgerEntry, writeLedger } from \"./ledgerWrite.js\";\n\nexport interface RuntimePluginInstallPaths {\n pluginsDir: string;\n ledgerPath: string;\n /** Where packages are unpacked for loading; `<pluginsDir>/.cache` when absent, the hosts' layout.\n * Install no longer touches it: each package file unpacks to a folder of its own (`prepareLedgerEntry`). */\n cacheDir?: string;\n}\n\n/** What is about to be installed, for the host to show before it asks. */\nexport interface InstallPlan {\n name: string;\n version: string;\n source: string;\n tgz: string;\n /** The entry of the same name this install replaces, when one is installed. */\n replaces: LedgerEntry | null;\n}\n\nexport interface InstallDeps extends FetchDeps {\n paths: RuntimePluginInstallPaths;\n /** The host's question to the user; false stops the install before anything is written. */\n confirm: (plan: InstallPlan) => Promise<boolean>;\n now?: () => Date;\n}\n\nexport type InstallResult =\n { status: \"installed\"; entry: LedgerEntry; replaced: LedgerEntry | null } | { status: \"cancelled\"; plan: InstallPlan } | { status: \"failed\"; error: string };\n\nclass InstallError extends Error {}\n\nfunction checkIdentity(source: InstallSource, resolved: string, name: string, version: string): void {\n if (!isNpmPackageName(name)) throw new InstallError(`the package's name ${JSON.stringify(name)} is not an npm package name`);\n if (!isExactVersion(version)) throw new InstallError(`the package's version ${JSON.stringify(version)} is not an exact version`);\n if (source.kind !== \"npm\") return;\n if (name !== source.name) throw new InstallError(`asked for ${source.name}, but the package is ${name}`);\n if (version !== resolved) throw new InstallError(`asked for ${source.name}@${resolved}, but the package is version ${version}`);\n}\n\nasync function preparePlan(source: InstallSource, deps: InstallDeps): Promise<{ plan: InstallPlan; bytes: Buffer }> {\n await mkdir(deps.paths.pluginsDir, { recursive: true });\n const ledger = await readLedgerForWrite(deps.paths.ledgerPath);\n if (!ledger.ok) throw new InstallError(ledger.error);\n const fetched = await fetchPackage(source, deps);\n const inspection = await inspectPackage(fetched.bytes, deps.paths.pluginsDir);\n if (!inspection.ok) throw new InstallError(inspection.error);\n const inspected = inspection.value;\n checkIdentity(source, fetched.resolved, inspected.name, inspected.version);\n const replaces = parseLedger(ledger.raw).find((entry) => entry.name === inspected.name) ?? null;\n const tgz = installedFileName(inspected.name, inspected.version, createHash(\"sha256\").update(fetched.bytes).digest(\"hex\"));\n const plan = { name: inspected.name, version: inspected.version, source: sourceLabel(source, fetched.resolved), tgz, replaces };\n return { plan, bytes: fetched.bytes };\n}\n\nasync function writePackageFile(plan: InstallPlan, bytes: Buffer, pluginsDir: string): Promise<{ tgzPath: string; fileWasThere: boolean }> {\n const tgzPath = path.join(pluginsDir, plan.tgz);\n const fileWasThere = existsSync(tgzPath);\n // The name carries a short hash, so another file under it is a collision, not this package: it may\n // be what an existing entry points at, and it is never replaced.\n if (fileWasThere && !(await readFile(tgzPath)).equals(bytes)) throw new InstallError(`${plan.tgz} already exists with different bytes; not overwritten`);\n if (!fileWasThere) await writeFileAtomic(tgzPath, bytes);\n return { tgzPath, fileWasThere };\n}\n\nconst sameEntry = (left: LedgerEntry | null, right: LedgerEntry | null): boolean =>\n left === null || right === null\n ? left === right\n : left.version === right.version && left.tgz === right.tgz && left.installedAt === right.installedAt && (left.source ?? null) === (right.source ?? null);\n\n/** The ledger as it is now, under the lock, refused when the entry this install replaces is no longer\n * the one the plan showed: another writer installed or removed it while this one downloaded. */\nasync function currentLedger(plan: InstallPlan, deps: InstallDeps): Promise<unknown[]> {\n const ledger = await readLedgerForWrite(deps.paths.ledgerPath);\n if (!ledger.ok) throw new InstallError(ledger.error);\n const current = parseLedger(ledger.raw).find((entry) => entry.name === plan.name) ?? null;\n if (!sameEntry(current, plan.replaces)) throw new InstallError(`${plan.name} changed in the ledger while this install ran; check it again`);\n return ledger.raw;\n}\n\n// Under the ledger lock, from a fresh read: the ledger read for the plan is minutes old after a\n// download, and writing it back would undo whatever another writer did in between.\nasync function commit(plan: InstallPlan, bytes: Buffer, deps: InstallDeps): Promise<LedgerEntry> {\n return withLedgerLock(deps.paths.ledgerPath, () => commitLocked(plan, bytes, deps));\n}\n\nasync function commitLocked(plan: InstallPlan, bytes: Buffer, deps: InstallDeps): Promise<LedgerEntry> {\n const raw = await currentLedger(plan, deps);\n const { tgzPath, fileWasThere } = await writePackageFile(plan, bytes, deps.paths.pluginsDir);\n const installedAt = (deps.now ?? (() => new Date()))().toISOString();\n const entry: LedgerEntry = { name: plan.name, version: plan.version, tgz: plan.tgz, installedAt, source: plan.source };\n try {\n await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));\n } catch (err) {\n // The ledger still names what it named — and its own file, never overwritten, unpacks again on\n // the next start; a new file nothing points at is taken back out.\n if (!fileWasThere) await rm(tgzPath, { force: true });\n throw err;\n }\n return entry;\n}\n\nconst failure = (err: unknown, action: string): { status: \"failed\"; error: string } => {\n if (err instanceof InstallError || err instanceof DownloadError || err instanceof LedgerBusyError) return { status: \"failed\", error: err.message };\n return { status: \"failed\", error: `${action} failed: ${err instanceof Error ? err.message : String(err)}` };\n};\n\n/** Install what `input` names (`<npm name>[@<version or dist-tag>]`, `github:<owner>/<repo>[#<tag>]`, or `file:<absolute path>.tgz`). */\nexport async function installRuntimePlugin(input: unknown, deps: InstallDeps): Promise<InstallResult> {\n const parsed = parseInstallSource(input);\n if (!parsed.ok) return { status: \"failed\", error: parsed.error };\n try {\n const { plan, bytes } = await preparePlan(parsed.source, deps);\n if (!(await deps.confirm(plan))) return { status: \"cancelled\", plan };\n const entry = await commit(plan, bytes, deps);\n return { status: \"installed\", entry, replaced: plan.replaces };\n } catch (err) {\n return failure(err, \"install\");\n }\n}\n\n/** `entry` is null when what was removed was an entry the ledger parser does not accept. */\nexport type UninstallResult = { status: \"removed\"; entry: LedgerEntry | null } | { status: \"not-installed\" } | { status: \"failed\"; error: string };\n\n/** Take `name` out of the ledger. Its package file, unpacked copy and data folders are left in place. */\nexport async function uninstallRuntimePlugin(name: string, paths: RuntimePluginInstallPaths): Promise<UninstallResult> {\n try {\n return await withLedgerLock(paths.ledgerPath, () => removeFromLedger(name, paths));\n } catch (err) {\n return failure(err, \"uninstall\");\n }\n}\n\nasync function removeFromLedger(name: string, paths: RuntimePluginInstallPaths): Promise<UninstallResult> {\n const ledger = await readLedgerForWrite(paths.ledgerPath);\n if (!ledger.ok) return { status: \"failed\", error: ledger.error };\n const entry = parseLedger(ledger.raw).find((candidate) => candidate.name === name) ?? null;\n const remaining = withoutLedgerEntry(ledger.raw, name);\n if (remaining.length === ledger.raw.length) return { status: \"not-installed\" };\n try {\n await writeLedger(paths.ledgerPath, remaining);\n } catch (err) {\n return failure(err, \"uninstall\");\n }\n return { status: \"removed\", entry };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAM,kBAAkB,UAA4C,CAAC,OAAO,OAAO,OAAO,QAAQ,KAAK,OAAO,MAAM,WAAW;AAE/H,IAAa,iBAAiB,UAC5BA,aAAAA,cAAc,OAAO,MAAM,KAC3BA,aAAAA,cAAc,OAAO,SAAS,KAC9BA,aAAAA,cAAc,OAAO,KAAK,KAC1BA,aAAAA,cAAc,OAAO,aAAa,KAClC,eAAe,KAAK;;AAGtB,IAAa,eAAe,QAAgC;CAC1D,IAAI,CAAC,MAAM,QAAQ,GAAG,GAAG,OAAO,CAAC;CACjC,OAAO,IAAI,OAAO,aAAa;AACjC;;ACpBA,I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pG,MAAM,SAAS,mBAAmB,KAAK;CACvC,IAAI,CAAC,OAAO,IAAI,OAAO;EAAE,QAAQ;EAAU,OAAO,OAAO;CAAM;CAC/D,IAAI;EACF,MAAM,EAAE,MAAM,UAAU,MAAM,YAAY,OAAO,QAAQ,IAAI;EAC7D,IAAI,CAAE,MAAM,KAAK,QAAQ,IAAI,GAAI,OAAO;GAAE,QAAQ;GAAa;EAAK;EAEpE,OAAO;GAAE,QAAQ;GAAa,OAAA,MADV,OAAO,MAAM,OAAO,IAAI;GACP,UAAU,KAAK;EAAS;CAC/D,SAAS,KAAK;EACZ,OAAO,QAAQ,KAAK,SAAS;CAC/B;AACF;;AAMA,eAAsB,uBAAuB,MAAc,OAA4D;CACrH,IAAI;EACF,OAAO,MAAM,eAAe,MAAM,kBAAkB,iBAAiB,MAAM,KAAK,CAAC;CACnF,SAAS,KAAK;EACZ,OAAO,QAAQ,KAAK,WAAW;CACjC;AACF;AAEA,eAAe,iBAAiB,MAAc,OAA4D;CACxG,MAAM,SAAS,MAAM,mBAAmB,MAAM,UAAU;CACxD,IAAI,CAAC,OAAO,IAAI,OAAO;EAAE,QAAQ;EAAU,OAAO,OAAO;CAAM;CAC/D,MAAM,QAAQ,YAAY,OAAO,GAAG,CAAC,CAAC,MAAM,cAAc,UAAU,SAAS,IAAI,KAAK;CACtF,MAAM,YAAY,mBAAmB,OAAO,KAAK,IAAI;CACrD,IAAI,UAAU,WAAW,OAAO,IAAI,QAAQ,OAAO,EAAE,QAAQ,gBAAgB;CAC7E,IAAI;EACF,MAAM,YAAY,MAAM,YAAY,SAAS;CAC/C,SAAS,KAAK;EACZ,OAAO,QAAQ,KAAK,WAAW;CACjC;CACA,OAAO;EAAE,QAAQ;EAAW;CAAM;AACpC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["hasStringProp","isRecord","existsSync","path","rmSync","writeFileSync","mkdirSync","execFileSync","renameSync","mkdtempSync","realpathSyncOrNull","isInsideRoot","readdirSync","path","isRecord","path","readFileSync","isPluginFactory","pathToFileURL","isWithinRoot","READ_CHUNK_BYTES","READ_FLAGS","constants","readSync","readPackageFile","openSync","fstatSync","closeSync","existsSync","createHash","refuse","path","isRecord","readFile","writeJsonAtomic","isRecord","open","rm","readFile","timingSafeEqual","randomUUID","mkdir","path","createHash","ONE_MIB","isRecord","createHash","constants","open","createGunzip","readFileSync","path","existsSync","statSync","mkdtemp","writeFile","rm","mkdir","createHash","path","existsSync","readFile","writeFileAtomic","rm"],"sources":["../../src/runtime-plugins/ledger.ts","../../src/runtime-plugins/packageJson.ts","../../src/runtime-plugins/extract.ts","../../src/runtime-plugins/containment.ts","../../src/runtime-plugins/load.ts","../../src/runtime-plugins/npmBuiltinNames.ts","../../src/runtime-plugins/installSource.ts","../../src/runtime-plugins/ledgerWrite.ts","../../src/runtime-plugins/ledgerLock.ts","../../src/runtime-plugins/download.ts","../../src/runtime-plugins/fetchPackage.ts","../../src/runtime-plugins/inspect.ts","../../src/runtime-plugins/install.ts"],"sourcesContent":["// The runtime-plugin install ledger (`plugins/plugins.json` in the workspace). Shared by every host\n// that reads the same workspace, so they agree on which entries count.\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\nexport interface LedgerEntry {\n /** npm package name, e.g. `@gui-chat-plugin/weather`. */\n name: string;\n /** Semver string from the tgz's `package.json`, e.g. `0.1.0`. */\n version: string;\n /** Basename of the tgz inside `plugins/`. Joined with the plugins\n * root to read. */\n tgz: string;\n /** ISO 8601 timestamp of the install. */\n installedAt: string;\n /** Where it was installed from — `npm:<name>@<version>`, `github:<owner>/<repo>#<tag>` or `file:<absolute path>`.\n * Optional: entries written by hand or by an older host have none. */\n source?: string;\n}\n\n// `source` is optional, but when present it must be a string, so the type above tells the truth.\n// No ledger written before the field existed carries one, so this rejects nothing that used to load.\nconst hasValidSource = (value: Record<string, unknown>): boolean => !Object.hasOwn(value, \"source\") || typeof value.source === \"string\";\n\nexport const isLedgerEntry = (value: unknown): value is LedgerEntry =>\n hasStringProp(value, \"name\") &&\n hasStringProp(value, \"version\") &&\n hasStringProp(value, \"tgz\") &&\n hasStringProp(value, \"installedAt\") &&\n hasValidSource(value);\n\n/** The well-formed entries of a parsed ledger; anything that is not an array reads as empty. */\nexport const parseLedger = (raw: unknown): LedgerEntry[] => {\n if (!Array.isArray(raw)) return [];\n return raw.filter(isLedgerEntry);\n};\n","// Reading a runtime plugin's `package.json`: the fields the loader uses, and the entry point it imports.\nimport { isRecord } from \"@mulmoclaude/common\";\n\nexport interface PackageJson {\n name?: string | undefined;\n version?: string | undefined;\n /** Left unnarrowed because every legal Node.js `exports` value is\n * accepted here — string sugar, array fallback chain, condition or\n * subpath map. `pickExportsTarget` is what discriminates them. */\n exports?: unknown | undefined;\n main?: string | undefined;\n module?: string | undefined;\n}\n\nconst optionalString = (value: unknown): string | undefined => (typeof value === \"string\" ? value : undefined);\n\n/** Rebuild the fields the loader reads from arbitrary parsed JSON.\n * Field-by-field rather than a predicate, so a plugin shipping a\n * non-string `main` can't reach `path.join` as if it were one.\n * Returns null when the parsed value isn't an object at all. */\nexport function toPackageJson(value: unknown): PackageJson | null {\n if (!isRecord(value)) return null;\n return {\n name: optionalString(value.name),\n version: optionalString(value.version),\n exports: value.exports,\n main: optionalString(value.main),\n module: optionalString(value.module),\n };\n}\n\n/** Resolve the entry-point path from a plugin's `package.json`. Covers\n * the four legal `exports` shapes per the Node.js spec, then falls\n * through to `module` / `main` for legacy packages.\n *\n * Legal `exports` forms (Node.js docs):\n * 1. String sugar: `\"exports\": \"./index.js\"`\n * 2. Conditional root: `\"exports\": { \"import\": \"./esm.js\", … }`\n * 3. Subpath map: `\"exports\": { \".\": \"./index.js\", \"./util\": \"./util.js\", … }`\n * 4. Subpath + cond.: `\"exports\": { \".\": { \"import\": \"./esm.js\", \"require\": \"./cjs.js\" } }`\n *\n * Earlier the loader only matched form (4) and fell straight through\n * to `module` / `main`. Real npm packages using forms (1)-(3) failed\n * to load (#1077 review). */\nexport function resolveEntrySpecifier(pkg: PackageJson): string | null {\n const fromExports = resolveExportsField(pkg.exports);\n if (fromExports) return fromExports;\n if (typeof pkg.module === \"string\") return pkg.module;\n if (typeof pkg.main === \"string\") return pkg.main;\n return null;\n}\n\nfunction resolveExportsField(exportsField: unknown): string | null {\n // Form 1: top-level string sugar.\n // Form A: array fallback chain (e.g. [\"./dist/index.js\", \"./fallback.js\"]).\n // Form 2: conditional root (e.g. `{ import, require, default }`).\n // Form 3 / 4: subpath map keyed by `.` — value can be a string,\n // array, or condition object (Codex review iter-2 on #1116).\n const root = pickExportsTarget(exportsField);\n if (root) return root;\n if (isRecord(exportsField)) {\n return pickExportsTarget(exportsField[\".\"]);\n }\n return null;\n}\n\n/** Walk a Node.js `exports` value and return the first string entry\n * point this ESM loader can use. Handles every legal target shape:\n *\n * - string: return it directly.\n * - array: try each element in order; first resolvable wins.\n * Per the spec arrays are a fallback chain — Node tries each\n * until one resolves on disk. We don't probe disk here, so\n * \"first string-or-resolvable-condition\" approximates that.\n * - condition object: prefer `import` (ESM-specific), then\n * `default` (universal fallback).\n * - everything else (e.g. only `require`, only nested arrays of\n * condition objects with no string targets): null. */\nfunction pickExportsTarget(value: unknown): string | null {\n if (typeof value === \"string\") return value;\n if (Array.isArray(value)) {\n for (const entry of value) {\n const resolved = pickExportsTarget(entry);\n if (resolved) return resolved;\n }\n return null;\n }\n if (!isRecord(value)) return null;\n // Condition object — `import` first (the ESM-specific condition\n // match), then `default` (the universal fallback that \"always\n // matches\" per the Node.js spec).\n const fromImport = pickExportsTarget(value.import);\n if (fromImport) return fromImport;\n return pickExportsTarget(value.default);\n}\n","// Extracting a runtime plugin's tgz into its version-keyed cache slot.\nimport { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync } from \"node:fs\";\nimport { execFileSync } from \"node:child_process\";\nimport path from \"node:path\";\n\n/** Sentinel file written at the end of a successful extract. The\n * loader uses its presence (not just `existsSync(cachePath)`) as the\n * cache-validity check, so a partial extract (interrupted tar, ENOSPC\n * half-write) is detected and re-extracted on the next boot instead\n * of becoming a permanent broken state. */\nexport const EXTRACT_MARKER = \".extract-complete\";\n\nexport function isCacheValid(cachePath: string): boolean {\n return existsSync(path.join(cachePath, EXTRACT_MARKER));\n}\n\n// The archive can ship its own `.extract-complete` — as a symlink, writing through which would empty\n// whatever it points at outside the folder. Whatever is there is removed (a link is removed, never its\n// target), and the marker is created only if nothing is in its place (`wx`), so it is never followed.\nfunction writeMarker(markerPath: string): void {\n rmSync(markerPath, { recursive: true, force: true });\n writeFileSync(markerPath, \"\", { flag: \"wx\" });\n}\n\n/** Run `tar xzf` to extract a tgz into the version-keyed cache slot.\n * `--strip-components=1` drops the `package/` prefix that npm packs\n * add. `execFileSync` (not `execSync`) so paths bypass shell parsing\n * and never trip on metacharacters in workspace paths. Synchronous\n * because boot is single-threaded and the alternative (a stream\n * pipeline) adds dependencies for no benefit.\n *\n * On failure, the partial directory is removed so the next boot\n * re-extracts cleanly (no sticky broken state). The completion\n * marker is written ONLY after tar exits 0 — readers should test\n * `isCacheValid()`, not `existsSync(cachePath)`. */\nexport function extractTgz(tgzAbs: string, destDir: string): void {\n // Wipe any leftover from a previous failed extract before writing.\n if (existsSync(destDir)) rmSync(destDir, { recursive: true, force: true });\n mkdirSync(destDir, { recursive: true });\n try {\n execFileSync(\"tar\", [\"-xzf\", tgzAbs, \"-C\", destDir, \"--strip-components=1\"], { stdio: \"pipe\" });\n writeMarker(path.join(destDir, EXTRACT_MARKER));\n } catch (err) {\n // Tear down the partial tree so isCacheValid() stays false next boot.\n try {\n rmSync(destDir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n\nconst removeQuietly = (dir: string): void => {\n try {\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // best-effort cleanup\n }\n};\n\n// Moves a complete staging folder into place, and never removes what is there: a folder at the\n// destination may be a complete one another process published a moment ago (same key, so the same\n// bytes), which a running host may be reading. Since every folder is completed before it is renamed in,\n// the destination is never partial in this layout; if it exists without its marker anyway, this refuses\n// rather than guessing, and the caller logs it.\nexport function publishStaged(staging: string, destDir: string): void {\n try {\n renameSync(staging, destDir);\n } catch (err) {\n removeQuietly(staging);\n if (!isCacheValid(destDir)) throw err;\n }\n}\n\n/** Unpack `bytes` (a gzipped npm tarball) to `destDir` so that no reader ever sees a partial tree, even\n * with two processes (MulmoClaude and MulmoTerminal on one workspace) unpacking the same folder at once:\n * into a unique sibling folder, completed with the marker, then renamed into place. The bytes are the\n * ones the caller already read and keyed the folder by, so what is unpacked is what the key names. */\nexport function extractBytesAtomically(bytes: Buffer, destDir: string): void {\n if (isCacheValid(destDir)) return;\n const parent = path.dirname(destDir);\n mkdirSync(parent, { recursive: true });\n const staging = mkdtempSync(path.join(parent, `.${path.basename(destDir)}-`));\n try {\n execFileSync(\"tar\", [\"-xzf\", \"-\", \"-C\", staging, \"--strip-components=1\"], { input: bytes, stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n writeMarker(path.join(staging, EXTRACT_MARKER));\n publishStaged(staging, destDir);\n } catch (err) {\n removeQuietly(staging);\n throw err;\n }\n}\n","// Whether what an extracted package holds stays inside it once links are followed. `tar` refuses to\n// WRITE outside the folder (absolute and `..` members, writes through a link), but it keeps a symlink\n// member as a link, so a file inside can point anywhere; these checks follow it.\nimport { readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { isInsideRoot, realpathSyncOrNull } from \"../files/containment.js\";\n\n/** True when `file` exists and, with every link followed, is inside `root`. */\nexport function resolvesInside(file: string, root: string): boolean {\n const rootReal = realpathSyncOrNull(root);\n const fileReal = realpathSyncOrNull(file);\n return rootReal !== null && fileReal !== null && isInsideRoot(rootReal, fileReal);\n}\n\n/** The first symlink under `root` that leads outside it (or nowhere), relative to `root`; null when\n * every link stays inside. */\nexport function linkLeadingOut(root: string, dir: string = root): string | null {\n for (const item of readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, item.name);\n if (item.isSymbolicLink() && !resolvesInside(full, root)) return path.relative(root, full);\n const nested = item.isDirectory() ? linkLeadingOut(root, full) : null;\n if (nested !== null) return nested;\n }\n return null;\n}\n","// Loading one runtime plugin: from an extracted cache directory to its TOOL_DEFINITION and handler.\n// The host injects what is its own — the runtime a factory plugin is built with, and the logger —\n// so every host that reads the same ledger loads a plugin the same way.\nimport { createHash } from \"node:crypto\";\nimport { closeSync, constants, existsSync, fstatSync, openSync, readFileSync, readSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { pathToFileURL } from \"node:url\";\nimport type { PluginRuntime, ToolDefinition } from \"gui-chat-protocol\";\nimport { isPluginFactory } from \"gui-chat-protocol\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { isWithinRoot } from \"../files/containment.js\";\nimport { resolvesInside } from \"./containment.js\";\nimport { extractBytesAtomically, isCacheValid } from \"./extract.js\";\nimport type { LedgerEntry } from \"./ledger.js\";\nimport { resolveEntrySpecifier, toPackageJson, type PackageJson } from \"./packageJson.js\";\n\nexport interface RuntimePlugin {\n /** npm package name, e.g. `@gui-chat-plugin/weather`. */\n name: string;\n /** Semver string from the tgz's `package.json`. */\n version: string;\n /** Absolute path to the extracted plugin directory, `plugins/.cache/<name>/<version>/<content key>/`\n * for a ledger entry (the full sha256 of the package file's bytes, in hex). */\n cachePath: string;\n /** TOOL_DEFINITION export from the plugin's `dist/index.js`. The\n * shape matches static plugins, so the same MCP merge / dispatch\n * path applies. */\n definition: ToolDefinition;\n /** Server-side handler the dispatch route calls. The convention\n * across @gui-chat-plugin packages is to export it under the same\n * key as `TOOL_DEFINITION.name` (e.g. weather → `fetchWeather`,\n * browse → `browse`); we capture it at load time so the dispatch\n * route doesn't have to re-resolve. The signature follows\n * gui-chat-protocol's `ToolPluginCore.execute`:\n * `(context: ToolContext, args) => Promise<ToolResult>` — context\n * first, args second. `null` means the module shipped a\n * TOOL_DEFINITION but no matching handler — the dispatch will 500\n * with a useful message. */\n execute: ((context: unknown, args: unknown) => unknown) | null;\n /** Optional short, URL-safe alias for the OAuth callback route\n * (#1162). When the plugin's module exports\n * `OAUTH_CALLBACK_ALIAS = \"<alias>\"`, the host registers\n * `/api/plugins/runtime/oauth-callback/<alias>` and forwards\n * `kind: \"oauthCallback\"` dispatch args to this plugin. The\n * package-name-in-path shape was rejected by Spotify Dashboard\n * because of the percent-encoded `@` / `/` characters, so OAuth\n * plugins declare a short alias (e.g. `\"spotify\"`) instead. Null\n * for non-OAuth plugins. */\n oauthCallbackAlias: string | null;\n}\n\n/** The host's logger. Every call carries a data object, so a host can prefix and forward it as is. */\nexport interface RuntimePluginLogger {\n info: (message: string, data: Record<string, unknown>) => void;\n warn: (message: string, data: Record<string, unknown>) => void;\n error: (message: string, data: Record<string, unknown>) => void;\n}\n\nexport interface LoadDeps {\n /** The runtime a FACTORY plugin (`export default definePlugin(...)`) is built with. Called only\n * for a factory module, once per load. */\n runtimeFor: (pkgName: string) => PluginRuntime;\n log: RuntimePluginLogger;\n}\n\n/** Where a ledger's tgz files live, and where they are extracted. */\nexport interface RuntimePluginRoots {\n pluginsDir: string;\n cacheDir: string;\n}\n\nconst isToolDefinition = (value: unknown): value is ToolDefinition => {\n if (!isRecord(value)) return false;\n return typeof value.name === \"string\" && typeof value.description === \"string\";\n};\n\nfunction readPackageJson(cachePath: string, log: RuntimePluginLogger): PackageJson | null {\n const pkgPath = path.join(cachePath, \"package.json\");\n try {\n const parsed: unknown = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n const pkg = toPackageJson(parsed);\n if (!pkg) log.warn(\"package.json is not an object — skipping\", { path: pkgPath });\n return pkg;\n } catch (err) {\n log.warn(\"package.json read/parse failed\", { path: pkgPath, error: String(err) });\n return null;\n }\n}\n\n/** Two carrier shapes (#1110 backward compatibility):\n *\n * 1. **Factory** (`export default definePlugin(setup)`) — `mod.default`\n * is a function. Call it with the plugin's runtime; the return\n * value carries `TOOL_DEFINITION` and the handler keyed by\n * `TOOL_DEFINITION.name`. Closure over runtime gives the handler\n * access to scoped pubsub / files / log without per-call context\n * threading.\n * 2. **Legacy** (`export const TOOL_DEFINITION = ...; export async\n * function <name>(context, args) ...`) — `mod.TOOL_DEFINITION` and\n * `mod[<name>]` directly. Continues to work; existing\n * @gui-chat-plugin packages don't need to migrate.\n */\nfunction resolveCarrier(name: string, mod: Record<string, unknown>, deps: LoadDeps): { carrier: Record<string, unknown>; usingFactory: boolean } {\n const defaultExport = mod.default;\n if (isPluginFactory(defaultExport)) {\n return { carrier: defaultExport(deps.runtimeFor(name)), usingFactory: true };\n }\n return { carrier: mod, usingFactory: false };\n}\n\n/** Callability is the whole of what a dynamically imported export can be\n * proved to have, so parameters and result stay `unknown` — the loader\n * never inspects either. */\nconst isPluginHandler = (value: unknown): value is (...args: unknown[]) => unknown => typeof value === \"function\";\n\n/** Pull the executable from a carrier. Factory-shape handlers take\n * `(args)` only (runtime is closed over) so we wrap to discard the\n * legacy `context` arg the dispatch route passes. Legacy-shape\n * handlers keep the `(context, args)` signature unchanged. Returns\n * null when no function is exported under `definition.name` — the\n * plugin still appears in `tools/list` but dispatch logs + 500s. */\nexport function resolveExecute(\n carrier: Record<string, unknown>,\n definitionName: string,\n usingFactory: boolean,\n): ((context: unknown, args: unknown) => unknown) | null {\n // Own-property guard: a bare `carrier[definitionName]` for a plugin naming its\n // tool `constructor` / `toString` resolves to an Object.prototype function,\n // defeating the `typeof … !== \"function\"` gate below (#2319).\n const handler = Object.hasOwn(carrier, definitionName) ? carrier[definitionName] : undefined;\n if (!isPluginHandler(handler)) return null;\n if (usingFactory) return (_context, args) => handler(args);\n return handler;\n}\n\n/** Read the optional `OAUTH_CALLBACK_ALIAS` named export. Validated\n * against `^[a-z0-9][a-z0-9-]{0,30}$` — short, lowercase,\n * URL-friendly, can't be `..` or contain `/`. A bad alias is logged\n * and ignored (the plugin still loads; just skips the OAuth route\n * registration). */\nconst OAUTH_CALLBACK_ALIAS_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;\nfunction resolveOauthCallbackAlias(name: string, mod: Record<string, unknown>, log: RuntimePluginLogger): string | null {\n const raw = mod.OAUTH_CALLBACK_ALIAS;\n if (raw === undefined) return null;\n if (typeof raw !== \"string\" || !OAUTH_CALLBACK_ALIAS_RE.test(raw)) {\n // eslint-disable-next-line @typescript-eslint/no-base-to-string -- this branch exists BECAUSE `raw` is the wrong shape; echoing whatever it stringifies to is the diagnostic.\n log.warn(\"OAUTH_CALLBACK_ALIAS export is not a valid alias — ignoring\", { name, raw: String(raw) });\n return null;\n }\n return raw;\n}\n\n/** Load a plugin from an already-extracted cache directory. Accepts\n * paths explicitly, so tests don't need a real workspace. Returns\n * null on any structural failure (missing package.json, missing\n * TOOL_DEFINITION, broken import); the caller treats nulls as \"skip\". */\nexport async function loadPluginFromCacheDir(name: string, version: string, cachePath: string, deps: LoadDeps): Promise<RuntimePlugin | null> {\n const { log } = deps;\n const pkg = readPackageJson(cachePath, log);\n if (!pkg) return null;\n const entrySpec = resolveEntrySpecifier(pkg);\n if (!entrySpec) {\n log.warn(\"no entry specifier in package.json — skipping\", { name });\n return null;\n }\n const entryAbs = path.join(cachePath, entrySpec);\n if (!resolvesInside(entryAbs, cachePath)) {\n log.warn(\"plugin entry is missing or leads outside its folder — skipping\", { name, entrySpec });\n return null;\n }\n try {\n const mod: unknown = await import(pathToFileURL(entryAbs).href);\n if (!isRecord(mod)) {\n log.warn(\"plugin module namespace is not an object — skipping\", { name, entrySpec });\n return null;\n }\n const { carrier, usingFactory } = resolveCarrier(name, mod, deps);\n const definition = carrier.TOOL_DEFINITION;\n if (!isToolDefinition(definition)) {\n log.warn(\"no TOOL_DEFINITION export — skipping\", { name, entrySpec, shape: usingFactory ? \"factory\" : \"legacy\" });\n return null;\n }\n const execute = resolveExecute(carrier, definition.name, usingFactory);\n if (!execute) {\n log.warn(\"no execute handler matching TOOL_DEFINITION.name — dispatch will fail\", {\n name,\n expectedExport: definition.name,\n shape: usingFactory ? \"factory\" : \"legacy\",\n });\n }\n const oauthCallbackAlias = resolveOauthCallbackAlias(name, mod, log);\n return { name, version, cachePath, definition, execute, oauthCallbackAlias };\n } catch (err) {\n log.error(\"import failed\", { name, entrySpec, error: String(err) });\n return null;\n }\n}\n\n/** Lexical anchor: confirm `candidate` resolves inside `base`. Catches\n * malformed ledger entries (`name` containing `../../etc`) before we\n * touch the disk. The asset route trusts registry membership, so a\n * registered cachePath that escaped the base would expose arbitrary\n * files via the unauthenticated GET — this check is the first\n * line of defence; `loadPluginFromCacheDir` checks the entry's realpath\n * after extraction as the symlink-escape backstop. */\nexport function ensureInsideBase(candidate: string, base: string): boolean {\n return isWithinRoot(path.resolve(base), path.resolve(candidate));\n}\n\n/** Make a ledger entry's cache directory ready to load: both of its paths anchored inside their\n * roots, its tgz present, and the tgz extracted unless a complete extract is already there.\n * Returns the cache directory, or null (logged) when the entry cannot be loaded. */\n// The unpacked copy is keyed by the BYTES of the package file as well as the name and version: a\n// host that loads while running would otherwise be handed the module it imported before (an ESM\n// import is cached by its URL), and the file name alone is no key — two ledger paths can share a\n// basename, and a hand-written entry can have its file's bytes replaced in place. Different bytes\n// therefore unpack to a different folder, and a reinstall never has to delete a folder a running host\n// may still be serving from. The file is read ONCE, from one handle and to at most the install's limit,\n// and that same read is both hashed and unpacked, so what is unpacked is what the key names.\nconst MAX_PACKAGE_FILE_BYTES = 50 * 1024 * 1024;\nconst READ_CHUNK_BYTES = 64 * 1024;\n// Non-blocking, so a FIFO named in the ledger is refused at open instead of waiting for a writer.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\n\nfunction readChunks(fileHandle: number, maxBytes: number): Buffer | null {\n const chunks: Buffer[] = [];\n let received = 0;\n for (;;) {\n const chunk = Buffer.alloc(READ_CHUNK_BYTES);\n const bytesRead = readSync(fileHandle, chunk, 0, READ_CHUNK_BYTES, null);\n if (bytesRead === 0) return Buffer.concat(chunks, received);\n received += bytesRead;\n if (received > maxBytes) return null;\n chunks.push(chunk.subarray(0, bytesRead));\n }\n}\n\n/** The package file's bytes, or null when it is not a regular file or grows past the limit while read. */\nfunction readPackageFile(tgzAbs: string): Buffer | null {\n const fileHandle = openSync(tgzAbs, READ_FLAGS);\n try {\n return fstatSync(fileHandle).isFile() ? readChunks(fileHandle, MAX_PACKAGE_FILE_BYTES) : null;\n } finally {\n closeSync(fileHandle);\n }\n}\n\nfunction loggedPackageBytes(tgzAbs: string, entry: LedgerEntry, log: RuntimePluginLogger): Buffer | null {\n try {\n const bytes = readPackageFile(tgzAbs);\n if (bytes === null) log.warn(\"tgz is not a package file within the size limit — skipping\", { name: entry.name, tgz: entry.tgz });\n return bytes;\n } catch (err) {\n log.error(\"tgz unreadable — skipping\", { name: entry.name, tgz: entry.tgz, error: String(err) });\n return null;\n }\n}\n\nexport function prepareLedgerEntry(entry: LedgerEntry, roots: RuntimePluginRoots, log: RuntimePluginLogger): string | null {\n const tgzAbs = path.join(roots.pluginsDir, entry.tgz);\n const versionDir = path.join(roots.cacheDir, entry.name, entry.version);\n // Anchor checks BEFORE any disk probe (`existsSync` / `realpath`).\n // The ledger has two separate user-controlled fields — `tgz` and\n // (`name`, `version`) — and each joins against a different base.\n // Both must stay inside their respective bases; otherwise even a\n // stat-only probe would touch a path outside the intended roots.\n if (!ensureInsideBase(tgzAbs, roots.pluginsDir)) {\n log.warn(\"ledger entry tgz escapes plugins root — skipping\", { name: entry.name, tgz: entry.tgz });\n return null;\n }\n if (!ensureInsideBase(versionDir, roots.cacheDir)) {\n log.warn(\"ledger entry escapes plugin cache root — skipping\", {\n name: entry.name,\n version: entry.version,\n });\n return null;\n }\n if (!existsSync(tgzAbs)) {\n log.warn(\"tgz missing — skipping\", { name: entry.name, tgz: entry.tgz });\n return null;\n }\n const bytes = loggedPackageBytes(tgzAbs, entry, log);\n if (bytes === null) return null;\n const cachePath = path.join(versionDir, createHash(\"sha256\").update(bytes).digest(\"hex\"));\n if (!isCacheValid(cachePath)) {\n try {\n extractBytesAtomically(bytes, cachePath);\n log.info(\"extracted\", { name: entry.name, version: entry.version });\n } catch (err) {\n log.error(\"extract failed\", { name: entry.name, error: String(err) });\n return null;\n }\n }\n return cachePath;\n}\n","// The names validate-npm-package-name 7.0.1 refuses for a new package because Node ships a module\n// by that name (lib/builtin-modules.json there). A fixed copy rather than node:module builtinModules,\n// which differs between Node versions, so every host refuses the same names.\nexport const NPM_BUILTIN_MODULE_NAMES: ReadonlySet<string> = new Set([\n \"_http_agent\",\n \"_http_client\",\n \"_http_common\",\n \"_http_incoming\",\n \"_http_outgoing\",\n \"_http_server\",\n \"_stream_duplex\",\n \"_stream_passthrough\",\n \"_stream_readable\",\n \"_stream_transform\",\n \"_stream_wrap\",\n \"_stream_writable\",\n \"_tls_common\",\n \"_tls_wrap\",\n \"assert\",\n \"assert/strict\",\n \"async_hooks\",\n \"buffer\",\n \"child_process\",\n \"cluster\",\n \"console\",\n \"constants\",\n \"crypto\",\n \"dgram\",\n \"diagnostics_channel\",\n \"dns\",\n \"dns/promises\",\n \"domain\",\n \"events\",\n \"fs\",\n \"fs/promises\",\n \"http\",\n \"http2\",\n \"https\",\n \"inspector\",\n \"inspector/promises\",\n \"module\",\n \"net\",\n \"os\",\n \"path\",\n \"path/posix\",\n \"path/win32\",\n \"perf_hooks\",\n \"process\",\n \"punycode\",\n \"querystring\",\n \"readline\",\n \"readline/promises\",\n \"repl\",\n \"stream\",\n \"stream/consumers\",\n \"stream/promises\",\n \"stream/web\",\n \"string_decoder\",\n \"sys\",\n \"timers\",\n \"timers/promises\",\n \"tls\",\n \"trace_events\",\n \"tty\",\n \"url\",\n \"util\",\n \"util/types\",\n \"v8\",\n \"vm\",\n \"wasi\",\n \"worker_threads\",\n \"zlib\",\n \"node:sea\",\n \"node:sqlite\",\n \"node:test\",\n \"node:test/reporters\",\n]);\n","// Where a runtime plugin is installed from, as a user types it: `<npm name>[@<version or dist-tag>]`,\n// `github:<owner>/<repo>[#<tag>]`, or `file:<absolute path>.tgz`. Parsing only — nothing here reaches\n// the network or the disk.\n\nimport path from \"node:path\";\nimport { NPM_BUILTIN_MODULE_NAMES } from \"./npmBuiltinNames.js\";\n\nexport type InstallSource =\n { kind: \"npm\"; name: string; spec: string | null } | { kind: \"github\"; owner: string; repo: string; tag: string | null } | { kind: \"file\"; path: string };\n\nexport type ParsedInstallSource = { ok: true; source: InstallSource } | { ok: false; error: string };\n\nconst MAX_NPM_NAME_LENGTH = 214;\nconst MAX_TAG_LENGTH = 255;\n// npm's rule for a NEW package name (validate-npm-package-name 7.0.1), one segment at a time: lower\n// case, URL-safe, no `~'!()*`. Its leading `.`, `-` and `_` checks apply to the WHOLE name, so inside\n// a scoped name a segment may start with `-` or `_` (`@_scope/-pkg`). A leading `.` is refused in every\n// segment here: it is what would let one read as `.` or `..` in a path. Split rather than one pattern,\n// so no quantifier nests.\nconst NPM_UNSCOPED_NAME = /^[a-z0-9][a-z0-9\\-._]*$/;\nconst NPM_SCOPED_SEGMENT = /^[a-z0-9\\-_][a-z0-9\\-._]*$/;\n// semver 2.0.0: a numeric identifier has no leading zero; an identifier is never empty.\nconst NUMERIC_IDENTIFIER = /^(?:0|[1-9]\\d*)$/;\nconst ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/;\nconst ALL_DIGITS = /^\\d+$/;\n// A dist-tag cannot parse as a version or a range, so one that starts with a letter is unambiguous.\nconst DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]*$/;\nconst GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;\nconst GITHUB_REPO = /^[A-Za-z0-9._-]{1,100}$/;\nconst GITHUB_TAG = /^[A-Za-z0-9._+/-]+$/;\nconst GITHUB_PREFIX = \"github:\";\nconst FILE_PREFIX = \"file:\";\nconst PACKAGE_FILE_SUFFIX = \".tgz\";\n\nconst refuse = (error: string): ParsedInstallSource => ({ ok: false, error });\n\nfunction isNpmNameShape(name: string): boolean {\n if (!name.startsWith(\"@\")) return NPM_UNSCOPED_NAME.test(name);\n const slash = name.indexOf(\"/\");\n return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1));\n}\n\n// npm refuses these whole names for a new package. npm compares them lower-cased; a name reaching here\n// is already lower case, so an exact match is the same test.\nconst NPM_EXCLUDED_NAMES: ReadonlySet<string> = new Set([\"node_modules\", \"favicon.ico\"]);\n\nconst isNpmReservedName = (name: string): boolean => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name);\n\nexport const isNpmPackageName = (name: string): boolean => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name);\n\nconst isVersionCore = (core: string): boolean => {\n const parts = core.split(\".\");\n return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part));\n};\n\n// A prerelease identifier that is all digits is numeric, so no leading zero; a build identifier may have one.\nconst isLabel = (label: string, prerelease: boolean): boolean =>\n label.split(\".\").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part)));\n\n/** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */\nfunction isSemverShape(version: string): boolean {\n const plus = version.indexOf(\"+\");\n const build = plus === -1 ? null : version.slice(plus + 1);\n const withoutBuild = plus === -1 ? version : version.slice(0, plus);\n const dash = withoutBuild.indexOf(\"-\");\n const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash);\n const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1);\n return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false));\n}\n\n/** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because\n * what it resolves to would change between the confirmation and the next install. */\nexport const isNpmVersionSpec = (spec: string): boolean => isSemverShape(spec) || DIST_TAG.test(spec);\n\n/** An exact version — what a package's own `version` must be, since it becomes part of a file name\n * and a cache folder. */\nexport const isExactVersion = (version: string): boolean => isSemverShape(version);\n\nfunction parseNpm(input: string): ParsedInstallSource {\n const specAt = input.lastIndexOf(\"@\");\n const hasSpec = specAt > 0;\n const name = hasSpec ? input.slice(0, specAt) : input;\n const spec = hasSpec ? input.slice(specAt + 1) : null;\n if (!isNpmPackageName(name)) return refuse(`not an npm package name: ${JSON.stringify(name)}`);\n if (spec !== null && !isNpmVersionSpec(spec)) return refuse(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`);\n return { ok: true, source: { kind: \"npm\", name, spec } };\n}\n\nconst isGithubTag = (tag: string): boolean =>\n tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split(\"/\").some((part) => part === \"\" || part === \".\" || part === \"..\");\n\nfunction parseGithub(rest: string): ParsedInstallSource {\n const hash = rest.indexOf(\"#\");\n const ownerRepo = hash === -1 ? rest : rest.slice(0, hash);\n const tag = hash === -1 ? null : rest.slice(hash + 1);\n const [owner = \"\", repo = \"\", ...extra] = ownerRepo.split(\"/\");\n if (extra.length > 0) return refuse(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`);\n return githubSource(owner, repo, tag, ownerRepo);\n}\n\n/** Owner, repo and tag already split apart, checked as one GitHub source. `shown` is how the owner/repo\n * was written, for the error. */\nfunction githubSource(owner: string, repo: string, tag: string | null, shown: string): ParsedInstallSource {\n if (!GITHUB_OWNER.test(owner)) return refuse(`not a GitHub owner/repo: ${JSON.stringify(shown)}`);\n if (!GITHUB_REPO.test(repo) || repo === \".\" || repo === \"..\") return refuse(`not a GitHub owner/repo: ${JSON.stringify(shown)}`);\n if (tag !== null && !isGithubTag(tag)) return refuse(`not a release tag: ${JSON.stringify(tag)}`);\n return { ok: true, source: { kind: \"github\", owner, repo, tag } };\n}\n\n// A package file already on disk. Absolute only: core has no working directory of its own, so the host\n// resolves a relative path against its own before calling. A folder is not a source — packing one\n// runs its lifecycle scripts, and installing never runs plugin code.\nfunction parseFile(rest: string): ParsedInstallSource {\n if (rest === \"\") return refuse(\"a file: source names no file\");\n if (rest.includes(\"\\0\")) return refuse(\"a file: source contains a NUL byte\");\n if (!path.isAbsolute(rest)) return refuse(`a file: source must be an absolute path: ${JSON.stringify(rest)}`);\n if (!rest.endsWith(PACKAGE_FILE_SUFFIX)) return refuse(`a file: source must name a ${PACKAGE_FILE_SUFFIX} package file: ${JSON.stringify(rest)}`);\n return { ok: true, source: { kind: \"file\", path: path.normalize(rest) } };\n}\n\nconst GITHUB_HOSTS: ReadonlySet<string> = new Set([\"github.com\", \"www.github.com\"]);\nconst URL_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\//;\nconst GIT_SUFFIX = /\\.git$/;\nconst GITHUB_URL_SHAPES = \"https://github.com/<owner>/<repo>, …/releases/latest or …/releases/tag/<tag>\";\n\n// URL reports `https://@github.com/…` with an empty username, so a userinfo part is found in the text as written.\nconst AUTHORITY_WITH_USERINFO = /^[A-Za-z][A-Za-z0-9+.-]*:\\/\\/[^/?#\\\\]*@/;\n\nconst refuseUrl = (input: string): ParsedInstallSource => refuse(`not a GitHub repository or release URL (${GITHUB_URL_SHAPES}): ${JSON.stringify(input)}`);\n\n/** The tag a release path names: none for the repository itself or `releases/latest`, else `releases/tag/<tag>`.\n * `undefined` when the path is something else (a branch, a file, an issue). */\nfunction releaseTagOf(rest: readonly string[]): string | null | undefined {\n if (rest.length === 0) return null;\n if (rest.length === 2 && rest[0] === \"releases\" && rest[1] === \"latest\") return null;\n if (rest.length >= 3 && rest[0] === \"releases\" && rest[1] === \"tag\") return rest.slice(2).join(\"/\");\n return undefined;\n}\n\n/** A URL path's segments, percent-decoded; `null` when one does not decode. Only the leading `/` and one\n * trailing `/` are dropped: an empty segment anywhere else is kept, so a tag written `x//y` is refused as\n * `github:` refuses it rather than read as `x/y`. */\nfunction decodedSegments(pathname: string): string[] | null {\n const segments = pathname.split(\"/\").slice(1);\n const withoutTrailing = segments.at(-1) === \"\" ? segments.slice(0, -1) : segments;\n try {\n return withoutTrailing.map((segment) => decodeURIComponent(segment));\n } catch {\n return null;\n }\n}\n\n// The URL a browser shows for a repository or one of its releases, read as the `github:` source it means.\n// A query or fragment is ignored; the owner, repo and tag are then checked exactly as `github:` checks them,\n// each on its own, so a decoded `#` or `/` cannot move a boundary between them. `:443` is the https\n// default, which URL drops, so it reads as the same address.\nfunction parseGithubUrl(input: string): ParsedInstallSource {\n const url = URL.canParse(input) ? new URL(input) : null;\n if (url === null || url.protocol !== \"https:\" || !GITHUB_HOSTS.has(url.hostname)) return refuseUrl(input);\n if (url.port !== \"\" || AUTHORITY_WITH_USERINFO.test(input)) return refuseUrl(input);\n const segments = decodedSegments(url.pathname);\n if (segments === null) return refuseUrl(input);\n const [owner = \"\", repo = \"\", ...rest] = segments;\n const tag = releaseTagOf(rest);\n if (tag === undefined || owner === \"\" || repo === \"\") return refuseUrl(input);\n const bareRepo = repo.replace(GIT_SUFFIX, \"\");\n return githubSource(owner, bareRepo, tag, `${owner}/${bareRepo}`);\n}\n\nexport function parseInstallSource(input: unknown): ParsedInstallSource {\n if (typeof input !== \"string\") return refuse(\"an install source is a string\");\n const trimmed = input.trim();\n if (trimmed === \"\") return refuse(\"an install source is empty\");\n if (trimmed.startsWith(GITHUB_PREFIX)) return parseGithub(trimmed.slice(GITHUB_PREFIX.length));\n if (trimmed.startsWith(FILE_PREFIX)) return parseFile(trimmed.slice(FILE_PREFIX.length));\n if (URL_SCHEME.test(trimmed)) return parseGithubUrl(trimmed);\n return parseNpm(trimmed);\n}\n\n/** The ledger's `source` field for what was actually installed: the resolved version or tag. */\nexport function sourceLabel(source: InstallSource, resolved: string): string {\n if (source.kind === \"npm\") return `npm:${source.name}@${resolved}`;\n if (source.kind === \"github\") return `github:${source.owner}/${source.repo}#${resolved}`;\n return `${FILE_PREFIX}${source.path}`;\n}\n\n/** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */\nexport const packageFileName = (name: string, version: string): string => `${name.replace(/^@/, \"\").replaceAll(\"/\", \"-\")}-${version}.tgz`;\n\nconst CONTENT_ID_LENGTH = 12;\n\n/** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`.\n * Two different packages with one name and version (a GitHub tag published again) then get different\n * files. The hash is short, so the install also refuses to write over an existing file whose bytes\n * differ: that is what keeps a file an entry points at from changing. */\nexport const installedFileName = (name: string, version: string, sha256Hex: string): string =>\n packageFileName(name, version).replace(/\\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);\n","// Writing the runtime-plugin ledger. The edits work on the RAW parsed value rather than on\n// `parseLedger`'s output: an entry the parser skips (hand-written, missing a field) is still the\n// user's, and an install must not delete it by rewriting the file from the entries it understood.\n// The one exception is a value carrying the name being installed or removed: the name gets exactly\n// one entry, so such a value is replaced or removed even when the parser would have skipped it.\nimport { readFile } from \"node:fs/promises\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { writeJsonAtomic } from \"../files/json.js\";\nimport type { LedgerEntry } from \"./ledger.js\";\n\nconst isEntryNamed = (value: unknown, name: string): boolean => isRecord(value) && Object.hasOwn(value, \"name\") && value.name === name;\n\n/** The ledger with `entry` in it, exactly once: it takes the place of the first entry of the same\n * name, any further ones are dropped (each would load another copy), and with none it is appended. */\nexport function withLedgerEntry(raw: readonly unknown[], entry: LedgerEntry): unknown[] {\n const first = raw.findIndex((value) => isEntryNamed(value, entry.name));\n if (first === -1) return [...raw, entry];\n return raw.flatMap((value, index) => {\n if (index === first) return [entry];\n return isEntryNamed(value, entry.name) ? [] : [value];\n });\n}\n\n/** The ledger without any entry named `name`; everything else is kept as it was. */\nexport const withoutLedgerEntry = (raw: readonly unknown[], name: string): unknown[] => raw.filter((value) => !isEntryNamed(value, name));\n\nexport type ReadLedgerResult = { ok: true; raw: unknown[] } | { ok: false; error: string };\n\nasync function readLedgerText(ledgerPath: string): Promise<{ ok: true; text: string | null } | { ok: false; error: string }> {\n try {\n return { ok: true, text: await readFile(ledgerPath, \"utf-8\") };\n } catch (err) {\n if (isRecord(err) && err.code === \"ENOENT\") return { ok: true, text: null };\n return { ok: false, error: `cannot read the plugin ledger ${ledgerPath}: ${String(err)}` };\n }\n}\n\nfunction parseLedgerText(ledgerPath: string, text: string): ReadLedgerResult {\n try {\n const parsed: unknown = JSON.parse(text);\n return Array.isArray(parsed)\n ? { ok: true, raw: parsed }\n : { ok: false, error: `the plugin ledger ${ledgerPath} is not a JSON array; fix it before installing` };\n } catch (err) {\n return { ok: false, error: `the plugin ledger ${ledgerPath} is not valid JSON; fix it before installing: ${String(err)}` };\n }\n}\n\n/** The ledger as an array to edit: a missing file is an empty ledger; a file that is not a JSON\n * array is refused rather than overwritten, since writing over it would lose what the user wrote. */\nexport async function readLedgerForWrite(ledgerPath: string): Promise<ReadLedgerResult> {\n const read = await readLedgerText(ledgerPath);\n if (!read.ok) return read;\n return read.text === null ? { ok: true, raw: [] } : parseLedgerText(ledgerPath, read.text);\n}\n\nexport const writeLedger = (ledgerPath: string, raw: readonly unknown[]): Promise<void> => writeJsonAtomic(ledgerPath, raw);\n","// One writer of a workspace's plugin ledger at a time, across processes: MulmoClaude's server, its\n// `plugin` command and MulmoTerminal all edit the same plugins.json. The lock is a file beside the\n// ledger created with O_EXCL, holding the holder's pid and a token.\n//\n// Nothing ever removes another writer's lock. Taking over a lock that looks abandoned cannot be made\n// safe with files alone — every scheme tried let a third writer in while the first still worked — and\n// an edit holds the lock for milliseconds, so a lock left behind means a writer crashed mid-edit. A\n// writer that waits past the limit fails instead, and when the pid in the lock is not running, it says\n// which file to remove.\nimport { randomUUID, timingSafeEqual } from \"node:crypto\";\nimport { mkdir, open, readFile, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n/** How long a writer waits for another to finish before giving up. */\nexport const LEDGER_LOCK_WAIT_MS = 10_000;\nconst LEDGER_LOCK_RETRY_MS = 50;\n\nexport class LedgerBusyError extends Error {}\n\nexport interface LedgerLockDeps {\n now?: () => number;\n sleep?: (delayMs: number) => Promise<void>;\n waitMs?: number;\n /** Whether a process with this pid is running; injectable for tests. */\n isRunning?: (pid: number) => boolean;\n}\n\nexport const ledgerLockPath = (ledgerPath: string): string => `${ledgerPath}.lock`;\n\nconst hasCode = (err: unknown, code: string): boolean => isRecord(err) && err.code === code;\n\n/** Creates the lock holding `token`; false when another writer holds it. A failed write leaves no lock. */\nasync function tryCreate(lockPath: string, token: string): Promise<boolean> {\n const opened = await open(lockPath, \"wx\").catch((err: unknown) => {\n if (hasCode(err, \"EEXIST\")) return null;\n throw err;\n });\n if (opened === null) return false;\n try {\n await opened.writeFile(token);\n } catch (err) {\n await opened.close().catch(() => undefined);\n await rm(lockPath, { force: true });\n throw err;\n }\n await opened.close();\n return true;\n}\n\n/** Removes the lock only while it still carries `token`: if someone removed it by hand, it is not ours. */\nasync function release(lockPath: string, token: string): Promise<void> {\n const held = await readFile(lockPath).catch(() => null);\n const ours = Buffer.from(token);\n if (held !== null && held.length === ours.length && timingSafeEqual(held, ours)) await rm(lockPath, { force: true });\n}\n\n/** `kill(pid, 0)` sends nothing: ESRCH means no such process, EPERM means one we may not signal. */\nexport function processIsRunning(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return hasCode(err, \"EPERM\");\n }\n}\n\nconst PID_PREFIX = /^(\\d+) /;\n\nasync function busyError(lockPath: string, ledgerPath: string, isRunning: (pid: number) => boolean): Promise<LedgerBusyError> {\n const held = await readFile(lockPath, \"utf-8\").catch(() => \"\");\n const pid = Number(PID_PREFIX.exec(held)?.[1] ?? Number.NaN);\n if (Number.isInteger(pid) && pid > 0 && !isRunning(pid)) {\n return new LedgerBusyError(`${lockPath} was left by a writer that is no longer running (pid ${pid}); remove it and try again`);\n }\n return new LedgerBusyError(`another install or removal is editing ${ledgerPath}; try again when it finishes`);\n}\n\nconst defaultSleep = (delayMs: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, delayMs));\n\n/** Runs `work` holding the ledger's lock; throws LedgerBusyError when another writer keeps it past the wait. */\nexport async function withLedgerLock<T>(ledgerPath: string, work: () => Promise<T>, deps: LedgerLockDeps = {}): Promise<T> {\n const now = deps.now ?? Date.now;\n const sleep = deps.sleep ?? defaultSleep;\n const lockPath = ledgerLockPath(ledgerPath);\n const token = `${process.pid} ${randomUUID()}\\n`;\n await mkdir(path.dirname(lockPath), { recursive: true });\n const deadline = now() + (deps.waitMs ?? LEDGER_LOCK_WAIT_MS);\n while (!(await tryCreate(lockPath, token))) {\n if (now() >= deadline) throw await busyError(lockPath, ledgerPath, deps.isRunning ?? processIsRunning);\n await sleep(LEDGER_LOCK_RETRY_MS);\n }\n try {\n return await work();\n } finally {\n await release(lockPath, token);\n }\n}\n","// Downloading a runtime plugin's metadata and package file. The deadline covers the whole transfer —\n// headers AND body — because a server that sends headers and then stalls would otherwise hold the\n// install forever, and the size cap is enforced while reading, so a lying Content-Length cannot\n// make the host buffer more than it agreed to.\nimport { createHash } from \"node:crypto\";\n\nexport type FetchFn = typeof fetch;\n\nexport interface DownloadLimits {\n timeoutMs: number;\n maxBytes: number;\n}\n\nexport class DownloadError extends Error {}\n\n// A pending read is ended when the deadline passes: cancelling the reader settles it at once (the\n// streams spec closes the reader whatever the source's own cancel does), and the abort reason is thrown.\n// Never awaited, so a body whose cancel never settles cannot hold the install.\nasync function readCapped(body: ReadableStream<Uint8Array>, url: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const reader = body.getReader();\n const onAbort = (): void => {\n reader.cancel(signal.reason).catch(() => undefined);\n };\n signal.addEventListener(\"abort\", onAbort, { once: true });\n try {\n return await collectChunks(reader, url, maxBytes, signal);\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n }\n}\n\nasync function collectChunks(reader: ReadableStreamDefaultReader<Uint8Array>, url: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const chunks: Uint8Array[] = [];\n let received = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (signal.aborted) throw signal.reason;\n if (done) return Buffer.concat(chunks);\n received += value.byteLength;\n if (received > maxBytes) {\n reader.cancel().catch(() => undefined);\n throw new DownloadError(`${url} is larger than ${maxBytes} bytes`);\n }\n chunks.push(value);\n }\n}\n\n/** The response's body once it is known to be a success within the cap. */\n// A refused response's body is cancelled, so the connection behind it is released rather than left\n// streaming whatever the server keeps sending.\nfunction refuseResponse(res: Response, message: string): never {\n res.body?.cancel().catch(() => undefined);\n throw new DownloadError(message);\n}\n\nfunction acceptedBody(res: Response, url: string, maxBytes: number): ReadableStream<Uint8Array> {\n if (!res.ok) refuseResponse(res, `${url} answered HTTP ${res.status}`);\n const declared = Number(res.headers.get(\"content-length\"));\n if (Number.isFinite(declared) && declared > maxBytes) refuseResponse(res, `${url} is ${declared} bytes, more than ${maxBytes}`);\n if (!res.body) throw new DownloadError(`${url} answered with no body`);\n return res.body;\n}\n\n// A fetch implementation is meant to reject once its signal aborts, but one that does not would hold\n// the install forever; the request is raced against the signal so the deadline holds either way.\nfunction settlesByDeadline<T>(pending: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n const onAbort = (): void => reject(signal.reason);\n if (signal.aborted) onAbort();\n signal.addEventListener(\"abort\", onAbort, { once: true });\n pending.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\nexport async function downloadBytes(fetchFn: FetchFn, url: string, headers: Record<string, string>, limits: DownloadLimits): Promise<Buffer> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(new DownloadError(`${url} did not finish within ${limits.timeoutMs}ms`)), limits.timeoutMs);\n try {\n const res = await settlesByDeadline(fetchFn(url, { headers, signal: controller.signal, redirect: \"follow\" }), controller.signal);\n return await readCapped(acceptedBody(res, url, limits.maxBytes), url, limits.maxBytes, controller.signal);\n } catch (err) {\n if (err instanceof DownloadError) throw err;\n const reason: unknown = controller.signal.aborted ? controller.signal.reason : err;\n throw reason instanceof DownloadError ? reason : new DownloadError(`${url} could not be downloaded: ${String(reason)}`);\n } finally {\n clearTimeout(timer);\n }\n}\n\nexport async function downloadJson(fetchFn: FetchFn, url: string, headers: Record<string, string>, limits: DownloadLimits): Promise<unknown> {\n const bytes = await downloadBytes(fetchFn, url, headers, limits);\n try {\n return JSON.parse(bytes.toString(\"utf-8\"));\n } catch {\n throw new DownloadError(`${url} did not answer with JSON`);\n }\n}\n\n// sha1 is not accepted: it is too weak to stand for \"these are the bytes the registry published\",\n// and every version published since 2017 carries a sha512.\nconst SRI = /^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/;\n\n/** Whether `bytes` match an npm `dist.integrity` (Subresource Integrity, possibly several space-\n * separated hashes) — the strongest algorithm present must match. False when none is recognised. */\nexport function matchesIntegrity(bytes: Uint8Array, integrity: string): boolean {\n const hashes = integrity\n .split(/\\s+/)\n .map((part) => SRI.exec(part))\n .filter((match): match is RegExpExecArray => match !== null);\n const order = [\"sha512\", \"sha384\", \"sha256\"];\n const strongest = order.find((algorithm) => hashes.some((match) => match[1] === algorithm));\n if (strongest === undefined) return false;\n const actual = createHash(strongest).update(bytes).digest(\"base64\");\n return hashes.some((match) => match[1] === strongest && match[2] === actual);\n}\n","// Fetching a runtime plugin's package file from npm, a GitHub release, or a file on disk. Which version\n// / asset to take is decided by pure functions over the registry's answer, so the choice is testable\n// without a network; the fetches around them only move bytes.\nimport { createHash } from \"node:crypto\";\nimport { constants, open, type FileHandle } from \"node:fs/promises\";\nimport { isRecord } from \"@mulmoclaude/common\";\nimport { DownloadError, downloadBytes, downloadJson, matchesIntegrity, type FetchFn } from \"./download.js\";\nimport type { InstallSource } from \"./installSource.js\";\n\nexport const NPM_REGISTRY = \"https://registry.npmjs.org\";\nexport const GITHUB_API = \"https://api.github.com\";\nconst ONE_SECOND_MS = 1000;\nconst ONE_MIB = 1024 * 1024;\nconst METADATA_LIMITS = { timeoutMs: 30 * ONE_SECOND_MS, maxBytes: 32 * ONE_MIB };\nconst PACKAGE_LIMITS = { timeoutMs: 120 * ONE_SECOND_MS, maxBytes: 50 * ONE_MIB };\n// GitHub's API refuses a request without a User-Agent; a generic one names no user or host.\nconst USER_AGENT = \"mulmo-runtime-plugins\";\n\nexport interface FetchedPackage {\n bytes: Buffer;\n /** The npm version, GitHub tag or file path that was resolved, for the ledger's `source`. */\n resolved: string;\n}\n\nexport interface NpmRelease {\n version: string;\n tarball: string;\n integrity: string | null;\n}\n\n/** A decision that either holds a value or says why there is none. */\nexport type Resolved<T> = { ok: true; value: T } | { ok: false; error: string };\n\nconst stringOrNull = (value: unknown): string | null => (typeof value === \"string\" ? value : null);\nconst fail = <T>(error: string): Resolved<T> => ({ ok: false, error });\nconst isHttpsUrl = (value: string): boolean => value.startsWith(\"https://\");\n\nfunction resolveNpmVersion(packument: Record<string, unknown>, versions: Record<string, unknown>, spec: string | null): Resolved<string> {\n const tags = isRecord(packument[\"dist-tags\"]) ? packument[\"dist-tags\"] : {};\n if (spec !== null && Object.hasOwn(versions, spec)) return { ok: true, value: spec };\n const tag = spec ?? \"latest\";\n const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null;\n if (fromTag !== null) return { ok: true, value: fromTag };\n return fail(spec === null ? \"the package has no latest version\" : `no version or dist-tag ${JSON.stringify(spec)}`);\n}\n\nfunction releaseOf(versions: Record<string, unknown>, version: string): Resolved<NpmRelease> {\n const entry = Object.hasOwn(versions, version) ? versions[version] : undefined;\n const dist = isRecord(entry) && isRecord(entry.dist) ? entry.dist : null;\n const tarball = dist ? stringOrNull(dist.tarball) : null;\n if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`);\n return { ok: true, value: { version, tarball, integrity: stringOrNull(dist.integrity) } };\n}\n\n/** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */\nexport function resolveNpmRelease(packument: unknown, spec: string | null): Resolved<NpmRelease> {\n if (!isRecord(packument) || !isRecord(packument.versions)) return fail(\"the registry did not answer with a package\");\n const version = resolveNpmVersion(packument, packument.versions, spec);\n return version.ok ? releaseOf(packument.versions, version.value) : version;\n}\n\n/** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */\nexport function verifyNpmBytes(bytes: Uint8Array, release: NpmRelease): string | null {\n if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`;\n return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`;\n}\n\nexport interface GithubAsset {\n tag: string;\n name: string;\n /** The browser download URL, for an unauthenticated download. */\n downloadUrl: string;\n /** The API URL of the asset, for a download with a token (private repositories). */\n apiUrl: string;\n /** GitHub's own `sha256:<hex>` for the asset, when the API gives one (assets uploaded before GitHub\n * started recording digests have none). */\n digest: string | null;\n}\n\nconst assetsOf = (release: Record<string, unknown>): Record<string, unknown>[] => (Array.isArray(release.assets) ? release.assets.filter(isRecord) : []);\n\n/** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin\n * is exactly what a user should not have to trust. */\nexport function resolveGithubAsset(release: unknown): Resolved<GithubAsset> {\n if (!isRecord(release) || typeof release.tag_name !== \"string\") return fail(\"GitHub did not answer with a release\");\n const assets = assetsOf(release);\n const tgz = assets.filter((asset) => typeof asset.name === \"string\" && asset.name.endsWith(\".tgz\"));\n const names = assets.map((asset) => String(asset.name)).join(\", \") || \"none\";\n if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`);\n const [asset] = tgz;\n const downloadUrl = stringOrNull(asset?.browser_download_url);\n const apiUrl = stringOrNull(asset?.url);\n if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl))\n return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`);\n return { ok: true, value: { tag: release.tag_name, name: String(asset?.name), downloadUrl, apiUrl, digest: stringOrNull(asset?.digest) } };\n}\n\nconst SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/;\n\n/** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older\n * uploads carry none, and the bytes still came over https from GitHub — but a digest that is present\n * must be a sha256 and must match. */\nexport function verifyGithubBytes(bytes: Uint8Array, asset: GithubAsset): string | null {\n if (asset.digest === null) return null;\n const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1];\n if (expected === undefined) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`;\n return createHash(\"sha256\").update(bytes).digest(\"hex\") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`;\n}\n\nexport interface FetchDeps {\n fetch: FetchFn;\n /** Sent to GitHub when present: raises the rate limit and reaches private repositories. */\n githubToken?: string | undefined;\n npmRegistry?: string | undefined;\n githubApi?: string | undefined;\n}\n\n// The metadata a base serves decides which bytes are trusted (npm's integrity, GitHub's asset URL),\n// and a GitHub token is sent to it, so a base reached over plain http is refused outright.\nfunction httpsBase(base: string, what: string): string {\n if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`);\n return base.endsWith(\"/\") ? base.slice(0, -1) : base;\n}\n\n// A scoped name keeps its `@` and has its `/` encoded, which is the form the registry routes.\nconst packumentUrl = (registry: string, name: string): string => `${registry}/${name.replaceAll(\"/\", \"%2f\")}`;\n\nasync function fetchNpm(source: Extract<InstallSource, { kind: \"npm\" }>, deps: FetchDeps): Promise<FetchedPackage> {\n const accept = { accept: \"application/vnd.npm.install-v1+json\", \"user-agent\": USER_AGENT };\n const packument = await downloadJson(\n deps.fetch,\n packumentUrl(httpsBase(deps.npmRegistry ?? NPM_REGISTRY, \"the npm registry\"), source.name),\n accept,\n METADATA_LIMITS,\n );\n const resolved = resolveNpmRelease(packument, source.spec);\n if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`);\n const release = resolved.value;\n const bytes = await downloadBytes(deps.fetch, release.tarball, { \"user-agent\": USER_AGENT }, PACKAGE_LIMITS);\n const mismatch = verifyNpmBytes(bytes, release);\n if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`);\n return { bytes, resolved: release.version };\n}\n\nfunction githubHeaders(deps: FetchDeps, accept: string): Record<string, string> {\n const headers: Record<string, string> = { accept, \"user-agent\": USER_AGENT };\n if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`;\n return headers;\n}\n\n// The token goes only to the API it was given for: an asset URL in the release's answer that names\n// another host is refused rather than handed the token, whatever scheme it uses.\nfunction assetUrl(asset: GithubAsset, deps: FetchDeps, apiBase: string): string {\n if (!deps.githubToken) return asset.downloadUrl;\n if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`);\n return asset.apiUrl;\n}\n\nasync function fetchGithub(source: Extract<InstallSource, { kind: \"github\" }>, deps: FetchDeps): Promise<FetchedPackage> {\n const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`;\n const which = source.tag === null ? \"latest\" : `tags/${encodeURIComponent(source.tag)}`;\n const apiBase = httpsBase(deps.githubApi ?? GITHUB_API, \"the GitHub API\");\n const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`;\n const release = await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, \"application/vnd.github+json\"), METADATA_LIMITS);\n const resolved = resolveGithubAsset(release);\n if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`);\n const asset = resolved.value;\n const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, \"application/octet-stream\"), PACKAGE_LIMITS);\n const mismatch = verifyGithubBytes(bytes, asset);\n if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`);\n return { bytes, resolved: asset.tag };\n}\n\nconst errorCode = (err: unknown): string => (err instanceof Error && \"code\" in err && typeof err.code === \"string\" ? err.code : String(err));\n\n// Non-blocking, so opening a FIFO that ends in .tgz returns at once instead of waiting for a writer;\n// it has no effect on reading a regular file. Windows has no such flag, and no FIFOs to open this way.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NONBLOCK ?? 0);\nconst READ_CHUNK_BYTES = 64 * 1024;\n\n/** Something to read from in chunks: a FileHandle, or a stand-in in tests. */\nexport interface ChunkReader {\n read: (buffer: Buffer, offset: number, length: number, position: null) => Promise<{ bytesRead: number }>;\n}\n\n/** Reads to the end, refusing as soon as more than `maxBytes` arrive: never holds more than one chunk past it.\n * Once `signal` aborts, no further read is started. */\nexport async function readAtMost(reader: ChunkReader, maxBytes: number, what: string, signal?: AbortSignal): Promise<Buffer> {\n const chunks: Buffer[] = [];\n let received = 0;\n for (;;) {\n if (signal?.aborted) throw new DownloadError(`${what}: reading stopped at the deadline`);\n const chunk = Buffer.alloc(READ_CHUNK_BYTES);\n const { bytesRead } = await reader.read(chunk, 0, READ_CHUNK_BYTES, null);\n if (bytesRead === 0) return Buffer.concat(chunks, received);\n received += bytesRead;\n if (received > maxBytes) throw new DownloadError(`${what} is larger than ${maxBytes} bytes`);\n chunks.push(chunk.subarray(0, bytesRead));\n }\n}\n\n/** Rejects with a DownloadError once `timeoutMs` pass, and aborts the signal `work` was given so it starts\n * nothing more. A read already stuck in the kernel cannot be cancelled from Node — closing its handle waits\n * for it — so at most that one read stays in flight, and its handle closes once it returns. */\nexport function withDeadline<T>(work: (signal: AbortSignal) => Promise<T>, timeoutMs: number, what: string): Promise<T> {\n const controller = new AbortController();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new DownloadError(`${what} took longer than ${timeoutMs} ms to read`));\n }, timeoutMs);\n });\n return Promise.race([work(controller.signal), late]).finally(() => clearTimeout(timer));\n}\n\n// Opened once, and the kind and size come from that handle: checking the path and then reading it\n// again would read whatever replaced it in between.\nasync function readPackageFile(file: string, maxBytes: number, signal: AbortSignal): Promise<Buffer> {\n const handle: FileHandle = await open(file, READ_FLAGS).catch((err: unknown) => {\n throw new DownloadError(`${file} could not be read (${errorCode(err)})`);\n });\n try {\n const info = await handle.stat();\n if (!info.isFile()) throw new DownloadError(`${file} is not a file`);\n if (info.size > maxBytes) throw new DownloadError(`${file} is larger than ${maxBytes} bytes`);\n return await readAtMost(handle, maxBytes, file, signal);\n } finally {\n await handle.close().catch(() => undefined);\n }\n}\n\n// Held to a download's byte limit and deadline.\nasync function fetchFile(source: Extract<InstallSource, { kind: \"file\" }>): Promise<FetchedPackage> {\n const bytes = await withDeadline((signal) => readPackageFile(source.path, PACKAGE_LIMITS.maxBytes, signal), PACKAGE_LIMITS.timeoutMs, source.path);\n return { bytes, resolved: source.path };\n}\n\nexport function fetchPackage(source: InstallSource, deps: FetchDeps): Promise<FetchedPackage> {\n if (source.kind === \"npm\") return fetchNpm(source, deps);\n if (source.kind === \"github\") return fetchGithub(source, deps);\n return fetchFile(source);\n}\n","// Reading what a package file says it is — before it is put in the ledger, and without running any of\n// its code. The file is unpacked into a temporary folder beside the plugins folder (a temporary file\n// belongs next to its destination, not in the OS temp dir), read, and removed.\nimport { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createGunzip } from \"node:zlib\";\nimport { linkLeadingOut, resolvesInside } from \"./containment.js\";\nimport { extractTgz } from \"./extract.js\";\nimport { ensureInsideBase } from \"./load.js\";\nimport { resolveEntrySpecifier, toPackageJson } from \"./packageJson.js\";\n\nexport interface InspectedPackage {\n name: string;\n version: string;\n entrySpec: string;\n}\n\nconst TEMP_PREFIX = \".inspect-\";\nconst ONE_MIB = 1024 * 1024;\n// What a package may expand to. The download is capped compressed; this caps what unpacking it can\n// cost in disk and time. It also bounds the member count, since every tar member is at least 512 bytes.\nexport const MAX_UNPACKED_BYTES = 256 * ONE_MIB;\n\n/** Whether the gzip stream expands to at most `maxBytes`, counted while it is inflated so a hostile\n * archive is stopped at the limit rather than after it has been written out. */\nexport function inflatesWithin(bytes: Uint8Array, maxBytes: number): Promise<boolean> {\n return new Promise((resolve, reject) => {\n const gunzip = createGunzip();\n let inflated = 0;\n gunzip.on(\"data\", (chunk: Buffer) => {\n inflated += chunk.length;\n if (inflated <= maxBytes) return;\n gunzip.destroy();\n resolve(false);\n });\n gunzip.on(\"end\", () => resolve(true));\n gunzip.on(\"error\", reject);\n gunzip.end(bytes);\n });\n}\n\nconst UNPARSABLE = Symbol(\"unparsable\");\n\nfunction parseJsonFile(file: string): unknown {\n try {\n return JSON.parse(readFileSync(file, \"utf-8\"));\n } catch {\n return UNPARSABLE;\n }\n}\n\nexport type Inspected = { ok: true; value: InspectedPackage } | { ok: false; error: string };\n\nconst refuse = (error: string): Inspected => ({ ok: false, error });\n\nfunction readPackage(dir: string): Inspected {\n const outward = linkLeadingOut(dir);\n if (outward !== null) return refuse(`the package holds a link that leads outside it: ${outward}`);\n const pkgPath = path.join(dir, \"package.json\");\n if (!existsSync(pkgPath)) return refuse(\"the package has no package.json\");\n const parsed = parseJsonFile(pkgPath);\n if (parsed === UNPARSABLE) return refuse(\"the package's package.json is not valid JSON\");\n const pkg = toPackageJson(parsed);\n if (pkg?.name === undefined || pkg.version === undefined) return refuse(\"the package's package.json has no name or version\");\n const entrySpec = resolveEntrySpecifier(pkg);\n if (entrySpec === null) return refuse(\"the package's package.json names no server entry (exports, module or main)\");\n const entryAbs = path.join(dir, entrySpec);\n if (!ensureInsideBase(entryAbs, dir) || !resolvesInside(entryAbs, dir)) return refuse(`the package's server entry ${entrySpec} is not in it`);\n // A folder passes the checks above, and `import()` of one fails at load, where the plugin would be skipped.\n if (!statSync(entryAbs).isFile()) return refuse(`the package's server entry ${entrySpec} is not a file`);\n return { ok: true, value: { name: pkg.name, version: pkg.version, entrySpec } };\n}\n\n/** What the package file says it is, or why it is not a package this loader can use. */\nexport async function inspectPackage(bytes: Uint8Array, pluginsDir: string): Promise<Inspected> {\n const withinLimit = await inflatesWithin(bytes, MAX_UNPACKED_BYTES).catch(() => null);\n if (withinLimit === null) return refuse(\"the file is not a gzip package\");\n if (!withinLimit) return refuse(`the package expands to more than ${MAX_UNPACKED_BYTES} bytes`);\n const work = await mkdtemp(path.join(pluginsDir, TEMP_PREFIX));\n try {\n const tgz = path.join(work, \"package.tgz\");\n await writeFile(tgz, bytes);\n const unpacked = path.join(work, \"unpacked\");\n try {\n extractTgz(tgz, unpacked);\n } catch (err) {\n return refuse(`the file could not be unpacked as a package: ${String(err)}`);\n }\n return readPackage(unpacked);\n } finally {\n await rm(work, { recursive: true, force: true });\n }\n}\n","// Installing a runtime plugin into the workspace ledger, the same way in every host: parse what the\n// user typed, fetch the package file, read what it says it is, let the host ask the user, then put\n// the file in `plugins/` and the entry in the ledger. Nothing here runs the plugin's code — the host\n// loads it at its next start, which is where a tool-name collision is refused, as it is today.\nimport { createHash } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readFile, rm } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { writeFileAtomic } from \"../files/atomic.js\";\nimport { DownloadError } from \"./download.js\";\nimport { fetchPackage, type FetchDeps } from \"./fetchPackage.js\";\nimport { inspectPackage } from \"./inspect.js\";\nimport { installedFileName, isExactVersion, isNpmPackageName, parseInstallSource, sourceLabel, type InstallSource } from \"./installSource.js\";\nimport { parseLedger, type LedgerEntry } from \"./ledger.js\";\nimport { LedgerBusyError, withLedgerLock } from \"./ledgerLock.js\";\nimport { readLedgerForWrite, withLedgerEntry, withoutLedgerEntry, writeLedger } from \"./ledgerWrite.js\";\n\nexport interface RuntimePluginInstallPaths {\n pluginsDir: string;\n ledgerPath: string;\n /** Where packages are unpacked for loading; `<pluginsDir>/.cache` when absent, the hosts' layout.\n * Install no longer touches it: each package file unpacks to a folder of its own (`prepareLedgerEntry`). */\n cacheDir?: string;\n}\n\n/** What is about to be installed, for the host to show before it asks. */\nexport interface InstallPlan {\n name: string;\n version: string;\n source: string;\n tgz: string;\n /** The entry of the same name this install replaces, when one is installed. */\n replaces: LedgerEntry | null;\n}\n\nexport interface InstallDeps extends FetchDeps {\n paths: RuntimePluginInstallPaths;\n /** The host's question to the user; false stops the install before anything is written. */\n confirm: (plan: InstallPlan) => Promise<boolean>;\n now?: () => Date;\n}\n\nexport type InstallResult =\n { status: \"installed\"; entry: LedgerEntry; replaced: LedgerEntry | null } | { status: \"cancelled\"; plan: InstallPlan } | { status: \"failed\"; error: string };\n\nclass InstallError extends Error {}\n\nfunction checkIdentity(source: InstallSource, resolved: string, name: string, version: string): void {\n if (!isNpmPackageName(name)) throw new InstallError(`the package's name ${JSON.stringify(name)} is not an npm package name`);\n if (!isExactVersion(version)) throw new InstallError(`the package's version ${JSON.stringify(version)} is not an exact version`);\n if (source.kind !== \"npm\") return;\n if (name !== source.name) throw new InstallError(`asked for ${source.name}, but the package is ${name}`);\n if (version !== resolved) throw new InstallError(`asked for ${source.name}@${resolved}, but the package is version ${version}`);\n}\n\nasync function preparePlan(source: InstallSource, deps: InstallDeps): Promise<{ plan: InstallPlan; bytes: Buffer }> {\n await mkdir(deps.paths.pluginsDir, { recursive: true });\n const ledger = await readLedgerForWrite(deps.paths.ledgerPath);\n if (!ledger.ok) throw new InstallError(ledger.error);\n const fetched = await fetchPackage(source, deps);\n const inspection = await inspectPackage(fetched.bytes, deps.paths.pluginsDir);\n if (!inspection.ok) throw new InstallError(inspection.error);\n const inspected = inspection.value;\n checkIdentity(source, fetched.resolved, inspected.name, inspected.version);\n const replaces = parseLedger(ledger.raw).find((entry) => entry.name === inspected.name) ?? null;\n const tgz = installedFileName(inspected.name, inspected.version, createHash(\"sha256\").update(fetched.bytes).digest(\"hex\"));\n const plan = { name: inspected.name, version: inspected.version, source: sourceLabel(source, fetched.resolved), tgz, replaces };\n return { plan, bytes: fetched.bytes };\n}\n\nasync function writePackageFile(plan: InstallPlan, bytes: Buffer, pluginsDir: string): Promise<{ tgzPath: string; fileWasThere: boolean }> {\n const tgzPath = path.join(pluginsDir, plan.tgz);\n const fileWasThere = existsSync(tgzPath);\n // The name carries a short hash, so another file under it is a collision, not this package: it may\n // be what an existing entry points at, and it is never replaced.\n if (fileWasThere && !(await readFile(tgzPath)).equals(bytes)) throw new InstallError(`${plan.tgz} already exists with different bytes; not overwritten`);\n if (!fileWasThere) await writeFileAtomic(tgzPath, bytes);\n return { tgzPath, fileWasThere };\n}\n\nconst sameEntry = (left: LedgerEntry | null, right: LedgerEntry | null): boolean =>\n left === null || right === null\n ? left === right\n : left.version === right.version && left.tgz === right.tgz && left.installedAt === right.installedAt && (left.source ?? null) === (right.source ?? null);\n\n/** The ledger as it is now, under the lock, refused when the entry this install replaces is no longer\n * the one the plan showed: another writer installed or removed it while this one downloaded. */\nasync function currentLedger(plan: InstallPlan, deps: InstallDeps): Promise<unknown[]> {\n const ledger = await readLedgerForWrite(deps.paths.ledgerPath);\n if (!ledger.ok) throw new InstallError(ledger.error);\n const current = parseLedger(ledger.raw).find((entry) => entry.name === plan.name) ?? null;\n if (!sameEntry(current, plan.replaces)) throw new InstallError(`${plan.name} changed in the ledger while this install ran; check it again`);\n return ledger.raw;\n}\n\n// Under the ledger lock, from a fresh read: the ledger read for the plan is minutes old after a\n// download, and writing it back would undo whatever another writer did in between.\nasync function commit(plan: InstallPlan, bytes: Buffer, deps: InstallDeps): Promise<LedgerEntry> {\n return withLedgerLock(deps.paths.ledgerPath, () => commitLocked(plan, bytes, deps));\n}\n\nasync function commitLocked(plan: InstallPlan, bytes: Buffer, deps: InstallDeps): Promise<LedgerEntry> {\n const raw = await currentLedger(plan, deps);\n const { tgzPath, fileWasThere } = await writePackageFile(plan, bytes, deps.paths.pluginsDir);\n const installedAt = (deps.now ?? (() => new Date()))().toISOString();\n const entry: LedgerEntry = { name: plan.name, version: plan.version, tgz: plan.tgz, installedAt, source: plan.source };\n try {\n await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));\n } catch (err) {\n // The ledger still names what it named — and its own file, never overwritten, unpacks again on\n // the next start; a new file nothing points at is taken back out.\n if (!fileWasThere) await rm(tgzPath, { force: true });\n throw err;\n }\n return entry;\n}\n\nconst failure = (err: unknown, action: string): { status: \"failed\"; error: string } => {\n if (err instanceof InstallError || err instanceof DownloadError || err instanceof LedgerBusyError) return { status: \"failed\", error: err.message };\n return { status: \"failed\", error: `${action} failed: ${err instanceof Error ? err.message : String(err)}` };\n};\n\n/** Install what `input` names (`<npm name>[@<version or dist-tag>]`, `github:<owner>/<repo>[#<tag>]`, or `file:<absolute path>.tgz`). */\nexport async function installRuntimePlugin(input: unknown, deps: InstallDeps): Promise<InstallResult> {\n const parsed = parseInstallSource(input);\n if (!parsed.ok) return { status: \"failed\", error: parsed.error };\n try {\n const { plan, bytes } = await preparePlan(parsed.source, deps);\n if (!(await deps.confirm(plan))) return { status: \"cancelled\", plan };\n const entry = await commit(plan, bytes, deps);\n return { status: \"installed\", entry, replaced: plan.replaces };\n } catch (err) {\n return failure(err, \"install\");\n }\n}\n\n/** `entry` is null when what was removed was an entry the ledger parser does not accept. */\nexport type UninstallResult = { status: \"removed\"; entry: LedgerEntry | null } | { status: \"not-installed\" } | { status: \"failed\"; error: string };\n\n/** Take `name` out of the ledger. Its package file, unpacked copy and data folders are left in place. */\nexport async function uninstallRuntimePlugin(name: string, paths: RuntimePluginInstallPaths): Promise<UninstallResult> {\n try {\n return await withLedgerLock(paths.ledgerPath, () => removeFromLedger(name, paths));\n } catch (err) {\n return failure(err, \"uninstall\");\n }\n}\n\nasync function removeFromLedger(name: string, paths: RuntimePluginInstallPaths): Promise<UninstallResult> {\n const ledger = await readLedgerForWrite(paths.ledgerPath);\n if (!ledger.ok) return { status: \"failed\", error: ledger.error };\n const entry = parseLedger(ledger.raw).find((candidate) => candidate.name === name) ?? null;\n const remaining = withoutLedgerEntry(ledger.raw, name);\n if (remaining.length === ledger.raw.length) return { status: \"not-installed\" };\n try {\n await writeLedger(paths.ledgerPath, remaining);\n } catch (err) {\n return failure(err, \"uninstall\");\n }\n return { status: \"removed\", entry };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAqBA,IAAM,kBAAkB,UAA4C,CAAC,OAAO,OAAO,OAAO,QAAQ,KAAK,OAAO,MAAM,WAAW;AAE/H,IAAa,iBAAi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