@mulmoclaude/core 7.0.0 → 7.2.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.
Files changed (58) hide show
  1. package/dist/collection/registry/server/index.cjs +6 -5
  2. package/dist/collection/registry/server/index.cjs.map +1 -1
  3. package/dist/collection/registry/server/index.js +6 -5
  4. package/dist/collection/registry/server/index.js.map +1 -1
  5. package/dist/collection/server/index.cjs +2 -2
  6. package/dist/collection/server/index.js +2 -2
  7. package/dist/collection-watchers/index.cjs +2 -2
  8. package/dist/collection-watchers/index.js +2 -2
  9. package/dist/containment-D_vAa6eT.js +40 -0
  10. package/dist/containment-D_vAa6eT.js.map +1 -0
  11. package/dist/containment-Dc3gO4wD.cjs +65 -0
  12. package/dist/containment-Dc3gO4wD.cjs.map +1 -0
  13. package/dist/{discovery-DR4GNqrp.js → discovery-BIQY56d1.js} +4 -4
  14. package/dist/discovery-BIQY56d1.js.map +1 -0
  15. package/dist/{discovery-BkCeYBf6.cjs → discovery-D3e3JaAv.cjs} +4 -4
  16. package/dist/discovery-D3e3JaAv.cjs.map +1 -0
  17. package/dist/feeds/server/index.cjs +2 -2
  18. package/dist/feeds/server/index.js +2 -2
  19. package/dist/files/containment.d.ts +9 -0
  20. package/dist/files/index.cjs +38 -8
  21. package/dist/files/index.cjs.map +1 -1
  22. package/dist/files/index.d.ts +2 -0
  23. package/dist/files/index.js +30 -5
  24. package/dist/files/index.js.map +1 -1
  25. package/dist/files/withinRoot.d.ts +5 -0
  26. package/dist/google/index.cjs +1 -1
  27. package/dist/google/index.js +1 -1
  28. package/dist/{server-CnCUBmSn.cjs → server-BGxmZppB.cjs} +4 -3
  29. package/dist/server-BGxmZppB.cjs.map +1 -0
  30. package/dist/{server-Dp5KWarO.js → server-MKJPGYKI.js} +4 -3
  31. package/dist/server-MKJPGYKI.js.map +1 -0
  32. package/dist/whisper/extra-args.d.ts +14 -0
  33. package/dist/whisper/index.cjs +76 -8
  34. package/dist/whisper/index.cjs.map +1 -1
  35. package/dist/whisper/index.js +76 -8
  36. package/dist/whisper/index.js.map +1 -1
  37. package/dist/whisper/sidecar-helpers.d.ts +3 -2
  38. package/dist/whisper/sidecar.d.ts +2 -2
  39. package/dist/wiki/server/fs.d.ts +0 -7
  40. package/dist/wiki/server/index.cjs +7 -59
  41. package/dist/wiki/server/index.cjs.map +1 -1
  42. package/dist/wiki/server/index.js +8 -60
  43. package/dist/wiki/server/index.js.map +1 -1
  44. package/dist/withinRoot-CHPN9eHD.cjs +53 -0
  45. package/dist/withinRoot-CHPN9eHD.cjs.map +1 -0
  46. package/dist/withinRoot-CheaBWt0.js +42 -0
  47. package/dist/withinRoot-CheaBWt0.js.map +1 -0
  48. package/dist/workspace-setup/index.js +36 -2
  49. package/dist/workspace-setup/index.js.map +1 -1
  50. package/package.json +1 -1
  51. package/dist/discovery-BkCeYBf6.cjs.map +0 -1
  52. package/dist/discovery-DR4GNqrp.js.map +0 -1
  53. package/dist/safe-D79sHxq1.cjs +0 -43
  54. package/dist/safe-D79sHxq1.cjs.map +0 -1
  55. package/dist/safe-DRNa8UBp.js +0 -30
  56. package/dist/safe-DRNa8UBp.js.map +0 -1
  57. package/dist/server-CnCUBmSn.cjs.map +0 -1
  58. package/dist/server-Dp5KWarO.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["delay"],"sources":["../../src/whisper/internal.ts","../../src/whisper/ffmpeg.ts","../../src/whisper/models.ts","../../src/whisper/sidecar-helpers.ts","../../src/whisper/sidecar.ts","../../src/whisper/whisper.ts"],"sourcesContent":["// Small self-contained utilities so the package has no host dependencies.\n\nexport const ONE_SECOND_MS = 1_000;\nexport const ONE_MINUTE_MS = 60_000;\n\nexport { errorMessage } from \"../utils/errors.js\";\n\n/** Minimal logger the host can inject; defaults to no-op so the package\n * is silent unless wired up. */\nexport interface WhisperLogger {\n info: (message: string, data?: unknown) => void;\n warn: (message: string, data?: unknown) => void;\n error: (message: string, data?: unknown) => void;\n}\n\nconst NOOP = (): void => undefined;\nexport const NOOP_LOGGER: WhisperLogger = { info: NOOP, warn: NOOP, error: NOOP };\n","// Thin wrapper around the system `ffmpeg` binary (provided by the host) for\n// converting a browser webm/opus clip to the 16 kHz mono 16-bit WAV whisper.cpp\n// requires.\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { ONE_MINUTE_MS } from \"./internal.ts\";\n\nconst execFileAsync = promisify(execFile);\n\n/** ffmpeg args to decode any input to 16 kHz mono signed-16-bit WAV. Pure +\n * exported for unit tests. */\nexport function buildWav16kArgs(inputPath: string, outputPath: string): string[] {\n return [\"-y\", \"-loglevel\", \"error\", \"-i\", inputPath, \"-ar\", \"16000\", \"-ac\", \"1\", \"-c:a\", \"pcm_s16le\", outputPath];\n}\n\n/** Convert `inputPath` to a 16 kHz mono WAV at `outputPath`. Throws on ffmpeg\n * failure or timeout. */\nexport async function convertToWav16k(inputPath: string, outputPath: string, ffmpegBinary = \"ffmpeg\"): Promise<void> {\n await execFileAsync(ffmpegBinary, buildWav16kArgs(inputPath, outputPath), {\n timeout: ONE_MINUTE_MS,\n });\n}\n","// Whisper GGML model registry + on-disk management. The host injects the models\n// directory (e.g. `{workspace}/models`); nothing here reads a host module.\n\nimport { createWriteStream, mkdirSync, renameSync, statSync, unlinkSync } from \"node:fs\";\nimport { once } from \"node:events\";\nimport path from \"node:path\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, type WhisperLogger } from \"./internal.ts\";\n\nexport interface WhisperModelSpec {\n /** GGML filename — identical on disk and in the Hugging Face repo. */\n readonly file: string;\n /** Download URL (Hugging Face whisper.cpp model repo). */\n readonly url: string;\n /** Conservative lower bound on the finished file size, in bytes — guards\n * against a truncated transfer or an HTML error page saved as the model\n * without pinning an exact checksum. */\n readonly minBytes: number;\n}\n\nconst HF_BASE = \"https://huggingface.co/ggerganov/whisper.cpp/resolve/main\";\n\n// large-v3-turbo: strong accuracy, near-real-time on Apple Silicon with Metal.\n// small/base are lighter fallbacks for low-RAM machines.\nexport const WHISPER_MODELS = {\n \"large-v3-turbo\": { file: \"ggml-large-v3-turbo.bin\", url: `${HF_BASE}/ggml-large-v3-turbo.bin`, minBytes: 1_000_000_000 },\n small: { file: \"ggml-small.bin\", url: `${HF_BASE}/ggml-small.bin`, minBytes: 300_000_000 },\n base: { file: \"ggml-base.bin\", url: `${HF_BASE}/ggml-base.bin`, minBytes: 100_000_000 },\n} as const satisfies Record<string, WhisperModelSpec>;\n\nexport type WhisperModelName = keyof typeof WHISPER_MODELS;\nexport const DEFAULT_WHISPER_MODEL: WhisperModelName = \"large-v3-turbo\";\n\nexport function isWhisperModelName(value: unknown): value is WhisperModelName {\n // Own-property check — `in` would accept inherited keys like \"toString\",\n // which then crash the `WHISPER_MODELS[name]` lookups instead of falling\n // back to the default.\n return typeof value === \"string\" && Object.prototype.hasOwnProperty.call(WHISPER_MODELS, value);\n}\n\n/** Resolve a possibly-unset / unknown model name to a valid one. */\nexport function resolveModelName(name: string | undefined): WhisperModelName {\n return isWhisperModelName(name) ? name : DEFAULT_WHISPER_MODEL;\n}\n\nexport function modelFilePath(modelsDir: string, name: WhisperModelName): string {\n return path.join(modelsDir, WHISPER_MODELS[name].file);\n}\n\n/** A model is \"ready\" when its file exists and meets the size floor. */\nexport function isModelReady(modelsDir: string, name: WhisperModelName): boolean {\n try {\n return statSync(modelFilePath(modelsDir, name)).size >= WHISPER_MODELS[name].minBytes;\n } catch {\n return false;\n }\n}\n\nexport type ModelDownloadState = \"idle\" | \"downloading\" | \"ready\" | \"error\";\n\nexport interface ModelStatus {\n state: ModelDownloadState;\n /** 0..1 — present only while downloading and Content-Length is known. */\n progress?: number;\n /** Present only in the \"error\" state. */\n error?: string;\n}\n\n/** Report status precedence: an in-flight download wins, then an on-disk ready\n * file, then the last transient state (idle if none). Pure so the precedence\n * is unit-testable without touching the filesystem. */\nexport function pickModelStatus(live: ModelStatus | undefined, isReady: boolean): ModelStatus {\n if (live?.state === \"downloading\") return live;\n if (isReady) return { state: \"ready\" };\n return live ?? { state: \"idle\" };\n}\n\n/** Parse a `Content-Length` header to a byte count; unknown / malformed → 0. */\nexport function parseContentLength(header: string | null): number {\n return Number(header) || 0;\n}\n\n// Abort a download if no bytes arrive for this long (stalled connection).\nconst DOWNLOAD_STALL_TIMEOUT_MS = ONE_MINUTE_MS;\n\nexport interface ModelDownloader {\n getStatus: (name: WhisperModelName) => ModelStatus;\n ensure: (name: WhisperModelName) => Promise<void>;\n}\n\ninterface StreamToFileDeps {\n downloadStatus: Map<WhisperModelName, ModelStatus>;\n onProgress: () => void;\n}\n\n/** Drain the response stream into the `.partial` file, resetting the stall\n * timer on every chunk and publishing progress once the total size is known. */\nasync function streamToFile(\n body: ReadableStream<Uint8Array>,\n partialPath: string,\n total: number,\n name: WhisperModelName,\n deps: StreamToFileDeps,\n): Promise<void> {\n const reader = body.getReader();\n const fileStream = createWriteStream(partialPath);\n let received = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n deps.onProgress();\n received += value.byteLength;\n if (!fileStream.write(value)) await once(fileStream, \"drain\");\n if (total > 0) deps.downloadStatus.set(name, { state: \"downloading\", progress: received / total });\n }\n fileStream.end();\n await once(fileStream, \"finish\");\n } catch (err) {\n // `createWriteStream` opens lazily. Destroying it while that open is still\n // in flight lets the open's own failure land later as an `error` event with\n // no listener — an uncaughtException that kills the process. `err` already\n // carries the real cause, so absorb the late one.\n fileStream.on(\"error\", () => {});\n fileStream.destroy();\n throw err;\n }\n}\n\n/** Fetch a model into a `.partial` file, reject a truncated transfer via the\n * size floor, then atomically rename it into place. */\nasync function downloadModel(name: WhisperModelName, modelsDir: string, downloadStatus: Map<WhisperModelName, ModelStatus>): Promise<void> {\n const spec = WHISPER_MODELS[name];\n mkdirSync(modelsDir, { recursive: true });\n const dest = modelFilePath(modelsDir, name);\n const partial = `${dest}.partial`;\n const controller = new AbortController();\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const resetStall = () => {\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => controller.abort(), DOWNLOAD_STALL_TIMEOUT_MS);\n };\n try {\n const response = await fetch(spec.url, { signal: controller.signal });\n if (!response.ok || !response.body) {\n throw new Error(`download failed: HTTP ${response.status}`);\n }\n const total = parseContentLength(response.headers.get(\"content-length\"));\n resetStall();\n await streamToFile(response.body, partial, total, name, { downloadStatus, onProgress: resetStall });\n if (statSync(partial).size < spec.minBytes) {\n unlinkSync(partial);\n throw new Error(\"downloaded file is smaller than expected — likely truncated\");\n }\n renameSync(partial, dest);\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n }\n}\n\nexport function createModelDownloader(modelsDir: string, logger: WhisperLogger = NOOP_LOGGER): ModelDownloader {\n // A finished file on disk is the source of truth for \"ready\"; this map tracks\n // transient progress + the last error.\n const downloadStatus = new Map<WhisperModelName, ModelStatus>();\n\n function getStatus(name: WhisperModelName): ModelStatus {\n return pickModelStatus(downloadStatus.get(name), isModelReady(modelsDir, name));\n }\n\n // Fire-and-forget friendly: errors land in the status map, never thrown.\n // Idempotent — a second call while a download is in flight does nothing.\n async function ensure(name: WhisperModelName): Promise<void> {\n if (isModelReady(modelsDir, name)) {\n downloadStatus.set(name, { state: \"ready\" });\n return;\n }\n if (downloadStatus.get(name)?.state === \"downloading\") return;\n downloadStatus.set(name, { state: \"downloading\", progress: 0 });\n logger.info(\"model download: start\", { model: name });\n try {\n await downloadModel(name, modelsDir, downloadStatus);\n downloadStatus.set(name, { state: \"ready\" });\n logger.info(\"model download: ok\", { model: name });\n } catch (err) {\n const error = errorMessage(err);\n downloadStatus.set(name, { state: \"error\", error });\n logger.error(\"model download: failed\", { model: name, error });\n }\n }\n\n return { getStatus, ensure };\n}\n","// Pure helpers for the whisper-server sidecar. Kept separate from `sidecar.ts`\n// so the argv/response/stderr logic can be unit-tested without spawning a\n// process or opening a socket.\n\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\n/** whisper-server CLI args to preload `modelPath` and bind to `host:port`. */\nexport function buildServerArgs(modelPath: string, host: string, port: number): string[] {\n return [\"--model\", modelPath, \"--host\", host, \"--port\", String(port)];\n}\n\n/** Append `chunk` to a bounded stderr tail, keeping only the last `maxChars`. */\nexport function appendStderrTail(previous: string, chunk: string, maxChars: number): string {\n return (previous + chunk).slice(-maxChars);\n}\n\n/** Extract the transcript from a whisper-server `/inference` JSON response.\n * Returns \"\" for any shape that lacks a string `text` field. */\nexport function parseInferenceText(data: unknown): string {\n return hasStringProp(data, \"text\") ? data.text : \"\";\n}\n","// whisper.cpp warm-model sidecar. Spawns `whisper-server` once with the model\n// preloaded and reuses it across transcriptions over its local HTTP API, so the\n// weights stay resident (no per-request reload). State is encapsulated per\n// instance via the factory closure.\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { createServer } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, ONE_SECOND_MS, type WhisperLogger } from \"./internal.ts\";\nimport { modelFilePath, type WhisperModelName } from \"./models.ts\";\nimport { appendStderrTail, buildServerArgs, parseInferenceText } from \"./sidecar-helpers.ts\";\n\nconst HOST = \"127.0.0.1\";\nconst READY_TIMEOUT_MS = 60 * ONE_SECOND_MS;\nconst READY_POLL_INTERVAL_MS = 500;\nconst INFERENCE_TIMEOUT_MS = 2 * ONE_MINUTE_MS;\nconst STDERR_TAIL_MAX_CHARS = 4_000;\n\nexport interface ActiveSidecar {\n readonly port: number;\n readonly proc: ChildProcess;\n readonly model: WhisperModelName;\n}\n\nexport interface Sidecar {\n transcribeWav: (wavPath: string, language: string, model: WhisperModelName) => Promise<string>;\n warmup: (model: WhisperModelName) => Promise<void>;\n shutdown: () => void;\n}\n\nasync function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.on(\"error\", reject);\n srv.listen(0, HOST, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"could not determine a free port\")));\n }\n });\n });\n}\n\n/** Resolve once the server answers any HTTP request (any status = listener up),\n * or throw after the ready timeout. */\nasync function waitUntilReady(port: number): Promise<void> {\n const deadline = Date.now() + READY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n try {\n await fetch(`http://${HOST}:${port}/`, { signal: AbortSignal.timeout(ONE_SECOND_MS) });\n return;\n } catch {\n await delay(READY_POLL_INTERVAL_MS);\n }\n }\n throw new Error(\"whisper-server did not become ready in time\");\n}\n\n// whisper-server logs verbosely to stderr; left unread the OS pipe buffer fills\n// and the child blocks on its next write. Drain into a small tail buffer.\nfunction drainStderr(proc: ChildProcess, tail: { text: string }): void {\n proc.stderr?.setEncoding(\"utf8\");\n proc.stderr?.on(\"data\", (chunk: string) => {\n tail.text = appendStderrTail(tail.text, chunk, STDERR_TAIL_MAX_CHARS);\n });\n}\n\n// Resolve when the server answers, or reject on spawn failure (e.g. ENOENT) /\n// early exit. Listeners are one-shot and removed once the race settles.\nfunction waitForReadyOrFailure(proc: ChildProcess, port: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let onError: (err: Error) => void = () => undefined;\n let onExit: (code: number | null) => void = () => undefined;\n const cleanup = () => {\n proc.removeListener(\"error\", onError);\n proc.removeListener(\"exit\", onExit);\n };\n onError = (err: Error) => {\n cleanup();\n reject(new Error(`spawn failed: ${errorMessage(err)}`));\n };\n onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`exited early (code ${code})`));\n };\n proc.once(\"error\", onError);\n proc.once(\"exit\", onExit);\n waitUntilReady(port)\n .then(() => {\n cleanup();\n resolve();\n })\n .catch((err: unknown) => {\n cleanup();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n });\n}\n\n// POST the wav to whisper-server's `/inference` and return the transcript.\n// Isolated from the lifecycle so the HTTP contract is unit-testable without a\n// live child (stub `fetch`, hand it a real wav path).\nexport async function postInference(port: number, wavPath: string, language: string): Promise<string> {\n const buf = await readFile(wavPath);\n const form = new FormData();\n form.append(\"file\", new Blob([buf], { type: \"audio/wav\" }), \"audio.wav\");\n form.append(\"response_format\", \"json\");\n form.append(\"language\", language || \"auto\");\n let res: Response;\n try {\n res = await fetch(`http://${HOST}:${port}/inference`, { method: \"POST\", body: form, signal: AbortSignal.timeout(INFERENCE_TIMEOUT_MS) });\n } catch (err) {\n throw new Error(`whisper-server request failed: ${errorMessage(err)}`);\n }\n if (!res.ok) throw new Error(`whisper-server returned HTTP ${res.status}`);\n return parseInferenceText(await res.json());\n}\n\n// The impure primitives the start lifecycle depends on, injected so the\n// cancellation / single-flight / model-switch logic can be driven with fakes.\nexport interface StartLifecycleDeps {\n /** Reserve a free TCP port for the next child — the sole async step of a start. */\n allocatePort: () => Promise<number>;\n /** Spawn the whisper-server child on `port`. MUST be synchronous so the spawn\n * and the `startingProc` handoff stay in one tick: `shutdown()` has to be able\n * to kill an in-flight child immediately, with no await gap after it exists. */\n spawnServer: (model: WhisperModelName, port: number) => ChildProcess;\n /** Resolve once the child answers HTTP, or reject on spawn failure / early exit. */\n waitReady: (proc: ChildProcess, port: number) => Promise<void>;\n logger: WhisperLogger;\n}\n\nexport interface StartLifecycle {\n ensureSidecar: (model: WhisperModelName) => Promise<ActiveSidecar>;\n shutdown: () => void;\n}\n\nexport function defaultSpawnServer(modelsDir: string, serverBinary: string, logger: WhisperLogger): StartLifecycleDeps[\"spawnServer\"] {\n return (model: WhisperModelName, port: number): ChildProcess => {\n const args = buildServerArgs(modelFilePath(modelsDir, model), HOST, port);\n logger.info(\"sidecar: spawning\", { model, port });\n return spawn(serverBinary, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n };\n}\n\n// Wires the three listeners every whisper-server child needs: stderr drain,\n// permanent `error` handler (an unhandled 'error' from ENOENT etc. would crash\n// the host), and `exit` handler that both logs and lets the caller decide\n// whether this proc is still the active one (identity check via `onExit` — a\n// stale process must not evict a newer live sidecar).\nfunction instrumentChildProcess(proc: ChildProcess, model: WhisperModelName, logger: WhisperLogger, onExit: (exited: ChildProcess) => void): { text: string } {\n const stderrTail = { text: \"\" };\n drainStderr(proc, stderrTail);\n proc.on(\"error\", (err) => logger.warn(\"sidecar: process error\", { model, error: errorMessage(err) }));\n proc.on(\"exit\", (code) => {\n logger.warn(\"sidecar: exited\", { model, code, stderrTail: stderrTail.text.slice(-500) });\n onExit(proc);\n });\n return stderrTail;\n}\n\n// Await server readiness; on failure, kill the child and surface both the\n// underlying error and the tail of stderr (whisper-server usually explains its\n// crash there). Kept at module scope so `startSidecar` stays under the\n// per-function line cap.\nasync function awaitReadyOrThrow(proc: ChildProcess, port: number, stderrTail: { text: string }, waitReady: StartLifecycleDeps[\"waitReady\"]): Promise<void> {\n try {\n await waitReady(proc, port);\n } catch (err) {\n proc.kill();\n throw new Error(`whisper-server failed to start: ${errorMessage(err)} — stderr: ${stderrTail.text.slice(-500)}`);\n }\n}\n\n// Abort a start that was raced by `shutdown()` (or a newer start). Compares\n// the token captured at start entry against the current token; if they differ,\n// kill the freshly-booted child rather than publish it after shutdown returned.\nfunction throwIfStartCancelled(startedToken: number, currentToken: number, proc: ChildProcess): void {\n if (startedToken !== currentToken) {\n proc.kill();\n throw new Error(\"whisper-server start cancelled\");\n }\n}\n\n// Owns the single warm child's lifecycle: which model is live, the in-flight\n// start, and the cancellation token. Kept as a factory closure so the mutable\n// state is encapsulated rather than threaded through parameters.\nexport function createStartLifecycle(deps: StartLifecycleDeps): StartLifecycle {\n const { allocatePort, spawnServer, waitReady, logger } = deps;\n let sidecar: ActiveSidecar | null = null;\n let starting: { model: WhisperModelName; promise: Promise<ActiveSidecar> } | null = null;\n // The child of an in-flight start (before it's published as `sidecar`), plus a\n // token that `shutdown()` bumps to cancel a start that's still booting — so\n // shutdown can't return with a child that then publishes itself afterwards.\n let startingProc: ChildProcess | null = null;\n let startToken = 0;\n\n function shutdown(): void {\n startToken += 1;\n startingProc?.kill();\n startingProc = null;\n sidecar?.proc.kill();\n sidecar = null;\n }\n\n async function startSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n const token = ++startToken;\n const port = await allocatePort();\n const proc = spawnServer(model, port);\n startingProc = proc;\n // onExit fires when THIS proc exits: only null out `sidecar` if it's still the live one.\n const stderrTail = instrumentChildProcess(proc, model, logger, (exited) => sidecar?.proc === exited && (sidecar = null));\n try {\n await awaitReadyOrThrow(proc, port, stderrTail, waitReady);\n } finally {\n if (startingProc === proc) startingProc = null;\n }\n throwIfStartCancelled(token, startToken, proc);\n sidecar = { port, proc, model };\n logger.info(\"sidecar: ready\", { model, port });\n return sidecar;\n }\n\n // Own function so it isn't a loop closure (no-loop-func). Only ever one start\n // is in flight at a time, so clearing `starting` on settle is safe.\n function beginStart(model: WhisperModelName): Promise<ActiveSidecar> {\n const promise = startSidecar(model).finally(() => (starting = null));\n starting = { model, promise };\n return promise;\n }\n\n async function ensureSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n // Loop so that after awaiting an in-flight start for a DIFFERENT model we\n // re-evaluate; the decision-to-spawn path (beginStart) has no await, so the\n // first waiter sets `starting` synchronously and siblings then reuse it.\n for (;;) {\n if (sidecar && sidecar.model === model && !sidecar.proc.killed) return sidecar;\n if (starting && starting.model === model) return starting.promise;\n if (starting) {\n await starting.promise.catch(() => undefined);\n continue;\n }\n if (sidecar && sidecar.model !== model) shutdown();\n return beginStart(model);\n }\n }\n\n return { ensureSidecar, shutdown };\n}\n\nexport function createSidecar(modelsDir: string, serverBinary = \"whisper-server\", logger: WhisperLogger = NOOP_LOGGER): Sidecar {\n const lifecycle = createStartLifecycle({\n allocatePort: findFreePort,\n spawnServer: defaultSpawnServer(modelsDir, serverBinary, logger),\n waitReady: waitForReadyOrFailure,\n logger,\n });\n\n async function warmup(model: WhisperModelName): Promise<void> {\n try {\n await lifecycle.ensureSidecar(model);\n } catch (err) {\n logger.warn(\"sidecar: warmup failed\", { model, error: errorMessage(err) });\n }\n }\n\n async function transcribeWav(wavPath: string, language: string, model: WhisperModelName): Promise<string> {\n const active = await lifecycle.ensureSidecar(model);\n return postInference(active.port, wavPath, language);\n }\n\n return { transcribeWav, warmup, shutdown: lifecycle.shutdown };\n}\n","// Public server-side façade: wires the model downloader, the warm sidecar, and\n// ffmpeg conversion into one host-agnostic service. The host injects the models\n// directory + a logger and gates capability itself (platform / binary presence);\n// this package assumes the binaries exist when called.\n\nimport { mkdirSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { NOOP_LOGGER, type WhisperLogger } from \"./internal.ts\";\nimport { convertToWav16k } from \"./ffmpeg.ts\";\nimport { createModelDownloader } from \"./models.ts\";\nimport { createSidecar } from \"./sidecar.ts\";\nimport { isModelReady, type ModelStatus, type WhisperModelName } from \"./models.ts\";\n\nexport interface WhisperOptions {\n /** Directory that holds the GGML model files (e.g. `{workspace}/models`). */\n modelsDir: string;\n logger?: WhisperLogger;\n /** Defaults to \"whisper-server\" / \"ffmpeg\" on PATH. */\n serverBinary?: string;\n ffmpegBinary?: string;\n}\n\nexport interface TranscribeRequest {\n base64: string;\n mimeType: string;\n language: string;\n model: WhisperModelName;\n}\n\nexport interface Whisper {\n isModelReady: (model: WhisperModelName) => boolean;\n getModelStatus: (model: WhisperModelName) => ModelStatus;\n /** Fire-and-forget friendly; never throws (errors land in the status). */\n ensureModelDownloaded: (model: WhisperModelName) => Promise<void>;\n warmup: (model: WhisperModelName) => Promise<void>;\n transcribe: (req: TranscribeRequest) => Promise<{ text: string }>;\n shutdown: () => void;\n}\n\n// whisper.cpp returns these sentinels for non-speech windows; treat them as\n// empty so the UI shows \"didn't catch that\" rather than a literal marker.\nconst BLANK_MARKERS = new Set([\"[blank_audio]\", \"[silence]\", \"(silence)\", \"[ inaudible ]\"]);\n\nfunction normalizeTranscript(raw: string): string {\n const trimmed = raw.trim().replace(/\\s+/g, \" \");\n return BLANK_MARKERS.has(trimmed.toLowerCase()) ? \"\" : trimmed;\n}\n\nexport function createWhisper(opts: WhisperOptions): Whisper {\n const { modelsDir } = opts;\n const logger = opts.logger ?? NOOP_LOGGER;\n const ffmpegBinary = opts.ffmpegBinary ?? \"ffmpeg\";\n const downloader = createModelDownloader(modelsDir, logger);\n const sidecar = createSidecar(modelsDir, opts.serverBinary ?? \"whisper-server\", logger);\n\n // Scratch dir for transient audio — a hidden subdir of the models dir so it\n // shares the (non-git) models tree. Files are deleted after each transcription.\n const scratchDir = path.join(modelsDir, \".scratch\");\n\n async function transcribe(req: TranscribeRequest): Promise<{ text: string }> {\n mkdirSync(scratchDir, { recursive: true });\n const clipId = randomUUID();\n const inputPath = path.join(scratchDir, `utterance-${clipId}.webm`);\n const wavPath = path.join(scratchDir, `utterance-${clipId}.wav`);\n try {\n await writeFile(inputPath, Buffer.from(req.base64, \"base64\"));\n await convertToWav16k(inputPath, wavPath, ffmpegBinary);\n const text = await sidecar.transcribeWav(wavPath, req.language, req.model);\n return { text: normalizeTranscript(text) };\n } finally {\n await rm(inputPath, { force: true });\n await rm(wavPath, { force: true });\n }\n }\n\n return {\n isModelReady: (model) => isModelReady(modelsDir, model),\n getModelStatus: (model) => downloader.getStatus(model),\n ensureModelDownloaded: (model) => downloader.ensure(model),\n warmup: (model) => sidecar.warmup(model),\n transcribe,\n shutdown: () => sidecar.shutdown(),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAEA,IAAa,gBAAgB;AAC7B,IAAa,gBAAgB;AAY7B,IAAM,aAAmB,KAAA;AACzB,IAAa,cAA6B;CAAE,MAAM;CAAM,MAAM;CAAM,OAAO;AAAK;;ACRhF,IAAM,gBAAgB,UAAU,QAAQ;;;AAIxC,SAAgB,gBAAgB,WAAmB,YAA8B;CAC/E,OAAO;EAAC;EAAM;EAAa;EAAS;EAAM;EAAW;EAAO;EAAS;EAAO;EAAK;EAAQ;EAAa;CAAU;AAClH;;;AAIA,eAAsB,gBAAgB,WAAmB,YAAoB,eAAe,UAAyB;CACnH,MA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AAQ,QAAQ,GAAG;CAC9C,OAAO,cAAc,IAAI,QAAQ,YAAY,CAAC,IAAI,KAAK;AACzD;AAEA,SAAgB,cAAc,MAA+B;CAC3D,MAAM,EAAE,cAAc;CACtB,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,eAAe,KAAK,gBAAgB;CAC1C,MAAM,aAAa,sBAAsB,WAAW,MAAM;CAC1D,MAAM,UAAU,cAAc,WAAW,KAAK,gBAAgB,kBAAkB,MAAM;CAItF,MAAM,aAAa,KAAK,KAAK,WAAW,UAAU;CAElD,eAAe,WAAW,KAAmD;EAC3E,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;EACzC,MAAM,SAAS,WAAW;EAC1B,MAAM,YAAY,KAAK,KAAK,YAAY,aAAa,OAAO,MAAM;EAClE,MAAM,UAAU,KAAK,KAAK,YAAY,aAAa,OAAO,KAAK;EAC/D,IAAI;GACF,MAAM,UAAU,WAAW,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC;GAC5D,MAAM,gBAAgB,WAAW,SAAS,YAAY;GAEtD,OAAO,EAAE,MAAM,oBAAoB,MADhB,QAAQ,cAAc,SAAS,IAAI,UAAU,IAAI,KAAK,CAClC,EAAE;EAC3C,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACnC,MAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC;EACnC;CACF;CAEA,OAAO;EACL,eAAe,UAAU,aAAa,WAAW,KAAK;EACtD,iBAAiB,UAAU,WAAW,UAAU,KAAK;EACrD,wBAAwB,UAAU,WAAW,OAAO,KAAK;EACzD,SAAS,UAAU,QAAQ,OAAO,KAAK;EACvC;EACA,gBAAgB,QAAQ,SAAS;CACnC;AACF"}
1
+ {"version":3,"file":"index.js","names":["delay"],"sources":["../../src/whisper/internal.ts","../../src/whisper/ffmpeg.ts","../../src/whisper/models.ts","../../src/whisper/sidecar-helpers.ts","../../src/whisper/sidecar.ts","../../src/whisper/extra-args.ts","../../src/whisper/whisper.ts"],"sourcesContent":["// Small self-contained utilities so the package has no host dependencies.\n\nexport const ONE_SECOND_MS = 1_000;\nexport const ONE_MINUTE_MS = 60_000;\n\nexport { errorMessage } from \"../utils/errors.js\";\n\n/** Minimal logger the host can inject; defaults to no-op so the package\n * is silent unless wired up. */\nexport interface WhisperLogger {\n info: (message: string, data?: unknown) => void;\n warn: (message: string, data?: unknown) => void;\n error: (message: string, data?: unknown) => void;\n}\n\nconst NOOP = (): void => undefined;\nexport const NOOP_LOGGER: WhisperLogger = { info: NOOP, warn: NOOP, error: NOOP };\n","// Thin wrapper around the system `ffmpeg` binary (provided by the host) for\n// converting a browser webm/opus clip to the 16 kHz mono 16-bit WAV whisper.cpp\n// requires.\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\nimport { ONE_MINUTE_MS } from \"./internal.ts\";\n\nconst execFileAsync = promisify(execFile);\n\n/** ffmpeg args to decode any input to 16 kHz mono signed-16-bit WAV. Pure +\n * exported for unit tests. */\nexport function buildWav16kArgs(inputPath: string, outputPath: string): string[] {\n return [\"-y\", \"-loglevel\", \"error\", \"-i\", inputPath, \"-ar\", \"16000\", \"-ac\", \"1\", \"-c:a\", \"pcm_s16le\", outputPath];\n}\n\n/** Convert `inputPath` to a 16 kHz mono WAV at `outputPath`. Throws on ffmpeg\n * failure or timeout. */\nexport async function convertToWav16k(inputPath: string, outputPath: string, ffmpegBinary = \"ffmpeg\"): Promise<void> {\n await execFileAsync(ffmpegBinary, buildWav16kArgs(inputPath, outputPath), {\n timeout: ONE_MINUTE_MS,\n });\n}\n","// Whisper GGML model registry + on-disk management. The host injects the models\n// directory (e.g. `{workspace}/models`); nothing here reads a host module.\n\nimport { createWriteStream, mkdirSync, renameSync, statSync, unlinkSync } from \"node:fs\";\nimport { once } from \"node:events\";\nimport path from \"node:path\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, type WhisperLogger } from \"./internal.ts\";\n\nexport interface WhisperModelSpec {\n /** GGML filename — identical on disk and in the Hugging Face repo. */\n readonly file: string;\n /** Download URL (Hugging Face whisper.cpp model repo). */\n readonly url: string;\n /** Conservative lower bound on the finished file size, in bytes — guards\n * against a truncated transfer or an HTML error page saved as the model\n * without pinning an exact checksum. */\n readonly minBytes: number;\n}\n\nconst HF_BASE = \"https://huggingface.co/ggerganov/whisper.cpp/resolve/main\";\n\n// large-v3-turbo: strong accuracy, near-real-time on Apple Silicon with Metal.\n// small/base are lighter fallbacks for low-RAM machines.\nexport const WHISPER_MODELS = {\n \"large-v3-turbo\": { file: \"ggml-large-v3-turbo.bin\", url: `${HF_BASE}/ggml-large-v3-turbo.bin`, minBytes: 1_000_000_000 },\n small: { file: \"ggml-small.bin\", url: `${HF_BASE}/ggml-small.bin`, minBytes: 300_000_000 },\n base: { file: \"ggml-base.bin\", url: `${HF_BASE}/ggml-base.bin`, minBytes: 100_000_000 },\n} as const satisfies Record<string, WhisperModelSpec>;\n\nexport type WhisperModelName = keyof typeof WHISPER_MODELS;\nexport const DEFAULT_WHISPER_MODEL: WhisperModelName = \"large-v3-turbo\";\n\nexport function isWhisperModelName(value: unknown): value is WhisperModelName {\n // Own-property check — `in` would accept inherited keys like \"toString\",\n // which then crash the `WHISPER_MODELS[name]` lookups instead of falling\n // back to the default.\n return typeof value === \"string\" && Object.prototype.hasOwnProperty.call(WHISPER_MODELS, value);\n}\n\n/** Resolve a possibly-unset / unknown model name to a valid one. */\nexport function resolveModelName(name: string | undefined): WhisperModelName {\n return isWhisperModelName(name) ? name : DEFAULT_WHISPER_MODEL;\n}\n\nexport function modelFilePath(modelsDir: string, name: WhisperModelName): string {\n return path.join(modelsDir, WHISPER_MODELS[name].file);\n}\n\n/** A model is \"ready\" when its file exists and meets the size floor. */\nexport function isModelReady(modelsDir: string, name: WhisperModelName): boolean {\n try {\n return statSync(modelFilePath(modelsDir, name)).size >= WHISPER_MODELS[name].minBytes;\n } catch {\n return false;\n }\n}\n\nexport type ModelDownloadState = \"idle\" | \"downloading\" | \"ready\" | \"error\";\n\nexport interface ModelStatus {\n state: ModelDownloadState;\n /** 0..1 — present only while downloading and Content-Length is known. */\n progress?: number;\n /** Present only in the \"error\" state. */\n error?: string;\n}\n\n/** Report status precedence: an in-flight download wins, then an on-disk ready\n * file, then the last transient state (idle if none). Pure so the precedence\n * is unit-testable without touching the filesystem. */\nexport function pickModelStatus(live: ModelStatus | undefined, isReady: boolean): ModelStatus {\n if (live?.state === \"downloading\") return live;\n if (isReady) return { state: \"ready\" };\n return live ?? { state: \"idle\" };\n}\n\n/** Parse a `Content-Length` header to a byte count; unknown / malformed → 0. */\nexport function parseContentLength(header: string | null): number {\n return Number(header) || 0;\n}\n\n// Abort a download if no bytes arrive for this long (stalled connection).\nconst DOWNLOAD_STALL_TIMEOUT_MS = ONE_MINUTE_MS;\n\nexport interface ModelDownloader {\n getStatus: (name: WhisperModelName) => ModelStatus;\n ensure: (name: WhisperModelName) => Promise<void>;\n}\n\ninterface StreamToFileDeps {\n downloadStatus: Map<WhisperModelName, ModelStatus>;\n onProgress: () => void;\n}\n\n/** Drain the response stream into the `.partial` file, resetting the stall\n * timer on every chunk and publishing progress once the total size is known. */\nasync function streamToFile(\n body: ReadableStream<Uint8Array>,\n partialPath: string,\n total: number,\n name: WhisperModelName,\n deps: StreamToFileDeps,\n): Promise<void> {\n const reader = body.getReader();\n const fileStream = createWriteStream(partialPath);\n let received = 0;\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n deps.onProgress();\n received += value.byteLength;\n if (!fileStream.write(value)) await once(fileStream, \"drain\");\n if (total > 0) deps.downloadStatus.set(name, { state: \"downloading\", progress: received / total });\n }\n fileStream.end();\n await once(fileStream, \"finish\");\n } catch (err) {\n // `createWriteStream` opens lazily. Destroying it while that open is still\n // in flight lets the open's own failure land later as an `error` event with\n // no listener — an uncaughtException that kills the process. `err` already\n // carries the real cause, so absorb the late one.\n fileStream.on(\"error\", () => {});\n fileStream.destroy();\n throw err;\n }\n}\n\n/** Fetch a model into a `.partial` file, reject a truncated transfer via the\n * size floor, then atomically rename it into place. */\nasync function downloadModel(name: WhisperModelName, modelsDir: string, downloadStatus: Map<WhisperModelName, ModelStatus>): Promise<void> {\n const spec = WHISPER_MODELS[name];\n mkdirSync(modelsDir, { recursive: true });\n const dest = modelFilePath(modelsDir, name);\n const partial = `${dest}.partial`;\n const controller = new AbortController();\n let stallTimer: ReturnType<typeof setTimeout> | null = null;\n const resetStall = () => {\n if (stallTimer) clearTimeout(stallTimer);\n stallTimer = setTimeout(() => controller.abort(), DOWNLOAD_STALL_TIMEOUT_MS);\n };\n try {\n const response = await fetch(spec.url, { signal: controller.signal });\n if (!response.ok || !response.body) {\n throw new Error(`download failed: HTTP ${response.status}`);\n }\n const total = parseContentLength(response.headers.get(\"content-length\"));\n resetStall();\n await streamToFile(response.body, partial, total, name, { downloadStatus, onProgress: resetStall });\n if (statSync(partial).size < spec.minBytes) {\n unlinkSync(partial);\n throw new Error(\"downloaded file is smaller than expected — likely truncated\");\n }\n renameSync(partial, dest);\n } finally {\n if (stallTimer) clearTimeout(stallTimer);\n }\n}\n\nexport function createModelDownloader(modelsDir: string, logger: WhisperLogger = NOOP_LOGGER): ModelDownloader {\n // A finished file on disk is the source of truth for \"ready\"; this map tracks\n // transient progress + the last error.\n const downloadStatus = new Map<WhisperModelName, ModelStatus>();\n\n function getStatus(name: WhisperModelName): ModelStatus {\n return pickModelStatus(downloadStatus.get(name), isModelReady(modelsDir, name));\n }\n\n // Fire-and-forget friendly: errors land in the status map, never thrown.\n // Idempotent — a second call while a download is in flight does nothing.\n async function ensure(name: WhisperModelName): Promise<void> {\n if (isModelReady(modelsDir, name)) {\n downloadStatus.set(name, { state: \"ready\" });\n return;\n }\n if (downloadStatus.get(name)?.state === \"downloading\") return;\n downloadStatus.set(name, { state: \"downloading\", progress: 0 });\n logger.info(\"model download: start\", { model: name });\n try {\n await downloadModel(name, modelsDir, downloadStatus);\n downloadStatus.set(name, { state: \"ready\" });\n logger.info(\"model download: ok\", { model: name });\n } catch (err) {\n const error = errorMessage(err);\n downloadStatus.set(name, { state: \"error\", error });\n logger.error(\"model download: failed\", { model: name, error });\n }\n }\n\n return { getStatus, ensure };\n}\n","// Pure helpers for the whisper-server sidecar. Kept separate from `sidecar.ts`\n// so the argv/response/stderr logic can be unit-tested without spawning a\n// process or opening a socket.\n\nimport { hasStringProp } from \"@mulmoclaude/common\";\n\n/** whisper-server CLI args to preload `modelPath` and bind to `host:port`,\n * followed by any user-supplied `extraArgs`. */\nexport function buildServerArgs(modelPath: string, host: string, port: number, extraArgs: readonly string[] = []): string[] {\n return [\"--model\", modelPath, \"--host\", host, \"--port\", String(port), ...extraArgs];\n}\n\n/** Append `chunk` to a bounded stderr tail, keeping only the last `maxChars`. */\nexport function appendStderrTail(previous: string, chunk: string, maxChars: number): string {\n return (previous + chunk).slice(-maxChars);\n}\n\n/** Extract the transcript from a whisper-server `/inference` JSON response.\n * Returns \"\" for any shape that lacks a string `text` field. */\nexport function parseInferenceText(data: unknown): string {\n return hasStringProp(data, \"text\") ? data.text : \"\";\n}\n","// whisper.cpp warm-model sidecar. Spawns `whisper-server` once with the model\n// preloaded and reuses it across transcriptions over its local HTTP API, so the\n// weights stay resident (no per-request reload). State is encapsulated per\n// instance via the factory closure.\n\nimport { spawn, type ChildProcess } from \"node:child_process\";\nimport { createServer } from \"node:net\";\nimport { readFile } from \"node:fs/promises\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { errorMessage, NOOP_LOGGER, ONE_MINUTE_MS, ONE_SECOND_MS, type WhisperLogger } from \"./internal.ts\";\nimport { modelFilePath, type WhisperModelName } from \"./models.ts\";\nimport { appendStderrTail, buildServerArgs, parseInferenceText } from \"./sidecar-helpers.ts\";\n\nconst HOST = \"127.0.0.1\";\nconst READY_TIMEOUT_MS = 60 * ONE_SECOND_MS;\nconst READY_POLL_INTERVAL_MS = 500;\nconst INFERENCE_TIMEOUT_MS = 2 * ONE_MINUTE_MS;\nconst STDERR_TAIL_MAX_CHARS = 4_000;\n\nexport interface ActiveSidecar {\n readonly port: number;\n readonly proc: ChildProcess;\n readonly model: WhisperModelName;\n}\n\nexport interface Sidecar {\n transcribeWav: (wavPath: string, language: string, model: WhisperModelName) => Promise<string>;\n warmup: (model: WhisperModelName) => Promise<void>;\n shutdown: () => void;\n}\n\nasync function findFreePort(): Promise<number> {\n return new Promise((resolve, reject) => {\n const srv = createServer();\n srv.on(\"error\", reject);\n srv.listen(0, HOST, () => {\n const addr = srv.address();\n if (addr && typeof addr === \"object\") {\n const { port } = addr;\n srv.close(() => resolve(port));\n } else {\n srv.close(() => reject(new Error(\"could not determine a free port\")));\n }\n });\n });\n}\n\n/** Resolve once the server answers any HTTP request (any status = listener up),\n * or throw after the ready timeout. */\nasync function waitUntilReady(port: number): Promise<void> {\n const deadline = Date.now() + READY_TIMEOUT_MS;\n while (Date.now() < deadline) {\n try {\n await fetch(`http://${HOST}:${port}/`, { signal: AbortSignal.timeout(ONE_SECOND_MS) });\n return;\n } catch {\n await delay(READY_POLL_INTERVAL_MS);\n }\n }\n throw new Error(\"whisper-server did not become ready in time\");\n}\n\n// whisper-server logs verbosely to stderr; left unread the OS pipe buffer fills\n// and the child blocks on its next write. Drain into a small tail buffer.\nfunction drainStderr(proc: ChildProcess, tail: { text: string }): void {\n proc.stderr?.setEncoding(\"utf8\");\n proc.stderr?.on(\"data\", (chunk: string) => {\n tail.text = appendStderrTail(tail.text, chunk, STDERR_TAIL_MAX_CHARS);\n });\n}\n\n// Resolve when the server answers, or reject on spawn failure (e.g. ENOENT) /\n// early exit. Listeners are one-shot and removed once the race settles.\nfunction waitForReadyOrFailure(proc: ChildProcess, port: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let onError: (err: Error) => void = () => undefined;\n let onExit: (code: number | null) => void = () => undefined;\n const cleanup = () => {\n proc.removeListener(\"error\", onError);\n proc.removeListener(\"exit\", onExit);\n };\n onError = (err: Error) => {\n cleanup();\n reject(new Error(`spawn failed: ${errorMessage(err)}`));\n };\n onExit = (code: number | null) => {\n cleanup();\n reject(new Error(`exited early (code ${code})`));\n };\n proc.once(\"error\", onError);\n proc.once(\"exit\", onExit);\n waitUntilReady(port)\n .then(() => {\n cleanup();\n resolve();\n })\n .catch((err: unknown) => {\n cleanup();\n reject(err instanceof Error ? err : new Error(String(err)));\n });\n });\n}\n\n// POST the wav to whisper-server's `/inference` and return the transcript.\n// Isolated from the lifecycle so the HTTP contract is unit-testable without a\n// live child (stub `fetch`, hand it a real wav path).\nexport async function postInference(port: number, wavPath: string, language: string): Promise<string> {\n const buf = await readFile(wavPath);\n const form = new FormData();\n form.append(\"file\", new Blob([buf], { type: \"audio/wav\" }), \"audio.wav\");\n form.append(\"response_format\", \"json\");\n form.append(\"language\", language || \"auto\");\n let res: Response;\n try {\n res = await fetch(`http://${HOST}:${port}/inference`, { method: \"POST\", body: form, signal: AbortSignal.timeout(INFERENCE_TIMEOUT_MS) });\n } catch (err) {\n throw new Error(`whisper-server request failed: ${errorMessage(err)}`);\n }\n if (!res.ok) throw new Error(`whisper-server returned HTTP ${res.status}`);\n return parseInferenceText(await res.json());\n}\n\n// The impure primitives the start lifecycle depends on, injected so the\n// cancellation / single-flight / model-switch logic can be driven with fakes.\nexport interface StartLifecycleDeps {\n /** Reserve a free TCP port for the next child — the sole async step of a start. */\n allocatePort: () => Promise<number>;\n /** Spawn the whisper-server child on `port`. MUST be synchronous so the spawn\n * and the `startingProc` handoff stay in one tick: `shutdown()` has to be able\n * to kill an in-flight child immediately, with no await gap after it exists. */\n spawnServer: (model: WhisperModelName, port: number) => ChildProcess;\n /** Resolve once the child answers HTTP, or reject on spawn failure / early exit. */\n waitReady: (proc: ChildProcess, port: number) => Promise<void>;\n logger: WhisperLogger;\n}\n\nexport interface StartLifecycle {\n ensureSidecar: (model: WhisperModelName) => Promise<ActiveSidecar>;\n shutdown: () => void;\n}\n\nexport function defaultSpawnServer(\n modelsDir: string,\n serverBinary: string,\n logger: WhisperLogger,\n extraArgs: readonly string[] = [],\n): StartLifecycleDeps[\"spawnServer\"] {\n return (model: WhisperModelName, port: number): ChildProcess => {\n const args = buildServerArgs(modelFilePath(modelsDir, model), HOST, port, extraArgs);\n logger.info(\"sidecar: spawning\", { model, port });\n return spawn(serverBinary, args, { stdio: [\"ignore\", \"ignore\", \"pipe\"] });\n };\n}\n\n// Wires the three listeners every whisper-server child needs: stderr drain,\n// permanent `error` handler (an unhandled 'error' from ENOENT etc. would crash\n// the host), and `exit` handler that both logs and lets the caller decide\n// whether this proc is still the active one (identity check via `onExit` — a\n// stale process must not evict a newer live sidecar).\nfunction instrumentChildProcess(proc: ChildProcess, model: WhisperModelName, logger: WhisperLogger, onExit: (exited: ChildProcess) => void): { text: string } {\n const stderrTail = { text: \"\" };\n drainStderr(proc, stderrTail);\n proc.on(\"error\", (err) => logger.warn(\"sidecar: process error\", { model, error: errorMessage(err) }));\n proc.on(\"exit\", (code) => {\n logger.warn(\"sidecar: exited\", { model, code, stderrTail: stderrTail.text.slice(-500) });\n onExit(proc);\n });\n return stderrTail;\n}\n\n// Await server readiness; on failure, kill the child and surface both the\n// underlying error and the tail of stderr (whisper-server usually explains its\n// crash there). Kept at module scope so `startSidecar` stays under the\n// per-function line cap.\nasync function awaitReadyOrThrow(proc: ChildProcess, port: number, stderrTail: { text: string }, waitReady: StartLifecycleDeps[\"waitReady\"]): Promise<void> {\n try {\n await waitReady(proc, port);\n } catch (err) {\n proc.kill();\n throw new Error(`whisper-server failed to start: ${errorMessage(err)} — stderr: ${stderrTail.text.slice(-500)}`);\n }\n}\n\n// Abort a start that was raced by `shutdown()` (or a newer start). Compares\n// the token captured at start entry against the current token; if they differ,\n// kill the freshly-booted child rather than publish it after shutdown returned.\nfunction throwIfStartCancelled(startedToken: number, currentToken: number, proc: ChildProcess): void {\n if (startedToken !== currentToken) {\n proc.kill();\n throw new Error(\"whisper-server start cancelled\");\n }\n}\n\n// Owns the single warm child's lifecycle: which model is live, the in-flight\n// start, and the cancellation token. Kept as a factory closure so the mutable\n// state is encapsulated rather than threaded through parameters.\nexport function createStartLifecycle(deps: StartLifecycleDeps): StartLifecycle {\n const { allocatePort, spawnServer, waitReady, logger } = deps;\n let sidecar: ActiveSidecar | null = null;\n let starting: { model: WhisperModelName; promise: Promise<ActiveSidecar> } | null = null;\n // The child of an in-flight start (before it's published as `sidecar`), plus a\n // token that `shutdown()` bumps to cancel a start that's still booting — so\n // shutdown can't return with a child that then publishes itself afterwards.\n let startingProc: ChildProcess | null = null;\n let startToken = 0;\n\n function shutdown(): void {\n startToken += 1;\n startingProc?.kill();\n startingProc = null;\n sidecar?.proc.kill();\n sidecar = null;\n }\n\n async function startSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n const token = ++startToken;\n const port = await allocatePort();\n const proc = spawnServer(model, port);\n startingProc = proc;\n // onExit fires when THIS proc exits: only null out `sidecar` if it's still the live one.\n const stderrTail = instrumentChildProcess(proc, model, logger, (exited) => sidecar?.proc === exited && (sidecar = null));\n try {\n await awaitReadyOrThrow(proc, port, stderrTail, waitReady);\n } finally {\n if (startingProc === proc) startingProc = null;\n }\n throwIfStartCancelled(token, startToken, proc);\n sidecar = { port, proc, model };\n logger.info(\"sidecar: ready\", { model, port });\n return sidecar;\n }\n\n // Own function so it isn't a loop closure (no-loop-func). Only ever one start\n // is in flight at a time, so clearing `starting` on settle is safe.\n function beginStart(model: WhisperModelName): Promise<ActiveSidecar> {\n const promise = startSidecar(model).finally(() => (starting = null));\n starting = { model, promise };\n return promise;\n }\n\n async function ensureSidecar(model: WhisperModelName): Promise<ActiveSidecar> {\n // Loop so that after awaiting an in-flight start for a DIFFERENT model we\n // re-evaluate; the decision-to-spawn path (beginStart) has no await, so the\n // first waiter sets `starting` synchronously and siblings then reuse it.\n for (;;) {\n if (sidecar && sidecar.model === model && !sidecar.proc.killed) return sidecar;\n if (starting && starting.model === model) return starting.promise;\n if (starting) {\n await starting.promise.catch(() => undefined);\n continue;\n }\n if (sidecar && sidecar.model !== model) shutdown();\n return beginStart(model);\n }\n }\n\n return { ensureSidecar, shutdown };\n}\n\nexport function createSidecar(\n modelsDir: string,\n serverBinary = \"whisper-server\",\n logger: WhisperLogger = NOOP_LOGGER,\n extraArgs: readonly string[] = [],\n): Sidecar {\n const lifecycle = createStartLifecycle({\n allocatePort: findFreePort,\n spawnServer: defaultSpawnServer(modelsDir, serverBinary, logger, extraArgs),\n waitReady: waitForReadyOrFailure,\n logger,\n });\n\n async function warmup(model: WhisperModelName): Promise<void> {\n try {\n await lifecycle.ensureSidecar(model);\n } catch (err) {\n logger.warn(\"sidecar: warmup failed\", { model, error: errorMessage(err) });\n }\n }\n\n async function transcribeWav(wavPath: string, language: string, model: WhisperModelName): Promise<string> {\n const active = await lifecycle.ensureSidecar(model);\n return postInference(active.port, wavPath, language);\n }\n\n return { transcribeWav, warmup, shutdown: lifecycle.shutdown };\n}\n","// Parses the opt-in extra whisper-server argv (e.g. `--vad --vad-model <path>`)\n// from an env var. Pure so the accept/reject rules are testable without a process.\n\nimport type { WhisperLogger } from \"./internal.ts\";\n\nexport const WHISPER_SERVER_EXTRA_ARGS_ENV = \"WHISPER_SERVER_EXTRA_ARGS\";\n\n// Every whisper-server SERVER-level option (upstream `server.cpp`), plus the\n// model and help: the sidecar owns where it listens, what it serves and which\n// model it loads, and a later flag would silently override ours. Every other\n// option is passed through untouched.\nconst RESERVED_FLAGS: ReadonlySet<string> = new Set([\n \"-m\",\n \"--model\",\n \"-h\",\n \"--help\",\n \"--host\",\n \"--port\",\n \"--public\",\n \"--request-path\",\n \"--inference-path\",\n \"--convert\",\n \"--tmp-dir\",\n]);\n\nexport type ExtraArgsResult = { readonly ok: true; readonly args: string[] } | { readonly ok: false; readonly reason: string };\n\nconst isStringArray = (value: unknown): value is string[] => Array.isArray(value) && value.every((item) => typeof item === \"string\");\n\nfunction parseJsonArray(text: string): string[] | null {\n try {\n const parsed: unknown = JSON.parse(text);\n return isStringArray(parsed) ? parsed : null;\n } catch {\n return null;\n }\n}\n\n// A JSON array lets a path contain spaces; plain text is split on whitespace.\nfunction tokenize(text: string): string[] | null {\n if (text.startsWith(\"[\")) return parseJsonArray(text);\n return text.split(/\\s+/);\n}\n\n// `--port=1` names the same option as `--port`.\nconst flagName = (arg: string): string => arg.split(\"=\", 1)[0] ?? arg;\n\nfunction findProblem(args: readonly string[]): string | null {\n // spawn() throws synchronously on a NUL byte, before any fallback could run.\n if (args.some((arg) => arg.includes(\"\\0\"))) return \"an argument contains a NUL character\";\n const reserved = args.find((arg) => RESERVED_FLAGS.has(flagName(arg)));\n return reserved === undefined ? null : `${flagName(reserved)} is set by MulmoClaude and cannot be overridden`;\n}\n\nexport function parseExtraServerArgs(raw: string | undefined): ExtraArgsResult {\n const text = (raw ?? \"\").trim();\n if (text === \"\") return { ok: true, args: [] };\n const args = tokenize(text);\n if (args === null) return { ok: false, reason: \"expected a JSON array of strings\" };\n const problem = findProblem(args);\n return problem === null ? { ok: true, args } : { ok: false, reason: problem };\n}\n\n/** Resolve the extra argv from the env value. A rejected value falls back to\n * no extras so a typo cannot stop voice input. Only the count is logged: a\n * value is a path, and nothing tells a flag from a value that starts with `-`. */\nexport function resolveExtraServerArgs(raw: string | undefined, logger: WhisperLogger): string[] {\n const result = parseExtraServerArgs(raw);\n if (!result.ok) {\n logger.warn(`${WHISPER_SERVER_EXTRA_ARGS_ENV} ignored`, { reason: result.reason });\n return [];\n }\n if (result.args.length > 0) logger.info(`${WHISPER_SERVER_EXTRA_ARGS_ENV} applied`, { count: result.args.length });\n return result.args;\n}\n","// Public server-side façade: wires the model downloader, the warm sidecar, and\n// ffmpeg conversion into one host-agnostic service. The host injects the models\n// directory + a logger and gates capability itself (platform / binary presence);\n// this package assumes the binaries exist when called.\n\nimport { mkdirSync } from \"node:fs\";\nimport { rm, writeFile } from \"node:fs/promises\";\nimport { randomUUID } from \"node:crypto\";\nimport path from \"node:path\";\nimport { NOOP_LOGGER, type WhisperLogger } from \"./internal.ts\";\nimport { convertToWav16k } from \"./ffmpeg.ts\";\nimport { createModelDownloader } from \"./models.ts\";\nimport { createSidecar } from \"./sidecar.ts\";\nimport { resolveExtraServerArgs, WHISPER_SERVER_EXTRA_ARGS_ENV } from \"./extra-args.ts\";\nimport { isModelReady, type ModelStatus, type WhisperModelName } from \"./models.ts\";\n\nexport interface WhisperOptions {\n /** Directory that holds the GGML model files (e.g. `{workspace}/models`). */\n modelsDir: string;\n logger?: WhisperLogger;\n /** Defaults to \"whisper-server\" / \"ffmpeg\" on PATH. */\n serverBinary?: string;\n ffmpegBinary?: string;\n}\n\nexport interface TranscribeRequest {\n base64: string;\n mimeType: string;\n language: string;\n model: WhisperModelName;\n}\n\nexport interface Whisper {\n isModelReady: (model: WhisperModelName) => boolean;\n getModelStatus: (model: WhisperModelName) => ModelStatus;\n /** Fire-and-forget friendly; never throws (errors land in the status). */\n ensureModelDownloaded: (model: WhisperModelName) => Promise<void>;\n warmup: (model: WhisperModelName) => Promise<void>;\n transcribe: (req: TranscribeRequest) => Promise<{ text: string }>;\n shutdown: () => void;\n}\n\n// whisper.cpp returns these sentinels for non-speech windows; treat them as\n// empty so the UI shows \"didn't catch that\" rather than a literal marker.\nconst BLANK_MARKERS = new Set([\"[blank_audio]\", \"[silence]\", \"(silence)\", \"[ inaudible ]\"]);\n\nfunction normalizeTranscript(raw: string): string {\n const trimmed = raw.trim().replace(/\\s+/g, \" \");\n return BLANK_MARKERS.has(trimmed.toLowerCase()) ? \"\" : trimmed;\n}\n\nexport function createWhisper(opts: WhisperOptions): Whisper {\n const { modelsDir } = opts;\n const logger = opts.logger ?? NOOP_LOGGER;\n const ffmpegBinary = opts.ffmpegBinary ?? \"ffmpeg\";\n const downloader = createModelDownloader(modelsDir, logger);\n const sidecar = createSidecar(\n modelsDir,\n opts.serverBinary ?? \"whisper-server\",\n logger,\n resolveExtraServerArgs(process.env[WHISPER_SERVER_EXTRA_ARGS_ENV], logger),\n );\n\n // Scratch dir for transient audio — a hidden subdir of the models dir so it\n // shares the (non-git) models tree. Files are deleted after each transcription.\n const scratchDir = path.join(modelsDir, \".scratch\");\n\n async function transcribe(req: TranscribeRequest): Promise<{ text: string }> {\n mkdirSync(scratchDir, { recursive: true });\n const clipId = randomUUID();\n const inputPath = path.join(scratchDir, `utterance-${clipId}.webm`);\n const wavPath = path.join(scratchDir, `utterance-${clipId}.wav`);\n try {\n await writeFile(inputPath, Buffer.from(req.base64, \"base64\"));\n await convertToWav16k(inputPath, wavPath, ffmpegBinary);\n const text = await sidecar.transcribeWav(wavPath, req.language, req.model);\n return { text: normalizeTranscript(text) };\n } finally {\n await rm(inputPath, { force: true });\n await rm(wavPath, { force: true });\n }\n }\n\n return {\n isModelReady: (model) => isModelReady(modelsDir, model),\n getModelStatus: (model) => downloader.getStatus(model),\n ensureModelDownloaded: (model) => downloader.ensure(model),\n warmup: (model) => sidecar.warmup(model),\n transcribe,\n shutdown: () => sidecar.shutdown(),\n };\n}\n"],"mappings":";;;;;;;;;;;;AAEA,IAAa,gBAAgB;AAC7B,IAAa,gBAAgB;AAY7B,IAAM,aAAmB,KAAA;AACzB,IAAa,cAA6B;CAAE,MAAM;CAAM,MAAM;CAAM,OAAO;AAAK;;ACRhF,IAAM,gBAAgB,UAAU,QAAQ;;;AAIxC,SAAgB,gBAAgB,WAAmB,YAA8B;CAC/E,OAAO;EAAC;EAAM;EAAa;EAAS;EAAM;EAAW;EAAO;EAAS;EAAO;EAAK;EAAQ;EAAa;CAAU;AAClH;;;AAIA,eAAsB,gBAAgB,WAAmB,YAAoB,eAAe,UAAyB;CACnH,MAAM,cAAc,cAAc,gBAAgB,WAAW,UAAU,GAAG,EACxE,SAAS,cACX,CAAC;AACH;;ACHA,IAAM,UAAU;AAIhB,IAAa,iBAAiB;CAC5B,kBAAkB;EAAE,MAAM;EAA2B,KAAK,GAAG,QAAQ;EAA2B,UAAU;CAAc;CACxH,OAAO;EAAE,MAAM;EAAkB,KAAK,GAAG,QAAQ;EAAkB,UAAU;CAAY;CACzF,MAAM;EAAE,MAAM;EAAiB,KAA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QAAQ,QAAQ,GAAG;CAC9C,OAAO,cAAc,IAAI,QAAQ,YAAY,CAAC,IAAI,KAAK;AACzD;AAEA,SAAgB,cAAc,MAA+B;CAC3D,MAAM,EAAE,cAAc;CACtB,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,eAAe,KAAK,gBAAgB;CAC1C,MAAM,aAAa,sBAAsB,WAAW,MAAM;CAC1D,MAAM,UAAU,cACd,WACA,KAAK,gBAAgB,kBACrB,QACA,uBAAuB,QAAQ,IAAI,gCAAgC,MAAM,CAC3E;CAIA,MAAM,aAAa,KAAK,KAAK,WAAW,UAAU;CAElD,eAAe,WAAW,KAAmD;EAC3E,UAAU,YAAY,EAAE,WAAW,KAAK,CAAC;EACzC,MAAM,SAAS,WAAW;EAC1B,MAAM,YAAY,KAAK,KAAK,YAAY,aAAa,OAAO,MAAM;EAClE,MAAM,UAAU,KAAK,KAAK,YAAY,aAAa,OAAO,KAAK;EAC/D,IAAI;GACF,MAAM,UAAU,WAAW,OAAO,KAAK,IAAI,QAAQ,QAAQ,CAAC;GAC5D,MAAM,gBAAgB,WAAW,SAAS,YAAY;GAEtD,OAAO,EAAE,MAAM,oBAAoB,MADhB,QAAQ,cAAc,SAAS,IAAI,UAAU,IAAI,KAAK,CAClC,EAAE;EAC3C,UAAU;GACR,MAAM,GAAG,WAAW,EAAE,OAAO,KAAK,CAAC;GACnC,MAAM,GAAG,SAAS,EAAE,OAAO,KAAK,CAAC;EACnC;CACF;CAEA,OAAO;EACL,eAAe,UAAU,aAAa,WAAW,KAAK;EACtD,iBAAiB,UAAU,WAAW,UAAU,KAAK;EACrD,wBAAwB,UAAU,WAAW,OAAO,KAAK;EACzD,SAAS,UAAU,QAAQ,OAAO,KAAK;EACvC;EACA,gBAAgB,QAAQ,SAAS;CACnC;AACF"}
@@ -1,5 +1,6 @@
1
- /** whisper-server CLI args to preload `modelPath` and bind to `host:port`. */
2
- export declare function buildServerArgs(modelPath: string, host: string, port: number): string[];
1
+ /** whisper-server CLI args to preload `modelPath` and bind to `host:port`,
2
+ * followed by any user-supplied `extraArgs`. */
3
+ export declare function buildServerArgs(modelPath: string, host: string, port: number, extraArgs?: readonly string[]): string[];
3
4
  /** Append `chunk` to a bounded stderr tail, keeping only the last `maxChars`. */
4
5
  export declare function appendStderrTail(previous: string, chunk: string, maxChars: number): string;
5
6
  /** Extract the transcript from a whisper-server `/inference` JSON response.
@@ -27,6 +27,6 @@ export interface StartLifecycle {
27
27
  ensureSidecar: (model: WhisperModelName) => Promise<ActiveSidecar>;
28
28
  shutdown: () => void;
29
29
  }
30
- export declare function defaultSpawnServer(modelsDir: string, serverBinary: string, logger: WhisperLogger): StartLifecycleDeps["spawnServer"];
30
+ export declare function defaultSpawnServer(modelsDir: string, serverBinary: string, logger: WhisperLogger, extraArgs?: readonly string[]): StartLifecycleDeps["spawnServer"];
31
31
  export declare function createStartLifecycle(deps: StartLifecycleDeps): StartLifecycle;
32
- export declare function createSidecar(modelsDir: string, serverBinary?: string, logger?: WhisperLogger): Sidecar;
32
+ export declare function createSidecar(modelsDir: string, serverBinary?: string, logger?: WhisperLogger, extraArgs?: readonly string[]): Sidecar;
@@ -1,10 +1,3 @@
1
1
  import { Dirent, Stats } from 'node:fs';
2
- export declare function isWithin(rootReal: string, candidateReal: string): boolean;
3
- export declare function realpathOrNull(absPath: string): string | null;
4
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
5
- * or is unreadable. */
6
- export declare function readTextSafe(absPath: string, rootReal: string): Promise<string | null>;
7
- /** Sync twin of `readTextSafe`. */
8
- export declare function readTextSafeSync(absPath: string, rootReal: string): string | null;
9
2
  export declare function statSafeAsync(absPath: string): Promise<Stats | null>;
10
3
  export declare function readDirSafeAsync(absPath: string): Promise<Dirent[]>;
@@ -1,67 +1,15 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_rolldown_runtime = require("../../rolldown-runtime-CmQyd0Gu.cjs");
3
3
  const require_wiki_paths = require("../paths.cjs");
4
- const require_safe = require("../../safe-D79sHxq1.cjs");
5
4
  const require_graph = require("../../graph-BvVMZfDV.cjs");
6
5
  const require_slug = require("../../slug-DVkuPjIv.cjs");
7
- let node_fs = require("node:fs");
6
+ const require_withinRoot = require("../../withinRoot-CHPN9eHD.cjs");
7
+ const require_containment = require("../../containment-Dc3gO4wD.cjs");
8
8
  let node_path = require("node:path");
9
9
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
10
10
  let node_fs_promises = require("node:fs/promises");
11
11
  let _mulmoclaude_markdown_utils_markdown_frontmatter = require("@mulmoclaude/markdown-utils/markdown/frontmatter");
12
12
  // src/wiki/server/fs.ts
13
- var READ_FLAGS = node_fs.constants.O_RDONLY | (node_fs.constants.O_NOFOLLOW ?? 0) | (node_fs.constants.O_NONBLOCK ?? 0);
14
- function isWithin(rootReal, candidateReal) {
15
- const rel = node_path.default.relative(rootReal, candidateReal);
16
- return rel !== ".." && !rel.startsWith(`..${node_path.default.sep}`) && !node_path.default.isAbsolute(rel);
17
- }
18
- function realpathOrNull(absPath) {
19
- try {
20
- return node_fs.realpathSync.native(absPath);
21
- } catch (err) {
22
- return require_safe.isEnoent(err) ? null : jsRealpathOrNull(absPath);
23
- }
24
- }
25
- function jsRealpathOrNull(absPath) {
26
- try {
27
- return (0, node_fs.realpathSync)(absPath);
28
- } catch {
29
- return null;
30
- }
31
- }
32
- function isOpenedFileInside(absPath, rootReal, opened) {
33
- const real = realpathOrNull(absPath);
34
- if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
35
- const onDisk = (0, node_fs.lstatSync)(real, { bigint: true });
36
- return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
37
- }
38
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
39
- * or is unreadable. */
40
- async function readTextSafe(absPath, rootReal) {
41
- try {
42
- const handle = await (0, node_fs_promises.open)(absPath, READ_FLAGS);
43
- try {
44
- return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
45
- } finally {
46
- await handle.close();
47
- }
48
- } catch {
49
- return null;
50
- }
51
- }
52
- /** Sync twin of `readTextSafe`. */
53
- function readTextSafeSync(absPath, rootReal) {
54
- try {
55
- const descriptor = (0, node_fs.openSync)(absPath, READ_FLAGS);
56
- try {
57
- return isOpenedFileInside(absPath, rootReal, (0, node_fs.fstatSync)(descriptor, { bigint: true })) ? (0, node_fs.readFileSync)(descriptor, "utf-8") : null;
58
- } finally {
59
- (0, node_fs.closeSync)(descriptor);
60
- }
61
- } catch {
62
- return null;
63
- }
64
- }
65
13
  async function statSafeAsync(absPath) {
66
14
  try {
67
15
  return await (0, node_fs_promises.stat)(absPath);
@@ -126,10 +74,10 @@ function parseFrontmatterTags(content) {
126
74
  // src/wiki/server/locations.ts
127
75
  function wikiReadLocations(workspace) {
128
76
  const dirs = require_wiki_paths.wikiDirs(workspace);
129
- const workspaceReal = realpathOrNull(workspace);
77
+ const workspaceReal = require_containment.realpathSyncOrNull(workspace);
130
78
  const insideWorkspace = (absPath) => {
131
- const candidateReal = workspaceReal === null ? null : realpathOrNull(node_path.default.resolve(workspaceReal, node_path.default.relative(workspace, absPath)));
132
- return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
79
+ const candidateReal = workspaceReal === null ? null : require_containment.realpathSyncOrNull(node_path.default.resolve(workspaceReal, node_path.default.relative(workspace, absPath)));
80
+ return workspaceReal !== null && candidateReal !== null && require_containment.isInsideRoot(workspaceReal, candidateReal) ? candidateReal : null;
133
81
  };
134
82
  return {
135
83
  pagesDir: dirs.pagesDir,
@@ -142,7 +90,7 @@ function wikiReadLocations(workspace) {
142
90
  // src/wiki/server/engine.ts
143
91
  var MIN_FUZZY_SLUG_LEN = 6;
144
92
  function readFileOrEmpty(absPath, workspaceReal) {
145
- return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
93
+ return absPath === null || workspaceReal === null ? "" : require_withinRoot.readTextWithinRootSync(workspaceReal, absPath) ?? "";
146
94
  }
147
95
  async function pageSlugs(locations) {
148
96
  return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
@@ -233,7 +181,7 @@ async function readWikiPage(workspace, pageName) {
233
181
  /** Page body, or "" when the file vanished between indexing and reading. */
234
182
  async function readPageBody(locations, fileName) {
235
183
  const { pagesReal, workspaceReal } = locations;
236
- return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(node_path.default.join(pagesReal, fileName), workspaceReal) ?? "";
184
+ return pagesReal === null || workspaceReal === null ? "" : await require_withinRoot.readTextWithinRoot(workspaceReal, node_path.default.join(pagesReal, fileName)) ?? "";
237
185
  }
238
186
  /** Read every page + the index and build the page→page link graph.
239
187
  * No cache: the graph is requested explicitly and a content edit does
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["constants","path","realpathSync","isEnoent","lstatSync","open","openSync","fstatSync","readFileSync","stat","readdir","parseFrontmatter","wikiDirs","path","parseIndexEntries","path","parseWikiLink","matchWikiSlug","wikiSlugify","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { BigIntStats, Dirent, Stats } from \"node:fs\";\nimport { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from \"node:fs\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { isEnoent } from \"../../files/safe.js\";\n\n// A FIFO must not block the server, and a link is refused at open where the OS can; both flags are undefined on\n// Windows, where the check after the open is what refuses a link out.\nconst READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);\n\n// `path.relative` rather than a `rootReal + sep` prefix, which a workspace at a filesystem root (`/`, `C:\\`) would fail.\nexport function isWithin(rootReal: string, candidateReal: string): boolean {\n const rel = path.relative(rootReal, candidateReal);\n return rel !== \"..\" && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);\n}\n\n// Native first: the JS realpath keeps a link's letter case, so on a case-insensitive disk an inside link looks outside.\n// The JS one is the fallback for drives where the native call throws (EISDIR on some Windows RAM disks).\nexport function realpathOrNull(absPath: string): string | null {\n try {\n return realpathSync.native(absPath);\n } catch (err) {\n return isEnoent(err) ? null : jsRealpathOrNull(absPath);\n }\n}\n\nfunction jsRealpathOrNull(absPath: string): string | null {\n try {\n return realpathSync(absPath);\n } catch {\n return null;\n }\n}\n\n// Checked after the open, so a folder or file swapped for a link out between the caller's check and the open, or\n// swapped back before this check, is refused: where the path leads now must be inside and be the opened file.\nfunction isOpenedFileInside(absPath: string, rootReal: string, opened: BigIntStats): boolean {\n const real = realpathOrNull(absPath);\n if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;\n const onDisk = lstatSync(real, { bigint: true });\n return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;\n}\n\n/** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,\n * or is unreadable. */\nexport async function readTextSafe(absPath: string, rootReal: string): Promise<string | null> {\n try {\n const handle = await open(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile(\"utf-8\") : null;\n } finally {\n await handle.close();\n }\n } catch {\n return null;\n }\n}\n\n/** Sync twin of `readTextSafe`. */\nexport function readTextSafeSync(absPath: string, rootReal: string): string | null {\n try {\n const descriptor = openSync(absPath, READ_FLAGS);\n try {\n return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, \"utf-8\") : null;\n } finally {\n closeSync(descriptor);\n }\n } catch {\n return null;\n }\n}\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isWithin, realpathOrNull } from \"./fs.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextSafe, readTextSafeSync } from \"./fs.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextSafeSync(absPath, workspaceReal) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextSafe(path.join(pagesReal, fileName), workspaceReal)) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName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AAC;EAC7E,GAAGC,cAAAA,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAcC,cAAAA,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["stat","readdir","parseFrontmatter","wikiDirs","realpathSyncOrNull","path","isInsideRoot","readTextWithinRootSync","parseIndexEntries","path","parseWikiLink","matchWikiSlug","wikiSlugify","readTextWithinRoot","buildWikiGraph","slugByIndexTitle","findOrphanPages","findMissingFiles","findBrokenLinksInPage","findTagDrift"],"sources":["../../../src/wiki/server/fs.ts","../../../src/wiki/server/pageIndex.ts","../../../src/wiki/server/frontmatter.ts","../../../src/wiki/server/locations.ts","../../../src/wiki/server/engine.ts"],"sourcesContent":["// Minimal ENOENT-swallowing fs wrappers for the wiki read-engine.\n// Self-contained (core can't reach the host's `server/utils/files/safe.ts`);\n// only the handful of helpers the wiki engine needs. Same \"return\n// null / [] on any error\" contract so callers branch on the value\n// instead of try/catch.\n\nimport type { Dirent, Stats } from \"node:fs\";\nimport { readdir, stat } from \"node:fs/promises\";\n\nexport async function statSafeAsync(absPath: string): Promise<Stats | null> {\n try {\n return await stat(absPath);\n } catch {\n return null;\n }\n}\n\nexport async function readDirSafeAsync(absPath: string): Promise<Dirent[]> {\n try {\n return await readdir(absPath, { withFileTypes: true });\n } catch {\n return [];\n }\n}\n","// In-memory index of `<pagesDir>/*.md` keyed by slug (= filename\n// without the `.md` extension). Kept fresh via `pagesDir` mtime —\n// adding, removing, or renaming a file under `pagesDir` advances the\n// directory's mtime on every major filesystem we target (macOS APFS,\n// Linux ext4, Windows NTFS), so one cheap `stat()` per request is\n// enough to decide whether to rebuild.\n\nimport { readDirSafeAsync, statSafeAsync } from \"./fs.js\";\n\nexport interface PageIndex {\n mtimeMs: number;\n /** slug → filename (e.g. \"sakura-internet\" → \"sakura-internet.md\"). */\n slugs: Map<string, string>;\n}\n\n// Keyed by `pagesDir`: the engine is workspace-injected and may be\n// called with more than one pages directory in a single process. A\n// single global slot would let one workspace's slug map be returned\n// for another whenever their mtimes happen to tie (Codex P2 on #1876).\nconst cache = new Map<string, PageIndex>();\n\n/**\n * Get the page index for `pagesDir`. Returns a cached value as long as\n * THAT directory's mtime hasn't advanced; otherwise rebuilds. Safe to\n * call concurrently — racing builds produce the same result.\n */\nexport async function getPageIndex(pagesDir: string): Promise<PageIndex> {\n const stat = await statSafeAsync(pagesDir);\n if (!stat) {\n // Dir doesn't exist yet (never ingested). Return empty but don't\n // cache a stale-forever value — the next call re-stats.\n return { mtimeMs: 0, slugs: new Map() };\n }\n const cached = cache.get(pagesDir);\n if (cached && cached.mtimeMs >= stat.mtimeMs) return cached;\n const entries = await readDirSafeAsync(pagesDir);\n const slugs = new Map<string, string>();\n for (const entry of entries) {\n if (!entry.isFile()) continue;\n const { name } = entry;\n if (!name.endsWith(\".md\")) continue;\n slugs.set(name.slice(0, -\".md\".length), name);\n }\n const built: PageIndex = { mtimeMs: stat.mtimeMs, slugs };\n cache.set(pagesDir, built);\n return built;\n}\n\n/** Test-only: drop the module-level cache (all directories). */\nexport function __resetPageIndexCache(): void {\n cache.clear();\n}\n","// Read-side frontmatter helpers for the wiki engine. The generic\n// `---\\n…\\n---\\n` envelope parsing is the canonical value-preserving\n// (FAILSAFE_SCHEMA) parser in `@mulmoclaude/markdown-utils`; only the\n// wiki-specific `tags:` reader stays here. Re-exporting `parseFrontmatter`\n// keeps the `@mulmoclaude/core/wiki/server` barrel surface stable — it now\n// returns the richer `{ meta, body, hasHeader }` shape.\n\nimport { parseFrontmatter } from \"@mulmoclaude/markdown-utils/markdown/frontmatter\";\n\nexport { parseFrontmatter };\n\nfunction cleanTagToken(token: string): string {\n return token\n .trim()\n .replace(/^['\"]|['\"]$/g, \"\")\n .replace(/^#/, \"\")\n .toLowerCase();\n}\n\n/** Narrow `tags:` reader. Handles flow (`tags: [a, b]`) and block-list\n * style; anything unparseable returns `[]` (best-effort, never throws). */\nexport function parseFrontmatterTags(content: string): string[] {\n const parsed = parseFrontmatter(content);\n if (!parsed.hasHeader) return [];\n const tagsValue = parsed.meta.tags;\n if (!Array.isArray(tagsValue)) return [];\n return tagsValue\n .filter((item): item is string => typeof item === \"string\")\n .map(cleanTagToken)\n .filter((token) => token.length > 0);\n}\n","// A wiki folder or file that leads out of the workspace counts as absent, so nothing outside is listed or read.\n\nimport path from \"node:path\";\nimport { isInsideRoot, realpathSyncOrNull } from \"../../files/containment.js\";\nimport { wikiDirs } from \"./paths.js\";\n\nexport interface WikiReadLocations {\n /** `<workspace>/data/wiki/pages` as the caller spelled it: resolved page paths handed back are joined onto this. */\n pagesDir: string;\n /** The workspace's realpath: every read re-checks against it after opening. */\n workspaceReal: string | null;\n pagesReal: string | null;\n indexReal: string | null;\n logReal: string | null;\n}\n\nexport function wikiReadLocations(workspace: string): WikiReadLocations {\n const dirs = wikiDirs(workspace);\n const workspaceReal = realpathSyncOrNull(workspace);\n const insideWorkspace = (absPath: string): string | null => {\n const candidateReal = workspaceReal === null ? null : realpathSyncOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));\n return workspaceReal !== null && candidateReal !== null && isInsideRoot(workspaceReal, candidateReal) ? candidateReal : null;\n };\n return {\n pagesDir: dirs.pagesDir,\n workspaceReal,\n pagesReal: insideWorkspace(dirs.pagesDir),\n indexReal: insideWorkspace(dirs.indexFile),\n logReal: insideWorkspace(dirs.logFile),\n };\n}\n","// Workspace-injected wiki read-engine — the filesystem layer that feeds\n// the pure helpers in `@mulmoclaude/core/wiki`. Shared by every host so\n// the two apps reading the same `data/wiki/` can't disagree on slug\n// resolution, graph edges, or lint findings. Mirrors the bodies that\n// previously lived in MulmoClaude's `server/api/routes/wiki.ts`; the\n// hosts keep only their HTTP response shaping on top.\n//\n// The read/write WRITE side (writeWikiPage / snapshots) stays host-side\n// until a host needs it shared.\n\nimport path from \"node:path\";\nimport { parseWikiLink } from \"../link.js\";\nimport { wikiSlugify } from \"../slug.js\";\nimport { matchWikiSlug, slugByIndexTitle } from \"../resolve.js\";\nimport { type WikiPageEntry, parseIndexEntries } from \"../index-parse.js\";\nimport { findBrokenLinksInPage, findMissingFiles, findOrphanPages, findTagDrift } from \"../lint.js\";\nimport { type WikiGraph, buildWikiGraph } from \"../graph.js\";\nimport { readTextWithinRoot, readTextWithinRootSync } from \"../../files/withinRoot.js\";\nimport { getPageIndex } from \"./pageIndex.js\";\nimport { parseFrontmatterTags } from \"./frontmatter.js\";\nimport { type WikiReadLocations, wikiReadLocations } from \"./locations.js\";\n\n// Below this length the fuzzy `includes` step is skipped — CJK /\n// emoji-only / very-short page names slugify down to a short noise\n// tail that partial-matches almost anything; the index.md title-match\n// fallback still handles the legitimate non-ASCII case (#1194).\nconst MIN_FUZZY_SLUG_LEN = 6;\n\nfunction readFileOrEmpty(absPath: string | null, workspaceReal: string | null): string {\n return absPath === null || workspaceReal === null ? \"\" : (readTextWithinRootSync(workspaceReal, absPath) ?? \"\");\n}\n\nasync function pageSlugs(locations: WikiReadLocations): Promise<Map<string, string>> {\n return locations.pagesReal === null ? new Map() : (await getPageIndex(locations.pagesReal)).slugs;\n}\n\n/** Walk every indexed slug for an `includes`-style match. Returns the\n * single best candidate, or null when the slug is too short OR several\n * candidates tie at the top score (ambiguous → defer to the caller's\n * title-match fallback). Score = min/max length, decoupled from Map\n * iteration order so resolution is deterministic across hosts. */\nexport function pickFuzzyMatch(slug: string, slugs: ReadonlyMap<string, string>): string | null {\n if (slug.length < MIN_FUZZY_SLUG_LEN) return null;\n let bestFile: string | null = null;\n let bestScore = 0;\n let bestIsTied = false;\n for (const [key, file] of slugs) {\n if (!slug.includes(key) && !key.includes(slug)) continue;\n const shorter = Math.min(slug.length, key.length);\n const longer = Math.max(slug.length, key.length);\n const score = shorter / longer;\n if (score > bestScore) {\n bestScore = score;\n bestFile = file;\n bestIsTied = false;\n } else if (score === bestScore) {\n bestIsTied = true;\n }\n }\n return bestIsTied ? null : bestFile;\n}\n\n/** File matching an index.md entry whose title equals `target` — the\n * last resort for a link written as the display title rather than\n * the page's own name. */\nfunction fileByIndexTitle(locations: WikiReadLocations, target: string, slugs: ReadonlyMap<string, string>): string | undefined {\n const entries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const trimmed = target.trim();\n const titleMatch = entries.find((entry) => entry.title === trimmed);\n return titleMatch ? slugs.get(titleMatch.slug) : undefined;\n}\n\n/** Resolve a page name to an absolute `.md` path: known slug (literal\n * or slugified) → fuzzy → index-title fallback. `pageName` may carry\n * the `[[target|display]]` form; `parseWikiLink` strips the display\n * half so the lookup uses just the target. */\nexport async function resolvePagePath(workspace: string, pageName: string): Promise<string | null> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n return fileName === null ? null : path.join(locations.pagesDir, fileName);\n}\n\nasync function resolvePageFile(locations: WikiReadLocations, pageName: string): Promise<string | null> {\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0) return null;\n\n const { target } = parseWikiLink(pageName);\n const matched = matchWikiSlug(target, slugs);\n const matchedFile = matched === null ? undefined : slugs.get(matched);\n if (matchedFile) return matchedFile;\n\n const fuzzy = pickFuzzyMatch(wikiSlugify(target), slugs);\n if (fuzzy) return fuzzy;\n\n return fileByIndexTitle(locations, target, slugs) ?? null;\n}\n\n/** Raw `index.md` content + its parsed entries. */\nexport function readWikiIndex(workspace: string): { content: string; entries: WikiPageEntry[] } {\n const locations = wikiReadLocations(workspace);\n const content = readFileOrEmpty(locations.indexReal, locations.workspaceReal);\n return { content, entries: parseIndexEntries(content) };\n}\n\n/** Raw `log.md` content (empty string if absent). */\nexport function readWikiLog(workspace: string): string {\n const locations = wikiReadLocations(workspace);\n return readFileOrEmpty(locations.logReal, locations.workspaceReal);\n}\n\nexport interface WikiPageRead {\n /** Absolute path of the resolved file, or null when nothing matched. */\n filePath: string | null;\n /** File body (empty when missing OR when the file is an empty placeholder). */\n content: string;\n /** True iff a page file resolved (distinct from empty content). */\n exists: boolean;\n /** Title to display — the resolved filename stem, or the raw pageName. */\n resolvedTitle: string;\n}\n\n/** Resolve + read a page. Distinguishes missing (`exists: false`) from\n * empty-but-present (`exists: true`, `content: \"\"`). */\nexport async function readWikiPage(workspace: string, pageName: string): Promise<WikiPageRead> {\n const locations = wikiReadLocations(workspace);\n const fileName = await resolvePageFile(locations, pageName);\n if (fileName === null || locations.pagesReal === null) return { filePath: null, content: \"\", exists: false, resolvedTitle: pageName };\n const content = readFileOrEmpty(path.join(locations.pagesReal, fileName), locations.workspaceReal);\n return { filePath: path.join(locations.pagesDir, fileName), content, exists: true, resolvedTitle: path.basename(fileName, \".md\") };\n}\n\n/** Page body, or \"\" when the file vanished between indexing and reading. */\nasync function readPageBody(locations: WikiReadLocations, fileName: string): Promise<string> {\n const { pagesReal, workspaceReal } = locations;\n return pagesReal === null || workspaceReal === null ? \"\" : ((await readTextWithinRoot(workspaceReal, path.join(pagesReal, fileName))) ?? \"\");\n}\n\n/** Read every page + the index and build the page→page link graph.\n * No cache: the graph is requested explicitly and a content edit does\n * not advance the pagesDir mtime the page index caches on. */\nexport async function loadWikiGraph(workspace: string): Promise<WikiGraph> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n const pages = await Promise.all([...slugs.entries()].map(async ([slug, fileName]) => ({ slug, content: await readPageBody(locations, fileName) })));\n const indexEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n return buildWikiGraph(pages, indexEntries);\n}\n\nexport interface PageBody {\n fileName: string;\n content: string;\n}\n\nasync function readPageBodies(locations: WikiReadLocations, fileNames: readonly string[]): Promise<PageBody[]> {\n return Promise.all(fileNames.map(async (fileName) => ({ fileName, content: await readPageBody(locations, fileName) })));\n}\n\n/** Frontmatter `tags:` per page, keyed for `findTagDrift`. Lowercased so\n * a `MyPage.md` filename matches an `entry.slug` of `mypage`, which is\n * what the drift rule looks up. */\nexport function frontmatterTagIndex(bodies: readonly PageBody[]): Map<string, string[]> {\n const tagsBySlug = new Map<string, string[]>();\n bodies.forEach(({ fileName, content }) => {\n tagsBySlug.set(fileName.replace(/\\.md$/i, \"\").toLowerCase(), parseFrontmatterTags(content));\n });\n return tagsBySlug;\n}\n\n/** Run every lint rule over the on-disk wiki, returning issue strings. */\nexport async function collectLintIssues(workspace: string): Promise<string[]> {\n const locations = wikiReadLocations(workspace);\n const slugs = await pageSlugs(locations);\n if (slugs.size === 0 || locations.pagesReal === null) {\n return [\"- Wiki `pages/` directory does not exist yet. Start ingesting sources.\"];\n }\n const pageEntries = parseIndexEntries(readFileOrEmpty(locations.indexReal, locations.workspaceReal));\n const fileSlugs = new Set(slugs.keys());\n const slugByTitle = slugByIndexTitle(pageEntries);\n const bodies = await readPageBodies(locations, [...slugs.values()]);\n return [\n ...findOrphanPages(fileSlugs, new Set(pageEntries.map((entry) => entry.slug))),\n ...findMissingFiles(pageEntries, fileSlugs),\n ...bodies.flatMap(({ fileName, content }) => findBrokenLinksInPage(fileName, content, fileSlugs, slugByTitle)),\n ...findTagDrift(pageEntries, frontmatterTagIndex(bodies)),\n ];\n}\n"],"mappings":";;;;;;;;;;;;AASA,eAAsB,cAAc,SAAwC;CAC1E,IAAI;EACF,OAAO,OAAA,GAAMA,iBAAAA,KAAAA,CAAK,OAAO;CAC3B,QAAQ;EACN,OAAO;CACT;AACF;AAEA,eAAsB,iBAAiB,SAAoC;CACzE,IAAI;EACF,OAAO,OAAA,GAAMC,iBAAAA,QAAAA,CAAQ,SAAS,EAAE,eAAe,KAAK,CAAC;CACvD,QAAQ;EACN,OAAO,CAAC;CACV;AACF;;ACJA,IAAM,wBAAQ,IAAI,IAAuB;;;;;;AAOzC,eAAsB,aAAa,UAAsC;CACvE,MAAM,OAAO,MAAM,cAAc,QAAQ;CACzC,IAAI,CAAC,MAGH,OAAO;EAAE,SAAS;EAAG,uBAAO,IAAI,IAAI;CAAE;CAExC,MAAM,SAAS,MA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S,KAAK,UAAU,cAAc,MAC9C,OAAO,CAAC,wEAAwE;CAElF,MAAM,cAAcN,cAAAA,kBAAkB,gBAAgB,UAAU,WAAW,UAAU,aAAa,CAAC;CACnG,MAAM,YAAY,IAAI,IAAI,MAAM,KAAK,CAAC;CACtC,MAAM,cAAcO,cAAAA,iBAAiB,WAAW;CAChD,MAAM,SAAS,MAAM,eAAe,WAAW,CAAC,GAAG,MAAM,OAAO,CAAC,CAAC;CAClE,OAAO;EACL,GAAGC,cAAAA,gBAAgB,WAAW,IAAI,IAAI,YAAY,KAAK,UAAU,MAAM,IAAI,CAAC,CAAC;EAC7E,GAAGC,cAAAA,iBAAiB,aAAa,SAAS;EAC1C,GAAG,OAAO,SAAS,EAAE,UAAU,cAAcC,cAAAA,sBAAsB,UAAU,SAAS,WAAW,WAAW,CAAC;EAC7G,GAAGC,cAAAA,aAAa,aAAa,oBAAoB,MAAM,CAAC;CAC1D;AACF"}
@@ -1,64 +1,12 @@
1
1
  import { wikiDirs, wikiSlugFromAbsPath } from "../paths.js";
2
- import { t as isEnoent } from "../../safe-DRNa8UBp.js";
3
2
  import { a as findMissingFiles, b as parseWikiLink, g as matchWikiSlug, i as findBrokenLinksInPage, m as parseIndexEntries, o as findOrphanPages, s as findTagDrift, t as buildWikiGraph, v as slugByIndexTitle } from "../../graph-DBbzemby.js";
4
3
  import { r as wikiSlugify } from "../../slug-D24AYqCZ.js";
5
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync } from "node:fs";
4
+ import { n as readTextWithinRootSync, t as readTextWithinRoot } from "../../withinRoot-CheaBWt0.js";
5
+ import { r as realpathSyncOrNull, t as isInsideRoot } from "../../containment-D_vAa6eT.js";
6
6
  import path from "node:path";
7
- import { open, readdir, stat } from "node:fs/promises";
7
+ import { readdir, stat } from "node:fs/promises";
8
8
  import { parseFrontmatter } from "@mulmoclaude/markdown-utils/markdown/frontmatter";
9
9
  // src/wiki/server/fs.ts
10
- var READ_FLAGS = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
11
- function isWithin(rootReal, candidateReal) {
12
- const rel = path.relative(rootReal, candidateReal);
13
- return rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel);
14
- }
15
- function realpathOrNull(absPath) {
16
- try {
17
- return realpathSync.native(absPath);
18
- } catch (err) {
19
- return isEnoent(err) ? null : jsRealpathOrNull(absPath);
20
- }
21
- }
22
- function jsRealpathOrNull(absPath) {
23
- try {
24
- return realpathSync(absPath);
25
- } catch {
26
- return null;
27
- }
28
- }
29
- function isOpenedFileInside(absPath, rootReal, opened) {
30
- const real = realpathOrNull(absPath);
31
- if (real === null || !isWithin(rootReal, real) || !opened.isFile()) return false;
32
- const onDisk = lstatSync(real, { bigint: true });
33
- return onDisk.isFile() && onDisk.dev === opened.dev && onDisk.ino === opened.ino;
34
- }
35
- /** Text of a regular file inside `rootReal`, or null when it is missing, leads outside, is a FIFO or other non-file,
36
- * or is unreadable. */
37
- async function readTextSafe(absPath, rootReal) {
38
- try {
39
- const handle = await open(absPath, READ_FLAGS);
40
- try {
41
- return isOpenedFileInside(absPath, rootReal, await handle.stat({ bigint: true })) ? await handle.readFile("utf-8") : null;
42
- } finally {
43
- await handle.close();
44
- }
45
- } catch {
46
- return null;
47
- }
48
- }
49
- /** Sync twin of `readTextSafe`. */
50
- function readTextSafeSync(absPath, rootReal) {
51
- try {
52
- const descriptor = openSync(absPath, READ_FLAGS);
53
- try {
54
- return isOpenedFileInside(absPath, rootReal, fstatSync(descriptor, { bigint: true })) ? readFileSync(descriptor, "utf-8") : null;
55
- } finally {
56
- closeSync(descriptor);
57
- }
58
- } catch {
59
- return null;
60
- }
61
- }
62
10
  async function statSafeAsync(absPath) {
63
11
  try {
64
12
  return await stat(absPath);
@@ -123,10 +71,10 @@ function parseFrontmatterTags(content) {
123
71
  // src/wiki/server/locations.ts
124
72
  function wikiReadLocations(workspace) {
125
73
  const dirs = wikiDirs(workspace);
126
- const workspaceReal = realpathOrNull(workspace);
74
+ const workspaceReal = realpathSyncOrNull(workspace);
127
75
  const insideWorkspace = (absPath) => {
128
- const candidateReal = workspaceReal === null ? null : realpathOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));
129
- return workspaceReal !== null && candidateReal !== null && isWithin(workspaceReal, candidateReal) ? candidateReal : null;
76
+ const candidateReal = workspaceReal === null ? null : realpathSyncOrNull(path.resolve(workspaceReal, path.relative(workspace, absPath)));
77
+ return workspaceReal !== null && candidateReal !== null && isInsideRoot(workspaceReal, candidateReal) ? candidateReal : null;
130
78
  };
131
79
  return {
132
80
  pagesDir: dirs.pagesDir,
@@ -139,7 +87,7 @@ function wikiReadLocations(workspace) {
139
87
  // src/wiki/server/engine.ts
140
88
  var MIN_FUZZY_SLUG_LEN = 6;
141
89
  function readFileOrEmpty(absPath, workspaceReal) {
142
- return absPath === null || workspaceReal === null ? "" : readTextSafeSync(absPath, workspaceReal) ?? "";
90
+ return absPath === null || workspaceReal === null ? "" : readTextWithinRootSync(workspaceReal, absPath) ?? "";
143
91
  }
144
92
  async function pageSlugs(locations) {
145
93
  return locations.pagesReal === null ? /* @__PURE__ */ new Map() : (await getPageIndex(locations.pagesReal)).slugs;
@@ -230,7 +178,7 @@ async function readWikiPage(workspace, pageName) {
230
178
  /** Page body, or "" when the file vanished between indexing and reading. */
231
179
  async function readPageBody(locations, fileName) {
232
180
  const { pagesReal, workspaceReal } = locations;
233
- return pagesReal === null || workspaceReal === null ? "" : await readTextSafe(path.join(pagesReal, fileName), workspaceReal) ?? "";
181
+ return pagesReal === null || workspaceReal === null ? "" : await readTextWithinRoot(workspaceReal, path.join(pagesReal, fileName)) ?? "";
234
182
  }
235
183
  /** Read every page + the index and build the page→page link graph.
236
184
  * No cache: the graph is requested explicitly and a content edit does