@caupulican/pi-adaptative 0.81.26 → 0.81.29
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.
- package/CHANGELOG.md +45 -0
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +3 -2
- package/dist/cli/args.js.map +1 -1
- package/dist/core/agent-session-services.d.ts +4 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +19 -2
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/agent-session.d.ts +30 -12
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +128 -36
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth-storage.d.ts +6 -0
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +35 -0
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +59 -19
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +2 -0
- package/dist/core/autonomy/contracts.d.ts.map +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +31 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -0
- package/dist/core/autonomy/lane-tool-surface.js +96 -0
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -0
- package/dist/core/autonomy/lane-tracker.d.ts +5 -0
- package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tracker.js +14 -3
- package/dist/core/autonomy/lane-tracker.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +28 -4
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +237 -28
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/billing-failover-controller.d.ts.map +1 -1
- package/dist/core/billing-failover-controller.js +1 -1
- package/dist/core/billing-failover-controller.js.map +1 -1
- package/dist/core/context/current-work-memory.d.ts +9 -0
- package/dist/core/context/current-work-memory.d.ts.map +1 -0
- package/dist/core/context/current-work-memory.js +61 -0
- package/dist/core/context/current-work-memory.js.map +1 -0
- package/dist/core/context/file-store-memory-provider.d.ts +9 -0
- package/dist/core/context/file-store-memory-provider.d.ts.map +1 -0
- package/dist/core/context/file-store-memory-provider.js +106 -0
- package/dist/core/context/file-store-memory-provider.js.map +1 -0
- package/dist/core/context/long-term-memory-trigger.d.ts +15 -0
- package/dist/core/context/long-term-memory-trigger.d.ts.map +1 -0
- package/dist/core/context/long-term-memory-trigger.js +39 -0
- package/dist/core/context/long-term-memory-trigger.js.map +1 -0
- package/dist/core/context/memory-prompt-block.d.ts +3 -1
- package/dist/core/context/memory-prompt-block.d.ts.map +1 -1
- package/dist/core/context/memory-prompt-block.js +20 -3
- package/dist/core/context/memory-prompt-block.js.map +1 -1
- package/dist/core/context/memory-prompt-budget.d.ts +17 -0
- package/dist/core/context/memory-prompt-budget.d.ts.map +1 -0
- package/dist/core/context/memory-prompt-budget.js +64 -0
- package/dist/core/context/memory-prompt-budget.js.map +1 -0
- package/dist/core/context/memory-provider-contract.d.ts.map +1 -1
- package/dist/core/context/memory-provider-contract.js +2 -5
- package/dist/core/context/memory-provider-contract.js.map +1 -1
- package/dist/core/context/memory-tier-composer.d.ts +27 -0
- package/dist/core/context/memory-tier-composer.d.ts.map +1 -0
- package/dist/core/context/memory-tier-composer.js +79 -0
- package/dist/core/context/memory-tier-composer.js.map +1 -0
- package/dist/core/context-gc.d.ts.map +1 -1
- package/dist/core/context-gc.js +2 -0
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +5 -3
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +15 -5
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/cost/cost-summary.d.ts +3 -1
- package/dist/core/cost/cost-summary.d.ts.map +1 -1
- package/dist/core/cost/cost-summary.js +3 -3
- package/dist/core/cost/cost-summary.js.map +1 -1
- package/dist/core/cost-guard.d.ts +17 -7
- package/dist/core/cost-guard.d.ts.map +1 -1
- package/dist/core/cost-guard.js +33 -10
- package/dist/core/cost-guard.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts +9 -0
- package/dist/core/default-tool-surface.d.ts.map +1 -0
- package/dist/core/default-tool-surface.js +18 -0
- package/dist/core/default-tool-surface.js.map +1 -0
- package/dist/core/delegation/worker-result.d.ts.map +1 -1
- package/dist/core/delegation/worker-result.js +3 -0
- package/dist/core/delegation/worker-result.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +11 -5
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +77 -16
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +15 -0
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +2 -0
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +7 -0
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -0
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/failure-corpus.d.ts.map +1 -1
- package/dist/core/failure-corpus.js +2 -4
- package/dist/core/failure-corpus.js.map +1 -1
- package/dist/core/footer-data-provider.d.ts.map +1 -1
- package/dist/core/footer-data-provider.js +9 -1
- package/dist/core/footer-data-provider.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +4 -3
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +12 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +42 -4
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/local-runtime-controller.d.ts +16 -0
- package/dist/core/local-runtime-controller.d.ts.map +1 -1
- package/dist/core/local-runtime-controller.js +107 -28
- package/dist/core/local-runtime-controller.js.map +1 -1
- package/dist/core/memory/memory-manager.d.ts +8 -3
- package/dist/core/memory/memory-manager.d.ts.map +1 -1
- package/dist/core/memory/memory-manager.js +27 -11
- package/dist/core/memory/memory-manager.js.map +1 -1
- package/dist/core/memory/memory-provider.d.ts +5 -1
- package/dist/core/memory/memory-provider.d.ts.map +1 -1
- package/dist/core/memory/memory-provider.js.map +1 -1
- package/dist/core/memory/providers/file-store.d.ts +3 -1
- package/dist/core/memory/providers/file-store.d.ts.map +1 -1
- package/dist/core/memory/providers/file-store.js +7 -2
- package/dist/core/memory/providers/file-store.js.map +1 -1
- package/dist/core/memory/providers/transcript-recall.d.ts +1 -0
- package/dist/core/memory/providers/transcript-recall.d.ts.map +1 -1
- package/dist/core/memory/providers/transcript-recall.js +4 -7
- package/dist/core/memory/providers/transcript-recall.js.map +1 -1
- package/dist/core/memory-controller.d.ts +36 -10
- package/dist/core/memory-controller.d.ts.map +1 -1
- package/dist/core/memory-controller.js +137 -21
- package/dist/core/memory-controller.js.map +1 -1
- package/dist/core/model-registry.d.ts +25 -0
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +91 -8
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +30 -11
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +33 -29
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/model-selection-controller.d.ts +3 -0
- package/dist/core/model-selection-controller.d.ts.map +1 -1
- package/dist/core/model-selection-controller.js +8 -1
- package/dist/core/model-selection-controller.js.map +1 -1
- package/dist/core/models/local-runtime.d.ts +2 -0
- package/dist/core/models/local-runtime.d.ts.map +1 -1
- package/dist/core/models/local-runtime.js +10 -4
- package/dist/core/models/local-runtime.js.map +1 -1
- package/dist/core/models/perf-profile.d.ts.map +1 -1
- package/dist/core/models/perf-profile.js +95 -33
- package/dist/core/models/perf-profile.js.map +1 -1
- package/dist/core/models/runtime-arbiter.d.ts +11 -0
- package/dist/core/models/runtime-arbiter.d.ts.map +1 -1
- package/dist/core/models/runtime-arbiter.js +35 -13
- package/dist/core/models/runtime-arbiter.js.map +1 -1
- package/dist/core/profile-filter-controller.d.ts +11 -0
- package/dist/core/profile-filter-controller.d.ts.map +1 -1
- package/dist/core/profile-filter-controller.js +56 -11
- package/dist/core/profile-filter-controller.js.map +1 -1
- package/dist/core/profile-registry.d.ts +2 -2
- package/dist/core/profile-registry.d.ts.map +1 -1
- package/dist/core/profile-registry.js +58 -7
- package/dist/core/profile-registry.js.map +1 -1
- package/dist/core/reflection-controller.d.ts +9 -7
- package/dist/core/reflection-controller.d.ts.map +1 -1
- package/dist/core/reflection-controller.js +81 -12
- package/dist/core/reflection-controller.js.map +1 -1
- package/dist/core/research/research-runner.d.ts +2 -2
- package/dist/core/research/research-runner.d.ts.map +1 -1
- package/dist/core/research/research-runner.js +8 -6
- package/dist/core/research/research-runner.js.map +1 -1
- package/dist/core/resource-loader.d.ts +4 -2
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +11 -1
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +30 -3
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +140 -40
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/sdk.d.ts +8 -7
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +38 -5
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/security/secret-text.d.ts +3 -0
- package/dist/core/security/secret-text.d.ts.map +1 -0
- package/dist/core/security/secret-text.js +26 -0
- package/dist/core/security/secret-text.js.map +1 -0
- package/dist/core/settings-manager.d.ts +59 -17
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +300 -51
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +1 -1
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +7 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +23 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/tool-gate-controller.d.ts +3 -0
- package/dist/core/tool-gate-controller.d.ts.map +1 -1
- package/dist/core/tool-gate-controller.js +20 -15
- package/dist/core/tool-gate-controller.js.map +1 -1
- package/dist/core/tool-selection/expected-utility.d.ts +51 -0
- package/dist/core/tool-selection/expected-utility.d.ts.map +1 -0
- package/dist/core/tool-selection/expected-utility.js +85 -0
- package/dist/core/tool-selection/expected-utility.js.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts +82 -0
- package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-performance-store.js +249 -0
- package/dist/core/tool-selection/tool-performance-store.js.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts +41 -0
- package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -0
- package/dist/core/tool-selection/tool-selection-controller.js +199 -0
- package/dist/core/tool-selection/tool-selection-controller.js.map +1 -0
- package/dist/core/tools/delegate-status.d.ts +9 -0
- package/dist/core/tools/delegate-status.d.ts.map +1 -0
- package/dist/core/tools/delegate-status.js +52 -0
- package/dist/core/tools/delegate-status.js.map +1 -0
- package/dist/core/tools/delegate.d.ts +10 -0
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +36 -13
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/run-toolkit-script.d.ts +3 -0
- package/dist/core/tools/run-toolkit-script.d.ts.map +1 -1
- package/dist/core/tools/run-toolkit-script.js +17 -7
- package/dist/core/tools/run-toolkit-script.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +2 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +8 -1
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +69 -29
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +2 -0
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/dist/modes/interactive/config-backup.d.ts +7 -1
- package/dist/modes/interactive/config-backup.d.ts.map +1 -1
- package/dist/modes/interactive/config-backup.js +196 -32
- package/dist/modes/interactive/config-backup.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +22 -28
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +2 -0
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.d.ts +6 -4
- package/dist/modes/interactive/profile-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/profile-menu-controller.js +248 -65
- package/dist/modes/interactive/profile-menu-controller.js.map +1 -1
- package/dist/modes/interactive/report-commands.d.ts.map +1 -1
- package/dist/modes/interactive/report-commands.js +8 -2
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.d.ts.map +1 -1
- package/dist/modes/interactive/settings-selector-flow.js +8 -0
- package/dist/modes/interactive/settings-selector-flow.js.map +1 -1
- package/dist/modes/interactive/theme/theme-schema.json +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +1 -1
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +3 -1
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/docs/extensions.md +32 -0
- package/docs/integration-sweep-builder-blueprint-2026-07-09.md +365 -0
- package/docs/integration-sweep-resume-2026-07-09.md +407 -0
- package/docs/resources.md +15 -7
- package/docs/settings.md +56 -5
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/preset.ts +2 -2
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +44 -35
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model-selection-controller.js","sourceRoot":"","sources":["../../src/core/model-selection-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAInC,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,iFAAiF;AACjF,MAAM,eAAe,GAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AA4BrF,MAAM,OAAO,wBAAwB;IACnB,IAAI,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;QACD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,uBAAuB,EAAE,IAAI,sBAAsB,CAAC;QAC3F,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;IAAA,CACpC;IAEO,mBAAmB,CAAC,KAAoB,EAAE,gBAAiC,EAAiB;QACnG,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACnC,OAAO,KAAK,CAAC,CAAC,CAAE,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAmB,CAAC,CAAC,CAAC,KAAK,CAAC;IAAA,CAC3E;CACD","sourcesContent":["/**\n * User-facing model + thinking-level selection.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the manual/explicit model\n * switch and cycle paths and the thinking-level set/cycle/clamp — the deliberate human choices, as\n * opposed to the per-turn auto-routing owned by ModelRouterController. It mutates `agent.state.model`\n * / `agent.state.thinkingLevel` through deps and re-derives the capability-scoped tool surface, but the\n * session keeps the `model`/`thinkingLevel` GETTERS so the drive loop's reads are untouched. Model\n * choice is advisory-only: it warns on a bad-fit fitness probe or an oversized local model, never blocks.\n */\n\nimport { totalmem } from \"node:os\";\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport { clampThinkingLevel, getSupportedThinkingLevels, modelsAreEqual } from \"@caupulican/pi-ai\";\nimport type { AgentSessionEvent, ModelCycleResult } from \"./agent-session.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner } from \"./extensions/index.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { OllamaRuntime } from \"./models/local-runtime.ts\";\nimport { matchesInstalledLocalModel } from \"./models/model-ref.ts\";\nimport { isProbeAllFailed } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\n/** Standard thinking levels (fallback set when the current model is unknown). */\nconst THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\nexport interface ModelSelectionControllerDeps {\n\tgetAgent(): Agent;\n\tgetModel(): Model<any> | undefined;\n\tgetThinkingLevel(): ThinkingLevel;\n\tgetModelRegistry(): ModelRegistry;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\tgetExtensionRunner(): ExtensionRunner;\n\tgetAgentDir(): string;\n\t/** Scoped models (--models flag), used by the cycle path. */\n\tgetScopedModels(): Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/** The user-requested active tool set, re-applied when the model's capability class changes. */\n\tgetRequestedActiveToolNames(): string[] | undefined;\n\tgetActiveToolNames(): string[];\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Session event emit (warnings + thinking_level_changed; model_select goes via the extension runner). */\n\temit(event: AgentSessionEvent): void;\n\t/** Context-window-usage warning check (session-owned, compaction-adjacent). */\n\tcheckContextWindowUsageWarning(): void;\n\t/** Resolve the Ollama server URL for a model base URL (local-runtime controller). */\n\tderiveOllamaServerUrl(modelBaseUrl: string): string;\n\t/** Local Ollama runtime for the given server URL (used for the oversized-model risk check). */\n\tgetLocalRuntime(serverUrl: string): OllamaRuntime;\n}\n\nexport class ModelSelectionController {\n\tprivate readonly deps: ModelSelectionControllerDeps;\n\n\tconstructor(deps: ModelSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate async _emitModelSelect(\n\t\tnextModel: Model<any>,\n\t\tpreviousModel: Model<any> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\",\n\t): Promise<void> {\n\t\tif (modelsAreEqual(previousModel, nextModel)) return;\n\t\tawait this.deps.getExtensionRunner().emit({\n\t\t\ttype: \"model_select\",\n\t\t\tmodel: nextModel,\n\t\t\tpreviousModel,\n\t\t\tsource,\n\t\t});\n\t}\n\n\t/**\n\t * Set model directly.\n\t * Validates that auth is configured, saves to session and settings.\n\t * @throws Error if no auth is configured for the model\n\t */\n\tasync setModel(model: Model<any>, options: { persistSettings?: boolean } = {}): Promise<void> {\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(model)) {\n\t\t\tthrow new Error(`No API key for ${model.provider}/${model.id}`);\n\t\t}\n\n\t\tconst persistSettings = options.persistSettings ?? true;\n\t\tconst previousModel = this.deps.getModel();\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.deps.getAgent().state.model = model;\n\t\tthis.deps.getSessionManager().appendModelChange(model.provider, model.id);\n\t\tif (persistSettings) {\n\t\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(model.provider, model.id);\n\t\t}\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel, { persistSettings });\n\n\t\tawait this._emitModelSelect(model, previousModel, \"set\");\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(model);\n\n\t\t// Re-derive the model-capability tool surface for the new model (restores the full requested\n\t\t// set when moving small -> large, reduces it when moving large -> small).\n\t\tconst requestedActiveToolNames = this.deps.getRequestedActiveToolNames();\n\t\tif (requestedActiveToolNames) {\n\t\t\tconst before = this.deps.getActiveToolNames().join(\",\");\n\t\t\tthis.deps.setActiveToolsByName(requestedActiveToolNames);\n\t\t\tconst capability = this.deps.getModelCapabilityProfile();\n\t\t\tif (capability.class !== \"full\" && this.deps.getActiveToolNames().join(\",\") !== before) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `Small-context model detected (${capability.contextWindow ?? \"unknown\"} tokens, class '${capability.class}'): active tools reduced to [${this.deps.getActiveToolNames().join(\", \")}]; background lanes ${capability.backgroundLanesEnabled ? \"enabled\" : \"disabled\"}.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manual model choice is a deliberate human decision, not an auto-adoption flow — it is\n\t * ADVISORY ONLY: warn on evidence the model is a bad fit, but never block and never prompt\n\t * (print/RPC modes only ever see plain warning text through the existing `warning` event, the\n\t * same channel `_checkContextWindowUsageWarning` above uses). Two independent checks, both\n\t * best-effort:\n\t * - a recorded all-lanes-failed fitness probe on THIS host (see `isProbeAllFailed`);\n\t * - for an Ollama-served local model, weights that exceed ~90% of total system memory, which\n\t * is the exact failure the OOM report reproduced (llama-server needs the whole model resident).\n\t */\n\tprivate async _warnIfManualModelChoiceIsRisky(model: Model<Api>): Promise<void> {\n\t\tconst canonicalRef = `${model.provider}/${model.id}`;\n\t\ttry {\n\t\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t\t.getForHost()\n\t\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\t\tif (fitness && isProbeAllFailed(fitness.report)) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `${canonicalRef} failed its fitness probe on all surfaces on this host (probed ${fitness.at}) — it is likely to fail in production too. Proceeding because you set it manually.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\t// advisory only; a lookup failure must never block a manual model choice\n\t\t}\n\n\t\tif (model.provider !== OLLAMA_PROVIDER) return;\n\t\ttry {\n\t\t\tconst serverUrl = this.deps.deriveOllamaServerUrl(model.baseUrl);\n\t\t\tconst installed = await this.deps.getLocalRuntime(serverUrl).list();\n\t\t\tconst entry = installed.find((candidate) => matchesInstalledLocalModel(model.id, candidate.name));\n\t\t\tif (!entry) return;\n\t\t\tconst memoryBudget = totalmem() * 0.9;\n\t\t\tif (entry.sizeBytes > memoryBudget) {\n\t\t\t\tconst sizeGb = (entry.sizeBytes / 1e9).toFixed(1);\n\t\t\t\tconst totalGb = (totalmem() / 1e9).toFixed(1);\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `${canonicalRef} is ~${sizeGb}GB, over 90% of this machine's ${totalGb}GB RAM — llama-server is likely to OOM when it runs. Proceeding because you set it manually.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\t// advisory only; an unreachable local server must never block a manual model choice\n\t\t}\n\t}\n\n\t/**\n\t * Cycle to next/previous model.\n\t * Uses scoped models (from --models flag) if available, otherwise all available models.\n\t * @param direction - \"forward\" (default) or \"backward\"\n\t * @returns The new model info, or undefined if only one model available\n\t */\n\tasync cycleModel(direction: \"forward\" | \"backward\" = \"forward\"): Promise<ModelCycleResult | undefined> {\n\t\tif (this.deps.getScopedModels().length > 0) {\n\t\t\treturn this._cycleScopedModel(direction);\n\t\t}\n\t\treturn this._cycleAvailableModel(direction);\n\t}\n\n\tprivate async _cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst scopedModels = this.deps\n\t\t\t.getScopedModels()\n\t\t\t.filter((scoped) => this.deps.getModelRegistry().hasConfiguredAuth(scoped.model));\n\t\tif (scopedModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.deps.getModel();\n\t\tlet currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = scopedModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst next = scopedModels[nextIndex];\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);\n\n\t\t// Apply model\n\t\tthis.deps.getAgent().state.model = next.model;\n\t\tthis.deps.getSessionManager().appendModelChange(next.model.provider, next.model.id);\n\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(next.model.provider, next.model.id);\n\n\t\t// Apply thinking level.\n\t\t// - Explicit scoped model thinking level overrides current session level\n\t\t// - Undefined scoped model thinking level inherits the current session preference\n\t\t// setThinkingLevel clamps to model capabilities.\n\t\tthis.setThinkingLevel(thinkingLevel);\n\n\t\tawait this._emitModelSelect(next.model, currentModel, \"cycle\");\n\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(next.model);\n\n\t\treturn { model: next.model, thinkingLevel: this.deps.getThinkingLevel(), isScoped: true };\n\t}\n\n\tprivate async _cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst availableModels = await this.deps.getModelRegistry().getAvailable();\n\t\tif (availableModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.deps.getModel();\n\t\tlet currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = availableModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst nextModel = availableModels[nextIndex];\n\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.deps.getAgent().state.model = nextModel;\n\t\tthis.deps.getSessionManager().appendModelChange(nextModel.provider, nextModel.id);\n\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel);\n\n\t\tawait this._emitModelSelect(nextModel, currentModel, \"cycle\");\n\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(nextModel);\n\n\t\treturn { model: nextModel, thinkingLevel: this.deps.getThinkingLevel(), isScoped: false };\n\t}\n\n\t/**\n\t * Set thinking level.\n\t * Clamps to model capabilities based on available thinking levels.\n\t * Saves to session and settings only if the level actually changes.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel, options: { persistSettings?: boolean } = {}): void {\n\t\tconst availableLevels = this.getAvailableThinkingLevels();\n\t\tconst effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);\n\n\t\t// Only persist if actually changing\n\t\tconst previousLevel = this.deps.getAgent().state.thinkingLevel;\n\t\tconst isChanging = effectiveLevel !== previousLevel;\n\t\tconst persistSettings = options.persistSettings ?? true;\n\n\t\tthis.deps.getAgent().state.thinkingLevel = effectiveLevel;\n\n\t\tif (isChanging) {\n\t\t\tthis.deps.getSessionManager().appendThinkingLevelChange(effectiveLevel);\n\t\t\tif (persistSettings && (this.supportsThinking() || effectiveLevel !== \"off\")) {\n\t\t\t\tthis.deps.getSettingsManager().setDefaultThinkingLevel(effectiveLevel);\n\t\t\t}\n\t\t\tthis.deps.emit({ type: \"thinking_level_changed\", level: effectiveLevel });\n\t\t\tvoid this.deps.getExtensionRunner().emit({\n\t\t\t\ttype: \"thinking_level_select\",\n\t\t\t\tlevel: effectiveLevel,\n\t\t\t\tpreviousLevel,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Cycle to next thinking level.\n\t * @returns New level, or undefined if model doesn't support thinking\n\t */\n\tcycleThinkingLevel(): ThinkingLevel | undefined {\n\t\tif (!this.supportsThinking()) return undefined;\n\n\t\tconst levels = this.getAvailableThinkingLevels();\n\t\tconst currentIndex = levels.indexOf(this.deps.getThinkingLevel());\n\t\tconst nextIndex = (currentIndex + 1) % levels.length;\n\t\tconst nextLevel = levels[nextIndex];\n\n\t\tthis.setThinkingLevel(nextLevel);\n\t\treturn nextLevel;\n\t}\n\n\t/**\n\t * Get available thinking levels for current model.\n\t * The provider will clamp to what the specific model supports internally.\n\t */\n\tgetAvailableThinkingLevels(): ThinkingLevel[] {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return THINKING_LEVELS;\n\t\treturn getSupportedThinkingLevels(model) as ThinkingLevel[];\n\t}\n\n\t/**\n\t * Check if current model supports thinking/reasoning.\n\t */\n\tsupportsThinking(): boolean {\n\t\treturn !!this.deps.getModel()?.reasoning;\n\t}\n\n\tprivate _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {\n\t\tif (explicitLevel !== undefined) {\n\t\t\treturn explicitLevel;\n\t\t}\n\t\tif (!this.supportsThinking()) {\n\t\t\treturn this.deps.getSettingsManager().getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\t\treturn this.deps.getThinkingLevel();\n\t}\n\n\tprivate _clampThinkingLevel(level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {\n\t\tconst model = this.deps.getModel();\n\t\treturn model ? (clampThinkingLevel(model, level) as ThinkingLevel) : \"off\";\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"model-selection-controller.js","sourceRoot":"","sources":["../../src/core/model-selection-controller.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAInC,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAEnG,OAAO,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAIvD,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AACnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,6BAA6B,CAAC;AAG/D,iFAAiF;AACjF,MAAM,eAAe,GAAoB,CAAC,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC;AA8BrF,MAAM,OAAO,wBAAwB;IACnB,IAAI,CAA+B;IAEpD,YAAY,IAAkC,EAAE;QAC/C,IAAI,CAAC,IAAI,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,QAAQ,EAAE,EAAE,SAAS,CAAC;IAAA,CACzC;IAEO,+BAA+B,CAAC,aAA6B,EAAiB;QACrF,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;YACjC,OAAO,aAAa,CAAC;QACtB,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,EAAE,CAAC;YAC9B,OAAO,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,CAAC,uBAAuB,EAAE,IAAI,sBAAsB,CAAC;QAC3F,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,gBAAgB,EAAE,CAAC;IAAA,CACpC;IAEO,mBAAmB,CAAC,KAAoB,EAAE,gBAAiC,EAAiB;QACnG,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;QACnC,OAAO,KAAK,CAAC,CAAC,CAAE,kBAAkB,CAAC,KAAK,EAAE,KAAK,CAAmB,CAAC,CAAC,CAAC,KAAK,CAAC;IAAA,CAC3E;CACD","sourcesContent":["/**\n * User-facing model + thinking-level selection.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the manual/explicit model\n * switch and cycle paths and the thinking-level set/cycle/clamp — the deliberate human choices, as\n * opposed to the per-turn auto-routing owned by ModelRouterController. It mutates `agent.state.model`\n * / `agent.state.thinkingLevel` through deps and re-derives the capability-scoped tool surface, but the\n * session keeps the `model`/`thinkingLevel` GETTERS so the drive loop's reads are untouched. Model\n * choice is advisory-only: it warns on a bad-fit fitness probe or an oversized local model, never blocks.\n */\n\nimport { totalmem } from \"node:os\";\nimport type { Agent, ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Api, Model } from \"@caupulican/pi-ai\";\nimport { clampThinkingLevel, getSupportedThinkingLevels, modelsAreEqual } from \"@caupulican/pi-ai\";\nimport type { AgentSessionEvent, ModelCycleResult } from \"./agent-session.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner } from \"./extensions/index.ts\";\nimport type { ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { ModelRegistry } from \"./model-registry.ts\";\nimport { FitnessStore } from \"./models/fitness-store.ts\";\nimport { OLLAMA_PROVIDER } from \"./models/local-registration.ts\";\nimport type { OllamaRuntime } from \"./models/local-runtime.ts\";\nimport { matchesInstalledLocalModel } from \"./models/model-ref.ts\";\nimport { isProbeAllFailed } from \"./research/model-fitness.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\n\n/** Standard thinking levels (fallback set when the current model is unknown). */\nconst THINKING_LEVELS: ThinkingLevel[] = [\"off\", \"minimal\", \"low\", \"medium\", \"high\"];\n\nexport interface ModelSelectionControllerDeps {\n\tgetAgent(): Agent;\n\tgetModel(): Model<any> | undefined;\n\tgetThinkingLevel(): ThinkingLevel;\n\tgetModelRegistry(): ModelRegistry;\n\tgetSessionManager(): SessionManager;\n\tgetSettingsManager(): SettingsManager;\n\tgetExtensionRunner(): ExtensionRunner;\n\tgetAgentDir(): string;\n\t/** Scoped models (--models flag), used by the cycle path. */\n\tgetScopedModels(): Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\t/** The user-requested active tool set, re-applied when the model's capability class changes. */\n\tgetRequestedActiveToolNames(): string[] | undefined;\n\tgetActiveToolNames(): string[];\n\tsetActiveToolsByName(toolNames: string[]): void;\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Rebuild the base prompt after a live orchestration-level change without altering requested tools. */\n\trefreshBaseSystemPrompt(): void;\n\t/** Session event emit (warnings + thinking_level_changed; model_select goes via the extension runner). */\n\temit(event: AgentSessionEvent): void;\n\t/** Context-window-usage warning check (session-owned, compaction-adjacent). */\n\tcheckContextWindowUsageWarning(): void;\n\t/** Resolve the Ollama server URL for a model base URL (local-runtime controller). */\n\tderiveOllamaServerUrl(modelBaseUrl: string): string;\n\t/** Local Ollama runtime for the given server URL (used for the oversized-model risk check). */\n\tgetLocalRuntime(serverUrl: string): OllamaRuntime;\n}\n\nexport class ModelSelectionController {\n\tprivate readonly deps: ModelSelectionControllerDeps;\n\n\tconstructor(deps: ModelSelectionControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tprivate async _emitModelSelect(\n\t\tnextModel: Model<any>,\n\t\tpreviousModel: Model<any> | undefined,\n\t\tsource: \"set\" | \"cycle\" | \"restore\",\n\t): Promise<void> {\n\t\tif (modelsAreEqual(previousModel, nextModel)) return;\n\t\tawait this.deps.getExtensionRunner().emit({\n\t\t\ttype: \"model_select\",\n\t\t\tmodel: nextModel,\n\t\t\tpreviousModel,\n\t\t\tsource,\n\t\t});\n\t}\n\n\t/**\n\t * Set model directly.\n\t * Validates that auth is configured, saves to session and settings.\n\t * @throws Error if no auth is configured for the model\n\t */\n\tasync setModel(model: Model<any>, options: { persistSettings?: boolean } = {}): Promise<void> {\n\t\tif (!this.deps.getModelRegistry().hasConfiguredAuth(model)) {\n\t\t\tthrow new Error(`No API key for ${model.provider}/${model.id}`);\n\t\t}\n\n\t\tconst persistSettings = options.persistSettings ?? true;\n\t\tconst previousModel = this.deps.getModel();\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.deps.getAgent().state.model = model;\n\t\tthis.deps.getSessionManager().appendModelChange(model.provider, model.id);\n\t\tif (persistSettings) {\n\t\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(model.provider, model.id);\n\t\t}\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel, { persistSettings });\n\t\tthis._resyncToolSurfaceForModel();\n\n\t\tawait this._emitModelSelect(model, previousModel, \"set\");\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(model);\n\t}\n\n\tprivate _resyncToolSurfaceForModel(): void {\n\t\t// Re-derive the model-capability tool surface for the new model (restores the full requested\n\t\t// set when moving small -> large, reduces it when moving large -> small). Every switch path,\n\t\t// including model cycling and RPC commands that delegate to it, must pass through this seam.\n\t\tconst requestedActiveToolNames = this.deps.getRequestedActiveToolNames();\n\t\tif (requestedActiveToolNames) {\n\t\t\tconst before = this.deps.getActiveToolNames().join(\",\");\n\t\t\tthis.deps.setActiveToolsByName(requestedActiveToolNames);\n\t\t\tconst capability = this.deps.getModelCapabilityProfile();\n\t\t\tif (capability.class !== \"full\" && this.deps.getActiveToolNames().join(\",\") !== before) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `Small-context model detected (${capability.contextWindow ?? \"unknown\"} tokens, class '${capability.class}'): active tools reduced to [${this.deps.getActiveToolNames().join(\", \")}]; background lanes ${capability.backgroundLanesEnabled ? \"enabled\" : \"disabled\"}.`,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Manual model choice is a deliberate human decision, not an auto-adoption flow — it is\n\t * ADVISORY ONLY: warn on evidence the model is a bad fit, but never block and never prompt\n\t * (print/RPC modes only ever see plain warning text through the existing `warning` event, the\n\t * same channel `_checkContextWindowUsageWarning` above uses). Two independent checks, both\n\t * best-effort:\n\t * - a recorded all-lanes-failed fitness probe on THIS host (see `isProbeAllFailed`);\n\t * - for an Ollama-served local model, weights that exceed ~90% of total system memory, which\n\t * is the exact failure the OOM report reproduced (llama-server needs the whole model resident).\n\t */\n\tprivate async _warnIfManualModelChoiceIsRisky(model: Model<Api>): Promise<void> {\n\t\tconst canonicalRef = `${model.provider}/${model.id}`;\n\t\ttry {\n\t\t\tconst fitness = FitnessStore.forAgentDir(this.deps.getAgentDir())\n\t\t\t\t.getForHost()\n\t\t\t\t.find((entry) => entry.model === canonicalRef);\n\t\t\tif (fitness && isProbeAllFailed(fitness.report)) {\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `${canonicalRef} failed its fitness probe on all surfaces on this host (probed ${fitness.at}) — it is likely to fail in production too. Proceeding because you set it manually.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\t// advisory only; a lookup failure must never block a manual model choice\n\t\t}\n\n\t\tif (model.provider !== OLLAMA_PROVIDER) return;\n\t\ttry {\n\t\t\tconst serverUrl = this.deps.deriveOllamaServerUrl(model.baseUrl);\n\t\t\tconst installed = await this.deps.getLocalRuntime(serverUrl).list();\n\t\t\tconst entry = installed.find((candidate) => matchesInstalledLocalModel(model.id, candidate.name));\n\t\t\tif (!entry) return;\n\t\t\tconst memoryBudget = totalmem() * 0.9;\n\t\t\tif (entry.sizeBytes > memoryBudget) {\n\t\t\t\tconst sizeGb = (entry.sizeBytes / 1e9).toFixed(1);\n\t\t\t\tconst totalGb = (totalmem() / 1e9).toFixed(1);\n\t\t\t\tthis.deps.emit({\n\t\t\t\t\ttype: \"warning\",\n\t\t\t\t\tmessage: `${canonicalRef} is ~${sizeGb}GB, over 90% of this machine's ${totalGb}GB RAM — llama-server is likely to OOM when it runs. Proceeding because you set it manually.`,\n\t\t\t\t});\n\t\t\t}\n\t\t} catch {\n\t\t\t// advisory only; an unreachable local server must never block a manual model choice\n\t\t}\n\t}\n\n\t/**\n\t * Cycle to next/previous model.\n\t * Uses scoped models (from --models flag) if available, otherwise all available models.\n\t * @param direction - \"forward\" (default) or \"backward\"\n\t * @returns The new model info, or undefined if only one model available\n\t */\n\tasync cycleModel(direction: \"forward\" | \"backward\" = \"forward\"): Promise<ModelCycleResult | undefined> {\n\t\tif (this.deps.getScopedModels().length > 0) {\n\t\t\treturn this._cycleScopedModel(direction);\n\t\t}\n\t\treturn this._cycleAvailableModel(direction);\n\t}\n\n\tprivate async _cycleScopedModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst scopedModels = this.deps\n\t\t\t.getScopedModels()\n\t\t\t.filter((scoped) => this.deps.getModelRegistry().hasConfiguredAuth(scoped.model));\n\t\tif (scopedModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.deps.getModel();\n\t\tlet currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = scopedModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst next = scopedModels[nextIndex];\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);\n\n\t\t// Apply model\n\t\tthis.deps.getAgent().state.model = next.model;\n\t\tthis.deps.getSessionManager().appendModelChange(next.model.provider, next.model.id);\n\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(next.model.provider, next.model.id);\n\n\t\t// Apply thinking level.\n\t\t// - Explicit scoped model thinking level overrides current session level\n\t\t// - Undefined scoped model thinking level inherits the current session preference\n\t\t// setThinkingLevel clamps to model capabilities.\n\t\tthis.setThinkingLevel(thinkingLevel);\n\t\tthis._resyncToolSurfaceForModel();\n\n\t\tawait this._emitModelSelect(next.model, currentModel, \"cycle\");\n\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(next.model);\n\n\t\treturn { model: next.model, thinkingLevel: this.deps.getThinkingLevel(), isScoped: true };\n\t}\n\n\tprivate async _cycleAvailableModel(direction: \"forward\" | \"backward\"): Promise<ModelCycleResult | undefined> {\n\t\tconst availableModels = await this.deps.getModelRegistry().getAvailable();\n\t\tif (availableModels.length <= 1) return undefined;\n\n\t\tconst currentModel = this.deps.getModel();\n\t\tlet currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));\n\n\t\tif (currentIndex === -1) currentIndex = 0;\n\t\tconst len = availableModels.length;\n\t\tconst nextIndex = direction === \"forward\" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;\n\t\tconst nextModel = availableModels[nextIndex];\n\n\t\tconst thinkingLevel = this._getThinkingLevelForModelSwitch();\n\t\tthis.deps.getAgent().state.model = nextModel;\n\t\tthis.deps.getSessionManager().appendModelChange(nextModel.provider, nextModel.id);\n\t\tthis.deps.getSettingsManager().setDefaultModelAndProvider(nextModel.provider, nextModel.id);\n\n\t\t// Re-clamp thinking level for new model's capabilities\n\t\tthis.setThinkingLevel(thinkingLevel);\n\t\tthis._resyncToolSurfaceForModel();\n\n\t\tawait this._emitModelSelect(nextModel, currentModel, \"cycle\");\n\n\t\tthis.deps.checkContextWindowUsageWarning();\n\t\tawait this._warnIfManualModelChoiceIsRisky(nextModel);\n\n\t\treturn { model: nextModel, thinkingLevel: this.deps.getThinkingLevel(), isScoped: false };\n\t}\n\n\t/**\n\t * Set thinking level.\n\t * Clamps to model capabilities based on available thinking levels.\n\t * Saves to session and settings only if the level actually changes.\n\t */\n\tsetThinkingLevel(level: ThinkingLevel, options: { persistSettings?: boolean } = {}): void {\n\t\tconst availableLevels = this.getAvailableThinkingLevels();\n\t\tconst effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);\n\n\t\t// Only persist if actually changing\n\t\tconst previousLevel = this.deps.getAgent().state.thinkingLevel;\n\t\tconst isChanging = effectiveLevel !== previousLevel;\n\t\tconst persistSettings = options.persistSettings ?? true;\n\n\t\tthis.deps.getAgent().state.thinkingLevel = effectiveLevel;\n\n\t\tif (isChanging) {\n\t\t\tthis.deps.refreshBaseSystemPrompt();\n\t\t\tthis.deps.getSessionManager().appendThinkingLevelChange(effectiveLevel);\n\t\t\tif (persistSettings && (this.supportsThinking() || effectiveLevel !== \"off\")) {\n\t\t\t\tthis.deps.getSettingsManager().setDefaultThinkingLevel(effectiveLevel);\n\t\t\t}\n\t\t\tthis.deps.emit({ type: \"thinking_level_changed\", level: effectiveLevel });\n\t\t\tvoid this.deps.getExtensionRunner().emit({\n\t\t\t\ttype: \"thinking_level_select\",\n\t\t\t\tlevel: effectiveLevel,\n\t\t\t\tpreviousLevel,\n\t\t\t});\n\t\t}\n\t}\n\n\t/**\n\t * Cycle to next thinking level.\n\t * @returns New level, or undefined if model doesn't support thinking\n\t */\n\tcycleThinkingLevel(): ThinkingLevel | undefined {\n\t\tif (!this.supportsThinking()) return undefined;\n\n\t\tconst levels = this.getAvailableThinkingLevels();\n\t\tconst currentIndex = levels.indexOf(this.deps.getThinkingLevel());\n\t\tconst nextIndex = (currentIndex + 1) % levels.length;\n\t\tconst nextLevel = levels[nextIndex];\n\n\t\tthis.setThinkingLevel(nextLevel);\n\t\treturn nextLevel;\n\t}\n\n\t/**\n\t * Get available thinking levels for current model.\n\t * The provider will clamp to what the specific model supports internally.\n\t */\n\tgetAvailableThinkingLevels(): ThinkingLevel[] {\n\t\tconst model = this.deps.getModel();\n\t\tif (!model) return THINKING_LEVELS;\n\t\treturn getSupportedThinkingLevels(model) as ThinkingLevel[];\n\t}\n\n\t/**\n\t * Check if current model supports thinking/reasoning.\n\t */\n\tsupportsThinking(): boolean {\n\t\treturn !!this.deps.getModel()?.reasoning;\n\t}\n\n\tprivate _getThinkingLevelForModelSwitch(explicitLevel?: ThinkingLevel): ThinkingLevel {\n\t\tif (explicitLevel !== undefined) {\n\t\t\treturn explicitLevel;\n\t\t}\n\t\tif (!this.supportsThinking()) {\n\t\t\treturn this.deps.getSettingsManager().getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;\n\t\t}\n\t\treturn this.deps.getThinkingLevel();\n\t}\n\n\tprivate _clampThinkingLevel(level: ThinkingLevel, _availableLevels: ThinkingLevel[]): ThinkingLevel {\n\t\tconst model = this.deps.getModel();\n\t\treturn model ? (clampThinkingLevel(model, level) as ThinkingLevel) : \"off\";\n\t}\n}\n"]}
|
|
@@ -29,6 +29,8 @@ export interface LocalRuntimeStatus {
|
|
|
29
29
|
ownedStore: OllamaStoreSummary;
|
|
30
30
|
userStore: OllamaStoreSummary;
|
|
31
31
|
activeStore?: OllamaStoreSummary;
|
|
32
|
+
/** Models reported by the configured live server; empty when it is down. */
|
|
33
|
+
serverModels: InstalledLocalModel[];
|
|
32
34
|
}
|
|
33
35
|
export interface InstalledLocalModel {
|
|
34
36
|
name: string;
|
|
@@ -1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4B3D;IAED,IAAI,IAAI;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAK3B;IAED,YAAY,IAAI,MAAM,EAAE,CAUvB;CACD","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport {\n\tcopyFileSync,\n\tcreateWriteStream,\n\ttype Dirent,\n\texistsSync,\n\tlinkSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n} from \"node:fs\";\nimport { homedir, arch as osArch, platform as osPlatform } from \"node:os\";\nimport { delimiter, dirname, join, relative } 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. User-level Ollama stores\n * can be imported into the owned store, but are never silently served or deleted.\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 type OllamaStoreKind = \"pi-owned\" | \"user\" | \"external\";\n\nexport interface OllamaStoreSummary {\n\tkind: OllamaStoreKind;\n\tpath: string;\n\tmodelCount: number;\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. This is pi's canonical Ollama store. */\n\townedModelsDir: string;\n\tuserModelsDir: string;\n\townedStore: OllamaStoreSummary;\n\tuserStore: OllamaStoreSummary;\n\tactiveStore?: OllamaStoreSummary;\n}\n\nexport interface InstalledLocalModel {\n\tname: string;\n\tsizeBytes: number;\n}\n\ninterface OllamaPsModel {\n\tname?: string;\n\tmodel?: string;\n\tsize?: number;\n\tsize_vram?: number;\n}\n\nexport interface OllamaImportResult {\n\tsourceDir: string;\n\ttargetDir: string;\n\tmanifestsImported: number;\n\tmanifestsSkipped: number;\n\tblobsHardlinked: number;\n\tblobsCopied: number;\n\tblobsSkipped: number;\n\tbytesImported: number;\n}\n\nexport interface OllamaModelInfo {\n\tmodelInfo: Record<string, unknown>;\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\tlinkFile?: (source: string, target: string) => void;\n\tcopyFile?: (source: string, target: string) => void;\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 TRANSFORMERS_REQUIRED_MODULES = [\"torch\", \"transformers\", \"huggingface_hub\", \"safetensors\"];\nconst TORCH_PINNED_VERSION = \"2.12.1\";\n\nfunction isCrossDeviceLinkError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"EXDEV\";\n}\n\nfunction fileSizeBytes(path: string): number {\n\ttry {\n\t\treturn statSync(path).size;\n\t} catch {\n\t\treturn 0;\n\t}\n}\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 _linkFile: (source: string, target: string) => void;\n\tprivate readonly _copyFile: (source: string, target: string) => void;\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\tprivate _childModelsDir: string | 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._linkFile = args.deps?.linkFile ?? linkSync;\n\t\tthis._copyFile = args.deps?.copyFile ?? copyFileSync;\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\tuserModelsDir(): string {\n\t\treturn join(this._homeDir, \".ollama\", \"models\");\n\t}\n\n\tprivate _storeSummary(kind: OllamaStoreKind, path: string): OllamaStoreSummary {\n\t\treturn { kind, path, modelCount: this._countStoreModels(path) };\n\t}\n\n\tprivate _countStoreModels(storeDir: string): number {\n\t\treturn this._walkFiles(join(storeDir, \"manifests\")).length;\n\t}\n\n\tprivate _walkFiles(root: string): string[] {\n\t\tif (!this._exists(root)) return [];\n\t\tlet entries: Dirent[];\n\t\ttry {\n\t\t\tentries = readdirSync(root, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\tconst files: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\tconst path = join(root, entry.name);\n\t\t\tif (entry.isDirectory()) files.push(...this._walkFiles(path));\n\t\t\telse if (entry.isFile()) files.push(path);\n\t\t}\n\t\treturn files;\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\treturn (await this._serverModels()).up;\n\t}\n\n\tprivate async _serverModels(): Promise<{ up: boolean; modelCount: number }> {\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\tif (!response.ok) return { up: false, modelCount: 0 };\n\t\t\tconst data = (await response.json().catch(() => ({}))) as { models?: unknown };\n\t\t\treturn { up: true, modelCount: Array.isArray(data.models) ? data.models.length : 0 };\n\t\t} catch {\n\t\t\treturn { up: false, modelCount: 0 };\n\t\t}\n\t}\n\n\tprivate _activeStoreSummary(\n\t\tserverModelCount: number,\n\t\townedStore: OllamaStoreSummary,\n\t\tuserStore: OllamaStoreSummary,\n\t): OllamaStoreSummary {\n\t\tif (this._childModelsDir) {\n\t\t\treturn {\n\t\t\t\tkind: this._childModelsDir === this.ownedModelsDir() ? \"pi-owned\" : \"user\",\n\t\t\t\tpath: this._childModelsDir,\n\t\t\t\tmodelCount: serverModelCount,\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\tserverModelCount > 0 &&\n\t\t\tserverModelCount === ownedStore.modelCount &&\n\t\t\tserverModelCount !== userStore.modelCount\n\t\t) {\n\t\t\treturn { ...ownedStore, modelCount: serverModelCount };\n\t\t}\n\t\tif (\n\t\t\tserverModelCount > 0 &&\n\t\t\tserverModelCount === userStore.modelCount &&\n\t\t\tserverModelCount !== ownedStore.modelCount\n\t\t) {\n\t\t\treturn { ...userStore, modelCount: serverModelCount };\n\t\t}\n\t\treturn { kind: \"external\", path: \"external/unknown\", modelCount: serverModelCount };\n\t}\n\n\tasync detect(): Promise<LocalRuntimeStatus> {\n\t\tconst binary = this._findBinary();\n\t\tconst serverModels = await this._serverModels();\n\t\tconst ownedStore = this._storeSummary(\"pi-owned\", this.ownedModelsDir());\n\t\tconst userStore = this._storeSummary(\"user\", this.userModelsDir());\n\t\tconst activeStore = serverModels.up\n\t\t\t? this._activeStoreSummary(serverModels.modelCount, ownedStore, userStore)\n\t\t\t: undefined;\n\t\treturn {\n\t\t\tbinaryPath: binary?.path,\n\t\t\tbinarySource: binary?.source,\n\t\t\tserverUp: serverModels.up,\n\t\t\tserverUrl: this._baseUrl,\n\t\t\tmanagedByPi: this._child !== undefined && serverModels.up,\n\t\t\townedModelsDir: this.ownedModelsDir(),\n\t\t\tuserModelsDir: this.userModelsDir(),\n\t\t\townedStore,\n\t\t\tuserStore,\n\t\t\tactiveStore,\n\t\t};\n\t}\n\n\timportUserModels(): OllamaImportResult {\n\t\tconst sourceDir = this.userModelsDir();\n\t\tconst targetDir = this.ownedModelsDir();\n\t\tconst result: OllamaImportResult = {\n\t\t\tsourceDir,\n\t\t\ttargetDir,\n\t\t\tmanifestsImported: 0,\n\t\t\tmanifestsSkipped: 0,\n\t\t\tblobsHardlinked: 0,\n\t\t\tblobsCopied: 0,\n\t\t\tblobsSkipped: 0,\n\t\t\tbytesImported: 0,\n\t\t};\n\t\tif (sourceDir === targetDir || !this._exists(sourceDir)) return result;\n\t\tmkdirSync(targetDir, { recursive: true });\n\t\tthis._importManifestFiles(join(sourceDir, \"manifests\"), join(targetDir, \"manifests\"), result);\n\t\tthis._importBlobFiles(join(sourceDir, \"blobs\"), join(targetDir, \"blobs\"), result);\n\t\treturn result;\n\t}\n\n\tprivate _importManifestFiles(sourceRoot: string, targetRoot: string, result: OllamaImportResult): void {\n\t\tfor (const source of this._walkFiles(sourceRoot)) {\n\t\t\tconst target = join(targetRoot, relative(sourceRoot, source));\n\t\t\tif (this._exists(target)) {\n\t\t\t\tresult.manifestsSkipped++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\tthis._copyFile(source, target);\n\t\t\tresult.manifestsImported++;\n\t\t}\n\t}\n\n\tprivate _importBlobFiles(sourceRoot: string, targetRoot: string, result: OllamaImportResult): void {\n\t\tfor (const source of this._walkFiles(sourceRoot)) {\n\t\t\tconst target = join(targetRoot, relative(sourceRoot, source));\n\t\t\tif (this._exists(target)) {\n\t\t\t\tresult.blobsSkipped++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\ttry {\n\t\t\t\tthis._linkFile(source, target);\n\t\t\t\tresult.blobsHardlinked++;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCrossDeviceLinkError(error)) throw error;\n\t\t\t\tthis._copyFile(source, target);\n\t\t\t\tresult.blobsCopied++;\n\t\t\t}\n\t\t\tresult.bytesImported += fileSizeBytes(target);\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\tconst env: NodeJS.ProcessEnv = { ...process.env, OLLAMA_HOST: host, ...extraEnv };\n\t\tthis._childModelsDir = env.OLLAMA_MODELS ?? this.userModelsDir();\n\t\tthis._child = this._spawn(binary.path, [\"serve\"], { env });\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_KEEP_ALIVE: \"30m\",\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_KEEP_ALIVE: \"30m\",\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\tthis._childModelsDir = 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\tasync listResidentModels(): Promise<InstalledLocalModel[]> {\n\t\tconst response = await this._fetch(`${this._baseUrl}/api/ps`, { signal: AbortSignal.timeout(10_000) });\n\t\tif (!response.ok) throw new Error(`ollama ps failed: HTTP ${response.status}`);\n\t\tconst data = (await response.json()) as { models?: OllamaPsModel[] };\n\t\treturn (data.models ?? [])\n\t\t\t.map((model) => ({ name: model.name ?? model.model, sizeBytes: model.size_vram ?? model.size ?? 0 }))\n\t\t\t.filter((model): model is InstalledLocalModel => typeof model.name === \"string\" && model.name.length > 0);\n\t}\n\n\tasync ensureResident(model: string): Promise<{ ok: boolean; error?: string }> {\n\t\treturn this._postKeepAlive(model, \"30m\");\n\t}\n\n\tasync releaseResident(model: string): Promise<{ ok: boolean; error?: string }> {\n\t\treturn this._postKeepAlive(model, 0);\n\t}\n\n\tprivate async _postKeepAlive(model: string, keepAlive: string | number): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/generate`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tprompt: \"\",\n\t\t\t\t\tstream: false,\n\t\t\t\t\tkeep_alive: keepAlive,\n\t\t\t\t\toptions: { num_predict: 0 },\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(60_000),\n\t\t\t});\n\t\t\tif (!response.ok)\n\t\t\t\treturn { ok: false, error: `HTTP ${response.status}: ${await response.text().catch(() => \"\")}` };\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\tasync show(ref: string): Promise<{ ok: true; info: OllamaModelInfo } | { ok: false; error: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/show`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref }),\n\t\t\t\tsignal: AbortSignal.timeout(10_000),\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: `show failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst data = (await response.json()) as { model_info?: Record<string, unknown> };\n\t\t\treturn { ok: true, info: { modelInfo: data.model_info ?? {} } };\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\tasync createFromModelfile(args: {\n\t\tname: string;\n\t\tmodelfile: string;\n\t}): Promise<{ ok: true } | { ok: false; error: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/create`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: args.name, modelfile: args.modelfile, stream: false }),\n\t\t\t\tsignal: AbortSignal.timeout(60_000),\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: `create 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\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\tconst serverUp = await this.serverUp();\n\t\treturn {\n\t\t\truntimeInstalled: this._exists(this.pythonPath) && (serverUp || (await this.runtimeDependenciesInstalled())),\n\t\t\tserverUp,\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\tconst envPython = process.env.PYTHON?.trim();\n\t\tconst envCandidates = envPython ? [{ command: envPython, args: [] }] : [];\n\t\treturn this._platform() === \"win32\"\n\t\t\t? [...envCandidates, { command: \"py\", args: [\"-3\"] }, { command: \"python\", args: [] }]\n\t\t\t: [...envCandidates, { command: \"python\", args: [] }, { command: \"python3\", args: [] }];\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\tprivate async runtimeDependenciesInstalled(): Promise<boolean> {\n\t\tif (!this._exists(this.pythonPath)) return false;\n\t\tconst modules = JSON.stringify(TRANSFORMERS_REQUIRED_MODULES);\n\t\tconst result = await this.runPython([\n\t\t\t\"-c\",\n\t\t\t`import importlib.util, sys; missing = [name for name in ${modules} if importlib.util.find_spec(name) is None]; sys.exit(1 if missing else 0)`,\n\t\t]);\n\t\treturn result.ok;\n\t}\n\n\tprivate readPyvenvHome(): string | undefined {\n\t\tconst pyvenvCfg = join(this.venvDir, \"pyvenv.cfg\");\n\t\tif (!this._exists(pyvenvCfg)) return undefined;\n\t\ttry {\n\t\t\tconst text = readFileSync(pyvenvCfg, \"utf8\");\n\t\t\tconst homeLine = text\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => line.trim())\n\t\t\t\t.find((line) => line.toLowerCase().startsWith(\"home =\"));\n\t\t\treturn homeLine?.slice(homeLine.indexOf(\"=\") + 1).trim() || undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async venvInterpreterCoherent(): Promise<boolean> {\n\t\tconst pyvenvHome = this.readPyvenvHome();\n\t\tif (!pyvenvHome) return false;\n\t\tconst base = await this.runPython([\"-c\", \"import sys; print(sys.base_prefix or sys.prefix)\"]);\n\t\tif (!base.ok) return false;\n\t\tconst basePrefix = base.stdout.trim();\n\t\tif (!basePrefix) return true;\n\t\treturn pyvenvHome === basePrefix || pyvenvHome.startsWith(basePrefix) || basePrefix.startsWith(pyvenvHome);\n\t}\n\n\tprivate async venvHealthy(): Promise<boolean> {\n\t\tconst pip = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\treturn pip.ok && (await this.venvInterpreterCoherent());\n\t}\n\n\tprivate linuxVenvPackageCommand(): string {\n\t\ttry {\n\t\t\tconst osRelease = readFileSync(\"/etc/os-release\", \"utf8\").toLowerCase();\n\t\t\tif (osRelease.includes(\"alpine\")) return \"sudo apk add python3 py3-pip\";\n\t\t\tif (osRelease.includes(\"fedora\") || osRelease.includes(\"rhel\") || osRelease.includes(\"centos\")) {\n\t\t\t\treturn \"sudo dnf install python3\";\n\t\t\t}\n\t\t} catch {\n\t\t\t// fall through to the most common Debian/Ubuntu package split.\n\t\t}\n\t\treturn \"sudo apt install python3-venv\";\n\t}\n\n\tprivate venvInstallHint(): string {\n\t\tif (this._platform() === \"darwin\") return \"install Python from python.org or run: brew install python\";\n\t\tif (this._platform() === \"win32\") return \"install Python 3 from python.org, then run: py -3 -m venv <path>\";\n\t\tif (this._platform() === \"linux\") return this.linuxVenvPackageCommand();\n\t\treturn \"install Python with venv/ensurepip support for this platform\";\n\t}\n\n\tprivate venvFailure(error: string | undefined): { ok: false; error: string } {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `venv-fail: ${sanitizeCommandOutput(error)}. Install Python venv support: ${this.venvInstallHint()}`,\n\t\t};\n\t}\n\n\tprivate async createVenv(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst python = await this.findPython();\n\t\tif (!python) return { ok: false, error: \"python-missing\" };\n\t\tonProgress?.(`creating isolated Python venv at ${this.venvDir}`);\n\t\tconst venv = await this._runCommand(python.command, [...python.args, \"-m\", \"venv\", this.venvDir]);\n\t\tif (!venv.ok) return this.venvFailure(venv.error ?? venv.stderr);\n\t\tif (!this._exists(this.pythonPath)) return this.venvFailure(`${this.pythonPath} was not created`);\n\t\treturn { ok: true };\n\t}\n\n\tprivate async repairExistingVenv(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tif (await this.venvHealthy()) return { ok: true };\n\t\tonProgress?.(\"repairing pi-managed Transformers venv with ensurepip\");\n\t\tconst ensurepip = await this.runPython([\"-m\", \"ensurepip\", \"--upgrade\"], onProgress);\n\t\tif (ensurepip.ok && (await this.venvHealthy())) return { ok: true };\n\t\tonProgress?.(\"recreating pi-managed Transformers venv\");\n\t\trmSync(this.venvDir, { recursive: true, force: true });\n\t\treturn this.createVenv(onProgress);\n\t}\n\n\tprivate async ensurePipAvailable(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst pip = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\tif (pip.ok) return { ok: true };\n\t\tonProgress?.(\"bootstrapping pip inside pi-managed venv\");\n\t\tconst ensurepip = await this.runPython([\"-m\", \"ensurepip\", \"--upgrade\"], onProgress);\n\t\tif (!ensurepip.ok) return this.venvFailure(ensurepip.error ?? ensurepip.stderr);\n\t\tconst verified = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\treturn verified.ok ? { ok: true } : this.venvFailure(verified.error ?? verified.stderr);\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 repaired = await this.repairExistingVenv(onProgress);\n\t\t\tif (!repaired.ok) return repaired;\n\t\t}\n\t\tif (!this._exists(this.pythonPath)) {\n\t\t\tconst created = await this.createVenv(onProgress);\n\t\t\tif (!created.ok) return created;\n\t\t}\n\t\tconst pipReady = await this.ensurePipAvailable(onProgress);\n\t\tif (!pipReady.ok) return pipReady;\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 (!(await this.runtimeDependenciesInstalled())) return { ok: false, error: \"runtime-dependencies-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` python -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"]}
|
|
1
|
+
{"version":3,"file":"local-runtime.d.ts","sourceRoot":"","sources":["../../../src/core/models/local-runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,YAAY,EAAS,MAAM,oBAAoB,CAAC;AAiC9D;;;;;;;;;;GAUG;AAEH,MAAM,MAAM,eAAe,GAAG,UAAU,GAAG,MAAM,GAAG,UAAU,CAAC;AAE/D,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,eAAe,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,kBAAkB;IAClC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,QAAQ,GAAG,MAAM,GAAG,UAAU,CAAC;IAC9C,QAAQ,EAAE,OAAO,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,6FAA6F;IAC7F,WAAW,EAAE,OAAO,CAAC;IACrB,oEAAoE;IACpE,cAAc,EAAE,MAAM,CAAC;IACvB,aAAa,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,kBAAkB,CAAC;IAC/B,SAAS,EAAE,kBAAkB,CAAC;IAC9B,WAAW,CAAC,EAAE,kBAAkB,CAAC;IACjC,4EAA4E;IAC5E,YAAY,EAAE,mBAAmB,EAAE,CAAC;CACpC;AAED,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CAClB;AASD,MAAM,WAAW,kBAAkB;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,gBAAgB,EAAE,MAAM,CAAC;IACzB,eAAe,EAAE,MAAM,CAAC;IACxB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAA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AAK,IAAI,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC,CA4B3D;IAED,IAAI,IAAI;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAK3B;IAED,YAAY,IAAI,MAAM,EAAE,CAUvB;CACD","sourcesContent":["import { type ChildProcess, spawn } from \"node:child_process\";\nimport {\n\tcopyFileSync,\n\tcreateWriteStream,\n\ttype Dirent,\n\texistsSync,\n\tlinkSync,\n\tmkdirSync,\n\treaddirSync,\n\treadFileSync,\n\trmSync,\n\tstatSync,\n} from \"node:fs\";\nimport { homedir, arch as osArch, platform as osPlatform } from \"node:os\";\nimport { delimiter, dirname, join, relative } 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. User-level Ollama stores\n * can be imported into the owned store, but are never silently served or deleted.\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 type OllamaStoreKind = \"pi-owned\" | \"user\" | \"external\";\n\nexport interface OllamaStoreSummary {\n\tkind: OllamaStoreKind;\n\tpath: string;\n\tmodelCount: number;\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. This is pi's canonical Ollama store. */\n\townedModelsDir: string;\n\tuserModelsDir: string;\n\townedStore: OllamaStoreSummary;\n\tuserStore: OllamaStoreSummary;\n\tactiveStore?: OllamaStoreSummary;\n\t/** Models reported by the configured live server; empty when it is down. */\n\tserverModels: InstalledLocalModel[];\n}\n\nexport interface InstalledLocalModel {\n\tname: string;\n\tsizeBytes: number;\n}\n\ninterface OllamaPsModel {\n\tname?: string;\n\tmodel?: string;\n\tsize?: number;\n\tsize_vram?: number;\n}\n\nexport interface OllamaImportResult {\n\tsourceDir: string;\n\ttargetDir: string;\n\tmanifestsImported: number;\n\tmanifestsSkipped: number;\n\tblobsHardlinked: number;\n\tblobsCopied: number;\n\tblobsSkipped: number;\n\tbytesImported: number;\n}\n\nexport interface OllamaModelInfo {\n\tmodelInfo: Record<string, unknown>;\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\tlinkFile?: (source: string, target: string) => void;\n\tcopyFile?: (source: string, target: string) => void;\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 TRANSFORMERS_REQUIRED_MODULES = [\"torch\", \"transformers\", \"huggingface_hub\", \"safetensors\"];\nconst TORCH_PINNED_VERSION = \"2.12.1\";\n\nfunction isCrossDeviceLinkError(error: unknown): boolean {\n\treturn typeof error === \"object\" && error !== null && (error as { code?: unknown }).code === \"EXDEV\";\n}\n\nfunction fileSizeBytes(path: string): number {\n\ttry {\n\t\treturn statSync(path).size;\n\t} catch {\n\t\treturn 0;\n\t}\n}\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 _linkFile: (source: string, target: string) => void;\n\tprivate readonly _copyFile: (source: string, target: string) => void;\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\tprivate _childModelsDir: string | 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._linkFile = args.deps?.linkFile ?? linkSync;\n\t\tthis._copyFile = args.deps?.copyFile ?? copyFileSync;\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\tuserModelsDir(): string {\n\t\treturn join(this._homeDir, \".ollama\", \"models\");\n\t}\n\n\tprivate _storeSummary(kind: OllamaStoreKind, path: string): OllamaStoreSummary {\n\t\treturn { kind, path, modelCount: this._countStoreModels(path) };\n\t}\n\n\tprivate _countStoreModels(storeDir: string): number {\n\t\treturn this._walkFiles(join(storeDir, \"manifests\")).length;\n\t}\n\n\tprivate _walkFiles(root: string): string[] {\n\t\tif (!this._exists(root)) return [];\n\t\tlet entries: Dirent[];\n\t\ttry {\n\t\t\tentries = readdirSync(root, { withFileTypes: true });\n\t\t} catch {\n\t\t\treturn [];\n\t\t}\n\t\tconst files: string[] = [];\n\t\tfor (const entry of entries) {\n\t\t\tconst path = join(root, entry.name);\n\t\t\tif (entry.isDirectory()) files.push(...this._walkFiles(path));\n\t\t\telse if (entry.isFile()) files.push(path);\n\t\t}\n\t\treturn files;\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\treturn (await this._serverModels()).up;\n\t}\n\n\tprivate async _serverModels(): Promise<{ up: boolean; models: InstalledLocalModel[] }> {\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\tif (!response.ok) return { up: false, models: [] };\n\t\t\tconst data = (await response.json().catch(() => ({}))) as {\n\t\t\t\tmodels?: Array<{ name?: unknown; size?: unknown }>;\n\t\t\t};\n\t\t\tconst models = Array.isArray(data.models)\n\t\t\t\t? data.models\n\t\t\t\t\t\t.filter((model): model is { name: string; size?: number } => typeof model.name === \"string\")\n\t\t\t\t\t\t.map((model) => ({ name: model.name, sizeBytes: typeof model.size === \"number\" ? model.size : 0 }))\n\t\t\t\t: [];\n\t\t\treturn { up: true, models };\n\t\t} catch {\n\t\t\treturn { up: false, models: [] };\n\t\t}\n\t}\n\n\tprivate _activeStoreSummary(\n\t\tserverModelCount: number,\n\t\townedStore: OllamaStoreSummary,\n\t\tuserStore: OllamaStoreSummary,\n\t): OllamaStoreSummary {\n\t\tif (this._childModelsDir) {\n\t\t\treturn {\n\t\t\t\tkind: this._childModelsDir === this.ownedModelsDir() ? \"pi-owned\" : \"user\",\n\t\t\t\tpath: this._childModelsDir,\n\t\t\t\tmodelCount: serverModelCount,\n\t\t\t};\n\t\t}\n\t\tif (\n\t\t\tserverModelCount > 0 &&\n\t\t\tserverModelCount === ownedStore.modelCount &&\n\t\t\tserverModelCount !== userStore.modelCount\n\t\t) {\n\t\t\treturn { ...ownedStore, modelCount: serverModelCount };\n\t\t}\n\t\tif (\n\t\t\tserverModelCount > 0 &&\n\t\t\tserverModelCount === userStore.modelCount &&\n\t\t\tserverModelCount !== ownedStore.modelCount\n\t\t) {\n\t\t\treturn { ...userStore, modelCount: serverModelCount };\n\t\t}\n\t\treturn { kind: \"external\", path: \"external/unknown\", modelCount: serverModelCount };\n\t}\n\n\tasync detect(): Promise<LocalRuntimeStatus> {\n\t\tconst binary = this._findBinary();\n\t\tconst serverModels = await this._serverModels();\n\t\tconst ownedStore = this._storeSummary(\"pi-owned\", this.ownedModelsDir());\n\t\tconst userStore = this._storeSummary(\"user\", this.userModelsDir());\n\t\tconst activeStore = serverModels.up\n\t\t\t? this._activeStoreSummary(serverModels.models.length, ownedStore, userStore)\n\t\t\t: undefined;\n\t\treturn {\n\t\t\tbinaryPath: binary?.path,\n\t\t\tbinarySource: binary?.source,\n\t\t\tserverUp: serverModels.up,\n\t\t\tserverUrl: this._baseUrl,\n\t\t\tmanagedByPi: this._child !== undefined && serverModels.up,\n\t\t\townedModelsDir: this.ownedModelsDir(),\n\t\t\tuserModelsDir: this.userModelsDir(),\n\t\t\townedStore,\n\t\t\tuserStore,\n\t\t\tactiveStore,\n\t\t\tserverModels: serverModels.models,\n\t\t};\n\t}\n\n\timportUserModels(): OllamaImportResult {\n\t\tconst sourceDir = this.userModelsDir();\n\t\tconst targetDir = this.ownedModelsDir();\n\t\tconst result: OllamaImportResult = {\n\t\t\tsourceDir,\n\t\t\ttargetDir,\n\t\t\tmanifestsImported: 0,\n\t\t\tmanifestsSkipped: 0,\n\t\t\tblobsHardlinked: 0,\n\t\t\tblobsCopied: 0,\n\t\t\tblobsSkipped: 0,\n\t\t\tbytesImported: 0,\n\t\t};\n\t\tif (sourceDir === targetDir || !this._exists(sourceDir)) return result;\n\t\tmkdirSync(targetDir, { recursive: true });\n\t\tthis._importManifestFiles(join(sourceDir, \"manifests\"), join(targetDir, \"manifests\"), result);\n\t\tthis._importBlobFiles(join(sourceDir, \"blobs\"), join(targetDir, \"blobs\"), result);\n\t\treturn result;\n\t}\n\n\tprivate _importManifestFiles(sourceRoot: string, targetRoot: string, result: OllamaImportResult): void {\n\t\tfor (const source of this._walkFiles(sourceRoot)) {\n\t\t\tconst target = join(targetRoot, relative(sourceRoot, source));\n\t\t\tif (this._exists(target)) {\n\t\t\t\tresult.manifestsSkipped++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\tthis._copyFile(source, target);\n\t\t\tresult.manifestsImported++;\n\t\t}\n\t}\n\n\tprivate _importBlobFiles(sourceRoot: string, targetRoot: string, result: OllamaImportResult): void {\n\t\tfor (const source of this._walkFiles(sourceRoot)) {\n\t\t\tconst target = join(targetRoot, relative(sourceRoot, source));\n\t\t\tif (this._exists(target)) {\n\t\t\t\tresult.blobsSkipped++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tmkdirSync(dirname(target), { recursive: true });\n\t\t\ttry {\n\t\t\t\tthis._linkFile(source, target);\n\t\t\t\tresult.blobsHardlinked++;\n\t\t\t} catch (error) {\n\t\t\t\tif (!isCrossDeviceLinkError(error)) throw error;\n\t\t\t\tthis._copyFile(source, target);\n\t\t\t\tresult.blobsCopied++;\n\t\t\t}\n\t\t\tresult.bytesImported += fileSizeBytes(target);\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\tconst env: NodeJS.ProcessEnv = { ...process.env, OLLAMA_HOST: host, ...extraEnv };\n\t\tthis._childModelsDir = env.OLLAMA_MODELS ?? this.userModelsDir();\n\t\tthis._child = this._spawn(binary.path, [\"serve\"], { env });\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_KEEP_ALIVE: \"30m\",\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_KEEP_ALIVE: \"30m\",\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\tthis._childModelsDir = 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\tasync listResidentModels(): Promise<InstalledLocalModel[]> {\n\t\tconst response = await this._fetch(`${this._baseUrl}/api/ps`, { signal: AbortSignal.timeout(10_000) });\n\t\tif (!response.ok) throw new Error(`ollama ps failed: HTTP ${response.status}`);\n\t\tconst data = (await response.json()) as { models?: OllamaPsModel[] };\n\t\treturn (data.models ?? [])\n\t\t\t.map((model) => ({ name: model.name ?? model.model, sizeBytes: model.size_vram ?? model.size ?? 0 }))\n\t\t\t.filter((model): model is InstalledLocalModel => typeof model.name === \"string\" && model.name.length > 0);\n\t}\n\n\tasync ensureResident(model: string): Promise<{ ok: boolean; error?: string }> {\n\t\treturn this._postKeepAlive(model, \"30m\");\n\t}\n\n\tasync releaseResident(model: string): Promise<{ ok: boolean; error?: string }> {\n\t\treturn this._postKeepAlive(model, 0);\n\t}\n\n\tprivate async _postKeepAlive(model: string, keepAlive: string | number): Promise<{ ok: boolean; error?: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/generate`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tmodel,\n\t\t\t\t\tprompt: \"\",\n\t\t\t\t\tstream: false,\n\t\t\t\t\tkeep_alive: keepAlive,\n\t\t\t\t\toptions: { num_predict: 0 },\n\t\t\t\t}),\n\t\t\t\tsignal: AbortSignal.timeout(60_000),\n\t\t\t});\n\t\t\tif (!response.ok)\n\t\t\t\treturn { ok: false, error: `HTTP ${response.status}: ${await response.text().catch(() => \"\")}` };\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\tasync show(ref: string): Promise<{ ok: true; info: OllamaModelInfo } | { ok: false; error: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/show`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: ref }),\n\t\t\t\tsignal: AbortSignal.timeout(10_000),\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: `show failed: HTTP ${response.status} ${await response.text().catch(() => \"\")}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst data = (await response.json()) as { model_info?: Record<string, unknown> };\n\t\t\treturn { ok: true, info: { modelInfo: data.model_info ?? {} } };\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\tasync createFromModelfile(args: {\n\t\tname: string;\n\t\tmodelfile: string;\n\t}): Promise<{ ok: true } | { ok: false; error: string }> {\n\t\ttry {\n\t\t\tconst response = await this._fetch(`${this._baseUrl}/api/create`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: { \"content-type\": \"application/json\" },\n\t\t\t\tbody: JSON.stringify({ model: args.name, modelfile: args.modelfile, stream: false }),\n\t\t\t\tsignal: AbortSignal.timeout(60_000),\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: `create 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\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\tconst serverUp = await this.serverUp();\n\t\treturn {\n\t\t\truntimeInstalled: this._exists(this.pythonPath) && (serverUp || (await this.runtimeDependenciesInstalled())),\n\t\t\tserverUp,\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\tconst envPython = process.env.PYTHON?.trim();\n\t\tconst envCandidates = envPython ? [{ command: envPython, args: [] }] : [];\n\t\treturn this._platform() === \"win32\"\n\t\t\t? [...envCandidates, { command: \"py\", args: [\"-3\"] }, { command: \"python\", args: [] }]\n\t\t\t: [...envCandidates, { command: \"python\", args: [] }, { command: \"python3\", args: [] }];\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\tprivate async runtimeDependenciesInstalled(): Promise<boolean> {\n\t\tif (!this._exists(this.pythonPath)) return false;\n\t\tconst modules = JSON.stringify(TRANSFORMERS_REQUIRED_MODULES);\n\t\tconst result = await this.runPython([\n\t\t\t\"-c\",\n\t\t\t`import importlib.util, sys; missing = [name for name in ${modules} if importlib.util.find_spec(name) is None]; sys.exit(1 if missing else 0)`,\n\t\t]);\n\t\treturn result.ok;\n\t}\n\n\tprivate readPyvenvHome(): string | undefined {\n\t\tconst pyvenvCfg = join(this.venvDir, \"pyvenv.cfg\");\n\t\tif (!this._exists(pyvenvCfg)) return undefined;\n\t\ttry {\n\t\t\tconst text = readFileSync(pyvenvCfg, \"utf8\");\n\t\t\tconst homeLine = text\n\t\t\t\t.split(/\\r?\\n/)\n\t\t\t\t.map((line) => line.trim())\n\t\t\t\t.find((line) => line.toLowerCase().startsWith(\"home =\"));\n\t\t\treturn homeLine?.slice(homeLine.indexOf(\"=\") + 1).trim() || undefined;\n\t\t} catch {\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate async venvInterpreterCoherent(): Promise<boolean> {\n\t\tconst pyvenvHome = this.readPyvenvHome();\n\t\tif (!pyvenvHome) return false;\n\t\tconst base = await this.runPython([\"-c\", \"import sys; print(sys.base_prefix or sys.prefix)\"]);\n\t\tif (!base.ok) return false;\n\t\tconst basePrefix = base.stdout.trim();\n\t\tif (!basePrefix) return true;\n\t\treturn pyvenvHome === basePrefix || pyvenvHome.startsWith(basePrefix) || basePrefix.startsWith(pyvenvHome);\n\t}\n\n\tprivate async venvHealthy(): Promise<boolean> {\n\t\tconst pip = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\treturn pip.ok && (await this.venvInterpreterCoherent());\n\t}\n\n\tprivate linuxVenvPackageCommand(): string {\n\t\ttry {\n\t\t\tconst osRelease = readFileSync(\"/etc/os-release\", \"utf8\").toLowerCase();\n\t\t\tif (osRelease.includes(\"alpine\")) return \"sudo apk add python3 py3-pip\";\n\t\t\tif (osRelease.includes(\"fedora\") || osRelease.includes(\"rhel\") || osRelease.includes(\"centos\")) {\n\t\t\t\treturn \"sudo dnf install python3\";\n\t\t\t}\n\t\t} catch {\n\t\t\t// fall through to the most common Debian/Ubuntu package split.\n\t\t}\n\t\treturn \"sudo apt install python3-venv\";\n\t}\n\n\tprivate venvInstallHint(): string {\n\t\tif (this._platform() === \"darwin\") return \"install Python from python.org or run: brew install python\";\n\t\tif (this._platform() === \"win32\") return \"install Python 3 from python.org, then run: py -3 -m venv <path>\";\n\t\tif (this._platform() === \"linux\") return this.linuxVenvPackageCommand();\n\t\treturn \"install Python with venv/ensurepip support for this platform\";\n\t}\n\n\tprivate venvFailure(error: string | undefined): { ok: false; error: string } {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `venv-fail: ${sanitizeCommandOutput(error)}. Install Python venv support: ${this.venvInstallHint()}`,\n\t\t};\n\t}\n\n\tprivate async createVenv(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst python = await this.findPython();\n\t\tif (!python) return { ok: false, error: \"python-missing\" };\n\t\tonProgress?.(`creating isolated Python venv at ${this.venvDir}`);\n\t\tconst venv = await this._runCommand(python.command, [...python.args, \"-m\", \"venv\", this.venvDir]);\n\t\tif (!venv.ok) return this.venvFailure(venv.error ?? venv.stderr);\n\t\tif (!this._exists(this.pythonPath)) return this.venvFailure(`${this.pythonPath} was not created`);\n\t\treturn { ok: true };\n\t}\n\n\tprivate async repairExistingVenv(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tif (await this.venvHealthy()) return { ok: true };\n\t\tonProgress?.(\"repairing pi-managed Transformers venv with ensurepip\");\n\t\tconst ensurepip = await this.runPython([\"-m\", \"ensurepip\", \"--upgrade\"], onProgress);\n\t\tif (ensurepip.ok && (await this.venvHealthy())) return { ok: true };\n\t\tonProgress?.(\"recreating pi-managed Transformers venv\");\n\t\trmSync(this.venvDir, { recursive: true, force: true });\n\t\treturn this.createVenv(onProgress);\n\t}\n\n\tprivate async ensurePipAvailable(onProgress?: (status: string) => void): Promise<{ ok: boolean; error?: string }> {\n\t\tconst pip = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\tif (pip.ok) return { ok: true };\n\t\tonProgress?.(\"bootstrapping pip inside pi-managed venv\");\n\t\tconst ensurepip = await this.runPython([\"-m\", \"ensurepip\", \"--upgrade\"], onProgress);\n\t\tif (!ensurepip.ok) return this.venvFailure(ensurepip.error ?? ensurepip.stderr);\n\t\tconst verified = await this.runPython([\"-m\", \"pip\", \"--version\"]);\n\t\treturn verified.ok ? { ok: true } : this.venvFailure(verified.error ?? verified.stderr);\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 repaired = await this.repairExistingVenv(onProgress);\n\t\t\tif (!repaired.ok) return repaired;\n\t\t}\n\t\tif (!this._exists(this.pythonPath)) {\n\t\t\tconst created = await this.createVenv(onProgress);\n\t\t\tif (!created.ok) return created;\n\t\t}\n\t\tconst pipReady = await this.ensurePipAvailable(onProgress);\n\t\tif (!pipReady.ok) return pipReady;\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 (!(await this.runtimeDependenciesInstalled())) return { ok: false, error: \"runtime-dependencies-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` python -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"]}
|
|
@@ -225,12 +225,17 @@ export class OllamaRuntime {
|
|
|
225
225
|
signal: AbortSignal.timeout(HEALTH_TIMEOUT_MS),
|
|
226
226
|
});
|
|
227
227
|
if (!response.ok)
|
|
228
|
-
return { up: false,
|
|
228
|
+
return { up: false, models: [] };
|
|
229
229
|
const data = (await response.json().catch(() => ({})));
|
|
230
|
-
|
|
230
|
+
const models = Array.isArray(data.models)
|
|
231
|
+
? data.models
|
|
232
|
+
.filter((model) => typeof model.name === "string")
|
|
233
|
+
.map((model) => ({ name: model.name, sizeBytes: typeof model.size === "number" ? model.size : 0 }))
|
|
234
|
+
: [];
|
|
235
|
+
return { up: true, models };
|
|
231
236
|
}
|
|
232
237
|
catch {
|
|
233
|
-
return { up: false,
|
|
238
|
+
return { up: false, models: [] };
|
|
234
239
|
}
|
|
235
240
|
}
|
|
236
241
|
_activeStoreSummary(serverModelCount, ownedStore, userStore) {
|
|
@@ -259,7 +264,7 @@ export class OllamaRuntime {
|
|
|
259
264
|
const ownedStore = this._storeSummary("pi-owned", this.ownedModelsDir());
|
|
260
265
|
const userStore = this._storeSummary("user", this.userModelsDir());
|
|
261
266
|
const activeStore = serverModels.up
|
|
262
|
-
? this._activeStoreSummary(serverModels.
|
|
267
|
+
? this._activeStoreSummary(serverModels.models.length, ownedStore, userStore)
|
|
263
268
|
: undefined;
|
|
264
269
|
return {
|
|
265
270
|
binaryPath: binary?.path,
|
|
@@ -272,6 +277,7 @@ export class OllamaRuntime {
|
|
|
272
277
|
ownedStore,
|
|
273
278
|
userStore,
|
|
274
279
|
activeStore,
|
|
280
|
+
serverModels: serverModels.models,
|
|
275
281
|
};
|
|
276
282
|
}
|
|
277
283
|
importUserModels() {
|