@caupulican/pi-adaptative 0.81.13 → 0.81.16

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 (55) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/dist/bundled-resources/runtimes/hf-transformers-openai-server.py +427 -0
  3. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +13 -11
  4. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +16 -10
  5. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +14 -7
  6. package/dist/core/agent-session.d.ts +11 -3
  7. package/dist/core/agent-session.d.ts.map +1 -1
  8. package/dist/core/agent-session.js +132 -23
  9. package/dist/core/agent-session.js.map +1 -1
  10. package/dist/core/local-runtime-controller.d.ts +17 -9
  11. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  12. package/dist/core/local-runtime-controller.js +124 -20
  13. package/dist/core/local-runtime-controller.js.map +1 -1
  14. package/dist/core/models/adaptation-store.d.ts +2 -0
  15. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  16. package/dist/core/models/adaptation-store.js +4 -0
  17. package/dist/core/models/adaptation-store.js.map +1 -1
  18. package/dist/core/models/default-model-suggestions.d.ts +4 -4
  19. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  20. package/dist/core/models/default-model-suggestions.js +9 -0
  21. package/dist/core/models/default-model-suggestions.js.map +1 -1
  22. package/dist/core/models/local-registration.d.ts +12 -0
  23. package/dist/core/models/local-registration.d.ts.map +1 -1
  24. package/dist/core/models/local-registration.js +68 -0
  25. package/dist/core/models/local-registration.js.map +1 -1
  26. package/dist/core/models/local-runtime.d.ts +77 -1
  27. package/dist/core/models/local-runtime.d.ts.map +1 -1
  28. package/dist/core/models/local-runtime.js +295 -4
  29. package/dist/core/models/local-runtime.js.map +1 -1
  30. package/dist/core/models/model-ref.d.ts +4 -0
  31. package/dist/core/models/model-ref.d.ts.map +1 -1
  32. package/dist/core/models/model-ref.js +12 -3
  33. package/dist/core/models/model-ref.js.map +1 -1
  34. package/dist/core/tool-repair-health.d.ts.map +1 -1
  35. package/dist/core/tool-repair-health.js +2 -1
  36. package/dist/core/tool-repair-health.js.map +1 -1
  37. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  38. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  39. package/dist/modes/interactive/interactive-mode.js +4 -0
  40. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  41. package/dist/modes/interactive/local-model-commands.d.ts +3 -1
  42. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  43. package/dist/modes/interactive/local-model-commands.js +133 -19
  44. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  45. package/docs/models.md +19 -1
  46. package/docs/tool-repair.md +2 -0
  47. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  48. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  49. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  50. package/examples/extensions/sandbox/package-lock.json +2 -2
  51. package/examples/extensions/sandbox/package.json +1 -1
  52. package/examples/extensions/with-deps/package-lock.json +2 -2
  53. package/examples/extensions/with-deps/package.json +1 -1
  54. package/npm-shrinkwrap.json +12 -12
  55. package/package.json +4 -4
@@ -1 +1 @@
1
- {"version":3,"file":"local-runtime.js","sourceRoot":"","sources":["../../../src/core/models/local-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAChD,OAAO,EAAE,OAAO,EAAE,IAAI,IAAI,MAAM,EAAE,QAAQ,IAAI,UAAU,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,KAAK,QAAQ,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,YAAY,EAAE,g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AM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,EAAE;iBACxF,CAAC;YACH,CAAC;YACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,CAAC;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;QACrF,CAAC;IAAA,CACD;CACD","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { existsSync, mkdirSync } from \"node:fs\";\nimport { homedir, arch as osArch, platform as osPlatform } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Readable, Writable } from \"node:stream\";\nimport * as nodeZlib from \"node:zlib\";\nimport { spawnProcess, spawnProcessSync, waitForChildProcess } from \"../../utils/child-process.ts\";\n\n/**\n * `spawnProcess(..., { stdio: [\"pipe\", \"pipe\", \"pipe\"] })` always yields a non-null `stdin` at\n * runtime, but child-process.ts's typed overload only narrows `.stdin` to non-null for the\n * capture-only (`StdioNull, StdioPipe, StdioPipe`) shape, so the generic overload's `Writable |\n * null` leaks through here. This makes the true invariant explicit and fails loudly (instead of\n * silently misbehaving) if it's ever violated by a future stdio change.\n */\nfunction requireStdin(proc: ChildProcess, label: string): Writable {\n\tif (!proc.stdin) throw new Error(`${label}: no stdin pipe`);\n\treturn proc.stdin;\n}\n\n/**\n * Local model runtime manager (local-model-lifecycle-design.md): Ollama first, interface kept\n * runtime-agnostic. Pi SPAWNS the serve process itself with OWNED model storage\n * (`OLLAMA_MODELS=<agentDir>/models/ollama`) so every downloaded weight lives inside pi's tree —\n * per-model disk accounting is trivial and full cleanup is one directory. If a system server is\n * already running, pi uses it instead of double-installing, with the honest tradeoff surfaced:\n * storage then lives in the system daemon's dir and removal control is limited to `ollama rm`.\n *\n * Hard boundaries (design \"Hard boundaries\"): lifecycle actions are USER commands only — this\n * module is never exposed as a model-invokable tool; install is GUIDE MODE (exact manual steps,\n * never `curl | sh`); removal is explicit, disclosed, and never automatic.\n */\n\nexport interface LocalRuntimeStatus {\n\tbinaryPath?: string;\n\tbinarySource?: \"system\" | \"user\" | \"pi-owned\";\n\tserverUp: boolean;\n\tserverUrl: string;\n\t/** True when the responding server is a child process pi spawned (owned storage applies). */\n\tmanagedByPi: boolean;\n\t/** Owned weights directory (only meaningful for pi-managed serves). */\n\townedModelsDir: string;\n}\n\nexport interface InstalledLocalModel {\n\tname: string;\n\tsizeBytes: number;\n}\n\n/** Pinned ollama release for the managed installer below. Bump here when needed — one constant. */\nexport const OLLAMA_PINNED_VERSION = \"0.31.1\";\n\nexport type OllamaAssetKind = \"tar-zst\" | \"tar-gz\" | \"zip\";\n\nexport interface OllamaReleaseAsset {\n\tname: string;\n\tkind: OllamaAssetKind;\n}\n\n/**\n * Maps a platform/arch pair (node's `os.platform()`/`os.arch()`) to the exact ollama release asset\n * name for {@link OLLAMA_PINNED_VERSION} — verified against the real ollama/ollama GitHub release\n * and its own install.sh, not guessed: darwin ships a CLI `.tgz` (the `.app`/`.dmg`/`Ollama-*.zip`\n * assets are the separate GUI-app installer, not what we want), linux ships `.tar.zst` per arch,\n * windows ships `.zip` per arch. Pure and exported so it's independently testable and reusable\n * (e.g. by a future doctor-driven managed install) without touching OllamaRuntime.\n */\nexport function resolveOllamaAsset(plat: string, architecture: string): OllamaReleaseAsset | undefined {\n\tif (plat === \"darwin\") {\n\t\t// Universal binary — one asset for both arm64 and x64.\n\t\treturn { name: \"ollama-darwin.tgz\", kind: \"tar-gz\" };\n\t}\n\tif (plat === \"linux\") {\n\t\tconst archName = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\treturn { name: `ollama-linux-${archName}.tar.zst`, kind: \"tar-zst\" };\n\t}\n\tif (plat === \"win32\") {\n\t\tconst archName = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\treturn { name: `ollama-windows-${archName}.zip`, kind: \"zip\" };\n\t}\n\treturn undefined;\n}\n\nexport interface LocalRuntimeDeps {\n\tfetchFn?: typeof fetch;\n\tspawnFn?: (\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions: { env: NodeJS.ProcessEnv },\n\t) => Pick<ChildProcess, \"pid\" | \"kill\" | \"unref\" | \"on\">;\n\texistsFn?: (path: string) => boolean;\n\tenvPath?: string;\n\thomeDir?: string;\n\tsleepFn?: (ms: number) => Promise<void>;\n\t/** os.platform()/os.arch() equivalents — injectable so asset resolution is testable per platform. */\n\tplatform?: () => string;\n\tarch?: () => string;\n\t/** Node's built-in zstd decompress transform, when THIS runtime's node:zlib has it — undefined\n\t * forces the system-zstd fallback. Injectable so tests can force either path deterministically\n\t * instead of depending on whatever Node happens to be running the test. */\n\tcreateZstdDecompress?: () => NodeJS.ReadWriteStream;\n\t/** Whether a named command exists on PATH (e.g. system `zstd`), for the extraction fallback. */\n\thasCommand?: (command: string) => boolean;\n\t/** Runs the extraction step for a downloaded archive. Injectable so installManaged's\n\t * download->extract->verify orchestration is testable without a real tar/zstd/unzip pipeline;\n\t * defaults to the real spawn-based extractor. */\n\textractArchive?: (\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: OllamaAssetKind,\n\t) => Promise<{ ok: boolean; error?: string }>;\n}\n\nconst DEFAULT_BASE_URL = \"http://127.0.0.1:11434\";\nconst HEALTH_TIMEOUT_MS = 2_000;\nconst START_POLL_ATTEMPTS = 20;\nconst START_POLL_INTERVAL_MS = 500;\n\nexport class OllamaRuntime {\n\tprivate readonly _agentDir: string;\n\tprivate readonly _baseUrl: string;\n\tprivate readonly _fetch: typeof fetch;\n\tprivate readonly _spawn: NonNullable<LocalRuntimeDeps[\"spawnFn\"]>;\n\tprivate readonly _exists: (path: string) => boolean;\n\tprivate readonly _envPath: string;\n\tprivate readonly _homeDir: string;\n\tprivate readonly _sleep: (ms: number) => Promise<void>;\n\tprivate readonly _platform: () => string;\n\tprivate readonly _arch: () => string;\n\tprivate readonly _createZstdDecompress: (() => NodeJS.ReadWriteStream) | undefined;\n\tprivate readonly _hasCommand: (command: string) => boolean;\n\tprivate readonly _extractArchiveOverride: LocalRuntimeDeps[\"extractArchive\"] | undefined;\n\tprivate _child: Pick<ChildProcess, \"pid\" | \"kill\" | \"unref\" | \"on\"> | undefined;\n\n\tconstructor(args: { agentDir: string; baseUrl?: string; deps?: LocalRuntimeDeps }) {\n\t\tthis._agentDir = args.agentDir;\n\t\tthis._baseUrl = (args.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n\t\tthis._fetch = args.deps?.fetchFn ?? fetch;\n\t\tthis._spawn = args.deps?.spawnFn ?? ((command, argv, options) => spawn(command, argv, options));\n\t\tthis._exists = args.deps?.existsFn ?? existsSync;\n\t\tthis._envPath = args.deps?.envPath ?? process.env.PATH ?? \"\";\n\t\tthis._homeDir = args.deps?.homeDir ?? homedir();\n\t\tthis._sleep = args.deps?.sleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis._platform = args.deps?.platform ?? osPlatform;\n\t\tthis._arch = args.deps?.arch ?? osArch;\n\t\t// Feature-detect (not version-sniff): recent Node added zstd natively to node:zlib. Verified\n\t\t// present on this repo's minimum supported Node (>=22.19.0); still detected at runtime rather\n\t\t// than assumed, so an older/different Node correctly falls through to the system-zstd path.\n\t\t// `\"createZstdDecompress\" in deps` (rather than `??`) so a test can force the fallback path by\n\t\t// passing the key as explicitly undefined, distinct from omitting it (real auto-detection).\n\t\tthis._createZstdDecompress =\n\t\t\targs.deps && \"createZstdDecompress\" in args.deps\n\t\t\t\t? args.deps.createZstdDecompress\n\t\t\t\t: typeof nodeZlib.createZstdDecompress === \"function\"\n\t\t\t\t\t? () => nodeZlib.createZstdDecompress()\n\t\t\t\t\t: undefined;\n\t\tthis._hasCommand =\n\t\t\targs.deps?.hasCommand ??\n\t\t\t((command) => spawnProcessSync(command, [\"--version\"], { encoding: \"utf8\" }).error === undefined);\n\t\tthis._extractArchiveOverride = args.deps?.extractArchive;\n\t}\n\n\tget baseUrl(): string {\n\t\treturn this._baseUrl;\n\t}\n\n\townedModelsDir(): string {\n\t\treturn join(this._agentDir, \"models\", \"ollama\");\n\t}\n\n\tprivate _findBinary(): { path: string; source: \"system\" | \"user\" | \"pi-owned\" } | undefined {\n\t\tconst piOwned = join(this._agentDir, \"runtimes\", \"ollama\", \"bin\", \"ollama\");\n\t\tif (this._exists(piOwned)) return { path: piOwned, source: \"pi-owned\" };\n\t\tconst userLevel = join(this._homeDir, \".local\", \"share\", \"ollama-dist\", \"bin\", \"ollama\");\n\t\tif (this._exists(userLevel)) return { path: userLevel, source: \"user\" };\n\t\tfor (const dir of this._envPath.split(delimiter)) {\n\t\t\tif (!dir) continue;\n\t\t\tconst candidate = join(dir, \"ollama\");\n\t\t\tif (this._exists(candidate)) return { path: candidate, source: \"system\" };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async _serverUp(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/tags`, {\n\t\t\t\tsignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),\n\t\t\t});\n\t\t\treturn response.ok;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync detect(): Promise<LocalRuntimeStatus> {\n\t\tconst binary = this._findBinary();\n\t\tconst serverUp = await this._serverUp();\n\t\treturn {\n\t\t\tbinaryPath: binary?.path,\n\t\t\tbinarySource: binary?.source,\n\t\t\tserverUp,\n\t\t\tserverUrl: this._baseUrl,\n\t\t\tmanagedByPi: this._child !== undefined && serverUp,\n\t\t\townedModelsDir: this.ownedModelsDir(),\n\t\t};\n\t}\n\n\t/**\n\t * Manual-steps fallback text — shown when the managed install below wasn't offered (headless),\n\t * was declined, or itself failed. #31 reversed the stance for ollama specifically: pi CAN install\n\t * it for you now (consent-gated, a controlled download into pi's own runtimes dir, never\n\t * `curl | sh`) — these steps are the alternative for when that path isn't taken.\n\t */\n\tinstallGuide(): string[] {\n\t\treturn [\n\t\t\t\"Ollama is not installed. Pi can install it for you now (asks first, never curl|sh) — or follow these manual steps yourself:\",\n\t\t\t\" 1. Download the pinned release archive for your platform:\",\n\t\t\t\" https://github.com/ollama/ollama/releases (asset: ollama-linux-amd64.tar.zst or your platform)\",\n\t\t\t` 2. Extract it to ${join(this._homeDir, \".local\", \"share\", \"ollama-dist\")}`,\n\t\t\t\" 3. Re-run your /models command - pi detects the binary automatically.\",\n\t\t\t\"Alternatively install system-wide from https://ollama.com/download and pi will use the system server.\",\n\t\t];\n\t}\n\n\t/** Which decompressor to use for a `.tar.zst` asset — native (this Node's own zlib) is always\n\t * preferred when available, even if a system `zstd` ALSO exists, since it needs no external\n\t * dependency at all. Verified per-runtime by feature detection (see the constructor), not by\n\t * guessing from a Node version number. */\n\tprivate _chooseZstdStrategy(): { kind: \"native\" } | { kind: \"system\" } | { kind: \"unavailable\" } {\n\t\tif (this._createZstdDecompress) return { kind: \"native\" };\n\t\tif (this._hasCommand(\"zstd\")) return { kind: \"system\" };\n\t\treturn { kind: \"unavailable\" };\n\t}\n\n\t/**\n\t * Managed install (#31): a consent-gated, controlled download of the pinned ollama release into\n\t * pi's OWN runtimes dir (`<agentDir>/runtimes/ollama/`) — never `curl | sh`, never a second\n\t * server instance, and distinct from {@link start}'s owned MODEL storage (this is the binary\n\t * itself). Callers (the router's consent flow, and later a doctor-driven install) own the\n\t * consent/UI; this method only does the mechanical download+extract+verify and reports the\n\t * outcome honestly. `onProgress` is best-effort UI feedback, not a completion signal.\n\t */\n\tasync installManaged(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst asset = resolveOllamaAsset(this._platform(), this._arch());\n\t\tif (!asset) return { ok: false, error: \"unsupported-platform\" };\n\n\t\tonProgress?.(`Downloading ${asset.name}…`);\n\t\tconst downloadUrl = `https://github.com/ollama/ollama/releases/download/v${OLLAMA_PINNED_VERSION}/${asset.name}`;\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await this._fetch(downloadUrl);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: `download-fail: ${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t\tif (!response.ok || !response.body) {\n\t\t\treturn { ok: false, error: `download-fail: HTTP ${response.status}` };\n\t\t}\n\n\t\tconst destDir = join(this._agentDir, \"runtimes\", \"ollama\");\n\t\tmkdirSync(destDir, { recursive: true });\n\n\t\tonProgress?.(`Extracting ${asset.name}…`);\n\t\tconst extract = this._extractArchiveOverride ?? ((input, dest, kind) => this._extractArchive(input, dest, kind));\n\t\tconst extracted = await extract(response.body as unknown as NodeJS.ReadableStream, destDir, asset.kind);\n\t\tif (!extracted.ok) return extracted;\n\n\t\tconst binaryName = this._platform() === \"win32\" ? \"ollama.exe\" : \"ollama\";\n\t\tconst binaryPath = join(destDir, \"bin\", binaryName);\n\t\tif (!this._exists(binaryPath)) {\n\t\t\treturn { ok: false, error: \"extract-fail: binary not found after extraction\" };\n\t\t}\n\t\tonProgress?.(\"Ollama installed.\");\n\t\treturn { ok: true };\n\t}\n\n\t/** Real extraction: `tar-gz` lets `tar` itself gunzip; `tar-zst` decompresses first (native\n\t * node:zlib preferred, system `zstd` as fallback, an honest error if neither exists — see\n\t * {@link _chooseZstdStrategy}); `zip` needs a seekable file, so it's buffered to disk first. */\n\tprivate async _extractArchive(\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: OllamaAssetKind,\n\t): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tif (kind === \"zip\") {\n\t\t\t\treturn await this._extractZip(input, destDir);\n\t\t\t}\n\t\t\treturn await this._extractTar(input, destDir, kind);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: `extract-fail: ${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\tprivate async _extractTar(\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: \"tar-gz\" | \"tar-zst\",\n\t): Promise<{ ok: boolean; error?: string }> {\n\t\tlet decompressed: Readable = input as unknown as Readable;\n\t\tconst tarArgs = [\"-xf\", \"-\", \"-C\", destDir];\n\t\tif (kind === \"tar-zst\") {\n\t\t\tconst strategy = this._chooseZstdStrategy();\n\t\t\tif (strategy.kind === \"unavailable\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: \"zstd-missing: this archive needs zstd to decompress and neither Node's built-in support nor a system `zstd` binary was found. Install zstd (e.g. `apt-get install zstd`, `dnf install zstd`, `pacman -S zstd`) and try again.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (strategy.kind === \"native\") {\n\t\t\t\tdecompressed = decompressed.pipe(\n\t\t\t\t\tthis._createZstdDecompress?.() as unknown as NodeJS.ReadWriteStream & Readable,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst zstdProc = spawnProcess(\"zstd\", [\"-d\"], { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\t\t\t\tdecompressed.pipe(requireStdin(zstdProc, \"zstd\"));\n\t\t\t\tdecompressed = zstdProc.stdout as unknown as Readable;\n\t\t\t}\n\t\t} else {\n\t\t\t// tar itself handles gzip via -z — no separate decompression step needed.\n\t\t\ttarArgs[0] = \"-xzf\";\n\t\t}\n\t\tconst tarProc = spawnProcess(\"tar\", tarArgs, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\t\tdecompressed.pipe(requireStdin(tarProc, \"tar\"));\n\t\tconst code = await waitForChildProcess(tarProc);\n\t\tif (code !== 0) {\n\t\t\treturn { ok: false, error: `extract-fail: tar exited with code ${code}` };\n\t\t}\n\t\treturn { ok: true };\n\t}\n\n\tprivate async _extractZip(input: NodeJS.ReadableStream, destDir: string): Promise<{ ok: boolean; error?: string }> {\n\t\t// Zip's central directory needs seekable file access — buffer to a temp file first.\n\t\tconst { createWriteStream } = await import(\"node:fs\");\n\t\tconst { pipeline } = await import(\"node:stream/promises\");\n\t\tconst zipPath = join(destDir, \"..\", `ollama-download-${process.pid}-${Date.now()}.zip`);\n\t\tawait pipeline(input as unknown as Readable, createWriteStream(zipPath));\n\t\ttry {\n\t\t\tconst extractCommand = this._platform() === \"win32\" && this._hasCommand(\"tar\") ? \"tar\" : \"unzip\";\n\t\t\tconst args = extractCommand === \"tar\" ? [\"-xf\", zipPath, \"-C\", destDir] : [\"-q\", zipPath, \"-d\", destDir];\n\t\t\tconst proc = spawnProcess(extractCommand, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\tconst code = await waitForChildProcess(proc);\n\t\t\tif (code !== 0) {\n\t\t\t\treturn { ok: false, error: `extract-fail: ${extractCommand} exited with code ${code}` };\n\t\t\t}\n\t\t\treturn { ok: true };\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tconst { rmSync } = await import(\"node:fs\");\n\t\t\t\trmSync(zipPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// best-effort cleanup\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Shared spawn-then-health-poll for both start modes below; `extraEnv` is the only thing that\n\t * differs between them (owned storage vs reusing the user's own). */\n\tprivate async _spawnAndPoll(\n\t\tbinary: { path: string },\n\t\textraEnv: NodeJS.ProcessEnv,\n\t): Promise<{ started: boolean; reason: string }> {\n\t\tconst host = this._baseUrl.replace(/^https?:\\/\\//, \"\");\n\t\tthis._child = this._spawn(binary.path, [\"serve\"], {\n\t\t\tenv: { ...process.env, OLLAMA_HOST: host, ...extraEnv },\n\t\t});\n\t\tthis._child.unref?.();\n\t\tfor (let attempt = 0; attempt < START_POLL_ATTEMPTS; attempt++) {\n\t\t\tif (await this._serverUp()) return { started: true, reason: \"started\" };\n\t\t\tawait this._sleep(START_POLL_INTERVAL_MS);\n\t\t}\n\t\tthis.stop();\n\t\treturn { started: false, reason: \"health_check_timeout\" };\n\t}\n\n\t/**\n\t * Start a pi-managed serve with OWNED storage and the hardened env verified on this class of\n\t * hardware. No-op (reported) when a server already responds — pi never double-serves. Used by\n\t * `/models add` et al, where isolated per-model-pull storage is the point.\n\t */\n\tasync start(): Promise<{ started: boolean; reason: string }> {\n\t\tif (await this._serverUp()) {\n\t\t\treturn { started: false, reason: this._child ? \"already_running_managed\" : \"already_running_system\" };\n\t\t}\n\t\tconst binary = this._findBinary();\n\t\tif (!binary) return { started: false, reason: \"binary_missing\" };\n\t\tmkdirSync(this.ownedModelsDir(), { recursive: true });\n\t\treturn this._spawnAndPoll(binary, {\n\t\t\tOLLAMA_MODELS: this.ownedModelsDir(),\n\t\t\tOLLAMA_FLASH_ATTENTION: \"1\",\n\t\t\tOLLAMA_KV_CACHE_TYPE: \"q8_0\",\n\t\t\tOLLAMA_NUM_PARALLEL: \"1\",\n\t\t\tOLLAMA_MAX_LOADED_MODELS: \"3\",\n\t\t});\n\t}\n\n\t/**\n\t * Start a serve that REUSES the user's own existing models directory (no `OLLAMA_MODELS`\n\t * override — falls through to Ollama's own default, `~/.ollama`), for callers that must see the\n\t * user's already-pulled models rather than pi's isolated/owned storage. Same idempotency and\n\t * hardened perf env as {@link start}; the only difference is which storage the server sees.\n\t */\n\tasync startReuseExisting(): Promise<{ started: boolean; reason: string }> {\n\t\tif (await this._serverUp()) {\n\t\t\treturn { started: false, reason: this._child ? \"already_running_managed\" : \"already_running_system\" };\n\t\t}\n\t\tconst binary = this._findBinary();\n\t\tif (!binary) return { started: false, reason: \"binary_missing\" };\n\t\treturn this._spawnAndPoll(binary, {\n\t\t\tOLLAMA_FLASH_ATTENTION: \"1\",\n\t\t\tOLLAMA_KV_CACHE_TYPE: \"q8_0\",\n\t\t\tOLLAMA_NUM_PARALLEL: \"1\",\n\t\t\tOLLAMA_MAX_LOADED_MODELS: \"3\",\n\t\t});\n\t}\n\n\t/** Resource hygiene only: stops the pi-managed serve process; never deletes anything. */\n\tstop(): { stopped: boolean } {\n\t\tif (!this._child) return { stopped: false };\n\t\ttry {\n\t\t\tthis._child.kill(\"SIGTERM\");\n\t\t} catch {\n\t\t\t// already gone\n\t\t}\n\t\tthis._child = undefined;\n\t\treturn { stopped: true };\n\t}\n\n\tasync list(): Promise<InstalledLocalModel[]> {\n\t\tconst response = await this._fetch(`${this._baseUrl}/api/tags`, { signal: AbortSignal.timeout(10_000) });\n\t\tif (!response.ok) throw new Error(`ollama list failed: HTTP ${response.status}`);\n\t\tconst data = (await response.json()) as { models?: Array<{ name?: string; size?: number }> };\n\t\treturn (data.models ?? [])\n\t\t\t.filter((model): model is { name: string; size?: number } => typeof model.name === \"string\")\n\t\t\t.map((model) => ({ name: model.name, sizeBytes: model.size ?? 0 }));\n\t}\n\n\t/** Pull a model through the server API (weights land in the SERVER's models dir). */\n\tasync pull(ref: string, onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/pull`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref, stream: true }),\n\t\t\t});\n\t\t\tif (!response.ok || !response.body) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `pull failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet lastStatus = \"\";\n\t\t\tlet errorMessage: string | undefined;\n\t\t\tconst handleLine = (line: string): void => {\n\t\t\t\tif (!line.trim()) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst event = JSON.parse(line) as { status?: string; error?: string };\n\t\t\t\t\tif (event.error) errorMessage = event.error;\n\t\t\t\t\tif (event.status && event.status !== lastStatus) {\n\t\t\t\t\t\tlastStatus = event.status;\n\t\t\t\t\t\tonProgress?.(event.status);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// partial line noise\n\t\t\t\t}\n\t\t\t};\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() ?? \"\";\n\t\t\t\tfor (const line of lines) handleLine(line);\n\t\t\t}\n\t\t\t// The stream's FINAL line has no trailing newline — it stays in the buffer and holds\n\t\t\t// the terminal \"success\"/error event; dropping it misreports every completed pull.\n\t\t\thandleLine(buffer);\n\t\t\tif (errorMessage) return { ok: false, error: errorMessage };\n\t\t\treturn lastStatus === \"success\"\n\t\t\t\t? { ok: true }\n\t\t\t\t: { ok: false, error: `pull ended with: ${lastStatus || \"unknown\"}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** EXPLICIT user action only — callers must have shown what gets deleted and confirmed. */\n\tasync remove(ref: string): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/delete`, {\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref }),\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `delete failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"local-runtime.js","sourceRoot":"","sources":["../../../src/core/models/local-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAqB,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,iBAAiB,EAAE,UAAU,EAAE,S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AAE,CAAC;IAAA,CAC1D;IAED,IAAI,GAAyB;QAC5B,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;QAC3C,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC;QAClB,IAAI,CAAC,KAAK,GAAG,SAAS,CAAC;QACvB,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAAA,CACzB;IAED,YAAY,GAAa;QACxB,OAAO;YACN,oEAAoE;YACpE,0CAA0C,IAAI,CAAC,OAAO,4BAA4B,IAAI,CAAC,QAAQ,GAAG;YAClG,oBAAoB;YACpB,qBAAqB,IAAI,CAAC,OAAO,EAAE;YACnC,KAAK,IAAI,CAAC,UAAU,+BAA+B;YACnD,KAAK,IAAI,CAAC,UAAU,mBAAmB,4BAA4B,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;YAC/E,KAAK,IAAI,CAAC,UAAU,IAAI,IAAI,CAAC,gBAAgB,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;SAC3D,CAAC;IAAA,CACF;CACD","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport { createWriteStream, existsSync, mkdirSync, rmSync } from \"node:fs\";\nimport { homedir, arch as osArch, platform as osPlatform } from \"node:os\";\nimport { delimiter, join } from \"node:path\";\nimport type { Readable, Writable } from \"node:stream\";\nimport { pipeline } from \"node:stream/promises\";\nimport * as nodeZlib from \"node:zlib\";\nimport { getBundledResourcesDir } from \"../../config.ts\";\nimport { spawnProcess, spawnProcessSync, waitForChildProcess } from \"../../utils/child-process.ts\";\n\n/**\n * `spawnProcess(..., { stdio: [\"pipe\", \"pipe\", \"pipe\"] })` always yields a non-null `stdin` at\n * runtime, but child-process.ts's typed overload only narrows `.stdin` to non-null for the\n * capture-only (`StdioNull, StdioPipe, StdioPipe`) shape, so the generic overload's `Writable |\n * null` leaks through here. This makes the true invariant explicit and fails loudly (instead of\n * silently misbehaving) if it's ever violated by a future stdio change.\n */\nfunction requireStdin(proc: ChildProcess, label: string): Writable {\n\tif (!proc.stdin) throw new Error(`${label}: no stdin pipe`);\n\treturn proc.stdin;\n}\n\n/**\n * Local model runtime manager (local-model-lifecycle-design.md): Ollama first, interface kept\n * runtime-agnostic. Pi SPAWNS the serve process itself with OWNED model storage\n * (`OLLAMA_MODELS=<agentDir>/models/ollama`) so every downloaded weight lives inside pi's tree —\n * per-model disk accounting is trivial and full cleanup is one directory. If a system server is\n * already running, pi uses it instead of double-installing, with the honest tradeoff surfaced:\n * storage then lives in the system daemon's dir and removal control is limited to `ollama rm`.\n *\n * Hard boundaries (design \"Hard boundaries\"): lifecycle actions are USER commands only — this\n * module is never exposed as a model-invokable tool; install is GUIDE MODE (exact manual steps,\n * never `curl | sh`); removal is explicit, disclosed, and never automatic.\n */\n\nexport interface LocalRuntimeStatus {\n\tbinaryPath?: string;\n\tbinarySource?: \"system\" | \"user\" | \"pi-owned\";\n\tserverUp: boolean;\n\tserverUrl: string;\n\t/** True when the responding server is a child process pi spawned (owned storage applies). */\n\tmanagedByPi: boolean;\n\t/** Owned weights directory (only meaningful for pi-managed serves). */\n\townedModelsDir: string;\n}\n\nexport interface InstalledLocalModel {\n\tname: string;\n\tsizeBytes: number;\n}\n\n/** Pinned ollama release for the managed installer below. Bump here when needed — one constant. */\nexport const OLLAMA_PINNED_VERSION = \"0.31.1\";\n\nexport type OllamaAssetKind = \"tar-zst\" | \"tar-gz\" | \"zip\";\n\nexport interface OllamaReleaseAsset {\n\tname: string;\n\tkind: OllamaAssetKind;\n}\n\n/**\n * Maps a platform/arch pair (node's `os.platform()`/`os.arch()`) to the exact ollama release asset\n * name for {@link OLLAMA_PINNED_VERSION} — verified against the real ollama/ollama GitHub release\n * and its own install.sh, not guessed: darwin ships a CLI `.tgz` (the `.app`/`.dmg`/`Ollama-*.zip`\n * assets are the separate GUI-app installer, not what we want), linux ships `.tar.zst` per arch,\n * windows ships `.zip` per arch. Pure and exported so it's independently testable and reusable\n * (e.g. by a future doctor-driven managed install) without touching OllamaRuntime.\n */\nexport function resolveOllamaAsset(plat: string, architecture: string): OllamaReleaseAsset | undefined {\n\tif (plat === \"darwin\") {\n\t\t// Universal binary — one asset for both arm64 and x64.\n\t\treturn { name: \"ollama-darwin.tgz\", kind: \"tar-gz\" };\n\t}\n\tif (plat === \"linux\") {\n\t\tconst archName = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\treturn { name: `ollama-linux-${archName}.tar.zst`, kind: \"tar-zst\" };\n\t}\n\tif (plat === \"win32\") {\n\t\tconst archName = architecture === \"arm64\" ? \"arm64\" : \"amd64\";\n\t\treturn { name: `ollama-windows-${archName}.zip`, kind: \"zip\" };\n\t}\n\treturn undefined;\n}\n\nexport interface RuntimeCommandResult {\n\tok: boolean;\n\tstdout: string;\n\tstderr: string;\n\tcode?: number | null;\n\terror?: string;\n}\n\nexport type RuntimeCommandRunner = (\n\tcommand: string,\n\targs: string[],\n\toptions?: { env?: NodeJS.ProcessEnv; onOutput?: (chunk: string) => void },\n) => Promise<RuntimeCommandResult>;\n\nexport interface LocalRuntimeDeps {\n\tfetchFn?: typeof fetch;\n\tspawnFn?: (\n\t\tcommand: string,\n\t\targs: string[],\n\t\toptions: { env: NodeJS.ProcessEnv },\n\t) => Pick<ChildProcess, \"pid\" | \"kill\" | \"unref\" | \"on\">;\n\texistsFn?: (path: string) => boolean;\n\tenvPath?: string;\n\thomeDir?: string;\n\tsleepFn?: (ms: number) => Promise<void>;\n\t/** os.platform()/os.arch() equivalents — injectable so asset/runtime resolution is testable per platform. */\n\tplatform?: () => string;\n\tarch?: () => string;\n\t/** Runs a runtime-management command (Python venv/pip/download probe). Injectable so tests never\n\t * install packages or hit the network. */\n\trunCommand?: RuntimeCommandRunner;\n\t/** Override for bundled runtime helper scripts, used by tests and source/binary packaging checks. */\n\ttransformersServerScriptPath?: string;\n\t/** Node's built-in zstd decompress transform, when THIS runtime's node:zlib has it — undefined\n\t * forces the system-zstd fallback. Injectable so tests can force either path deterministically\n\t * instead of depending on whatever Node happens to be running the test. */\n\tcreateZstdDecompress?: () => NodeJS.ReadWriteStream;\n\t/** Whether a named command exists on PATH (e.g. system `zstd`), for the extraction fallback. */\n\thasCommand?: (command: string) => boolean;\n\t/** Runs the extraction step for a downloaded archive. Injectable so installManaged's\n\t * download->extract->verify orchestration is testable without a real tar/zstd/unzip pipeline;\n\t * defaults to the real spawn-based extractor. */\n\textractArchive?: (\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: OllamaAssetKind,\n\t) => Promise<{ ok: boolean; error?: string }>;\n}\n\nconst DEFAULT_BASE_URL = \"http://127.0.0.1:11434\";\nconst HEALTH_TIMEOUT_MS = 2_000;\nconst START_POLL_ATTEMPTS = 20;\nconst START_POLL_INTERVAL_MS = 500;\nconst TRANSFORMERS_PORT_BASE = 18_100;\nconst TRANSFORMERS_PORT_SPAN = 1_000;\nconst TRANSFORMERS_START_POLL_ATTEMPTS = 240;\nconst TRANSFORMERS_RUNTIME_DIR_NAME = \"hf-transformers\";\nconst TRANSFORMERS_VENV_DIR_NAME = \"venv\";\nconst TRANSFORMERS_SERVER_RELATIVE_PATH = join(\"runtimes\", \"hf-transformers-openai-server.py\");\nconst TRANSFORMERS_PINNED_PACKAGES = [\"transformers==5.13.0\", \"huggingface-hub==1.22.0\", \"safetensors==0.8.0\"];\nconst TORCH_PINNED_VERSION = \"2.12.1\";\n\nasync function runCommandDefault(\n\tcommand: string,\n\targs: string[],\n\toptions: { env?: NodeJS.ProcessEnv; onOutput?: (chunk: string) => void } = {},\n): Promise<RuntimeCommandResult> {\n\ttry {\n\t\tconst proc = spawnProcess(command, args, {\n\t\t\tstdio: [\"ignore\", \"pipe\", \"pipe\"],\n\t\t\tenv: options.env ? { ...process.env, ...options.env } : process.env,\n\t\t});\n\t\tlet stdout = \"\";\n\t\tlet stderr = \"\";\n\t\tproc.stdout.setEncoding(\"utf8\");\n\t\tproc.stderr.setEncoding(\"utf8\");\n\t\tproc.stdout.on(\"data\", (chunk: string) => {\n\t\t\tstdout += chunk;\n\t\t\toptions.onOutput?.(chunk);\n\t\t});\n\t\tproc.stderr.on(\"data\", (chunk: string) => {\n\t\t\tstderr += chunk;\n\t\t\toptions.onOutput?.(chunk);\n\t\t});\n\t\tconst code = await waitForChildProcess(proc);\n\t\treturn {\n\t\t\tok: code === 0,\n\t\t\tstdout,\n\t\t\tstderr,\n\t\t\tcode,\n\t\t\t...(code === 0 ? {} : { error: stderr.trim() || stdout.trim() || `exit code ${code ?? \"unknown\"}` }),\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tstdout: \"\",\n\t\t\tstderr: \"\",\n\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t};\n\t}\n}\n\nfunction sanitizeCommandOutput(value: string | undefined): string {\n\treturn value?.trim().split(\"\\n\").slice(-3).join(\"\\n\") || \"unknown error\";\n}\n\nfunction hashString(value: string): number {\n\tlet hash = 2_166_136_261;\n\tfor (let index = 0; index < value.length; index++) {\n\t\thash ^= value.charCodeAt(index);\n\t\thash = Math.imul(hash, 16_777_619) >>> 0;\n\t}\n\treturn hash;\n}\n\nexport function resolveTransformersBaseUrl(modelId: string): string {\n\tconst port = TRANSFORMERS_PORT_BASE + (hashString(modelId) % TRANSFORMERS_PORT_SPAN);\n\treturn `http://127.0.0.1:${port}`;\n}\n\nexport class OllamaRuntime {\n\tprivate readonly _agentDir: string;\n\tprivate readonly _baseUrl: string;\n\tprivate readonly _fetch: typeof fetch;\n\tprivate readonly _spawn: NonNullable<LocalRuntimeDeps[\"spawnFn\"]>;\n\tprivate readonly _exists: (path: string) => boolean;\n\tprivate readonly _envPath: string;\n\tprivate readonly _homeDir: string;\n\tprivate readonly _sleep: (ms: number) => Promise<void>;\n\tprivate readonly _platform: () => string;\n\tprivate readonly _arch: () => string;\n\tprivate readonly _createZstdDecompress: (() => NodeJS.ReadWriteStream) | undefined;\n\tprivate readonly _hasCommand: (command: string) => boolean;\n\tprivate readonly _extractArchiveOverride: LocalRuntimeDeps[\"extractArchive\"] | undefined;\n\tprivate _child: Pick<ChildProcess, \"pid\" | \"kill\" | \"unref\" | \"on\"> | undefined;\n\n\tconstructor(args: { agentDir: string; baseUrl?: string; deps?: LocalRuntimeDeps }) {\n\t\tthis._agentDir = args.agentDir;\n\t\tthis._baseUrl = (args.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/$/, \"\");\n\t\tthis._fetch = args.deps?.fetchFn ?? fetch;\n\t\tthis._spawn = args.deps?.spawnFn ?? ((command, argv, options) => spawn(command, argv, options));\n\t\tthis._exists = args.deps?.existsFn ?? existsSync;\n\t\tthis._envPath = args.deps?.envPath ?? process.env.PATH ?? \"\";\n\t\tthis._homeDir = args.deps?.homeDir ?? homedir();\n\t\tthis._sleep = args.deps?.sleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis._platform = args.deps?.platform ?? osPlatform;\n\t\tthis._arch = args.deps?.arch ?? osArch;\n\t\t// Feature-detect (not version-sniff): recent Node added zstd natively to node:zlib. Verified\n\t\t// present on this repo's minimum supported Node (>=22.19.0); still detected at runtime rather\n\t\t// than assumed, so an older/different Node correctly falls through to the system-zstd path.\n\t\t// `\"createZstdDecompress\" in deps` (rather than `??`) so a test can force the fallback path by\n\t\t// passing the key as explicitly undefined, distinct from omitting it (real auto-detection).\n\t\tthis._createZstdDecompress =\n\t\t\targs.deps && \"createZstdDecompress\" in args.deps\n\t\t\t\t? args.deps.createZstdDecompress\n\t\t\t\t: typeof nodeZlib.createZstdDecompress === \"function\"\n\t\t\t\t\t? () => nodeZlib.createZstdDecompress()\n\t\t\t\t\t: undefined;\n\t\tthis._hasCommand =\n\t\t\targs.deps?.hasCommand ??\n\t\t\t((command) => spawnProcessSync(command, [\"--version\"], { encoding: \"utf8\" }).error === undefined);\n\t\tthis._extractArchiveOverride = args.deps?.extractArchive;\n\t}\n\n\tget baseUrl(): string {\n\t\treturn this._baseUrl;\n\t}\n\n\townedModelsDir(): string {\n\t\treturn join(this._agentDir, \"models\", \"ollama\");\n\t}\n\n\tprivate _findBinary(): { path: string; source: \"system\" | \"user\" | \"pi-owned\" } | undefined {\n\t\tconst piOwned = join(this._agentDir, \"runtimes\", \"ollama\", \"bin\", \"ollama\");\n\t\tif (this._exists(piOwned)) return { path: piOwned, source: \"pi-owned\" };\n\t\tconst userLevel = join(this._homeDir, \".local\", \"share\", \"ollama-dist\", \"bin\", \"ollama\");\n\t\tif (this._exists(userLevel)) return { path: userLevel, source: \"user\" };\n\t\tfor (const dir of this._envPath.split(delimiter)) {\n\t\t\tif (!dir) continue;\n\t\t\tconst candidate = join(dir, \"ollama\");\n\t\t\tif (this._exists(candidate)) return { path: candidate, source: \"system\" };\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate async _serverUp(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/tags`, {\n\t\t\t\tsignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),\n\t\t\t});\n\t\t\treturn response.ok;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync detect(): Promise<LocalRuntimeStatus> {\n\t\tconst binary = this._findBinary();\n\t\tconst serverUp = await this._serverUp();\n\t\treturn {\n\t\t\tbinaryPath: binary?.path,\n\t\t\tbinarySource: binary?.source,\n\t\t\tserverUp,\n\t\t\tserverUrl: this._baseUrl,\n\t\t\tmanagedByPi: this._child !== undefined && serverUp,\n\t\t\townedModelsDir: this.ownedModelsDir(),\n\t\t};\n\t}\n\n\t/**\n\t * Manual-steps fallback text — shown when the managed install below wasn't offered (headless),\n\t * was declined, or itself failed. #31 reversed the stance for ollama specifically: pi CAN install\n\t * it for you now (consent-gated, a controlled download into pi's own runtimes dir, never\n\t * `curl | sh`) — these steps are the alternative for when that path isn't taken.\n\t */\n\tinstallGuide(): string[] {\n\t\treturn [\n\t\t\t\"Ollama is not installed. Pi can install it for you now (asks first, never curl|sh) — or follow these manual steps yourself:\",\n\t\t\t\" 1. Download the pinned release archive for your platform:\",\n\t\t\t\" https://github.com/ollama/ollama/releases (asset: ollama-linux-amd64.tar.zst or your platform)\",\n\t\t\t` 2. Extract it to ${join(this._homeDir, \".local\", \"share\", \"ollama-dist\")}`,\n\t\t\t\" 3. Re-run your /models command - pi detects the binary automatically.\",\n\t\t\t\"Alternatively install system-wide from https://ollama.com/download and pi will use the system server.\",\n\t\t];\n\t}\n\n\t/** Which decompressor to use for a `.tar.zst` asset — native (this Node's own zlib) is always\n\t * preferred when available, even if a system `zstd` ALSO exists, since it needs no external\n\t * dependency at all. Verified per-runtime by feature detection (see the constructor), not by\n\t * guessing from a Node version number. */\n\tprivate _chooseZstdStrategy(): { kind: \"native\" } | { kind: \"system\" } | { kind: \"unavailable\" } {\n\t\tif (this._createZstdDecompress) return { kind: \"native\" };\n\t\tif (this._hasCommand(\"zstd\")) return { kind: \"system\" };\n\t\treturn { kind: \"unavailable\" };\n\t}\n\n\t/**\n\t * Managed install (#31): a consent-gated, controlled download of the pinned ollama release into\n\t * pi's OWN runtimes dir (`<agentDir>/runtimes/ollama/`) — never `curl | sh`, never a second\n\t * server instance, and distinct from {@link start}'s owned MODEL storage (this is the binary\n\t * itself). Callers (the router's consent flow, and later a doctor-driven install) own the\n\t * consent/UI; this method only does the mechanical download+extract+verify and reports the\n\t * outcome honestly. `onProgress` is best-effort UI feedback, not a completion signal.\n\t */\n\tasync installManaged(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst asset = resolveOllamaAsset(this._platform(), this._arch());\n\t\tif (!asset) return { ok: false, error: \"unsupported-platform\" };\n\n\t\tonProgress?.(`Downloading ${asset.name}…`);\n\t\tconst downloadUrl = `https://github.com/ollama/ollama/releases/download/v${OLLAMA_PINNED_VERSION}/${asset.name}`;\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await this._fetch(downloadUrl);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: `download-fail: ${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t\tif (!response.ok || !response.body) {\n\t\t\treturn { ok: false, error: `download-fail: HTTP ${response.status}` };\n\t\t}\n\n\t\tconst destDir = join(this._agentDir, \"runtimes\", \"ollama\");\n\t\tmkdirSync(destDir, { recursive: true });\n\n\t\tonProgress?.(`Extracting ${asset.name}…`);\n\t\tconst extract = this._extractArchiveOverride ?? ((input, dest, kind) => this._extractArchive(input, dest, kind));\n\t\tconst extracted = await extract(response.body as unknown as NodeJS.ReadableStream, destDir, asset.kind);\n\t\tif (!extracted.ok) return extracted;\n\n\t\tconst binaryName = this._platform() === \"win32\" ? \"ollama.exe\" : \"ollama\";\n\t\tconst binaryPath = join(destDir, \"bin\", binaryName);\n\t\tif (!this._exists(binaryPath)) {\n\t\t\treturn { ok: false, error: \"extract-fail: binary not found after extraction\" };\n\t\t}\n\t\tonProgress?.(\"Ollama installed.\");\n\t\treturn { ok: true };\n\t}\n\n\t/** Real extraction: `tar-gz` lets `tar` itself gunzip; `tar-zst` decompresses first (native\n\t * node:zlib preferred, system `zstd` as fallback, an honest error if neither exists — see\n\t * {@link _chooseZstdStrategy}); `zip` needs a seekable file, so it's buffered to disk first. */\n\tprivate async _extractArchive(\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: OllamaAssetKind,\n\t): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tif (kind === \"zip\") {\n\t\t\t\treturn await this._extractZip(input, destDir);\n\t\t\t}\n\t\t\treturn await this._extractTar(input, destDir, kind);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: `extract-fail: ${error instanceof Error ? error.message : String(error)}` };\n\t\t}\n\t}\n\n\tprivate async _extractTar(\n\t\tinput: NodeJS.ReadableStream,\n\t\tdestDir: string,\n\t\tkind: \"tar-gz\" | \"tar-zst\",\n\t): Promise<{ ok: boolean; error?: string }> {\n\t\tlet decompressed: Readable = input as unknown as Readable;\n\t\tconst tarArgs = [\"-xf\", \"-\", \"-C\", destDir];\n\t\tif (kind === \"tar-zst\") {\n\t\t\tconst strategy = this._chooseZstdStrategy();\n\t\t\tif (strategy.kind === \"unavailable\") {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: \"zstd-missing: this archive needs zstd to decompress and neither Node's built-in support nor a system `zstd` binary was found. Install zstd (e.g. `apt-get install zstd`, `dnf install zstd`, `pacman -S zstd`) and try again.\",\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (strategy.kind === \"native\") {\n\t\t\t\tdecompressed = decompressed.pipe(\n\t\t\t\t\tthis._createZstdDecompress?.() as unknown as NodeJS.ReadWriteStream & Readable,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tconst zstdProc = spawnProcess(\"zstd\", [\"-d\"], { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\t\t\t\tdecompressed.pipe(requireStdin(zstdProc, \"zstd\"));\n\t\t\t\tdecompressed = zstdProc.stdout as unknown as Readable;\n\t\t\t}\n\t\t} else {\n\t\t\t// tar itself handles gzip via -z — no separate decompression step needed.\n\t\t\ttarArgs[0] = \"-xzf\";\n\t\t}\n\t\tconst tarProc = spawnProcess(\"tar\", tarArgs, { stdio: [\"pipe\", \"pipe\", \"pipe\"] });\n\t\tdecompressed.pipe(requireStdin(tarProc, \"tar\"));\n\t\tconst code = await waitForChildProcess(tarProc);\n\t\tif (code !== 0) {\n\t\t\treturn { ok: false, error: `extract-fail: tar exited with code ${code}` };\n\t\t}\n\t\treturn { ok: true };\n\t}\n\n\tprivate async _extractZip(input: NodeJS.ReadableStream, destDir: string): Promise<{ ok: boolean; error?: string }> {\n\t\t// Zip's central directory needs seekable file access — buffer to a temp file first.\n\t\tconst zipPath = join(destDir, \"..\", `ollama-download-${process.pid}-${Date.now()}.zip`);\n\t\tawait pipeline(input as unknown as Readable, createWriteStream(zipPath));\n\t\ttry {\n\t\t\tconst extractCommand = this._platform() === \"win32\" && this._hasCommand(\"tar\") ? \"tar\" : \"unzip\";\n\t\t\tconst args = extractCommand === \"tar\" ? [\"-xf\", zipPath, \"-C\", destDir] : [\"-q\", zipPath, \"-d\", destDir];\n\t\t\tconst proc = spawnProcess(extractCommand, args, { stdio: [\"ignore\", \"pipe\", \"pipe\"] });\n\t\t\tconst code = await waitForChildProcess(proc);\n\t\t\tif (code !== 0) {\n\t\t\t\treturn { ok: false, error: `extract-fail: ${extractCommand} exited with code ${code}` };\n\t\t\t}\n\t\t\treturn { ok: true };\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\trmSync(zipPath, { force: true });\n\t\t\t} catch {\n\t\t\t\t// best-effort cleanup\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Shared spawn-then-health-poll for both start modes below; `extraEnv` is the only thing that\n\t * differs between them (owned storage vs reusing the user's own). */\n\tprivate async _spawnAndPoll(\n\t\tbinary: { path: string },\n\t\textraEnv: NodeJS.ProcessEnv,\n\t): Promise<{ started: boolean; reason: string }> {\n\t\tconst host = this._baseUrl.replace(/^https?:\\/\\//, \"\");\n\t\tthis._child = this._spawn(binary.path, [\"serve\"], {\n\t\t\tenv: { ...process.env, OLLAMA_HOST: host, ...extraEnv },\n\t\t});\n\t\tthis._child.unref?.();\n\t\tfor (let attempt = 0; attempt < START_POLL_ATTEMPTS; attempt++) {\n\t\t\tif (await this._serverUp()) return { started: true, reason: \"started\" };\n\t\t\tawait this._sleep(START_POLL_INTERVAL_MS);\n\t\t}\n\t\tthis.stop();\n\t\treturn { started: false, reason: \"health_check_timeout\" };\n\t}\n\n\t/**\n\t * Start a pi-managed serve with OWNED storage and the hardened env verified on this class of\n\t * hardware. No-op (reported) when a server already responds — pi never double-serves. Used by\n\t * `/models add` et al, where isolated per-model-pull storage is the point.\n\t */\n\tasync start(): Promise<{ started: boolean; reason: string }> {\n\t\tif (await this._serverUp()) {\n\t\t\treturn { started: false, reason: this._child ? \"already_running_managed\" : \"already_running_system\" };\n\t\t}\n\t\tconst binary = this._findBinary();\n\t\tif (!binary) return { started: false, reason: \"binary_missing\" };\n\t\tmkdirSync(this.ownedModelsDir(), { recursive: true });\n\t\treturn this._spawnAndPoll(binary, {\n\t\t\tOLLAMA_MODELS: this.ownedModelsDir(),\n\t\t\tOLLAMA_FLASH_ATTENTION: \"1\",\n\t\t\tOLLAMA_KV_CACHE_TYPE: \"q8_0\",\n\t\t\tOLLAMA_NUM_PARALLEL: \"1\",\n\t\t\tOLLAMA_MAX_LOADED_MODELS: \"3\",\n\t\t});\n\t}\n\n\t/**\n\t * Start a serve that REUSES the user's own existing models directory (no `OLLAMA_MODELS`\n\t * override — falls through to Ollama's own default, `~/.ollama`), for callers that must see the\n\t * user's already-pulled models rather than pi's isolated/owned storage. Same idempotency and\n\t * hardened perf env as {@link start}; the only difference is which storage the server sees.\n\t */\n\tasync startReuseExisting(): Promise<{ started: boolean; reason: string }> {\n\t\tif (await this._serverUp()) {\n\t\t\treturn { started: false, reason: this._child ? \"already_running_managed\" : \"already_running_system\" };\n\t\t}\n\t\tconst binary = this._findBinary();\n\t\tif (!binary) return { started: false, reason: \"binary_missing\" };\n\t\treturn this._spawnAndPoll(binary, {\n\t\t\tOLLAMA_FLASH_ATTENTION: \"1\",\n\t\t\tOLLAMA_KV_CACHE_TYPE: \"q8_0\",\n\t\t\tOLLAMA_NUM_PARALLEL: \"1\",\n\t\t\tOLLAMA_MAX_LOADED_MODELS: \"3\",\n\t\t});\n\t}\n\n\t/** Resource hygiene only: stops the pi-managed serve process; never deletes anything. */\n\tstop(): { stopped: boolean } {\n\t\tif (!this._child) return { stopped: false };\n\t\ttry {\n\t\t\tthis._child.kill(\"SIGTERM\");\n\t\t} catch {\n\t\t\t// already gone\n\t\t}\n\t\tthis._child = undefined;\n\t\treturn { stopped: true };\n\t}\n\n\tasync list(): Promise<InstalledLocalModel[]> {\n\t\tconst response = await this._fetch(`${this._baseUrl}/api/tags`, { signal: AbortSignal.timeout(10_000) });\n\t\tif (!response.ok) throw new Error(`ollama list failed: HTTP ${response.status}`);\n\t\tconst data = (await response.json()) as { models?: Array<{ name?: string; size?: number }> };\n\t\treturn (data.models ?? [])\n\t\t\t.filter((model): model is { name: string; size?: number } => typeof model.name === \"string\")\n\t\t\t.map((model) => ({ name: model.name, sizeBytes: model.size ?? 0 }));\n\t}\n\n\t/** Pull a model through the server API (weights land in the SERVER's models dir). */\n\tasync pull(ref: string, onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/pull`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref, stream: true }),\n\t\t\t});\n\t\t\tif (!response.ok || !response.body) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `pull failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst reader = response.body.getReader();\n\t\t\tconst decoder = new TextDecoder();\n\t\t\tlet buffer = \"\";\n\t\t\tlet lastStatus = \"\";\n\t\t\tlet errorMessage: string | undefined;\n\t\t\tconst handleLine = (line: string): void => {\n\t\t\t\tif (!line.trim()) return;\n\t\t\t\ttry {\n\t\t\t\t\tconst event = JSON.parse(line) as { status?: string; error?: string };\n\t\t\t\t\tif (event.error) errorMessage = event.error;\n\t\t\t\t\tif (event.status && event.status !== lastStatus) {\n\t\t\t\t\t\tlastStatus = event.status;\n\t\t\t\t\t\tonProgress?.(event.status);\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\t// partial line noise\n\t\t\t\t}\n\t\t\t};\n\t\t\tfor (;;) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) break;\n\t\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t\t\tconst lines = buffer.split(\"\\n\");\n\t\t\t\tbuffer = lines.pop() ?? \"\";\n\t\t\t\tfor (const line of lines) handleLine(line);\n\t\t\t}\n\t\t\t// The stream's FINAL line has no trailing newline — it stays in the buffer and holds\n\t\t\t// the terminal \"success\"/error event; dropping it misreports every completed pull.\n\t\t\thandleLine(buffer);\n\t\t\tif (errorMessage) return { ok: false, error: errorMessage };\n\t\t\treturn lastStatus === \"success\"\n\t\t\t\t? { ok: true }\n\t\t\t\t: { ok: false, error: `pull ended with: ${lastStatus || \"unknown\"}` };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n\n\t/** EXPLICIT user action only — callers must have shown what gets deleted and confirmed. */\n\tasync remove(ref: string): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/delete`, {\n\t\t\t\tmethod: \"DELETE\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref }),\n\t\t\t});\n\t\t\tif (!response.ok) {\n\t\t\t\treturn {\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: `delete failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn { ok: true };\n\t\t} catch (error) {\n\t\t\treturn { ok: false, error: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t}\n}\n\nexport interface TransformersRuntimeStatus {\n\truntimeInstalled: boolean;\n\tserverUp: boolean;\n\tbaseUrl: string;\n\tmodelId: string;\n\tvenvDir: string;\n\tcacheDir: string;\n\tserverScriptPath: string;\n}\n\nexport class TransformersRuntime {\n\tprivate readonly _agentDir: string;\n\tprivate readonly _modelId: string;\n\tprivate readonly _baseUrl: string;\n\tprivate readonly _fetch: typeof fetch;\n\tprivate readonly _spawn: NonNullable<LocalRuntimeDeps[\"spawnFn\"]>;\n\tprivate readonly _exists: (path: string) => boolean;\n\tprivate readonly _sleep: (ms: number) => Promise<void>;\n\tprivate readonly _platform: () => string;\n\tprivate readonly _runCommand: RuntimeCommandRunner;\n\tprivate readonly _serverScriptPath: string;\n\tprivate _proc?: Pick<ChildProcess, \"pid\" | \"kill\" | \"unref\" | \"on\">;\n\n\tconstructor(args: { agentDir: string; modelId: string; baseUrl?: string; deps?: LocalRuntimeDeps }) {\n\t\tthis._agentDir = args.agentDir;\n\t\tthis._modelId = args.modelId;\n\t\tthis._baseUrl = args.baseUrl?.replace(/\\/$/, \"\") ?? resolveTransformersBaseUrl(args.modelId);\n\t\tthis._fetch = args.deps?.fetchFn ?? fetch;\n\t\tthis._spawn = args.deps?.spawnFn ?? ((command, argv, options) => spawn(command, argv, { env: options.env }));\n\t\tthis._exists = args.deps?.existsFn ?? existsSync;\n\t\tthis._sleep = args.deps?.sleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));\n\t\tthis._platform = args.deps?.platform ?? osPlatform;\n\t\tthis._runCommand = args.deps?.runCommand ?? runCommandDefault;\n\t\tthis._serverScriptPath =\n\t\t\targs.deps?.transformersServerScriptPath ?? join(getBundledResourcesDir(), TRANSFORMERS_SERVER_RELATIVE_PATH);\n\t}\n\n\tget baseUrl(): string {\n\t\treturn this._baseUrl;\n\t}\n\n\tget modelId(): string {\n\t\treturn this._modelId;\n\t}\n\n\tget runtimeDir(): string {\n\t\treturn join(this._agentDir, \"runtimes\", TRANSFORMERS_RUNTIME_DIR_NAME);\n\t}\n\n\tget venvDir(): string {\n\t\treturn join(this.runtimeDir, TRANSFORMERS_VENV_DIR_NAME);\n\t}\n\n\tget cacheDir(): string {\n\t\treturn join(this._agentDir, \"models\", \"huggingface\");\n\t}\n\n\tget pythonPath(): string {\n\t\treturn this._platform() === \"win32\"\n\t\t\t? join(this.venvDir, \"Scripts\", \"python.exe\")\n\t\t\t: join(this.venvDir, \"bin\", \"python\");\n\t}\n\n\tprivate get serverPort(): string {\n\t\tconst parsed = new URL(this._baseUrl);\n\t\treturn parsed.port || (parsed.protocol === \"https:\" ? \"443\" : \"80\");\n\t}\n\n\tprivate get serverHost(): string {\n\t\treturn new URL(this._baseUrl).hostname;\n\t}\n\n\tprivate runtimeEnv(): NodeJS.ProcessEnv {\n\t\tconst venvBin = this._platform() === \"win32\" ? join(this.venvDir, \"Scripts\") : join(this.venvDir, \"bin\");\n\t\treturn {\n\t\t\t...process.env,\n\t\t\tVIRTUAL_ENV: this.venvDir,\n\t\t\tPATH: `${venvBin}${delimiter}${process.env.PATH ?? \"\"}`,\n\t\t\tPYTHONNOUSERSITE: \"1\",\n\t\t\tHF_HOME: this.cacheDir,\n\t\t\tHUGGINGFACE_HUB_CACHE: join(this.cacheDir, \"hub\"),\n\t\t\tTRANSFORMERS_CACHE: join(this.cacheDir, \"transformers\"),\n\t\t\tHF_HUB_DISABLE_TELEMETRY: \"1\",\n\t\t};\n\t}\n\n\tprivate async serverUp(): Promise<boolean> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/health`, {\n\t\t\t\tsignal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),\n\t\t\t});\n\t\t\tif (!response.ok) return false;\n\t\t\tconst body = (await response.json().catch(() => undefined)) as { model?: unknown } | undefined;\n\t\t\treturn body?.model === this._modelId;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync detect(): Promise<TransformersRuntimeStatus> {\n\t\treturn {\n\t\t\truntimeInstalled: this._exists(this.pythonPath),\n\t\t\tserverUp: await this.serverUp(),\n\t\t\tbaseUrl: this._baseUrl,\n\t\t\tmodelId: this._modelId,\n\t\t\tvenvDir: this.venvDir,\n\t\t\tcacheDir: this.cacheDir,\n\t\t\tserverScriptPath: this._serverScriptPath,\n\t\t};\n\t}\n\n\tprivate pythonCandidates(): Array<{ command: string; args: string[] }> {\n\t\treturn this._platform() === \"win32\"\n\t\t\t? [\n\t\t\t\t\t{ command: \"py\", args: [\"-3\"] },\n\t\t\t\t\t{ command: \"python\", args: [] },\n\t\t\t\t]\n\t\t\t: [\n\t\t\t\t\t{ command: \"python3\", args: [] },\n\t\t\t\t\t{ command: \"python\", args: [] },\n\t\t\t\t];\n\t}\n\n\tprivate async findPython(): Promise<{ command: string; args: string[] } | undefined> {\n\t\tfor (const candidate of this.pythonCandidates()) {\n\t\t\tconst result = await this._runCommand(candidate.command, [...candidate.args, \"--version\"]);\n\t\t\tif (result.ok) return candidate;\n\t\t}\n\t\treturn undefined;\n\t}\n\n\tprivate torchInstallArgs(): string[] {\n\t\tif (this._platform() === \"darwin\") {\n\t\t\treturn [\"-m\", \"pip\", \"install\", `torch==${TORCH_PINNED_VERSION}`];\n\t\t}\n\t\treturn [\n\t\t\t\"-m\",\n\t\t\t\"pip\",\n\t\t\t\"install\",\n\t\t\t`torch==${TORCH_PINNED_VERSION}+cpu`,\n\t\t\t\"--index-url\",\n\t\t\t\"https://download.pytorch.org/whl/cpu\",\n\t\t];\n\t}\n\n\tprivate async runPython(args: string[], onProgress?: (status: string) => void): Promise<RuntimeCommandResult> {\n\t\treturn this._runCommand(this.pythonPath, args, {\n\t\t\tenv: this.runtimeEnv(),\n\t\t\tonOutput: onProgress\n\t\t\t\t? (chunk) => {\n\t\t\t\t\t\tconst line = chunk.trim();\n\t\t\t\t\t\tif (line) onProgress(line);\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t});\n\t}\n\n\tasync installManaged(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tmkdirSync(this.runtimeDir, { recursive: true });\n\t\tmkdirSync(this.cacheDir, { recursive: true });\n\t\tif (!this._exists(this.pythonPath)) {\n\t\t\tconst python = await this.findPython();\n\t\t\tif (!python) return { ok: false, error: \"python-missing\" };\n\t\t\tonProgress?.(`creating isolated Python venv at ${this.venvDir}`);\n\t\t\tconst venv = await this._runCommand(python.command, [...python.args, \"-m\", \"venv\", this.venvDir]);\n\t\t\tif (!venv.ok) return { ok: false, error: `venv-fail: ${sanitizeCommandOutput(venv.error ?? venv.stderr)}` };\n\t\t}\n\t\tif (!this._exists(this.pythonPath)) {\n\t\t\treturn { ok: false, error: `venv-fail: ${this.pythonPath} was not created` };\n\t\t}\n\n\t\tonProgress?.(\"upgrading pip inside pi-managed venv\");\n\t\tconst pip = await this.runPython([\"-m\", \"pip\", \"install\", \"--upgrade\", \"pip\"], onProgress);\n\t\tif (!pip.ok) return { ok: false, error: `pip-upgrade-fail: ${sanitizeCommandOutput(pip.error ?? pip.stderr)}` };\n\n\t\tonProgress?.(\"installing pinned Transformers runtime packages\");\n\t\tconst transformers = await this.runPython([\"-m\", \"pip\", \"install\", ...TRANSFORMERS_PINNED_PACKAGES], onProgress);\n\t\tif (!transformers.ok) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\terror: `transformers-install-fail: ${sanitizeCommandOutput(transformers.error ?? transformers.stderr)}`,\n\t\t\t};\n\t\t}\n\n\t\tonProgress?.(\"installing pinned CPU PyTorch backend\");\n\t\tconst torch = await this.runPython(this.torchInstallArgs(), onProgress);\n\t\tif (!torch.ok)\n\t\t\treturn { ok: false, error: `torch-install-fail: ${sanitizeCommandOutput(torch.error ?? torch.stderr)}` };\n\n\t\tconst verify = await this.runPython([\n\t\t\t\"-c\",\n\t\t\t\"import torch, transformers, huggingface_hub; print(transformers.__version__)\",\n\t\t]);\n\t\tif (!verify.ok)\n\t\t\treturn { ok: false, error: `verify-fail: ${sanitizeCommandOutput(verify.error ?? verify.stderr)}` };\n\t\treturn { ok: true };\n\t}\n\n\tasync downloadModel(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tif (!this._exists(this.pythonPath)) return { ok: false, error: \"runtime-missing\" };\n\t\tif (!this._exists(this._serverScriptPath))\n\t\t\treturn { ok: false, error: `server-script-missing: ${this._serverScriptPath}` };\n\t\tmkdirSync(this.cacheDir, { recursive: true });\n\t\tonProgress?.(`downloading ${this._modelId} into ${this.cacheDir}`);\n\t\tconst result = await this.runPython(\n\t\t\t[this._serverScriptPath, \"--model-id\", this._modelId, \"--cache-dir\", this.cacheDir, \"--download-only\"],\n\t\t\tonProgress,\n\t\t);\n\t\treturn result.ok\n\t\t\t? { ok: true }\n\t\t\t: { ok: false, error: `download-fail: ${sanitizeCommandOutput(result.error ?? result.stderr)}` };\n\t}\n\n\tasync start(): Promise<{ started: boolean; reason: string }> {\n\t\tif (await this.serverUp()) return { started: false, reason: \"already_running\" };\n\t\tif (!this._exists(this.pythonPath)) return { started: false, reason: \"runtime_missing\" };\n\t\tif (!this._exists(this._serverScriptPath)) return { started: false, reason: \"server_script_missing\" };\n\t\tmkdirSync(this.cacheDir, { recursive: true });\n\t\tconst env = this.runtimeEnv();\n\t\tthis._proc = this._spawn(\n\t\t\tthis.pythonPath,\n\t\t\t[\n\t\t\t\tthis._serverScriptPath,\n\t\t\t\t\"--model-id\",\n\t\t\t\tthis._modelId,\n\t\t\t\t\"--host\",\n\t\t\t\tthis.serverHost,\n\t\t\t\t\"--port\",\n\t\t\t\tthis.serverPort,\n\t\t\t\t\"--cache-dir\",\n\t\t\t\tthis.cacheDir,\n\t\t\t],\n\t\t\t{ env },\n\t\t);\n\t\tthis._proc.unref?.();\n\t\tfor (let attempt = 0; attempt < TRANSFORMERS_START_POLL_ATTEMPTS; attempt++) {\n\t\t\tif (await this.serverUp()) return { started: true, reason: \"started\" };\n\t\t\tawait this._sleep(START_POLL_INTERVAL_MS);\n\t\t}\n\t\tthis.stop();\n\t\treturn { started: false, reason: \"health_check_timeout\" };\n\t}\n\n\tstop(): { stopped: boolean } {\n\t\tif (!this._proc) return { stopped: false };\n\t\tthis._proc.kill();\n\t\tthis._proc = undefined;\n\t\treturn { stopped: true };\n\t}\n\n\tinstallGuide(): string[] {\n\t\treturn [\n\t\t\t\"Hugging Face Transformers runtime is not installed for this model.\",\n\t\t\t`Pi can install it into its own venv at ${this.venvDir} and cache weights under ${this.cacheDir}.`,\n\t\t\t\"Manual equivalent:\",\n\t\t\t` python3 -m venv ${this.venvDir}`,\n\t\t\t` ${this.pythonPath} -m pip install --upgrade pip`,\n\t\t\t` ${this.pythonPath} -m pip install ${TRANSFORMERS_PINNED_PACKAGES.join(\" \")}`,\n\t\t\t` ${this.pythonPath} ${this.torchInstallArgs().join(\" \")}`,\n\t\t];\n\t}\n}\n"]}
@@ -11,6 +11,10 @@ export type ModelSource = {
11
11
  } | {
12
12
  type: "local";
13
13
  pullRef: string;
14
+ } | {
15
+ type: "transformers";
16
+ modelId: string;
17
+ ref: string;
14
18
  } | {
15
19
  type: "rejected";
16
20
  reason: string;
@@ -1 +1 @@
1
- {"version":3,"file":"model-ref.d.ts","sourceRoot":"","sources":["../../../src/core/models/model-ref.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,WAAW,GACpB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC5B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAOxC,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAqDlE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAMtF","sourcesContent":["/**\n * Model source normalizer (local-model-lifecycle-design.md, \"one panel, three types\"):\n * everything a user can paste — an ollama tag, an hf.co GGUF ref, a full HuggingFace URL, a\n * copied `ollama pull ...` install command, or an API `provider/model` name — normalizes to ONE\n * typed source. Pure string work: pasted install commands are PARSED for their reference and\n * NEVER executed as shell; unknown forms are rejected with the reason.\n */\n\nexport type ModelSource =\n\t| { type: \"api\"; ref: string }\n\t| { type: \"local\"; pullRef: string }\n\t| { type: \"rejected\"; reason: string };\n\nconst OLLAMA_TAG = /^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9._-]+)?$/;\nconst HF_REF = /^hf\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?::([\\w.-]+))?$/i;\nconst HF_URL = /^https?:\\/\\/(?:www\\.)?huggingface\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/.*)?$/i;\nconst SHELL_METACHARS = /[;&|`$<>(){}\\\\]/;\n\nexport function normalizeModelSource(rawInput: string): ModelSource {\n\tconst input = rawInput.trim();\n\tif (input.length === 0) return { type: \"rejected\", reason: \"empty input\" };\n\tif (input.length > 500) return { type: \"rejected\", reason: \"input too long to be a model reference\" };\n\n\t// Pasted install command: extract the reference, never execute anything.\n\tconst installCommand = /^ollama\\s+(?:pull|run)\\s+(.+)$/i.exec(input);\n\tif (installCommand) {\n\t\tconst argument = installCommand[1]!.trim().split(/\\s+/)[0] ?? \"\";\n\t\tif (SHELL_METACHARS.test(argument)) {\n\t\t\treturn { type: \"rejected\", reason: \"install command argument contains shell metacharacters\" };\n\t\t}\n\t\tconst inner = normalizeModelSource(argument);\n\t\tif (inner.type === \"local\") return inner;\n\t\treturn { type: \"rejected\", reason: `could not extract a model reference from the install command` };\n\t}\n\n\tif (SHELL_METACHARS.test(input) || /\\s/.test(input)) {\n\t\treturn { type: \"rejected\", reason: \"not a recognized model reference (contains spaces or shell characters)\" };\n\t}\n\n\t// Full HuggingFace URL -> hf.co pull ref (org/repo; a :quant suffix must be given explicitly).\n\tconst hfUrl = HF_URL.exec(input);\n\tif (hfUrl) {\n\t\treturn { type: \"local\", pullRef: `hf.co/${hfUrl[1]}/${hfUrl[2]}` };\n\t}\n\n\t// hf.co/org/repo[:quant]\n\tconst hfRef = HF_REF.exec(input);\n\tif (hfRef) {\n\t\treturn { type: \"local\", pullRef: `hf.co/${hfRef[1]}/${hfRef[2]}${hfRef[3] ? `:${hfRef[3]}` : \"\"}` };\n\t}\n\n\tif (input.includes(\"://\")) {\n\t\treturn { type: \"rejected\", reason: \"only huggingface.co URLs are recognized as local model links\" };\n\t}\n\n\t// provider/model -> API-registered model (nothing to install; auth + selection only).\n\tif (input.includes(\"/\")) {\n\t\tconst [provider, ...rest] = input.split(\"/\");\n\t\tconst model = rest.join(\"/\");\n\t\tif (provider && model && !model.includes(\"/\")) {\n\t\t\treturn { type: \"api\", ref: `${provider}/${model}` };\n\t\t}\n\t\treturn { type: \"rejected\", reason: \"expected provider/model or hf.co/org/repo[:quant]\" };\n\t}\n\n\t// Bare ollama tag (\"qwen3:1.7b\", \"pi-lifter:latest\", \"llama3\").\n\tif (OLLAMA_TAG.test(input)) {\n\t\treturn { type: \"local\", pullRef: input };\n\t}\n\n\treturn { type: \"rejected\", reason: \"not a recognized model reference\" };\n}\n\n/**\n * Whether an installed-model listing entry (`installedName`, as `OllamaRuntime.list()` reports it)\n * is the same model as `ref` (a user-typed reference, or a `models.json`-registered id). Ollama\n * always reports installed models with an explicit tag — a pull with no tag is normalized to\n * `:latest` server-side — but a `ref` is frequently bare (\"llama3\"), so an exact string compare\n * alone misses that pairing. Exact match always counts; otherwise treat a bare ref against its\n * `:latest`-tagged listing as the same model, and the reverse (a `ref` explicitly pinned to\n * `:latest` against a bare listing), since the local-runtime interface is kept runtime-agnostic\n * (see local-runtime.ts's module docstring) and a future/alternate runtime could list bare names.\n * Shared by every ref-vs-installed-list comparison — see `AgentSession._warnIfManualModelChoiceIsRisky`\n * and `removeLocalModel` in interactive-mode.ts, which had the identical bug independently.\n */\nexport function matchesInstalledLocalModel(ref: string, installedName: string): boolean {\n\tif (ref === installedName) return true;\n\tconst hasTag = (value: string): boolean => value.includes(\":\");\n\tif (!hasTag(ref) && installedName === `${ref}:latest`) return true;\n\tif (!hasTag(installedName) && ref === `${installedName}:latest`) return true;\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"model-ref.d.ts","sourceRoot":"","sources":["../../../src/core/models/model-ref.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,MAAM,WAAW,GACpB;IAAE,IAAI,EAAE,KAAK,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAC5B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAClC;IAAE,IAAI,EAAE,cAAc,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GACtD;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAgBxC,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,MAAM,GAAG,WAAW,CAsDlE;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,GAAG,OAAO,CAMtF","sourcesContent":["/**\n * Model source normalizer (local-model-lifecycle-design.md, \"one panel, three types\"):\n * everything a user can paste — an ollama tag, an hf.co GGUF ref, a full HuggingFace URL, a\n * copied `ollama pull ...` install command, or an API `provider/model` name — normalizes to ONE\n * typed source. Pure string work: pasted install commands are PARSED for their reference and\n * NEVER executed as shell; unknown forms are rejected with the reason.\n */\n\nexport type ModelSource =\n\t| { type: \"api\"; ref: string }\n\t| { type: \"local\"; pullRef: string }\n\t| { type: \"transformers\"; modelId: string; ref: string }\n\t| { type: \"rejected\"; reason: string };\n\nconst OLLAMA_TAG = /^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9._-]+)?$/;\nconst HF_REF = /^hf\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?::([\\w.-]+))?$/i;\nconst HF_URL = /^https?:\\/\\/(?:www\\.)?huggingface\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/.*)?$/i;\nconst SHELL_METACHARS = /[;&|`$<>(){}\\\\]/;\nconst PI_MANAGED_TRANSFORMERS_MODEL_IDS = new Set([\"openbmb/MiniCPM5-1B\"]);\n\nfunction normalizeHuggingFaceReference(org: string, repo: string, quant?: string): ModelSource {\n\tconst modelId = `${org}/${repo}`;\n\tif (!quant && PI_MANAGED_TRANSFORMERS_MODEL_IDS.has(modelId)) {\n\t\treturn { type: \"transformers\", modelId, ref: `hf.co/${modelId}` };\n\t}\n\treturn { type: \"local\", pullRef: `hf.co/${modelId}${quant ? `:${quant}` : \"\"}` };\n}\n\nexport function normalizeModelSource(rawInput: string): ModelSource {\n\tconst input = rawInput.trim();\n\tif (input.length === 0) return { type: \"rejected\", reason: \"empty input\" };\n\tif (input.length > 500) return { type: \"rejected\", reason: \"input too long to be a model reference\" };\n\n\t// Pasted install command: extract the reference, never execute anything.\n\tconst installCommand = /^ollama\\s+(?:pull|run)\\s+(.+)$/i.exec(input);\n\tif (installCommand) {\n\t\tconst argument = installCommand[1]!.trim().split(/\\s+/)[0] ?? \"\";\n\t\tif (SHELL_METACHARS.test(argument)) {\n\t\t\treturn { type: \"rejected\", reason: \"install command argument contains shell metacharacters\" };\n\t\t}\n\t\tconst inner = normalizeModelSource(argument);\n\t\tif (inner.type === \"local\") return inner;\n\t\treturn { type: \"rejected\", reason: `could not extract a model reference from the install command` };\n\t}\n\n\tif (SHELL_METACHARS.test(input) || /\\s/.test(input)) {\n\t\treturn { type: \"rejected\", reason: \"not a recognized model reference (contains spaces or shell characters)\" };\n\t}\n\n\t// Full HuggingFace URL -> either a pi-managed Transformers model (curated full-base ids) or an\n\t// Ollama hf.co pull ref (GGUF/quant refs still belong to Ollama and keep their :quant suffix).\n\tconst hfUrl = HF_URL.exec(input);\n\tif (hfUrl) {\n\t\treturn normalizeHuggingFaceReference(hfUrl[1]!, hfUrl[2]!);\n\t}\n\n\t// hf.co/org/repo[:quant]\n\tconst hfRef = HF_REF.exec(input);\n\tif (hfRef) {\n\t\treturn normalizeHuggingFaceReference(hfRef[1]!, hfRef[2]!, hfRef[3]);\n\t}\n\n\tif (input.includes(\"://\")) {\n\t\treturn { type: \"rejected\", reason: \"only huggingface.co URLs are recognized as local model links\" };\n\t}\n\n\t// provider/model -> API-registered model (nothing to install; auth + selection only).\n\tif (input.includes(\"/\")) {\n\t\tconst [provider, ...rest] = input.split(\"/\");\n\t\tconst model = rest.join(\"/\");\n\t\tif (provider && model && !model.includes(\"/\")) {\n\t\t\treturn { type: \"api\", ref: `${provider}/${model}` };\n\t\t}\n\t\treturn { type: \"rejected\", reason: \"expected provider/model or hf.co/org/repo[:quant]\" };\n\t}\n\n\t// Bare ollama tag (\"qwen3:1.7b\", \"pi-lifter:latest\", \"llama3\").\n\tif (OLLAMA_TAG.test(input)) {\n\t\treturn { type: \"local\", pullRef: input };\n\t}\n\n\treturn { type: \"rejected\", reason: \"not a recognized model reference\" };\n}\n\n/**\n * Whether an installed-model listing entry (`installedName`, as `OllamaRuntime.list()` reports it)\n * is the same model as `ref` (a user-typed reference, or a `models.json`-registered id). Ollama\n * always reports installed models with an explicit tag — a pull with no tag is normalized to\n * `:latest` server-side — but a `ref` is frequently bare (\"llama3\"), so an exact string compare\n * alone misses that pairing. Exact match always counts; otherwise treat a bare ref against its\n * `:latest`-tagged listing as the same model, and the reverse (a `ref` explicitly pinned to\n * `:latest` against a bare listing), since the local-runtime interface is kept runtime-agnostic\n * (see local-runtime.ts's module docstring) and a future/alternate runtime could list bare names.\n * Shared by every ref-vs-installed-list comparison — see `AgentSession._warnIfManualModelChoiceIsRisky`\n * and `removeLocalModel` in interactive-mode.ts, which had the identical bug independently.\n */\nexport function matchesInstalledLocalModel(ref: string, installedName: string): boolean {\n\tif (ref === installedName) return true;\n\tconst hasTag = (value: string): boolean => value.includes(\":\");\n\tif (!hasTag(ref) && installedName === `${ref}:latest`) return true;\n\tif (!hasTag(installedName) && ref === `${installedName}:latest`) return true;\n\treturn false;\n}\n"]}
@@ -9,6 +9,14 @@ const OLLAMA_TAG = /^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9._-]+)?$/;
9
9
  const HF_REF = /^hf\.co\/([\w.-]+)\/([\w.-]+)(?::([\w.-]+))?$/i;
10
10
  const HF_URL = /^https?:\/\/(?:www\.)?huggingface\.co\/([\w.-]+)\/([\w.-]+)(?:\/.*)?$/i;
11
11
  const SHELL_METACHARS = /[;&|`$<>(){}\\]/;
12
+ const PI_MANAGED_TRANSFORMERS_MODEL_IDS = new Set(["openbmb/MiniCPM5-1B"]);
13
+ function normalizeHuggingFaceReference(org, repo, quant) {
14
+ const modelId = `${org}/${repo}`;
15
+ if (!quant && PI_MANAGED_TRANSFORMERS_MODEL_IDS.has(modelId)) {
16
+ return { type: "transformers", modelId, ref: `hf.co/${modelId}` };
17
+ }
18
+ return { type: "local", pullRef: `hf.co/${modelId}${quant ? `:${quant}` : ""}` };
19
+ }
12
20
  export function normalizeModelSource(rawInput) {
13
21
  const input = rawInput.trim();
14
22
  if (input.length === 0)
@@ -30,15 +38,16 @@ export function normalizeModelSource(rawInput) {
30
38
  if (SHELL_METACHARS.test(input) || /\s/.test(input)) {
31
39
  return { type: "rejected", reason: "not a recognized model reference (contains spaces or shell characters)" };
32
40
  }
33
- // Full HuggingFace URL -> hf.co pull ref (org/repo; a :quant suffix must be given explicitly).
41
+ // Full HuggingFace URL -> either a pi-managed Transformers model (curated full-base ids) or an
42
+ // Ollama hf.co pull ref (GGUF/quant refs still belong to Ollama and keep their :quant suffix).
34
43
  const hfUrl = HF_URL.exec(input);
35
44
  if (hfUrl) {
36
- return { type: "local", pullRef: `hf.co/${hfUrl[1]}/${hfUrl[2]}` };
45
+ return normalizeHuggingFaceReference(hfUrl[1], hfUrl[2]);
37
46
  }
38
47
  // hf.co/org/repo[:quant]
39
48
  const hfRef = HF_REF.exec(input);
40
49
  if (hfRef) {
41
- return { type: "local", pullRef: `hf.co/${hfRef[1]}/${hfRef[2]}${hfRef[3] ? `:${hfRef[3]}` : ""}` };
50
+ return normalizeHuggingFaceReference(hfRef[1], hfRef[2], hfRef[3]);
42
51
  }
43
52
  if (input.includes("://")) {
44
53
  return { type: "rejected", reason: "only huggingface.co URLs are recognized as local model links" };
@@ -1 +1 @@
1
- {"version":3,"file":"model-ref.js","sourceRoot":"","sources":["../../../src/core/models/model-ref.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH,MAAM,UAAU,GAAG,6CAA6C,CAA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AO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,mDAAmD,EAAE,CAAC;IAC1F,CAAC;IAED,gEAAgE;IAChE,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC;AAAA,CACxE;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAW,EAAE,aAAqB,EAAW;IACvF,IAAI,GAAG,KAAK,aAAa;QAAE,OAAO,IAAI,CAAC;IACvC,MAAM,MAAM,GAAG,CAAC,KAAa,EAAW,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,aAAa,KAAK,GAAG,GAAG,SAAS;QAAE,OAAO,IAAI,CAAC;IACnE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,GAAG,KAAK,GAAG,aAAa,SAAS;QAAE,OAAO,IAAI,CAAC;IAC7E,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * Model source normalizer (local-model-lifecycle-design.md, \"one panel, three types\"):\n * everything a user can paste — an ollama tag, an hf.co GGUF ref, a full HuggingFace URL, a\n * copied `ollama pull ...` install command, or an API `provider/model` name — normalizes to ONE\n * typed source. Pure string work: pasted install commands are PARSED for their reference and\n * NEVER executed as shell; unknown forms are rejected with the reason.\n */\n\nexport type ModelSource =\n\t| { type: \"api\"; ref: string }\n\t| { type: \"local\"; pullRef: string }\n\t| { type: \"rejected\"; reason: string };\n\nconst OLLAMA_TAG = /^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9._-]+)?$/;\nconst HF_REF = /^hf\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?::([\\w.-]+))?$/i;\nconst HF_URL = /^https?:\\/\\/(?:www\\.)?huggingface\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/.*)?$/i;\nconst SHELL_METACHARS = /[;&|`$<>(){}\\\\]/;\n\nexport function normalizeModelSource(rawInput: string): ModelSource {\n\tconst input = rawInput.trim();\n\tif (input.length === 0) return { type: \"rejected\", reason: \"empty input\" };\n\tif (input.length > 500) return { type: \"rejected\", reason: \"input too long to be a model reference\" };\n\n\t// Pasted install command: extract the reference, never execute anything.\n\tconst installCommand = /^ollama\\s+(?:pull|run)\\s+(.+)$/i.exec(input);\n\tif (installCommand) {\n\t\tconst argument = installCommand[1]!.trim().split(/\\s+/)[0] ?? \"\";\n\t\tif (SHELL_METACHARS.test(argument)) {\n\t\t\treturn { type: \"rejected\", reason: \"install command argument contains shell metacharacters\" };\n\t\t}\n\t\tconst inner = normalizeModelSource(argument);\n\t\tif (inner.type === \"local\") return inner;\n\t\treturn { type: \"rejected\", reason: `could not extract a model reference from the install command` };\n\t}\n\n\tif (SHELL_METACHARS.test(input) || /\\s/.test(input)) {\n\t\treturn { type: \"rejected\", reason: \"not a recognized model reference (contains spaces or shell characters)\" };\n\t}\n\n\t// Full HuggingFace URL -> hf.co pull ref (org/repo; a :quant suffix must be given explicitly).\n\tconst hfUrl = HF_URL.exec(input);\n\tif (hfUrl) {\n\t\treturn { type: \"local\", pullRef: `hf.co/${hfUrl[1]}/${hfUrl[2]}` };\n\t}\n\n\t// hf.co/org/repo[:quant]\n\tconst hfRef = HF_REF.exec(input);\n\tif (hfRef) {\n\t\treturn { type: \"local\", pullRef: `hf.co/${hfRef[1]}/${hfRef[2]}${hfRef[3] ? `:${hfRef[3]}` : \"\"}` };\n\t}\n\n\tif (input.includes(\"://\")) {\n\t\treturn { type: \"rejected\", reason: \"only huggingface.co URLs are recognized as local model links\" };\n\t}\n\n\t// provider/model -> API-registered model (nothing to install; auth + selection only).\n\tif (input.includes(\"/\")) {\n\t\tconst [provider, ...rest] = input.split(\"/\");\n\t\tconst model = rest.join(\"/\");\n\t\tif (provider && model && !model.includes(\"/\")) {\n\t\t\treturn { type: \"api\", ref: `${provider}/${model}` };\n\t\t}\n\t\treturn { type: \"rejected\", reason: \"expected provider/model or hf.co/org/repo[:quant]\" };\n\t}\n\n\t// Bare ollama tag (\"qwen3:1.7b\", \"pi-lifter:latest\", \"llama3\").\n\tif (OLLAMA_TAG.test(input)) {\n\t\treturn { type: \"local\", pullRef: input };\n\t}\n\n\treturn { type: \"rejected\", reason: \"not a recognized model reference\" };\n}\n\n/**\n * Whether an installed-model listing entry (`installedName`, as `OllamaRuntime.list()` reports it)\n * is the same model as `ref` (a user-typed reference, or a `models.json`-registered id). Ollama\n * always reports installed models with an explicit tag — a pull with no tag is normalized to\n * `:latest` server-side — but a `ref` is frequently bare (\"llama3\"), so an exact string compare\n * alone misses that pairing. Exact match always counts; otherwise treat a bare ref against its\n * `:latest`-tagged listing as the same model, and the reverse (a `ref` explicitly pinned to\n * `:latest` against a bare listing), since the local-runtime interface is kept runtime-agnostic\n * (see local-runtime.ts's module docstring) and a future/alternate runtime could list bare names.\n * Shared by every ref-vs-installed-list comparison — see `AgentSession._warnIfManualModelChoiceIsRisky`\n * and `removeLocalModel` in interactive-mode.ts, which had the identical bug independently.\n */\nexport function matchesInstalledLocalModel(ref: string, installedName: string): boolean {\n\tif (ref === installedName) return true;\n\tconst hasTag = (value: string): boolean => value.includes(\":\");\n\tif (!hasTag(ref) && installedName === `${ref}:latest`) return true;\n\tif (!hasTag(installedName) && ref === `${installedName}:latest`) return true;\n\treturn false;\n}\n"]}
1
+ {"version":3,"file":"model-ref.js","sourceRoot":"","sources":["../../../src/core/models/model-ref.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAQH,MAAM,UAAU,GAAG,6CAA6C,CAAC;AACjE,MAAM,MAAM,GAAG,gDAAgD,CAAC;AAChE,MAAM,MAAM,GAAG,wEAAwE,CAAC;AACxF,MAAM,eAAe,GAAG,iB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C,KAAK,CAAC,GAAG,CAAC,CAAC;QAC7C,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC7B,IAAI,QAAQ,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YAC/C,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,QAAQ,IAAI,KAAK,EAAE,EAAE,CAAC;QACrD,CAAC;QACD,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,mDAAmD,EAAE,CAAC;IAC1F,CAAC;IAED,gEAAgE;IAChE,IAAI,UAAU,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;IAC1C,CAAC;IAED,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,kCAAkC,EAAE,CAAC;AAAA,CACxE;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,0BAA0B,CAAC,GAAW,EAAE,aAAqB,EAAW;IACvF,IAAI,GAAG,KAAK,aAAa;QAAE,OAAO,IAAI,CAAC;IACvC,MAAM,MAAM,GAAG,CAAC,KAAa,EAAW,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IAC/D,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,aAAa,KAAK,GAAG,GAAG,SAAS;QAAE,OAAO,IAAI,CAAC;IACnE,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,IAAI,GAAG,KAAK,GAAG,aAAa,SAAS;QAAE,OAAO,IAAI,CAAC;IAC7E,OAAO,KAAK,CAAC;AAAA,CACb","sourcesContent":["/**\n * Model source normalizer (local-model-lifecycle-design.md, \"one panel, three types\"):\n * everything a user can paste — an ollama tag, an hf.co GGUF ref, a full HuggingFace URL, a\n * copied `ollama pull ...` install command, or an API `provider/model` name — normalizes to ONE\n * typed source. Pure string work: pasted install commands are PARSED for their reference and\n * NEVER executed as shell; unknown forms are rejected with the reason.\n */\n\nexport type ModelSource =\n\t| { type: \"api\"; ref: string }\n\t| { type: \"local\"; pullRef: string }\n\t| { type: \"transformers\"; modelId: string; ref: string }\n\t| { type: \"rejected\"; reason: string };\n\nconst OLLAMA_TAG = /^[a-z0-9][a-z0-9._-]*(?::[A-Za-z0-9._-]+)?$/;\nconst HF_REF = /^hf\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?::([\\w.-]+))?$/i;\nconst HF_URL = /^https?:\\/\\/(?:www\\.)?huggingface\\.co\\/([\\w.-]+)\\/([\\w.-]+)(?:\\/.*)?$/i;\nconst SHELL_METACHARS = /[;&|`$<>(){}\\\\]/;\nconst PI_MANAGED_TRANSFORMERS_MODEL_IDS = new Set([\"openbmb/MiniCPM5-1B\"]);\n\nfunction normalizeHuggingFaceReference(org: string, repo: string, quant?: string): ModelSource {\n\tconst modelId = `${org}/${repo}`;\n\tif (!quant && PI_MANAGED_TRANSFORMERS_MODEL_IDS.has(modelId)) {\n\t\treturn { type: \"transformers\", modelId, ref: `hf.co/${modelId}` };\n\t}\n\treturn { type: \"local\", pullRef: `hf.co/${modelId}${quant ? `:${quant}` : \"\"}` };\n}\n\nexport function normalizeModelSource(rawInput: string): ModelSource {\n\tconst input = rawInput.trim();\n\tif (input.length === 0) return { type: \"rejected\", reason: \"empty input\" };\n\tif (input.length > 500) return { type: \"rejected\", reason: \"input too long to be a model reference\" };\n\n\t// Pasted install command: extract the reference, never execute anything.\n\tconst installCommand = /^ollama\\s+(?:pull|run)\\s+(.+)$/i.exec(input);\n\tif (installCommand) {\n\t\tconst argument = installCommand[1]!.trim().split(/\\s+/)[0] ?? \"\";\n\t\tif (SHELL_METACHARS.test(argument)) {\n\t\t\treturn { type: \"rejected\", reason: \"install command argument contains shell metacharacters\" };\n\t\t}\n\t\tconst inner = normalizeModelSource(argument);\n\t\tif (inner.type === \"local\") return inner;\n\t\treturn { type: \"rejected\", reason: `could not extract a model reference from the install command` };\n\t}\n\n\tif (SHELL_METACHARS.test(input) || /\\s/.test(input)) {\n\t\treturn { type: \"rejected\", reason: \"not a recognized model reference (contains spaces or shell characters)\" };\n\t}\n\n\t// Full HuggingFace URL -> either a pi-managed Transformers model (curated full-base ids) or an\n\t// Ollama hf.co pull ref (GGUF/quant refs still belong to Ollama and keep their :quant suffix).\n\tconst hfUrl = HF_URL.exec(input);\n\tif (hfUrl) {\n\t\treturn normalizeHuggingFaceReference(hfUrl[1]!, hfUrl[2]!);\n\t}\n\n\t// hf.co/org/repo[:quant]\n\tconst hfRef = HF_REF.exec(input);\n\tif (hfRef) {\n\t\treturn normalizeHuggingFaceReference(hfRef[1]!, hfRef[2]!, hfRef[3]);\n\t}\n\n\tif (input.includes(\"://\")) {\n\t\treturn { type: \"rejected\", reason: \"only huggingface.co URLs are recognized as local model links\" };\n\t}\n\n\t// provider/model -> API-registered model (nothing to install; auth + selection only).\n\tif (input.includes(\"/\")) {\n\t\tconst [provider, ...rest] = input.split(\"/\");\n\t\tconst model = rest.join(\"/\");\n\t\tif (provider && model && !model.includes(\"/\")) {\n\t\t\treturn { type: \"api\", ref: `${provider}/${model}` };\n\t\t}\n\t\treturn { type: \"rejected\", reason: \"expected provider/model or hf.co/org/repo[:quant]\" };\n\t}\n\n\t// Bare ollama tag (\"qwen3:1.7b\", \"pi-lifter:latest\", \"llama3\").\n\tif (OLLAMA_TAG.test(input)) {\n\t\treturn { type: \"local\", pullRef: input };\n\t}\n\n\treturn { type: \"rejected\", reason: \"not a recognized model reference\" };\n}\n\n/**\n * Whether an installed-model listing entry (`installedName`, as `OllamaRuntime.list()` reports it)\n * is the same model as `ref` (a user-typed reference, or a `models.json`-registered id). Ollama\n * always reports installed models with an explicit tag — a pull with no tag is normalized to\n * `:latest` server-side — but a `ref` is frequently bare (\"llama3\"), so an exact string compare\n * alone misses that pairing. Exact match always counts; otherwise treat a bare ref against its\n * `:latest`-tagged listing as the same model, and the reverse (a `ref` explicitly pinned to\n * `:latest` against a bare listing), since the local-runtime interface is kept runtime-agnostic\n * (see local-runtime.ts's module docstring) and a future/alternate runtime could list bare names.\n * Shared by every ref-vs-installed-list comparison — see `AgentSession._warnIfManualModelChoiceIsRisky`\n * and `removeLocalModel` in interactive-mode.ts, which had the identical bug independently.\n */\nexport function matchesInstalledLocalModel(ref: string, installedName: string): boolean {\n\tif (ref === installedName) return true;\n\tconst hasTag = (value: string): boolean => value.includes(\":\");\n\tif (!hasTag(ref) && installedName === `${ref}:latest`) return true;\n\tif (!hasTag(installedName) && ref === `${installedName}:latest`) return true;\n\treturn false;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"tool-repair-health.d.ts","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAyB,MAAM,8BAA8B,CAAC;AAahG,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,oBAAoB,EAAE,GAAG,GAAE,IAAiB,GAAG,MAAM,CAoDxG","sourcesContent":["import chalk from \"chalk\";\nimport type { ModelAdaptationStore, StoredModelAdaptation } from \"./models/adaptation-store.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nexport function formatToolRepairHealthReport(store: ModelAdaptationStore, now: Date = new Date()): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) return \"Tool repair health: no model adaptation records for this host.\";\n\n\tconst lines = [chalk.bold(\"Tool repair health\")];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"tool-repair-health.d.ts","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAyB,MAAM,8BAA8B,CAAC;AAahG,wBAAgB,4BAA4B,CAAC,KAAK,EAAE,oBAAoB,EAAE,GAAG,GAAE,IAAiB,GAAG,MAAM,CAqDxG","sourcesContent":["import chalk from \"chalk\";\nimport type { ModelAdaptationStore, StoredModelAdaptation } from \"./models/adaptation-store.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nexport function formatToolRepairHealthReport(store: ModelAdaptationStore, now: Date = new Date()): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) return \"Tool repair health: no model adaptation records for this host.\";\n\n\tconst lines = [chalk.bold(\"Tool repair health\")];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tconst nativeGrade = toolProbe.nativeGrade ? ` native=${toolProbe.nativeGrade}` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant}${nativeGrade} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -22,7 +22,8 @@ export function formatToolRepairHealthReport(store, now = new Date()) {
22
22
  }
23
23
  else {
24
24
  const variant = toolProbe.variant ? ` (${toolProbe.variant})` : "";
25
- lines.push(` tool probe: v${toolProbe.version} ${toolProbe.status}${variant} ${formatAgeDays(toolProbe.probedAt, now)}`);
25
+ const nativeGrade = toolProbe.nativeGrade ? ` native=${toolProbe.nativeGrade}` : "";
26
+ lines.push(` tool probe: v${toolProbe.version} ${toolProbe.status}${variant}${nativeGrade} ${formatAgeDays(toolProbe.probedAt, now)}`);
26
27
  if (toolProbe.diagnostic)
27
28
  lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);
28
29
  }
@@ -1 +1 @@
1
- {"version":3,"file":"tool-repair-health.js","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,SAAS,aAAa,CAAC,GAAW,EAAE,GAAS,EAAU;IACtD,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,aAAa,CAAC;IAC/C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;IACnF,OAAO,GAAG,IAAI,OAAO,CAAC;AAAA,CACtB;AAED,SAAS,YAAY,CAAC,QAAiC,EAA2B;IACjF,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;AAAA,CAClF;AAED,MAAM,UAAU,4BAA4B,CAAC,KAA2B,EAAE,GAAG,GAAS,IAAI,IAAI,EAAE,EAAU;IACzG,MAAM,QAAQ,GAAG,YAAY,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC;IAClD,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,gEAAgE,CAAC;IAEnG,MAAM,KAAK,GAA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B,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,YAAY,EAAE,CAAC;gBAC1C,KAAK,CAAC,IAAI,CACT,SAAS,IAAI,YAAY,KAAK,CAAC,MAAM,WAAW,KAAK,CAAC,gBAAgB,UAAU,KAAK,CAAC,eAAe,EAAE,CACvG,CAAC;YACH,CAAC;QACF,CAAC;IACF,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["import chalk from \"chalk\";\nimport type { ModelAdaptationStore, StoredModelAdaptation } from \"./models/adaptation-store.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nexport function formatToolRepairHealthReport(store: ModelAdaptationStore, now: Date = new Date()): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) return \"Tool repair health: no model adaptation records for this host.\";\n\n\tconst lines = [chalk.bold(\"Tool repair health\")];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"tool-repair-health.js","sourceRoot":"","sources":["../../src/core/tool-repair-health.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B,SAAS,aAAa,CAAC,GAAW,EAAE,GAAS,EAAU;IACtD,MAAM,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC;QAAE,OAAO,aAAa,CAAC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store.ts\";\n\nfunction formatAgeDays(iso: string, now: Date): string {\n\tconst ms = Date.parse(iso);\n\tif (!Number.isFinite(ms)) return \"age unknown\";\n\tconst days = Math.max(0, Math.floor((now.getTime() - ms) / (24 * 60 * 60 * 1000)));\n\treturn `${days}d ago`;\n}\n\nfunction sortProfiles(profiles: StoredModelAdaptation[]): StoredModelAdaptation[] {\n\treturn [...profiles].sort((left, right) => left.model.localeCompare(right.model));\n}\n\nexport function formatToolRepairHealthReport(store: ModelAdaptationStore, now: Date = new Date()): string {\n\tconst profiles = sortProfiles(store.getForHost());\n\tif (profiles.length === 0) return \"Tool repair health: no model adaptation records for this host.\";\n\n\tconst lines = [chalk.bold(\"Tool repair health\")];\n\tfor (const entry of profiles) {\n\t\tlines.push(`${entry.model}`);\n\t\tconst toolProbe = entry.profile.toolProbe;\n\t\tif (!toolProbe) {\n\t\t\tlines.push(\" tool probe: none\");\n\t\t} else {\n\t\t\tconst variant = toolProbe.variant ? ` (${toolProbe.variant})` : \"\";\n\t\t\tconst nativeGrade = toolProbe.nativeGrade ? ` native=${toolProbe.nativeGrade}` : \"\";\n\t\t\tlines.push(\n\t\t\t\t` tool probe: v${toolProbe.version} ${toolProbe.status}${variant}${nativeGrade} ${formatAgeDays(toolProbe.probedAt, now)}`,\n\t\t\t);\n\t\t\tif (toolProbe.diagnostic) lines.push(` probe diagnostic: ${toolProbe.diagnostic}`);\n\t\t}\n\t\tconst protocol = entry.profile.protocol;\n\t\tif (!protocol) {\n\t\t\tlines.push(\" protocol: none\");\n\t\t} else if (protocol.status === \"failed\") {\n\t\t\tlines.push(` protocol: v${protocol.version} failed ${formatAgeDays(protocol.attemptedAt, now)}`);\n\t\t\tlines.push(` variants tried: ${protocol.variantsTried.join(\", \")}`);\n\t\t\tlines.push(` reset: /toolprotocol-reset ${entry.model}`);\n\t\t} else {\n\t\t\tlines.push(\n\t\t\t\t` protocol: v${protocol.version} ${protocol.variant} calibrated ${formatAgeDays(protocol.calibratedAt, now)}`,\n\t\t\t);\n\t\t}\n\t\tif (entry.profile.rules.length === 0) {\n\t\t\tlines.push(\" rules: none\");\n\t\t} else {\n\t\t\tlines.push(\" rules:\");\n\t\t\tfor (const rule of [...entry.profile.rules].sort((left, right) => left.mode.localeCompare(right.mode))) {\n\t\t\t\tlines.push(` - ${rule.mode} (${formatAgeDays(rule.lastFiredAt, now)}): ${rule.text}`);\n\t\t\t}\n\t\t}\n\t\tconst teachEntries = Object.entries(entry.profile.teachStats).sort(([left], [right]) =>\n\t\t\tleft.localeCompare(right),\n\t\t);\n\t\tif (teachEntries.length === 0) {\n\t\t\tlines.push(\" teach stats: none\");\n\t\t} else {\n\t\t\tlines.push(\" teach stats:\");\n\t\t\tfor (const [mode, stats] of teachEntries) {\n\t\t\t\tlines.push(\n\t\t\t\t\t` - ${mode}: taught=${stats.taught} before=${stats.recurrenceBefore} after=${stats.recurrenceAfter}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -301,6 +301,7 @@ export declare class InteractiveMode {
301
301
  * tracked separately here.
302
302
  */
303
303
  private get localRuntime();
304
+ private getTransformersRuntime;
304
305
  /** Narrow seam shared by the /models and /fitness flows. */
305
306
  private localModelHost;
306
307
  private handleModelsCommand;