@caupulican/pi-adaptative 0.81.2 → 0.81.3
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 +15 -0
- package/dist/core/agent-session.d.ts +1 -23
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +117 -131
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +2 -0
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +3 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/billing-failover-controller.d.ts +31 -0
- package/dist/core/billing-failover-controller.d.ts.map +1 -0
- package/dist/core/billing-failover-controller.js +72 -0
- package/dist/core/billing-failover-controller.js.map +1 -0
- package/dist/core/billing-failover.d.ts +25 -0
- package/dist/core/billing-failover.d.ts.map +1 -0
- package/dist/core/billing-failover.js +21 -0
- package/dist/core/billing-failover.js.map +1 -0
- package/dist/core/context-pipeline.d.ts +1 -0
- package/dist/core/context-pipeline.d.ts.map +1 -1
- package/dist/core/context-pipeline.js +51 -14
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/model-router/config-diagnostics.d.ts +1 -1
- package/dist/core/model-router/config-diagnostics.d.ts.map +1 -1
- package/dist/core/model-router/config-diagnostics.js +29 -1
- package/dist/core/model-router/config-diagnostics.js.map +1 -1
- package/dist/core/model-router/fitness-gate.d.ts +23 -0
- package/dist/core/model-router/fitness-gate.d.ts.map +1 -0
- package/dist/core/model-router/fitness-gate.js +33 -0
- package/dist/core/model-router/fitness-gate.js.map +1 -0
- package/dist/core/model-router/status.d.ts +25 -1
- package/dist/core/model-router/status.d.ts.map +1 -1
- package/dist/core/model-router/status.js +27 -4
- package/dist/core/model-router/status.js.map +1 -1
- package/dist/core/model-router-controller.d.ts +10 -1
- package/dist/core/model-router-controller.d.ts.map +1 -1
- package/dist/core/model-router-controller.js +108 -27
- package/dist/core/model-router-controller.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +16 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +88 -1
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +44 -0
- package/dist/core/scout-controller.d.ts.map +1 -0
- package/dist/core/scout-controller.js +165 -0
- package/dist/core/scout-controller.js.map +1 -0
- package/dist/core/settings-manager.d.ts +16 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +35 -3
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/context-scout.d.ts +19 -0
- package/dist/core/tools/context-scout.d.ts.map +1 -0
- package/dist/core/tools/context-scout.js +47 -0
- package/dist/core/tools/context-scout.js.map +1 -0
- package/dist/core/tools/index.d.ts +1 -0
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -0
- package/dist/core/tools/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -1
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +77 -7
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/local-model-commands.d.ts +5 -2
- package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
- package/dist/modes/interactive/local-model-commands.js +115 -1
- package/dist/modes/interactive/local-model-commands.js.map +1 -1
- package/docs/index.md +1 -0
- package/docs/providers.md +2 -0
- package/docs/scout.md +71 -0
- package/docs/settings.md +14 -3
- 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/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/examples/sdk/12-full-control.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
* fitness-role-assignment), which keep exercising interactive-mode's thin
|
|
11
11
|
* wrappers unchanged.
|
|
12
12
|
*/
|
|
13
|
-
import type
|
|
13
|
+
import { type Component, Container, type TUI } from "@caupulican/pi-tui";
|
|
14
14
|
import type { AgentSession } from "../../core/agent-session.ts";
|
|
15
|
+
import type { ModelRegistry } from "../../core/model-registry.ts";
|
|
15
16
|
import type { OllamaRuntime } from "../../core/models/local-runtime.ts";
|
|
16
17
|
import type { SettingsManager } from "../../core/settings-manager.ts";
|
|
17
18
|
import { type FitnessRole } from "./components/fitness-role-selector.ts";
|
|
@@ -26,7 +27,9 @@ export interface AssignRoleHost {
|
|
|
26
27
|
}
|
|
27
28
|
/** Seam for the fitness probe + role-selector flow — matches the fitness-probe-gate test. */
|
|
28
29
|
export interface RunFitnessHost {
|
|
29
|
-
readonly session: Pick<AgentSession, "runModelFitness"
|
|
30
|
+
readonly session: Pick<AgentSession, "runModelFitness"> & {
|
|
31
|
+
modelRegistry?: ModelRegistry;
|
|
32
|
+
};
|
|
30
33
|
readonly settingsManager: SettingsManager;
|
|
31
34
|
readonly chatContainer: Container;
|
|
32
35
|
readonly ui: TUI;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-model-commands.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/local-model-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAGpE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAIhE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAGxE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,KAAK,WAAW,EAAgC,MAA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AO,CAAC,IAAI,CAAC,CAwD/F;AAED,wBAAsB,iBAAiB,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,OAAO,CAAC,CAgB9E;AAED,wBAAsB,eAAe,CAAC,IAAI,EAAE,cAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BzE;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,cAAc,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CA8BrH;AAED,wBAAsB,gBAAgB,CAAC,IAAI,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,EAAE,SAAS,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAqC3G;AAED,iGAAiG;AACjG,kGAA4F;AAC5F,wBAAgB,2BAA2B,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAiBtE;AAED,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,cAAc,GAAG,IAAI,CAmBnE;AAED;kGACkG;AAClG,wBAAsB,mBAAmB,CACxC,IAAI,EAAE,cAAc,EACpB,QAAQ,EAAE,MAAM,EAChB,aAAa,CAAC,EAAE,WAAW,GACzB,OAAO,CAAC,IAAI,CAAC,CAuCf;AAED,yFAAyF;AACzF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CAgCjG","sourcesContent":["/**\n * `/models` local-model lifecycle and `/fitness` probe/role-assignment flows\n * extracted from interactive-mode.\n *\n * `/models` is a USER-invoked local-model manager (list/add/remove/stop, never a\n * model-invokable tool); the fitness helpers probe a model on the current host\n * and land a shaped role. The server/selector flows share a `LocalModelHost`\n * seam, while `runFitnessAndAssign`/`assignFitnessRole` take narrow host shapes\n * matching their prototype-driven behaviour tests (fitness-probe-gate,\n * fitness-role-assignment), which keep exercising interactive-mode's thin\n * wrappers unchanged.\n */\n\nimport type { Component, Container, TUI } from \"@caupulican/pi-tui\";\nimport { Spacer, Text } from \"@caupulican/pi-tui\";\nimport { getAgentDir } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport { DEFAULT_MODEL_SUGGESTIONS } from \"../../core/models/default-model-suggestions.ts\";\nimport { FitnessStore } from \"../../core/models/fitness-store.ts\";\nimport { registerLocalModel, unregisterLocalModel } from \"../../core/models/local-registration.ts\";\nimport type { OllamaRuntime } from \"../../core/models/local-runtime.ts\";\nimport { matchesInstalledLocalModel, normalizeModelSource } from \"../../core/models/model-ref.ts\";\nimport { formatModelFitnessReport, isProbeAllFailed } from \"../../core/research/model-fitness.ts\";\nimport type { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { type FitnessRole, FitnessRoleSelectorComponent } from \"./components/fitness-role-selector.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { ModelSuggestionSelectorComponent } from \"./components/model-suggestion-selector.ts\";\n\ntype SelectorFactory = (done: () => void) => { component: Component; focus: Component };\n\n/** Narrow seam for persisting a probed model's role — matches the fitness-role test. */\nexport interface AssignRoleHost {\n\treadonly settingsManager: SettingsManager;\n\tshowStatus(message: string): void;\n}\n\n/** Seam for the fitness probe + role-selector flow — matches the fitness-probe-gate test. */\nexport interface RunFitnessHost {\n\treadonly session: Pick<AgentSession, \"runModelFitness\">;\n\treadonly settingsManager: SettingsManager;\n\treadonly chatContainer: Container;\n\treadonly ui: TUI;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/** Full seam for the `/models` server/selector flows. */\nexport interface LocalModelHost {\n\treadonly localRuntime: OllamaRuntime;\n\treadonly session: AgentSession;\n\treadonly settingsManager: SettingsManager;\n\treadonly ui: TUI;\n\treadonly chatContainer: Container;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/**\n * /models — USER-invoked local model lifecycle (never a model-invokable tool):\n * list/add/remove/stop per local-model-lifecycle-design.md. Removal is explicit-only with\n * full disclosure; a pasted install command is parsed for its ref, never executed.\n */\nexport async function handleModelsCommand(host: LocalModelHost, argsText: string): Promise<void> {\n\tconst [action = \"list\", ...rest] = argsText.split(/\\s+/).filter(Boolean);\n\ttry {\n\t\tif (action === \"suggest\" || action === \"suggestions\") {\n\t\t\tshowModelSuggestionSelector(host);\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"stop\") {\n\t\t\tconst stopped = host.localRuntime.stop();\n\t\t\thost.showStatus(\n\t\t\t\tstopped.stopped\n\t\t\t\t\t? \"Pi-managed local model server stopped (models remain installed).\"\n\t\t\t\t\t: \"No pi-managed server running (a system server, if any, is not pi's to stop).\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"add\") {\n\t\t\tconst rawRef = rest.join(\" \");\n\t\t\tif (!rawRef) {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t\"Usage: /models add <ollama-tag | hf.co/org/repo[:quant] | huggingface URL | pasted install command>\",\n\t\t\t\t);\n\t\t\t\thost.showStatus(\"Or start from a validated suggestion: /models suggest\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst source = normalizeModelSource(rawRef);\n\t\t\tif (source.type === \"rejected\") {\n\t\t\t\thost.showStatus(`Not added: ${source.reason}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (source.type === \"api\") {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t`${source.ref} is an API model — nothing to install. Configure auth for the provider, then probe it with /fitness ${source.ref}.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait addLocalModel(host, source.pullRef);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"remove\") {\n\t\t\tconst ref = rest[0];\n\t\t\tconst confirmed = rest[1] === \"confirm\";\n\t\t\tif (!ref) {\n\t\t\t\thost.showStatus(\"Usage: /models remove <ref> confirm\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait removeLocalModel(host, ref, confirmed);\n\t\t\treturn;\n\t\t}\n\n\t\tawait listLocalModels(host);\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\nexport async function ensureLocalServer(host: LocalModelHost): Promise<boolean> {\n\tconst status = await host.localRuntime.detect();\n\tif (status.serverUp) return true;\n\tif (!status.binaryPath) {\n\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\treturn false;\n\t}\n\thost.showStatus(\n\t\t`Starting local model server (${status.binarySource} binary, owned storage: ${status.ownedModelsDir})…`,\n\t);\n\tconst started = await host.localRuntime.start();\n\tif (!started.started) {\n\t\thost.showStatus(`Could not start the local server: ${started.reason}`);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport async function listLocalModels(host: LocalModelHost): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\tif (!status.binaryPath) {\n\t\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\t\treturn;\n\t\t}\n\t\thost.showStatus(\n\t\t\t`Local server not running (binary: ${status.binarySource}). /models add starts it on demand; /fitness probes registered models.`,\n\t\t);\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst fitness = FitnessStore.forAgentDir(getAgentDir()).getForHost();\n\tconst lines = [\n\t\t`Local models (${status.managedByPi ? `pi-managed server, storage: ${status.ownedModelsDir}` : \"system server — storage owned by the system daemon\"}):`,\n\t\t...(models.length === 0\n\t\t\t? [\" (none installed — /models add <ref>, or /models suggest for a validated roster)\"]\n\t\t\t: []),\n\t\t...models.map((model) => {\n\t\t\tconst report = fitness.find((entry) => entry.model === `ollama/${model.name}`);\n\t\t\tconst gb = (model.sizeBytes / 1e9).toFixed(2);\n\t\t\tconst probe = report\n\t\t\t\t? `probed ${report.at.slice(0, 10)}: digest ${report.report.digest?.succeeded ?? \"?\"}/${report.report.digest?.total ?? \"?\"}, tool-calls ${report.report.toolCall.succeeded}/${report.report.toolCall.total}${report.report.tokensPerSecond ? `, ~${report.report.tokensPerSecond} tok/s` : \"\"}`\n\t\t\t\t: `unprobed — run /fitness ollama/${model.name}`;\n\t\t\treturn ` - ${model.name} (${gb} GB) · ${probe}`;\n\t\t}),\n\t\t\"Commands: /models add <ref> · /models remove <ref> confirm · /models stop\",\n\t];\n\tfor (const line of lines) host.showStatus(line);\n}\n\nexport async function addLocalModel(host: LocalModelHost, pullRef: string, preselectRole?: FitnessRole): Promise<void> {\n\tif (!(await ensureLocalServer(host))) return;\n\thost.showStatus(`Pulling ${pullRef}… (weights land in the server's model storage)`);\n\tlet lastShown = 0;\n\tconst pulled = await host.localRuntime.pull(pullRef, (progress) => {\n\t\tconst now = Date.now();\n\t\tif (now - lastShown > 2000) {\n\t\t\tlastShown = now;\n\t\t\thost.showStatus(` ${pullRef}: ${progress}`);\n\t\t}\n\t});\n\tif (!pulled.ok) {\n\t\thost.showStatus(`Pull failed: ${pulled.error}`);\n\t\treturn;\n\t}\n\tconst registration = registerLocalModel({\n\t\tagentDir: getAgentDir(),\n\t\tref: pullRef,\n\t\tbaseUrl: host.localRuntime.baseUrl,\n\t});\n\tif (!registration.ok) {\n\t\thost.showStatus(`Pulled, but not auto-registered: ${registration.reason}`);\n\t\tif (registration.manualSnippet) {\n\t\t\thost.showStatus(`Add this to ${registration.modelsJsonPath} yourself:\\n${registration.manualSnippet}`);\n\t\t}\n\t\treturn;\n\t}\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${pullRef} installed and registered as ollama/${pullRef}. Probing fitness…`);\n\tawait runFitnessAndAssign(host, `ollama/${pullRef}`, preselectRole);\n}\n\nexport async function removeLocalModel(host: LocalModelHost, ref: string, confirmed: boolean): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\thost.showStatus(\"Local server not running — start it (any /models action) before removing.\");\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst target = models.find((model) => matchesInstalledLocalModel(ref, model.name));\n\tif (!target) {\n\t\thost.showStatus(\n\t\t\t`${ref} is not installed. Installed: ${models.map((model) => model.name).join(\", \") || \"(none)\"}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!confirmed) {\n\t\t// EXPLICIT USER ACTION ONLY: full disclosure, then require the confirm token.\n\t\tconst gb = (target.sizeBytes / 1e9).toFixed(2);\n\t\thost.showStatus(\n\t\t\t[\n\t\t\t\t`Removing ${ref} will delete:`,\n\t\t\t\t` - model weights (${gb} GB) from ${status.managedByPi ? status.ownedModelsDir : \"the system server's storage\"}`,\n\t\t\t\t` - the ollama/${ref} entry in models.json`,\n\t\t\t\t` - its cached fitness report for this host`,\n\t\t\t\t`Run: /models remove ${ref} confirm`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn;\n\t}\n\tconst removed = await host.localRuntime.remove(ref);\n\tif (!removed.ok) {\n\t\thost.showStatus(`Remove failed: ${removed.error}`);\n\t\treturn;\n\t}\n\tunregisterLocalModel({ agentDir: getAgentDir(), ref });\n\tFitnessStore.forAgentDir(getAgentDir()).remove(`ollama/${ref}`);\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${ref} removed: weights deleted, registration and fitness report dropped.`);\n}\n\n/** /fitness with no args: pick a model from the configured registry, probe it, assign a role. */\n/** Pick a validated suggestion → install it → probe on this host → land its shaped role. */\nexport function showModelSuggestionSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSuggestionSelectorComponent(\n\t\t\tDEFAULT_MODEL_SUGGESTIONS,\n\t\t\tasync (suggestion) => {\n\t\t\t\tdone();\n\t\t\t\t// The shaped role rides along so the post-probe selector lands on it pre-selected;\n\t\t\t\t// non-tool-callers carry curator/judge/none, never executor, so this can't footgun.\n\t\t\t\tawait addLocalModel(host, suggestion.pullRef, suggestion.assignRole);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\nexport function showFitnessModelSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSelectorComponent(\n\t\t\thost.ui,\n\t\t\thost.session.model,\n\t\t\thost.settingsManager,\n\t\t\thost.session.modelRegistry,\n\t\t\thost.session.scopedModels,\n\t\t\tasync (model) => {\n\t\t\t\tdone();\n\t\t\t\tawait runFitnessAndAssign(host, `${model.provider}/${model.id}`);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Probe a model's fitness, show the report, then offer one-step role assignment. When the model\n * came from a validated suggestion, `preselectRole` lands its shaped role already highlighted. */\nexport async function runFitnessAndAssign(\n\thost: RunFitnessHost,\n\tmodelRef: string,\n\tpreselectRole?: FitnessRole,\n): Promise<void> {\n\thost.showStatus(`Model fitness probe running on ${modelRef}… (6 surfaces; local models may take a few minutes)`);\n\ttry {\n\t\tconst outcome = await host.session.runModelFitness({ model: modelRef });\n\t\tif (!outcome.started) {\n\t\t\thost.showStatus(`Model fitness skipped: ${outcome.skipReason}`);\n\t\t\treturn;\n\t\t}\n\t\thost.chatContainer.addChild(new Spacer(1));\n\t\thost.chatContainer.addChild(new Text(formatModelFitnessReport(outcome.model, outcome.report), 1, 0));\n\t\thost.ui.requestRender();\n\t\t// Validate-before-load: zero successes on every probed surface means the model cannot\n\t\t// drive any of the harness's subagent contracts on this host — refuse adoption instead\n\t\t// of landing a role selector the user might reflexively confirm (this is the reported\n\t\t// bug: a 0/3-everywhere model still got set as judge model and saved to Model Router).\n\t\tif (isProbeAllFailed(outcome.report)) {\n\t\t\thost.showStatus(\n\t\t\t\t`${outcome.model} failed the fitness probe on all surfaces — not configured. Use /model to set it manually if you accept the risk.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\thost.showSelector((done) => {\n\t\t\tconst selector = new FitnessRoleSelectorComponent(\n\t\t\t\toutcome.model,\n\t\t\t\t(role) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tassignFitnessRole(host, outcome.model, role);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\thost.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tpreselectRole,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/** Persist a role assignment from the post-probe selector into the matching settings. */\nexport function assignFitnessRole(host: AssignRoleHost, modelRef: string, role: FitnessRole): void {\n\tif (role === \"none\") {\n\t\thost.showStatus(`Fitness result for ${modelRef} saved. Assign a role later from /settings.`);\n\t\treturn;\n\t}\n\tif (role === \"curator\") {\n\t\tconst current = host.settingsManager.getContextCurationSettings();\n\t\thost.settingsManager.setContextCurationSettings({ ...current, enabled: true, model: modelRef });\n\t\thost.showStatus(`Context curation enabled with ${modelRef} as the curator.`);\n\t\treturn;\n\t}\n\tif (role === \"executor\") {\n\t\tconst router = host.settingsManager.getModelRouterSettings();\n\t\thost.settingsManager.setModelRouterSettings({ ...router, executorModel: modelRef });\n\t\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\t\thost.showStatus(`${modelRef} set as the toolkit executor (direct Level-0 hits route to it).${hint}`);\n\t\treturn;\n\t}\n\tconst router = host.settingsManager.getModelRouterSettings();\n\tconst field =\n\t\trole === \"router-cheap\"\n\t\t\t? \"cheapModel\"\n\t\t\t: role === \"router-medium\"\n\t\t\t\t? \"mediumModel\"\n\t\t\t\t: role === \"router-expensive\"\n\t\t\t\t\t? \"expensiveModel\"\n\t\t\t\t\t: role === \"judge\"\n\t\t\t\t\t\t? \"judgeModel\"\n\t\t\t\t\t\t: \"learningModel\";\n\thost.settingsManager.setModelRouterSettings({ ...router, [field]: modelRef });\n\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\thost.showStatus(`${modelRef} set as ${role.replace(\"router-\", \"router \")} model.${hint}`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-model-commands.d.ts","sourceRoot":"","sources":["../../../src/modes/interactive/local-model-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAIH,OAAO,EACN,KAAK,SAAS,EACd,SAAS,EAMT,KAAK,GAAG,EACR,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAKlE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oCAAoC,CAAC;AAGxE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEtE,OAAO,EAAE,KAAK,WAAW,EAAgC,MAAM,uCAAuC,CAAC;AAKvG,KAAK,eAAe,GAAG,CAAC,IAAI,EAAE,MAAM,IAAI,KAAK;IAAE,SAAS,EAAE,SAAS,CAAC;IAAC,KAAK,EAAE,SAAS,CAAA;CAAE,CAAC;AAoCxF,0FAAwF;AACxF,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,eAAe,EAAE,eAAe,CAAC;IAC1C,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CAClC;AAED,+FAA6F;AAC7F,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,iBAAiB,CAAC,GAAG;QAAE,aAAa,CAAC,EAAE,aAAa,CAAA;KAAE,CAAC;IAC5F,QAAQ,CAAC,eAAe,EAAE,eAAe,CAAC;IAC1C,QAAQ,CAAC,aAAa,EAAE,SAAS,CAAC;IAClC,QAAQ,CAAC,EAAE,EAAE,GAAG,CAAC;IACjB,UAAU,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAClC,SAAS,CAAC,OAAO,EAAE,MAAM,GAA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kGACkG;AAClG,wBAAsB,mBAAmB,CACxC,IAAI,EAAE,cAAc,EACpB,QAAQ,EAAE,MAAM,EAChB,aAAa,CAAC,EAAE,WAAW,GACzB,OAAO,CAAC,IAAI,CAAC,CAwCf;AAED,yFAAyF;AACzF,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,GAAG,IAAI,CAgCjG","sourcesContent":["/**\n * `/models` local-model lifecycle and `/fitness` probe/role-assignment flows\n * extracted from interactive-mode.\n *\n * `/models` is a USER-invoked local-model manager (list/add/remove/stop, never a\n * model-invokable tool); the fitness helpers probe a model on the current host\n * and land a shaped role. The server/selector flows share a `LocalModelHost`\n * seam, while `runFitnessAndAssign`/`assignFitnessRole` take narrow host shapes\n * matching their prototype-driven behaviour tests (fitness-probe-gate,\n * fitness-role-assignment), which keep exercising interactive-mode's thin\n * wrappers unchanged.\n */\n\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getSupportedThinkingLevels } from \"@caupulican/pi-ai\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype SelectItem,\n\tSelectList,\n\ttype SelectListLayoutOptions,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@caupulican/pi-tui\";\nimport { getAgentDir } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport { resolveCliModel } from \"../../core/model-resolver.ts\";\nimport { DEFAULT_MODEL_SUGGESTIONS } from \"../../core/models/default-model-suggestions.ts\";\nimport { FitnessStore } from \"../../core/models/fitness-store.ts\";\nimport { registerLocalModel, unregisterLocalModel } from \"../../core/models/local-registration.ts\";\nimport type { OllamaRuntime } from \"../../core/models/local-runtime.ts\";\nimport { matchesInstalledLocalModel, normalizeModelSource } from \"../../core/models/model-ref.ts\";\nimport { formatModelFitnessReport, isProbeAllFailed } from \"../../core/research/model-fitness.ts\";\nimport type { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { type FitnessRole, FitnessRoleSelectorComponent } from \"./components/fitness-role-selector.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { ModelSuggestionSelectorComponent } from \"./components/model-suggestion-selector.ts\";\nimport { getSelectListTheme } from \"./theme/theme.ts\";\n\ntype SelectorFactory = (done: () => void) => { component: Component; focus: Component };\n\nconst MODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst MODEL_ROUTER_THINKING_INHERIT_VALUE = \"__inherit_model_router_thinking__\";\nconst MODEL_ROUTER_THINKING_INHERIT_LABEL = \"(inherit)\";\n\nconst THINKING_LEVEL_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Maximum reasoning (~32k tokens)\",\n};\n\nconst MODEL_ROUTER_THINKING_FALLBACK_LEVELS: readonly ThinkingLevel[] = [\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n];\n\ntype RouterThinkingLevel = ThinkingLevel | typeof MODEL_ROUTER_THINKING_INHERIT_VALUE;\ntype ModelRouterThinkingField =\n\t| \"cheapThinking\"\n\t| \"mediumThinking\"\n\t| \"expensiveThinking\"\n\t| \"executorThinking\"\n\t| \"judgeThinking\";\n\n/** Narrow seam for persisting a probed model's role — matches the fitness-role test. */\nexport interface AssignRoleHost {\n\treadonly settingsManager: SettingsManager;\n\tshowStatus(message: string): void;\n}\n\n/** Seam for the fitness probe + role-selector flow — matches the fitness-probe-gate test. */\nexport interface RunFitnessHost {\n\treadonly session: Pick<AgentSession, \"runModelFitness\"> & { modelRegistry?: ModelRegistry };\n\treadonly settingsManager: SettingsManager;\n\treadonly chatContainer: Container;\n\treadonly ui: TUI;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/** Full seam for the `/models` server/selector flows. */\nexport interface LocalModelHost {\n\treadonly localRuntime: OllamaRuntime;\n\treadonly session: AgentSession;\n\treadonly settingsManager: SettingsManager;\n\treadonly ui: TUI;\n\treadonly chatContainer: Container;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\nclass ModelRouterThinkingSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentLevel: RouterThinkingLevel,\n\t\tavailableLevels: ThinkingLevel[],\n\t\tonSelect: (level: RouterThinkingLevel) => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst thinkingOptions: SelectItem[] = [\n\t\t\t{\n\t\t\t\tvalue: MODEL_ROUTER_THINKING_INHERIT_VALUE,\n\t\t\t\tlabel: MODEL_ROUTER_THINKING_INHERIT_LABEL,\n\t\t\t\tdescription: \"Use current session default for this tier.\",\n\t\t\t},\n\t\t\t...availableLevels.map((level) => ({\n\t\t\t\tvalue: level,\n\t\t\t\tlabel: level,\n\t\t\t\tdescription: THINKING_LEVEL_DESCRIPTIONS[level],\n\t\t\t})),\n\t\t];\n\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.selectList = new SelectList(\n\t\t\tthinkingOptions,\n\t\t\tthinkingOptions.length,\n\t\t\tgetSelectListTheme(),\n\t\t\tMODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\tconst index = thinkingOptions.findIndex((item) => item.value === currentLevel);\n\t\tif (index !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(index);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as RouterThinkingLevel);\n\t\t};\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\t\tthis.addChild(new DynamicBorder());\n\t}\n}\n/**\n * /models — USER-invoked local model lifecycle (never a model-invokable tool):\n * list/add/remove/stop per local-model-lifecycle-design.md. Removal is explicit-only with\n * full disclosure; a pasted install command is parsed for its ref, never executed.\n */\nexport async function handleModelsCommand(host: LocalModelHost, argsText: string): Promise<void> {\n\tconst [action = \"list\", ...rest] = argsText.split(/\\s+/).filter(Boolean);\n\ttry {\n\t\tif (action === \"suggest\" || action === \"suggestions\") {\n\t\t\tshowModelSuggestionSelector(host);\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"stop\") {\n\t\t\tconst stopped = host.localRuntime.stop();\n\t\t\thost.showStatus(\n\t\t\t\tstopped.stopped\n\t\t\t\t\t? \"Pi-managed local model server stopped (models remain installed).\"\n\t\t\t\t\t: \"No pi-managed server running (a system server, if any, is not pi's to stop).\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"add\") {\n\t\t\tconst rawRef = rest.join(\" \");\n\t\t\tif (!rawRef) {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t\"Usage: /models add <ollama-tag | hf.co/org/repo[:quant] | huggingface URL | pasted install command>\",\n\t\t\t\t);\n\t\t\t\thost.showStatus(\"Or start from a validated suggestion: /models suggest\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst source = normalizeModelSource(rawRef);\n\t\t\tif (source.type === \"rejected\") {\n\t\t\t\thost.showStatus(`Not added: ${source.reason}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (source.type === \"api\") {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t`${source.ref} is an API model — nothing to install. Configure auth for the provider, then probe it with /fitness ${source.ref}.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait addLocalModel(host, source.pullRef);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"remove\") {\n\t\t\tconst ref = rest[0];\n\t\t\tconst confirmed = rest[1] === \"confirm\";\n\t\t\tif (!ref) {\n\t\t\t\thost.showStatus(\"Usage: /models remove <ref> confirm\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait removeLocalModel(host, ref, confirmed);\n\t\t\treturn;\n\t\t}\n\n\t\tawait listLocalModels(host);\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\nexport async function ensureLocalServer(host: LocalModelHost): Promise<boolean> {\n\tconst status = await host.localRuntime.detect();\n\tif (status.serverUp) return true;\n\tif (!status.binaryPath) {\n\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\treturn false;\n\t}\n\thost.showStatus(\n\t\t`Starting local model server (${status.binarySource} binary, owned storage: ${status.ownedModelsDir})…`,\n\t);\n\tconst started = await host.localRuntime.start();\n\tif (!started.started) {\n\t\thost.showStatus(`Could not start the local server: ${started.reason}`);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport async function listLocalModels(host: LocalModelHost): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\tif (!status.binaryPath) {\n\t\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\t\treturn;\n\t\t}\n\t\thost.showStatus(\n\t\t\t`Local server not running (binary: ${status.binarySource}). /models add starts it on demand; /fitness probes registered models.`,\n\t\t);\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst fitness = FitnessStore.forAgentDir(getAgentDir()).getForHost();\n\tconst lines = [\n\t\t`Local models (${status.managedByPi ? `pi-managed server, storage: ${status.ownedModelsDir}` : \"system server — storage owned by the system daemon\"}):`,\n\t\t...(models.length === 0\n\t\t\t? [\" (none installed — /models add <ref>, or /models suggest for a validated roster)\"]\n\t\t\t: []),\n\t\t...models.map((model) => {\n\t\t\tconst report = fitness.find((entry) => entry.model === `ollama/${model.name}`);\n\t\t\tconst gb = (model.sizeBytes / 1e9).toFixed(2);\n\t\t\tconst probe = report\n\t\t\t\t? `probed ${report.at.slice(0, 10)}: digest ${report.report.digest?.succeeded ?? \"?\"}/${report.report.digest?.total ?? \"?\"}, tool-calls ${report.report.toolCall.succeeded}/${report.report.toolCall.total}${report.report.tokensPerSecond ? `, ~${report.report.tokensPerSecond} tok/s` : \"\"}`\n\t\t\t\t: `unprobed — run /fitness ollama/${model.name}`;\n\t\t\treturn ` - ${model.name} (${gb} GB) · ${probe}`;\n\t\t}),\n\t\t\"Commands: /models add <ref> · /models remove <ref> confirm · /models stop\",\n\t];\n\tfor (const line of lines) host.showStatus(line);\n}\n\nexport async function addLocalModel(host: LocalModelHost, pullRef: string, preselectRole?: FitnessRole): Promise<void> {\n\tif (!(await ensureLocalServer(host))) return;\n\thost.showStatus(`Pulling ${pullRef}… (weights land in the server's model storage)`);\n\tlet lastShown = 0;\n\tconst pulled = await host.localRuntime.pull(pullRef, (progress) => {\n\t\tconst now = Date.now();\n\t\tif (now - lastShown > 2000) {\n\t\t\tlastShown = now;\n\t\t\thost.showStatus(` ${pullRef}: ${progress}`);\n\t\t}\n\t});\n\tif (!pulled.ok) {\n\t\thost.showStatus(`Pull failed: ${pulled.error}`);\n\t\treturn;\n\t}\n\tconst registration = registerLocalModel({\n\t\tagentDir: getAgentDir(),\n\t\tref: pullRef,\n\t\tbaseUrl: host.localRuntime.baseUrl,\n\t});\n\tif (!registration.ok) {\n\t\thost.showStatus(`Pulled, but not auto-registered: ${registration.reason}`);\n\t\tif (registration.manualSnippet) {\n\t\t\thost.showStatus(`Add this to ${registration.modelsJsonPath} yourself:\\n${registration.manualSnippet}`);\n\t\t}\n\t\treturn;\n\t}\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${pullRef} installed and registered as ollama/${pullRef}. Probing fitness…`);\n\tawait runFitnessAndAssign(host, `ollama/${pullRef}`, preselectRole);\n}\n\nexport async function removeLocalModel(host: LocalModelHost, ref: string, confirmed: boolean): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\thost.showStatus(\"Local server not running — start it (any /models action) before removing.\");\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst target = models.find((model) => matchesInstalledLocalModel(ref, model.name));\n\tif (!target) {\n\t\thost.showStatus(\n\t\t\t`${ref} is not installed. Installed: ${models.map((model) => model.name).join(\", \") || \"(none)\"}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!confirmed) {\n\t\t// EXPLICIT USER ACTION ONLY: full disclosure, then require the confirm token.\n\t\tconst gb = (target.sizeBytes / 1e9).toFixed(2);\n\t\thost.showStatus(\n\t\t\t[\n\t\t\t\t`Removing ${ref} will delete:`,\n\t\t\t\t` - model weights (${gb} GB) from ${status.managedByPi ? status.ownedModelsDir : \"the system server's storage\"}`,\n\t\t\t\t` - the ollama/${ref} entry in models.json`,\n\t\t\t\t` - its cached fitness report for this host`,\n\t\t\t\t`Run: /models remove ${ref} confirm`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn;\n\t}\n\tconst removed = await host.localRuntime.remove(ref);\n\tif (!removed.ok) {\n\t\thost.showStatus(`Remove failed: ${removed.error}`);\n\t\treturn;\n\t}\n\tunregisterLocalModel({ agentDir: getAgentDir(), ref });\n\tFitnessStore.forAgentDir(getAgentDir()).remove(`ollama/${ref}`);\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${ref} removed: weights deleted, registration and fitness report dropped.`);\n}\n\n/** /fitness with no args: pick a model from the configured registry, probe it, assign a role. */\n/** Pick a validated suggestion → install it → probe on this host → land its shaped role. */\nexport function showModelSuggestionSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSuggestionSelectorComponent(\n\t\t\tDEFAULT_MODEL_SUGGESTIONS,\n\t\t\tasync (suggestion) => {\n\t\t\t\tdone();\n\t\t\t\t// The shaped role rides along so the post-probe selector lands on it pre-selected;\n\t\t\t\t// non-tool-callers carry curator/judge/none, never executor, so this can't footgun.\n\t\t\t\tawait addLocalModel(host, suggestion.pullRef, suggestion.assignRole);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\nexport function showFitnessModelSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSelectorComponent(\n\t\t\thost.ui,\n\t\t\thost.session.model,\n\t\t\thost.settingsManager,\n\t\t\thost.session.modelRegistry,\n\t\t\thost.session.scopedModels,\n\t\t\tasync (model) => {\n\t\t\t\tdone();\n\t\t\t\tawait runFitnessAndAssign(host, `${model.provider}/${model.id}`);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Resolve the routed model's supported thinking levels for a fitness-assignment flow, with a safe fallback. */\nfunction getModelThinkingLevels(modelRegistry: ModelRegistry | undefined, modelRef: string): ThinkingLevel[] {\n\tif (!modelRegistry) {\n\t\treturn [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];\n\t}\n\tconst resolved = resolveCliModel({ cliModel: modelRef, modelRegistry });\n\tif (!resolved.model) {\n\t\treturn [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];\n\t}\n\treturn getSupportedThinkingLevels(resolved.model);\n}\n\nfunction getModelRouterThinkingField(role: FitnessRole): ModelRouterThinkingField | undefined {\n\tif (role === \"router-cheap\") {\n\t\treturn \"cheapThinking\";\n\t}\n\tif (role === \"router-medium\") {\n\t\treturn \"mediumThinking\";\n\t}\n\tif (role === \"router-expensive\") {\n\t\treturn \"expensiveThinking\";\n\t}\n\tif (role === \"executor\") {\n\t\treturn \"executorThinking\";\n\t}\n\tif (role === \"judge\") {\n\t\treturn \"judgeThinking\";\n\t}\n\treturn undefined;\n}\n\nfunction promptForModelRouterThinking(host: RunFitnessHost, modelRef: string, role: FitnessRole): void {\n\tconst thinkingField = getModelRouterThinkingField(role);\n\tif (!thinkingField) {\n\t\treturn;\n\t}\n\n\tconst modelRegistry = host.session.modelRegistry;\n\tconst availableLevels = getModelThinkingLevels(modelRegistry, modelRef);\n\tconst settings = host.settingsManager.getModelRouterSettings();\n\tconst configuredThinking = settings[thinkingField];\n\tconst currentThinking =\n\t\tconfiguredThinking && availableLevels.includes(configuredThinking)\n\t\t\t? configuredThinking\n\t\t\t: MODEL_ROUTER_THINKING_INHERIT_VALUE;\n\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelRouterThinkingSelectorComponent(\n\t\t\tcurrentThinking,\n\t\t\tavailableLevels,\n\t\t\t(level) => {\n\t\t\t\tdone();\n\t\t\t\thost.settingsManager.setModelRouterSettings({\n\t\t\t\t\t...settings,\n\t\t\t\t\t[thinkingField]: level === MODEL_ROUTER_THINKING_INHERIT_VALUE ? undefined : level,\n\t\t\t\t});\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Probe a model's fitness, show the report, then offer one-step role assignment. When the model\n * came from a validated suggestion, `preselectRole` lands its shaped role already highlighted. */\nexport async function runFitnessAndAssign(\n\thost: RunFitnessHost,\n\tmodelRef: string,\n\tpreselectRole?: FitnessRole,\n): Promise<void> {\n\thost.showStatus(`Model fitness probe running on ${modelRef}… (6 surfaces; local models may take a few minutes)`);\n\ttry {\n\t\tconst outcome = await host.session.runModelFitness({ model: modelRef });\n\t\tif (!outcome.started) {\n\t\t\thost.showStatus(`Model fitness skipped: ${outcome.skipReason}`);\n\t\t\treturn;\n\t\t}\n\t\thost.chatContainer.addChild(new Spacer(1));\n\t\thost.chatContainer.addChild(new Text(formatModelFitnessReport(outcome.model, outcome.report), 1, 0));\n\t\thost.ui.requestRender();\n\t\t// Validate-before-load: zero successes on every probed surface means the model cannot\n\t\t// drive any of the harness's subagent contracts on this host — refuse adoption instead\n\t\t// of landing a role selector the user might reflexively confirm (this is the reported\n\t\t// bug: a 0/3-everywhere model still got set as judge model and saved to Model Router).\n\t\tif (isProbeAllFailed(outcome.report)) {\n\t\t\thost.showStatus(\n\t\t\t\t`${outcome.model} failed the fitness probe on all surfaces — not configured. Use /model to set it manually if you accept the risk.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\thost.showSelector((done) => {\n\t\t\tconst selector = new FitnessRoleSelectorComponent(\n\t\t\t\toutcome.model,\n\t\t\t\t(role) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tassignFitnessRole(host, outcome.model, role);\n\t\t\t\t\tpromptForModelRouterThinking(host, outcome.model, role);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\thost.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tpreselectRole,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/** Persist a role assignment from the post-probe selector into the matching settings. */\nexport function assignFitnessRole(host: AssignRoleHost, modelRef: string, role: FitnessRole): void {\n\tif (role === \"none\") {\n\t\thost.showStatus(`Fitness result for ${modelRef} saved. Assign a role later from /settings.`);\n\t\treturn;\n\t}\n\tif (role === \"curator\") {\n\t\tconst current = host.settingsManager.getContextCurationSettings();\n\t\thost.settingsManager.setContextCurationSettings({ ...current, enabled: true, model: modelRef });\n\t\thost.showStatus(`Context curation enabled with ${modelRef} as the curator.`);\n\t\treturn;\n\t}\n\tif (role === \"executor\") {\n\t\tconst router = host.settingsManager.getModelRouterSettings();\n\t\thost.settingsManager.setModelRouterSettings({ ...router, executorModel: modelRef });\n\t\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\t\thost.showStatus(`${modelRef} set as the toolkit executor (direct Level-0 hits route to it).${hint}`);\n\t\treturn;\n\t}\n\tconst router = host.settingsManager.getModelRouterSettings();\n\tconst field =\n\t\trole === \"router-cheap\"\n\t\t\t? \"cheapModel\"\n\t\t\t: role === \"router-medium\"\n\t\t\t\t? \"mediumModel\"\n\t\t\t\t: role === \"router-expensive\"\n\t\t\t\t\t? \"expensiveModel\"\n\t\t\t\t\t: role === \"judge\"\n\t\t\t\t\t\t? \"judgeModel\"\n\t\t\t\t\t\t: \"learningModel\";\n\thost.settingsManager.setModelRouterSettings({ ...router, [field]: modelRef });\n\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\thost.showStatus(`${modelRef} set as ${role.replace(\"router-\", \"router \")} model.${hint}`);\n}\n"]}
|
|
@@ -10,16 +10,74 @@
|
|
|
10
10
|
* fitness-role-assignment), which keep exercising interactive-mode's thin
|
|
11
11
|
* wrappers unchanged.
|
|
12
12
|
*/
|
|
13
|
-
import {
|
|
13
|
+
import { getSupportedThinkingLevels } from "@caupulican/pi-ai";
|
|
14
|
+
import { Container, SelectList, Spacer, Text, } from "@caupulican/pi-tui";
|
|
14
15
|
import { getAgentDir } from "../../config.js";
|
|
16
|
+
import { resolveCliModel } from "../../core/model-resolver.js";
|
|
15
17
|
import { DEFAULT_MODEL_SUGGESTIONS } from "../../core/models/default-model-suggestions.js";
|
|
16
18
|
import { FitnessStore } from "../../core/models/fitness-store.js";
|
|
17
19
|
import { registerLocalModel, unregisterLocalModel } from "../../core/models/local-registration.js";
|
|
18
20
|
import { matchesInstalledLocalModel, normalizeModelSource } from "../../core/models/model-ref.js";
|
|
19
21
|
import { formatModelFitnessReport, isProbeAllFailed } from "../../core/research/model-fitness.js";
|
|
22
|
+
import { DynamicBorder } from "./components/dynamic-border.js";
|
|
20
23
|
import { FitnessRoleSelectorComponent } from "./components/fitness-role-selector.js";
|
|
21
24
|
import { ModelSelectorComponent } from "./components/model-selector.js";
|
|
22
25
|
import { ModelSuggestionSelectorComponent } from "./components/model-suggestion-selector.js";
|
|
26
|
+
import { getSelectListTheme } from "./theme/theme.js";
|
|
27
|
+
const MODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT = {
|
|
28
|
+
minPrimaryColumnWidth: 12,
|
|
29
|
+
maxPrimaryColumnWidth: 32,
|
|
30
|
+
};
|
|
31
|
+
const MODEL_ROUTER_THINKING_INHERIT_VALUE = "__inherit_model_router_thinking__";
|
|
32
|
+
const MODEL_ROUTER_THINKING_INHERIT_LABEL = "(inherit)";
|
|
33
|
+
const THINKING_LEVEL_DESCRIPTIONS = {
|
|
34
|
+
off: "No reasoning",
|
|
35
|
+
minimal: "Very brief reasoning (~1k tokens)",
|
|
36
|
+
low: "Light reasoning (~2k tokens)",
|
|
37
|
+
medium: "Moderate reasoning (~8k tokens)",
|
|
38
|
+
high: "Deep reasoning (~16k tokens)",
|
|
39
|
+
xhigh: "Maximum reasoning (~32k tokens)",
|
|
40
|
+
};
|
|
41
|
+
const MODEL_ROUTER_THINKING_FALLBACK_LEVELS = [
|
|
42
|
+
"off",
|
|
43
|
+
"minimal",
|
|
44
|
+
"low",
|
|
45
|
+
"medium",
|
|
46
|
+
"high",
|
|
47
|
+
"xhigh",
|
|
48
|
+
];
|
|
49
|
+
class ModelRouterThinkingSelectorComponent extends Container {
|
|
50
|
+
selectList;
|
|
51
|
+
constructor(currentLevel, availableLevels, onSelect, onCancel) {
|
|
52
|
+
super();
|
|
53
|
+
const thinkingOptions = [
|
|
54
|
+
{
|
|
55
|
+
value: MODEL_ROUTER_THINKING_INHERIT_VALUE,
|
|
56
|
+
label: MODEL_ROUTER_THINKING_INHERIT_LABEL,
|
|
57
|
+
description: "Use current session default for this tier.",
|
|
58
|
+
},
|
|
59
|
+
...availableLevels.map((level) => ({
|
|
60
|
+
value: level,
|
|
61
|
+
label: level,
|
|
62
|
+
description: THINKING_LEVEL_DESCRIPTIONS[level],
|
|
63
|
+
})),
|
|
64
|
+
];
|
|
65
|
+
this.addChild(new DynamicBorder());
|
|
66
|
+
this.selectList = new SelectList(thinkingOptions, thinkingOptions.length, getSelectListTheme(), MODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT);
|
|
67
|
+
const index = thinkingOptions.findIndex((item) => item.value === currentLevel);
|
|
68
|
+
if (index !== -1) {
|
|
69
|
+
this.selectList.setSelectedIndex(index);
|
|
70
|
+
}
|
|
71
|
+
this.selectList.onSelect = (item) => {
|
|
72
|
+
onSelect(item.value);
|
|
73
|
+
};
|
|
74
|
+
this.selectList.onCancel = () => {
|
|
75
|
+
onCancel();
|
|
76
|
+
};
|
|
77
|
+
this.addChild(this.selectList);
|
|
78
|
+
this.addChild(new DynamicBorder());
|
|
79
|
+
}
|
|
80
|
+
}
|
|
23
81
|
/**
|
|
24
82
|
* /models — USER-invoked local model lifecycle (never a model-invokable tool):
|
|
25
83
|
* list/add/remove/stop per local-model-lifecycle-design.md. Removal is explicit-only with
|
|
@@ -216,6 +274,61 @@ export function showFitnessModelSelector(host) {
|
|
|
216
274
|
return { component: selector, focus: selector };
|
|
217
275
|
});
|
|
218
276
|
}
|
|
277
|
+
/** Resolve the routed model's supported thinking levels for a fitness-assignment flow, with a safe fallback. */
|
|
278
|
+
function getModelThinkingLevels(modelRegistry, modelRef) {
|
|
279
|
+
if (!modelRegistry) {
|
|
280
|
+
return [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];
|
|
281
|
+
}
|
|
282
|
+
const resolved = resolveCliModel({ cliModel: modelRef, modelRegistry });
|
|
283
|
+
if (!resolved.model) {
|
|
284
|
+
return [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];
|
|
285
|
+
}
|
|
286
|
+
return getSupportedThinkingLevels(resolved.model);
|
|
287
|
+
}
|
|
288
|
+
function getModelRouterThinkingField(role) {
|
|
289
|
+
if (role === "router-cheap") {
|
|
290
|
+
return "cheapThinking";
|
|
291
|
+
}
|
|
292
|
+
if (role === "router-medium") {
|
|
293
|
+
return "mediumThinking";
|
|
294
|
+
}
|
|
295
|
+
if (role === "router-expensive") {
|
|
296
|
+
return "expensiveThinking";
|
|
297
|
+
}
|
|
298
|
+
if (role === "executor") {
|
|
299
|
+
return "executorThinking";
|
|
300
|
+
}
|
|
301
|
+
if (role === "judge") {
|
|
302
|
+
return "judgeThinking";
|
|
303
|
+
}
|
|
304
|
+
return undefined;
|
|
305
|
+
}
|
|
306
|
+
function promptForModelRouterThinking(host, modelRef, role) {
|
|
307
|
+
const thinkingField = getModelRouterThinkingField(role);
|
|
308
|
+
if (!thinkingField) {
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
const modelRegistry = host.session.modelRegistry;
|
|
312
|
+
const availableLevels = getModelThinkingLevels(modelRegistry, modelRef);
|
|
313
|
+
const settings = host.settingsManager.getModelRouterSettings();
|
|
314
|
+
const configuredThinking = settings[thinkingField];
|
|
315
|
+
const currentThinking = configuredThinking && availableLevels.includes(configuredThinking)
|
|
316
|
+
? configuredThinking
|
|
317
|
+
: MODEL_ROUTER_THINKING_INHERIT_VALUE;
|
|
318
|
+
host.showSelector((done) => {
|
|
319
|
+
const selector = new ModelRouterThinkingSelectorComponent(currentThinking, availableLevels, (level) => {
|
|
320
|
+
done();
|
|
321
|
+
host.settingsManager.setModelRouterSettings({
|
|
322
|
+
...settings,
|
|
323
|
+
[thinkingField]: level === MODEL_ROUTER_THINKING_INHERIT_VALUE ? undefined : level,
|
|
324
|
+
});
|
|
325
|
+
}, () => {
|
|
326
|
+
done();
|
|
327
|
+
host.ui.requestRender();
|
|
328
|
+
});
|
|
329
|
+
return { component: selector, focus: selector };
|
|
330
|
+
});
|
|
331
|
+
}
|
|
219
332
|
/** Probe a model's fitness, show the report, then offer one-step role assignment. When the model
|
|
220
333
|
* came from a validated suggestion, `preselectRole` lands its shaped role already highlighted. */
|
|
221
334
|
export async function runFitnessAndAssign(host, modelRef, preselectRole) {
|
|
@@ -241,6 +354,7 @@ export async function runFitnessAndAssign(host, modelRef, preselectRole) {
|
|
|
241
354
|
const selector = new FitnessRoleSelectorComponent(outcome.model, (role) => {
|
|
242
355
|
done();
|
|
243
356
|
assignFitnessRole(host, outcome.model, role);
|
|
357
|
+
promptForModelRouterThinking(host, outcome.model, role);
|
|
244
358
|
}, () => {
|
|
245
359
|
done();
|
|
246
360
|
host.ui.requestRender();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-model-commands.js","sourceRoot":"","sources":["../../../src/modes/interactive/local-model-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AAEnG,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAElG,OAAO,EAAoB,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACvG,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,MAAM,2CAA2C,CAAC;AAiC7F;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,IAAoB,EAAE,QAAgB,EAAiB;IAChG,MAAM,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,IAAI,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACzE,IAAI,CAAC;QACJ,IAAI,MAAM,KAAK,SAAS,IAAI,MAAM,KAAK,aAAa,EAAE,CAAC;YACtD,2BAA2B,CAAC,IAAI,CAAC,CAAC;YAClC,OAAO;QACR,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C;QAC7D,IAAI,CAAC,eAAe,CAAC,sBAAsB,CAAC,EAAE,GAAG,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpF,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,kFAA8E,CAAC;QAClH,IAAI,CAAC,UAAU,CAAC,GAAG,QAAQ,kEAAkE,IAAI,EAAE,CAAC,CAAC;QACrG,OAAO;IACR,CAAC;IACD,MAAM,MAAM,GAAG,IAAI,CAAC,eAAe,CAAC,sBAAsB,EAAE,CAAC;IAC7D,MAAM,KAAK,GACV,IAAI,KAAK,cAAc;QACtB,CAAC,CAAC,YAAY;QACd,CAAC,CAAC,IAAI,KAAK,eAAe;YACzB,CAAC,CAAC,aAAa;YACf,CAAC,CAAC,IAAI,KAAK,kBAAkB;gBAC5B,CAAC,CAAC,gBAAgB;gBAClB,CAAC,CAAC,IAAI,KAAK,OAAO;oBACjB,CAAC,CAAC,YAAY;oBACd,CAAC,CAAC,eAAe,CAAC;IACvB,IAAI,CAAC,eAAe,CAAC,sBAAsB,CAAC,EAAE,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC9E,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,kFAA8E,CAAC;IAClH,IAAI,CAAC,UAAU,CAAC,GAAG,QAAQ,WAAW,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;AAAA,CAC1F","sourcesContent":["/**\n * `/models` local-model lifecycle and `/fitness` probe/role-assignment flows\n * extracted from interactive-mode.\n *\n * `/models` is a USER-invoked local-model manager (list/add/remove/stop, never a\n * model-invokable tool); the fitness helpers probe a model on the current host\n * and land a shaped role. The server/selector flows share a `LocalModelHost`\n * seam, while `runFitnessAndAssign`/`assignFitnessRole` take narrow host shapes\n * matching their prototype-driven behaviour tests (fitness-probe-gate,\n * fitness-role-assignment), which keep exercising interactive-mode's thin\n * wrappers unchanged.\n */\n\nimport type { Component, Container, TUI } from \"@caupulican/pi-tui\";\nimport { Spacer, Text } from \"@caupulican/pi-tui\";\nimport { getAgentDir } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport { DEFAULT_MODEL_SUGGESTIONS } from \"../../core/models/default-model-suggestions.ts\";\nimport { FitnessStore } from \"../../core/models/fitness-store.ts\";\nimport { registerLocalModel, unregisterLocalModel } from \"../../core/models/local-registration.ts\";\nimport type { OllamaRuntime } from \"../../core/models/local-runtime.ts\";\nimport { matchesInstalledLocalModel, normalizeModelSource } from \"../../core/models/model-ref.ts\";\nimport { formatModelFitnessReport, isProbeAllFailed } from \"../../core/research/model-fitness.ts\";\nimport type { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { type FitnessRole, FitnessRoleSelectorComponent } from \"./components/fitness-role-selector.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { ModelSuggestionSelectorComponent } from \"./components/model-suggestion-selector.ts\";\n\ntype SelectorFactory = (done: () => void) => { component: Component; focus: Component };\n\n/** Narrow seam for persisting a probed model's role — matches the fitness-role test. */\nexport interface AssignRoleHost {\n\treadonly settingsManager: SettingsManager;\n\tshowStatus(message: string): void;\n}\n\n/** Seam for the fitness probe + role-selector flow — matches the fitness-probe-gate test. */\nexport interface RunFitnessHost {\n\treadonly session: Pick<AgentSession, \"runModelFitness\">;\n\treadonly settingsManager: SettingsManager;\n\treadonly chatContainer: Container;\n\treadonly ui: TUI;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/** Full seam for the `/models` server/selector flows. */\nexport interface LocalModelHost {\n\treadonly localRuntime: OllamaRuntime;\n\treadonly session: AgentSession;\n\treadonly settingsManager: SettingsManager;\n\treadonly ui: TUI;\n\treadonly chatContainer: Container;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/**\n * /models — USER-invoked local model lifecycle (never a model-invokable tool):\n * list/add/remove/stop per local-model-lifecycle-design.md. Removal is explicit-only with\n * full disclosure; a pasted install command is parsed for its ref, never executed.\n */\nexport async function handleModelsCommand(host: LocalModelHost, argsText: string): Promise<void> {\n\tconst [action = \"list\", ...rest] = argsText.split(/\\s+/).filter(Boolean);\n\ttry {\n\t\tif (action === \"suggest\" || action === \"suggestions\") {\n\t\t\tshowModelSuggestionSelector(host);\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"stop\") {\n\t\t\tconst stopped = host.localRuntime.stop();\n\t\t\thost.showStatus(\n\t\t\t\tstopped.stopped\n\t\t\t\t\t? \"Pi-managed local model server stopped (models remain installed).\"\n\t\t\t\t\t: \"No pi-managed server running (a system server, if any, is not pi's to stop).\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"add\") {\n\t\t\tconst rawRef = rest.join(\" \");\n\t\t\tif (!rawRef) {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t\"Usage: /models add <ollama-tag | hf.co/org/repo[:quant] | huggingface URL | pasted install command>\",\n\t\t\t\t);\n\t\t\t\thost.showStatus(\"Or start from a validated suggestion: /models suggest\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst source = normalizeModelSource(rawRef);\n\t\t\tif (source.type === \"rejected\") {\n\t\t\t\thost.showStatus(`Not added: ${source.reason}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (source.type === \"api\") {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t`${source.ref} is an API model — nothing to install. Configure auth for the provider, then probe it with /fitness ${source.ref}.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait addLocalModel(host, source.pullRef);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"remove\") {\n\t\t\tconst ref = rest[0];\n\t\t\tconst confirmed = rest[1] === \"confirm\";\n\t\t\tif (!ref) {\n\t\t\t\thost.showStatus(\"Usage: /models remove <ref> confirm\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait removeLocalModel(host, ref, confirmed);\n\t\t\treturn;\n\t\t}\n\n\t\tawait listLocalModels(host);\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\nexport async function ensureLocalServer(host: LocalModelHost): Promise<boolean> {\n\tconst status = await host.localRuntime.detect();\n\tif (status.serverUp) return true;\n\tif (!status.binaryPath) {\n\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\treturn false;\n\t}\n\thost.showStatus(\n\t\t`Starting local model server (${status.binarySource} binary, owned storage: ${status.ownedModelsDir})…`,\n\t);\n\tconst started = await host.localRuntime.start();\n\tif (!started.started) {\n\t\thost.showStatus(`Could not start the local server: ${started.reason}`);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport async function listLocalModels(host: LocalModelHost): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\tif (!status.binaryPath) {\n\t\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\t\treturn;\n\t\t}\n\t\thost.showStatus(\n\t\t\t`Local server not running (binary: ${status.binarySource}). /models add starts it on demand; /fitness probes registered models.`,\n\t\t);\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst fitness = FitnessStore.forAgentDir(getAgentDir()).getForHost();\n\tconst lines = [\n\t\t`Local models (${status.managedByPi ? `pi-managed server, storage: ${status.ownedModelsDir}` : \"system server — storage owned by the system daemon\"}):`,\n\t\t...(models.length === 0\n\t\t\t? [\" (none installed — /models add <ref>, or /models suggest for a validated roster)\"]\n\t\t\t: []),\n\t\t...models.map((model) => {\n\t\t\tconst report = fitness.find((entry) => entry.model === `ollama/${model.name}`);\n\t\t\tconst gb = (model.sizeBytes / 1e9).toFixed(2);\n\t\t\tconst probe = report\n\t\t\t\t? `probed ${report.at.slice(0, 10)}: digest ${report.report.digest?.succeeded ?? \"?\"}/${report.report.digest?.total ?? \"?\"}, tool-calls ${report.report.toolCall.succeeded}/${report.report.toolCall.total}${report.report.tokensPerSecond ? `, ~${report.report.tokensPerSecond} tok/s` : \"\"}`\n\t\t\t\t: `unprobed — run /fitness ollama/${model.name}`;\n\t\t\treturn ` - ${model.name} (${gb} GB) · ${probe}`;\n\t\t}),\n\t\t\"Commands: /models add <ref> · /models remove <ref> confirm · /models stop\",\n\t];\n\tfor (const line of lines) host.showStatus(line);\n}\n\nexport async function addLocalModel(host: LocalModelHost, pullRef: string, preselectRole?: FitnessRole): Promise<void> {\n\tif (!(await ensureLocalServer(host))) return;\n\thost.showStatus(`Pulling ${pullRef}… (weights land in the server's model storage)`);\n\tlet lastShown = 0;\n\tconst pulled = await host.localRuntime.pull(pullRef, (progress) => {\n\t\tconst now = Date.now();\n\t\tif (now - lastShown > 2000) {\n\t\t\tlastShown = now;\n\t\t\thost.showStatus(` ${pullRef}: ${progress}`);\n\t\t}\n\t});\n\tif (!pulled.ok) {\n\t\thost.showStatus(`Pull failed: ${pulled.error}`);\n\t\treturn;\n\t}\n\tconst registration = registerLocalModel({\n\t\tagentDir: getAgentDir(),\n\t\tref: pullRef,\n\t\tbaseUrl: host.localRuntime.baseUrl,\n\t});\n\tif (!registration.ok) {\n\t\thost.showStatus(`Pulled, but not auto-registered: ${registration.reason}`);\n\t\tif (registration.manualSnippet) {\n\t\t\thost.showStatus(`Add this to ${registration.modelsJsonPath} yourself:\\n${registration.manualSnippet}`);\n\t\t}\n\t\treturn;\n\t}\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${pullRef} installed and registered as ollama/${pullRef}. Probing fitness…`);\n\tawait runFitnessAndAssign(host, `ollama/${pullRef}`, preselectRole);\n}\n\nexport async function removeLocalModel(host: LocalModelHost, ref: string, confirmed: boolean): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\thost.showStatus(\"Local server not running — start it (any /models action) before removing.\");\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst target = models.find((model) => matchesInstalledLocalModel(ref, model.name));\n\tif (!target) {\n\t\thost.showStatus(\n\t\t\t`${ref} is not installed. Installed: ${models.map((model) => model.name).join(\", \") || \"(none)\"}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!confirmed) {\n\t\t// EXPLICIT USER ACTION ONLY: full disclosure, then require the confirm token.\n\t\tconst gb = (target.sizeBytes / 1e9).toFixed(2);\n\t\thost.showStatus(\n\t\t\t[\n\t\t\t\t`Removing ${ref} will delete:`,\n\t\t\t\t` - model weights (${gb} GB) from ${status.managedByPi ? status.ownedModelsDir : \"the system server's storage\"}`,\n\t\t\t\t` - the ollama/${ref} entry in models.json`,\n\t\t\t\t` - its cached fitness report for this host`,\n\t\t\t\t`Run: /models remove ${ref} confirm`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn;\n\t}\n\tconst removed = await host.localRuntime.remove(ref);\n\tif (!removed.ok) {\n\t\thost.showStatus(`Remove failed: ${removed.error}`);\n\t\treturn;\n\t}\n\tunregisterLocalModel({ agentDir: getAgentDir(), ref });\n\tFitnessStore.forAgentDir(getAgentDir()).remove(`ollama/${ref}`);\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${ref} removed: weights deleted, registration and fitness report dropped.`);\n}\n\n/** /fitness with no args: pick a model from the configured registry, probe it, assign a role. */\n/** Pick a validated suggestion → install it → probe on this host → land its shaped role. */\nexport function showModelSuggestionSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSuggestionSelectorComponent(\n\t\t\tDEFAULT_MODEL_SUGGESTIONS,\n\t\t\tasync (suggestion) => {\n\t\t\t\tdone();\n\t\t\t\t// The shaped role rides along so the post-probe selector lands on it pre-selected;\n\t\t\t\t// non-tool-callers carry curator/judge/none, never executor, so this can't footgun.\n\t\t\t\tawait addLocalModel(host, suggestion.pullRef, suggestion.assignRole);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\nexport function showFitnessModelSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSelectorComponent(\n\t\t\thost.ui,\n\t\t\thost.session.model,\n\t\t\thost.settingsManager,\n\t\t\thost.session.modelRegistry,\n\t\t\thost.session.scopedModels,\n\t\t\tasync (model) => {\n\t\t\t\tdone();\n\t\t\t\tawait runFitnessAndAssign(host, `${model.provider}/${model.id}`);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Probe a model's fitness, show the report, then offer one-step role assignment. When the model\n * came from a validated suggestion, `preselectRole` lands its shaped role already highlighted. */\nexport async function runFitnessAndAssign(\n\thost: RunFitnessHost,\n\tmodelRef: string,\n\tpreselectRole?: FitnessRole,\n): Promise<void> {\n\thost.showStatus(`Model fitness probe running on ${modelRef}… (6 surfaces; local models may take a few minutes)`);\n\ttry {\n\t\tconst outcome = await host.session.runModelFitness({ model: modelRef });\n\t\tif (!outcome.started) {\n\t\t\thost.showStatus(`Model fitness skipped: ${outcome.skipReason}`);\n\t\t\treturn;\n\t\t}\n\t\thost.chatContainer.addChild(new Spacer(1));\n\t\thost.chatContainer.addChild(new Text(formatModelFitnessReport(outcome.model, outcome.report), 1, 0));\n\t\thost.ui.requestRender();\n\t\t// Validate-before-load: zero successes on every probed surface means the model cannot\n\t\t// drive any of the harness's subagent contracts on this host — refuse adoption instead\n\t\t// of landing a role selector the user might reflexively confirm (this is the reported\n\t\t// bug: a 0/3-everywhere model still got set as judge model and saved to Model Router).\n\t\tif (isProbeAllFailed(outcome.report)) {\n\t\t\thost.showStatus(\n\t\t\t\t`${outcome.model} failed the fitness probe on all surfaces — not configured. Use /model to set it manually if you accept the risk.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\thost.showSelector((done) => {\n\t\t\tconst selector = new FitnessRoleSelectorComponent(\n\t\t\t\toutcome.model,\n\t\t\t\t(role) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tassignFitnessRole(host, outcome.model, role);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\thost.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tpreselectRole,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/** Persist a role assignment from the post-probe selector into the matching settings. */\nexport function assignFitnessRole(host: AssignRoleHost, modelRef: string, role: FitnessRole): void {\n\tif (role === \"none\") {\n\t\thost.showStatus(`Fitness result for ${modelRef} saved. Assign a role later from /settings.`);\n\t\treturn;\n\t}\n\tif (role === \"curator\") {\n\t\tconst current = host.settingsManager.getContextCurationSettings();\n\t\thost.settingsManager.setContextCurationSettings({ ...current, enabled: true, model: modelRef });\n\t\thost.showStatus(`Context curation enabled with ${modelRef} as the curator.`);\n\t\treturn;\n\t}\n\tif (role === \"executor\") {\n\t\tconst router = host.settingsManager.getModelRouterSettings();\n\t\thost.settingsManager.setModelRouterSettings({ ...router, executorModel: modelRef });\n\t\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\t\thost.showStatus(`${modelRef} set as the toolkit executor (direct Level-0 hits route to it).${hint}`);\n\t\treturn;\n\t}\n\tconst router = host.settingsManager.getModelRouterSettings();\n\tconst field =\n\t\trole === \"router-cheap\"\n\t\t\t? \"cheapModel\"\n\t\t\t: role === \"router-medium\"\n\t\t\t\t? \"mediumModel\"\n\t\t\t\t: role === \"router-expensive\"\n\t\t\t\t\t? \"expensiveModel\"\n\t\t\t\t\t: role === \"judge\"\n\t\t\t\t\t\t? \"judgeModel\"\n\t\t\t\t\t\t: \"learningModel\";\n\thost.settingsManager.setModelRouterSettings({ ...router, [field]: modelRef });\n\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\thost.showStatus(`${modelRef} set as ${role.replace(\"router-\", \"router \")} model.${hint}`);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-model-commands.js","sourceRoot":"","sources":["../../../src/modes/interactive/local-model-commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAC/D,OAAO,EAEN,SAAS,EAET,UAAU,EAEV,MAAM,EACN,IAAI,GAEJ,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAG9C,OAAO,EAAE,eAAe,EAAE,MAAM,8BAA8B,CAAC;AAC/D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gDAAgD,CAAC;AAC3F,OAAO,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,oBAAoB,EAAE,MAAM,yCAAyC,CAAC;AAEnG,OAAO,EAAE,0BAA0B,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AAClG,OAAO,EAAE,wBAAwB,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAElG,OAAO,EAAE,aAAa,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAoB,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACvG,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,gCAAgC,EAAE,MAAM,2CAA2C,CAAC;AAC7F,OAAO,EAAE,kBAAkB,EAAE,MAAM,kBAAkB,CAAC;AAItD,MAAM,wCAAwC,GAA4B;IACzE,qBAAqB,EAAE,EAAE;IACzB,qBAAqB,EAAE,EAAE;CACzB,CAAC;AAEF,MAAM,mCAAmC,GAAG,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IAC9E,MAAM,IAAI,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,kFAA8E,CAAC;IAClH,IAAI,CAAC,UAAU,CAAC,GAAG,QAAQ,WAAW,IAAI,CAAC,OAAO,CAAC,SAAS,EAAE,SAAS,CAAC,UAAU,IAAI,EAAE,CAAC,CAAC;AAAA,CAC1F","sourcesContent":["/**\n * `/models` local-model lifecycle and `/fitness` probe/role-assignment flows\n * extracted from interactive-mode.\n *\n * `/models` is a USER-invoked local-model manager (list/add/remove/stop, never a\n * model-invokable tool); the fitness helpers probe a model on the current host\n * and land a shaped role. The server/selector flows share a `LocalModelHost`\n * seam, while `runFitnessAndAssign`/`assignFitnessRole` take narrow host shapes\n * matching their prototype-driven behaviour tests (fitness-probe-gate,\n * fitness-role-assignment), which keep exercising interactive-mode's thin\n * wrappers unchanged.\n */\n\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getSupportedThinkingLevels } from \"@caupulican/pi-ai\";\nimport {\n\ttype Component,\n\tContainer,\n\ttype SelectItem,\n\tSelectList,\n\ttype SelectListLayoutOptions,\n\tSpacer,\n\tText,\n\ttype TUI,\n} from \"@caupulican/pi-tui\";\nimport { getAgentDir } from \"../../config.ts\";\nimport type { AgentSession } from \"../../core/agent-session.ts\";\nimport type { ModelRegistry } from \"../../core/model-registry.ts\";\nimport { resolveCliModel } from \"../../core/model-resolver.ts\";\nimport { DEFAULT_MODEL_SUGGESTIONS } from \"../../core/models/default-model-suggestions.ts\";\nimport { FitnessStore } from \"../../core/models/fitness-store.ts\";\nimport { registerLocalModel, unregisterLocalModel } from \"../../core/models/local-registration.ts\";\nimport type { OllamaRuntime } from \"../../core/models/local-runtime.ts\";\nimport { matchesInstalledLocalModel, normalizeModelSource } from \"../../core/models/model-ref.ts\";\nimport { formatModelFitnessReport, isProbeAllFailed } from \"../../core/research/model-fitness.ts\";\nimport type { SettingsManager } from \"../../core/settings-manager.ts\";\nimport { DynamicBorder } from \"./components/dynamic-border.ts\";\nimport { type FitnessRole, FitnessRoleSelectorComponent } from \"./components/fitness-role-selector.ts\";\nimport { ModelSelectorComponent } from \"./components/model-selector.ts\";\nimport { ModelSuggestionSelectorComponent } from \"./components/model-suggestion-selector.ts\";\nimport { getSelectListTheme } from \"./theme/theme.ts\";\n\ntype SelectorFactory = (done: () => void) => { component: Component; focus: Component };\n\nconst MODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT: SelectListLayoutOptions = {\n\tminPrimaryColumnWidth: 12,\n\tmaxPrimaryColumnWidth: 32,\n};\n\nconst MODEL_ROUTER_THINKING_INHERIT_VALUE = \"__inherit_model_router_thinking__\";\nconst MODEL_ROUTER_THINKING_INHERIT_LABEL = \"(inherit)\";\n\nconst THINKING_LEVEL_DESCRIPTIONS: Record<ThinkingLevel, string> = {\n\toff: \"No reasoning\",\n\tminimal: \"Very brief reasoning (~1k tokens)\",\n\tlow: \"Light reasoning (~2k tokens)\",\n\tmedium: \"Moderate reasoning (~8k tokens)\",\n\thigh: \"Deep reasoning (~16k tokens)\",\n\txhigh: \"Maximum reasoning (~32k tokens)\",\n};\n\nconst MODEL_ROUTER_THINKING_FALLBACK_LEVELS: readonly ThinkingLevel[] = [\n\t\"off\",\n\t\"minimal\",\n\t\"low\",\n\t\"medium\",\n\t\"high\",\n\t\"xhigh\",\n];\n\ntype RouterThinkingLevel = ThinkingLevel | typeof MODEL_ROUTER_THINKING_INHERIT_VALUE;\ntype ModelRouterThinkingField =\n\t| \"cheapThinking\"\n\t| \"mediumThinking\"\n\t| \"expensiveThinking\"\n\t| \"executorThinking\"\n\t| \"judgeThinking\";\n\n/** Narrow seam for persisting a probed model's role — matches the fitness-role test. */\nexport interface AssignRoleHost {\n\treadonly settingsManager: SettingsManager;\n\tshowStatus(message: string): void;\n}\n\n/** Seam for the fitness probe + role-selector flow — matches the fitness-probe-gate test. */\nexport interface RunFitnessHost {\n\treadonly session: Pick<AgentSession, \"runModelFitness\"> & { modelRegistry?: ModelRegistry };\n\treadonly settingsManager: SettingsManager;\n\treadonly chatContainer: Container;\n\treadonly ui: TUI;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\n/** Full seam for the `/models` server/selector flows. */\nexport interface LocalModelHost {\n\treadonly localRuntime: OllamaRuntime;\n\treadonly session: AgentSession;\n\treadonly settingsManager: SettingsManager;\n\treadonly ui: TUI;\n\treadonly chatContainer: Container;\n\tshowStatus(message: string): void;\n\tshowError(message: string): void;\n\tshowSelector(create: SelectorFactory): void;\n}\n\nclass ModelRouterThinkingSelectorComponent extends Container {\n\tprivate selectList: SelectList;\n\n\tconstructor(\n\t\tcurrentLevel: RouterThinkingLevel,\n\t\tavailableLevels: ThinkingLevel[],\n\t\tonSelect: (level: RouterThinkingLevel) => void,\n\t\tonCancel: () => void,\n\t) {\n\t\tsuper();\n\n\t\tconst thinkingOptions: SelectItem[] = [\n\t\t\t{\n\t\t\t\tvalue: MODEL_ROUTER_THINKING_INHERIT_VALUE,\n\t\t\t\tlabel: MODEL_ROUTER_THINKING_INHERIT_LABEL,\n\t\t\t\tdescription: \"Use current session default for this tier.\",\n\t\t\t},\n\t\t\t...availableLevels.map((level) => ({\n\t\t\t\tvalue: level,\n\t\t\t\tlabel: level,\n\t\t\t\tdescription: THINKING_LEVEL_DESCRIPTIONS[level],\n\t\t\t})),\n\t\t];\n\n\t\tthis.addChild(new DynamicBorder());\n\n\t\tthis.selectList = new SelectList(\n\t\t\tthinkingOptions,\n\t\t\tthinkingOptions.length,\n\t\t\tgetSelectListTheme(),\n\t\t\tMODEL_ROUTER_THINKING_SELECT_LIST_LAYOUT,\n\t\t);\n\n\t\tconst index = thinkingOptions.findIndex((item) => item.value === currentLevel);\n\t\tif (index !== -1) {\n\t\t\tthis.selectList.setSelectedIndex(index);\n\t\t}\n\n\t\tthis.selectList.onSelect = (item) => {\n\t\t\tonSelect(item.value as RouterThinkingLevel);\n\t\t};\n\t\tthis.selectList.onCancel = () => {\n\t\t\tonCancel();\n\t\t};\n\n\t\tthis.addChild(this.selectList);\n\t\tthis.addChild(new DynamicBorder());\n\t}\n}\n/**\n * /models — USER-invoked local model lifecycle (never a model-invokable tool):\n * list/add/remove/stop per local-model-lifecycle-design.md. Removal is explicit-only with\n * full disclosure; a pasted install command is parsed for its ref, never executed.\n */\nexport async function handleModelsCommand(host: LocalModelHost, argsText: string): Promise<void> {\n\tconst [action = \"list\", ...rest] = argsText.split(/\\s+/).filter(Boolean);\n\ttry {\n\t\tif (action === \"suggest\" || action === \"suggestions\") {\n\t\t\tshowModelSuggestionSelector(host);\n\t\t\treturn;\n\t\t}\n\t\tif (action === \"stop\") {\n\t\t\tconst stopped = host.localRuntime.stop();\n\t\t\thost.showStatus(\n\t\t\t\tstopped.stopped\n\t\t\t\t\t? \"Pi-managed local model server stopped (models remain installed).\"\n\t\t\t\t\t: \"No pi-managed server running (a system server, if any, is not pi's to stop).\",\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"add\") {\n\t\t\tconst rawRef = rest.join(\" \");\n\t\t\tif (!rawRef) {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t\"Usage: /models add <ollama-tag | hf.co/org/repo[:quant] | huggingface URL | pasted install command>\",\n\t\t\t\t);\n\t\t\t\thost.showStatus(\"Or start from a validated suggestion: /models suggest\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst source = normalizeModelSource(rawRef);\n\t\t\tif (source.type === \"rejected\") {\n\t\t\t\thost.showStatus(`Not added: ${source.reason}`);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (source.type === \"api\") {\n\t\t\t\thost.showStatus(\n\t\t\t\t\t`${source.ref} is an API model — nothing to install. Configure auth for the provider, then probe it with /fitness ${source.ref}.`,\n\t\t\t\t);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait addLocalModel(host, source.pullRef);\n\t\t\treturn;\n\t\t}\n\n\t\tif (action === \"remove\") {\n\t\t\tconst ref = rest[0];\n\t\t\tconst confirmed = rest[1] === \"confirm\";\n\t\t\tif (!ref) {\n\t\t\t\thost.showStatus(\"Usage: /models remove <ref> confirm\");\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait removeLocalModel(host, ref, confirmed);\n\t\t\treturn;\n\t\t}\n\n\t\tawait listLocalModels(host);\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\nexport async function ensureLocalServer(host: LocalModelHost): Promise<boolean> {\n\tconst status = await host.localRuntime.detect();\n\tif (status.serverUp) return true;\n\tif (!status.binaryPath) {\n\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\treturn false;\n\t}\n\thost.showStatus(\n\t\t`Starting local model server (${status.binarySource} binary, owned storage: ${status.ownedModelsDir})…`,\n\t);\n\tconst started = await host.localRuntime.start();\n\tif (!started.started) {\n\t\thost.showStatus(`Could not start the local server: ${started.reason}`);\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nexport async function listLocalModels(host: LocalModelHost): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\tif (!status.binaryPath) {\n\t\t\tfor (const line of host.localRuntime.installGuide()) host.showStatus(line);\n\t\t\treturn;\n\t\t}\n\t\thost.showStatus(\n\t\t\t`Local server not running (binary: ${status.binarySource}). /models add starts it on demand; /fitness probes registered models.`,\n\t\t);\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst fitness = FitnessStore.forAgentDir(getAgentDir()).getForHost();\n\tconst lines = [\n\t\t`Local models (${status.managedByPi ? `pi-managed server, storage: ${status.ownedModelsDir}` : \"system server — storage owned by the system daemon\"}):`,\n\t\t...(models.length === 0\n\t\t\t? [\" (none installed — /models add <ref>, or /models suggest for a validated roster)\"]\n\t\t\t: []),\n\t\t...models.map((model) => {\n\t\t\tconst report = fitness.find((entry) => entry.model === `ollama/${model.name}`);\n\t\t\tconst gb = (model.sizeBytes / 1e9).toFixed(2);\n\t\t\tconst probe = report\n\t\t\t\t? `probed ${report.at.slice(0, 10)}: digest ${report.report.digest?.succeeded ?? \"?\"}/${report.report.digest?.total ?? \"?\"}, tool-calls ${report.report.toolCall.succeeded}/${report.report.toolCall.total}${report.report.tokensPerSecond ? `, ~${report.report.tokensPerSecond} tok/s` : \"\"}`\n\t\t\t\t: `unprobed — run /fitness ollama/${model.name}`;\n\t\t\treturn ` - ${model.name} (${gb} GB) · ${probe}`;\n\t\t}),\n\t\t\"Commands: /models add <ref> · /models remove <ref> confirm · /models stop\",\n\t];\n\tfor (const line of lines) host.showStatus(line);\n}\n\nexport async function addLocalModel(host: LocalModelHost, pullRef: string, preselectRole?: FitnessRole): Promise<void> {\n\tif (!(await ensureLocalServer(host))) return;\n\thost.showStatus(`Pulling ${pullRef}… (weights land in the server's model storage)`);\n\tlet lastShown = 0;\n\tconst pulled = await host.localRuntime.pull(pullRef, (progress) => {\n\t\tconst now = Date.now();\n\t\tif (now - lastShown > 2000) {\n\t\t\tlastShown = now;\n\t\t\thost.showStatus(` ${pullRef}: ${progress}`);\n\t\t}\n\t});\n\tif (!pulled.ok) {\n\t\thost.showStatus(`Pull failed: ${pulled.error}`);\n\t\treturn;\n\t}\n\tconst registration = registerLocalModel({\n\t\tagentDir: getAgentDir(),\n\t\tref: pullRef,\n\t\tbaseUrl: host.localRuntime.baseUrl,\n\t});\n\tif (!registration.ok) {\n\t\thost.showStatus(`Pulled, but not auto-registered: ${registration.reason}`);\n\t\tif (registration.manualSnippet) {\n\t\t\thost.showStatus(`Add this to ${registration.modelsJsonPath} yourself:\\n${registration.manualSnippet}`);\n\t\t}\n\t\treturn;\n\t}\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${pullRef} installed and registered as ollama/${pullRef}. Probing fitness…`);\n\tawait runFitnessAndAssign(host, `ollama/${pullRef}`, preselectRole);\n}\n\nexport async function removeLocalModel(host: LocalModelHost, ref: string, confirmed: boolean): Promise<void> {\n\tconst status = await host.localRuntime.detect();\n\tif (!status.serverUp) {\n\t\thost.showStatus(\"Local server not running — start it (any /models action) before removing.\");\n\t\treturn;\n\t}\n\tconst models = await host.localRuntime.list();\n\tconst target = models.find((model) => matchesInstalledLocalModel(ref, model.name));\n\tif (!target) {\n\t\thost.showStatus(\n\t\t\t`${ref} is not installed. Installed: ${models.map((model) => model.name).join(\", \") || \"(none)\"}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (!confirmed) {\n\t\t// EXPLICIT USER ACTION ONLY: full disclosure, then require the confirm token.\n\t\tconst gb = (target.sizeBytes / 1e9).toFixed(2);\n\t\thost.showStatus(\n\t\t\t[\n\t\t\t\t`Removing ${ref} will delete:`,\n\t\t\t\t` - model weights (${gb} GB) from ${status.managedByPi ? status.ownedModelsDir : \"the system server's storage\"}`,\n\t\t\t\t` - the ollama/${ref} entry in models.json`,\n\t\t\t\t` - its cached fitness report for this host`,\n\t\t\t\t`Run: /models remove ${ref} confirm`,\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t\treturn;\n\t}\n\tconst removed = await host.localRuntime.remove(ref);\n\tif (!removed.ok) {\n\t\thost.showStatus(`Remove failed: ${removed.error}`);\n\t\treturn;\n\t}\n\tunregisterLocalModel({ agentDir: getAgentDir(), ref });\n\tFitnessStore.forAgentDir(getAgentDir()).remove(`ollama/${ref}`);\n\thost.session.modelRegistry.refresh();\n\thost.showStatus(`${ref} removed: weights deleted, registration and fitness report dropped.`);\n}\n\n/** /fitness with no args: pick a model from the configured registry, probe it, assign a role. */\n/** Pick a validated suggestion → install it → probe on this host → land its shaped role. */\nexport function showModelSuggestionSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSuggestionSelectorComponent(\n\t\t\tDEFAULT_MODEL_SUGGESTIONS,\n\t\t\tasync (suggestion) => {\n\t\t\t\tdone();\n\t\t\t\t// The shaped role rides along so the post-probe selector lands on it pre-selected;\n\t\t\t\t// non-tool-callers carry curator/judge/none, never executor, so this can't footgun.\n\t\t\t\tawait addLocalModel(host, suggestion.pullRef, suggestion.assignRole);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\nexport function showFitnessModelSelector(host: LocalModelHost): void {\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelSelectorComponent(\n\t\t\thost.ui,\n\t\t\thost.session.model,\n\t\t\thost.settingsManager,\n\t\t\thost.session.modelRegistry,\n\t\t\thost.session.scopedModels,\n\t\t\tasync (model) => {\n\t\t\t\tdone();\n\t\t\t\tawait runFitnessAndAssign(host, `${model.provider}/${model.id}`);\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Resolve the routed model's supported thinking levels for a fitness-assignment flow, with a safe fallback. */\nfunction getModelThinkingLevels(modelRegistry: ModelRegistry | undefined, modelRef: string): ThinkingLevel[] {\n\tif (!modelRegistry) {\n\t\treturn [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];\n\t}\n\tconst resolved = resolveCliModel({ cliModel: modelRef, modelRegistry });\n\tif (!resolved.model) {\n\t\treturn [...MODEL_ROUTER_THINKING_FALLBACK_LEVELS];\n\t}\n\treturn getSupportedThinkingLevels(resolved.model);\n}\n\nfunction getModelRouterThinkingField(role: FitnessRole): ModelRouterThinkingField | undefined {\n\tif (role === \"router-cheap\") {\n\t\treturn \"cheapThinking\";\n\t}\n\tif (role === \"router-medium\") {\n\t\treturn \"mediumThinking\";\n\t}\n\tif (role === \"router-expensive\") {\n\t\treturn \"expensiveThinking\";\n\t}\n\tif (role === \"executor\") {\n\t\treturn \"executorThinking\";\n\t}\n\tif (role === \"judge\") {\n\t\treturn \"judgeThinking\";\n\t}\n\treturn undefined;\n}\n\nfunction promptForModelRouterThinking(host: RunFitnessHost, modelRef: string, role: FitnessRole): void {\n\tconst thinkingField = getModelRouterThinkingField(role);\n\tif (!thinkingField) {\n\t\treturn;\n\t}\n\n\tconst modelRegistry = host.session.modelRegistry;\n\tconst availableLevels = getModelThinkingLevels(modelRegistry, modelRef);\n\tconst settings = host.settingsManager.getModelRouterSettings();\n\tconst configuredThinking = settings[thinkingField];\n\tconst currentThinking =\n\t\tconfiguredThinking && availableLevels.includes(configuredThinking)\n\t\t\t? configuredThinking\n\t\t\t: MODEL_ROUTER_THINKING_INHERIT_VALUE;\n\n\thost.showSelector((done) => {\n\t\tconst selector = new ModelRouterThinkingSelectorComponent(\n\t\t\tcurrentThinking,\n\t\t\tavailableLevels,\n\t\t\t(level) => {\n\t\t\t\tdone();\n\t\t\t\thost.settingsManager.setModelRouterSettings({\n\t\t\t\t\t...settings,\n\t\t\t\t\t[thinkingField]: level === MODEL_ROUTER_THINKING_INHERIT_VALUE ? undefined : level,\n\t\t\t\t});\n\t\t\t},\n\t\t\t() => {\n\t\t\t\tdone();\n\t\t\t\thost.ui.requestRender();\n\t\t\t},\n\t\t);\n\t\treturn { component: selector, focus: selector };\n\t});\n}\n\n/** Probe a model's fitness, show the report, then offer one-step role assignment. When the model\n * came from a validated suggestion, `preselectRole` lands its shaped role already highlighted. */\nexport async function runFitnessAndAssign(\n\thost: RunFitnessHost,\n\tmodelRef: string,\n\tpreselectRole?: FitnessRole,\n): Promise<void> {\n\thost.showStatus(`Model fitness probe running on ${modelRef}… (6 surfaces; local models may take a few minutes)`);\n\ttry {\n\t\tconst outcome = await host.session.runModelFitness({ model: modelRef });\n\t\tif (!outcome.started) {\n\t\t\thost.showStatus(`Model fitness skipped: ${outcome.skipReason}`);\n\t\t\treturn;\n\t\t}\n\t\thost.chatContainer.addChild(new Spacer(1));\n\t\thost.chatContainer.addChild(new Text(formatModelFitnessReport(outcome.model, outcome.report), 1, 0));\n\t\thost.ui.requestRender();\n\t\t// Validate-before-load: zero successes on every probed surface means the model cannot\n\t\t// drive any of the harness's subagent contracts on this host — refuse adoption instead\n\t\t// of landing a role selector the user might reflexively confirm (this is the reported\n\t\t// bug: a 0/3-everywhere model still got set as judge model and saved to Model Router).\n\t\tif (isProbeAllFailed(outcome.report)) {\n\t\t\thost.showStatus(\n\t\t\t\t`${outcome.model} failed the fitness probe on all surfaces — not configured. Use /model to set it manually if you accept the risk.`,\n\t\t\t);\n\t\t\treturn;\n\t\t}\n\t\thost.showSelector((done) => {\n\t\t\tconst selector = new FitnessRoleSelectorComponent(\n\t\t\t\toutcome.model,\n\t\t\t\t(role) => {\n\t\t\t\t\tdone();\n\t\t\t\t\tassignFitnessRole(host, outcome.model, role);\n\t\t\t\t\tpromptForModelRouterThinking(host, outcome.model, role);\n\t\t\t\t},\n\t\t\t\t() => {\n\t\t\t\t\tdone();\n\t\t\t\t\thost.ui.requestRender();\n\t\t\t\t},\n\t\t\t\tpreselectRole,\n\t\t\t);\n\t\t\treturn { component: selector, focus: selector };\n\t\t});\n\t} catch (error) {\n\t\thost.showError(error instanceof Error ? error.message : String(error));\n\t}\n}\n\n/** Persist a role assignment from the post-probe selector into the matching settings. */\nexport function assignFitnessRole(host: AssignRoleHost, modelRef: string, role: FitnessRole): void {\n\tif (role === \"none\") {\n\t\thost.showStatus(`Fitness result for ${modelRef} saved. Assign a role later from /settings.`);\n\t\treturn;\n\t}\n\tif (role === \"curator\") {\n\t\tconst current = host.settingsManager.getContextCurationSettings();\n\t\thost.settingsManager.setContextCurationSettings({ ...current, enabled: true, model: modelRef });\n\t\thost.showStatus(`Context curation enabled with ${modelRef} as the curator.`);\n\t\treturn;\n\t}\n\tif (role === \"executor\") {\n\t\tconst router = host.settingsManager.getModelRouterSettings();\n\t\thost.settingsManager.setModelRouterSettings({ ...router, executorModel: modelRef });\n\t\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\t\thost.showStatus(`${modelRef} set as the toolkit executor (direct Level-0 hits route to it).${hint}`);\n\t\treturn;\n\t}\n\tconst router = host.settingsManager.getModelRouterSettings();\n\tconst field =\n\t\trole === \"router-cheap\"\n\t\t\t? \"cheapModel\"\n\t\t\t: role === \"router-medium\"\n\t\t\t\t? \"mediumModel\"\n\t\t\t\t: role === \"router-expensive\"\n\t\t\t\t\t? \"expensiveModel\"\n\t\t\t\t\t: role === \"judge\"\n\t\t\t\t\t\t? \"judgeModel\"\n\t\t\t\t\t\t: \"learningModel\";\n\thost.settingsManager.setModelRouterSettings({ ...router, [field]: modelRef });\n\tconst hint = router.enabled ? \"\" : \" Model router is currently disabled — enable it in /settings → Model Router.\";\n\thost.showStatus(`${modelRef} set as ${role.replace(\"router-\", \"router \")} model.${hint}`);\n}\n"]}
|
package/docs/index.md
CHANGED
|
@@ -45,6 +45,7 @@ For the full first-run flow, see [Quickstart](quickstart.md).
|
|
|
45
45
|
- [Keybindings](keybindings.md) - default shortcuts and custom keybindings.
|
|
46
46
|
- [Sessions](sessions.md) - session management, branching, and tree navigation.
|
|
47
47
|
- [Compaction](compaction.md) - context compaction and branch summarization.
|
|
48
|
+
- [FastContext scout](scout.md) - read-only repository scout setup and 10 GB local profile.
|
|
48
49
|
|
|
49
50
|
## Customization
|
|
50
51
|
|
package/docs/providers.md
CHANGED
|
@@ -21,6 +21,8 @@ Use `/login` in interactive mode, then select a provider, or pass one directly (
|
|
|
21
21
|
|
|
22
22
|
Use `/logout` to clear credentials. Tokens are stored per provider in `~/.pi/agent/auth.json` and auto-refresh when expired.
|
|
23
23
|
|
|
24
|
+
If a subscription provider reports a terminal usage limit, Pi stops retrying that exhausted model, announces the condition, and switches the session to that provider's default model when it is authenticated and not already exhausted. API-key/metered quota failures do not auto-hop; Pi halts the turn and asks you to switch models, wait for the limit window, or resend explicitly.
|
|
25
|
+
|
|
24
26
|
## Running Multiple Providers at Once
|
|
25
27
|
|
|
26
28
|
Pi does not keep a single global active provider for running agents. Each Pi process/session has its own selected model, and `auth.json` can hold credentials for many providers at the same time. After logging in to both subscription providers, start separate terminals with explicit provider or model selection:
|
package/docs/scout.md
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
# FastContext scout
|
|
2
|
+
|
|
3
|
+
Pi can delegate broad repository exploration to a bounded read-only scout through the `context_scout` tool. The scout runs a fresh subagent with only `read`, `grep`, and `find`, then returns a short summary plus validated `file:line` citations. Treat scout output like other tool output: use it as evidence, then read the cited ranges yourself before editing.
|
|
4
|
+
|
|
5
|
+
## Install the reference local model
|
|
6
|
+
|
|
7
|
+
Pull the verified Q4 GGUF tag:
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
ollama pull hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
The Hugging Face repository also exposes `fastcontext4b.IQ3_M.imx.gguf`; use the Q4 tag above unless you need the smaller IQ3 quant.
|
|
14
|
+
|
|
15
|
+
After pulling:
|
|
16
|
+
|
|
17
|
+
1. Start pi in the target repo.
|
|
18
|
+
2. Run `/models` and confirm the Ollama model appears.
|
|
19
|
+
3. Run `/fitness` against the model before assigning it to `scout.model` or a router tier.
|
|
20
|
+
4. Only assign it if the tool-calls and research-lane probe surfaces pass. Pi's model-adoption gates refuse all-lanes-failed probes automatically.
|
|
21
|
+
|
|
22
|
+
Enable the tool with settings after the probe passes:
|
|
23
|
+
|
|
24
|
+
```json
|
|
25
|
+
{
|
|
26
|
+
"scout": {
|
|
27
|
+
"enabled": true,
|
|
28
|
+
"model": "ollama/hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`"model": "auto"` looks for an installed model whose provider/name/id contains `fastcontext`, then requires a host-local `/fitness` report that passes both `research` and `toolCall`. If no model resolves, the model is unprobed, or the required lanes failed, `context_scout` returns `scout unavailable: <cause>` instead of failing the main turn. An explicit `scout.model` pattern is a user choice and resolves without this auto-selection proof gate; scout output is still validated at runtime through citation checks.
|
|
34
|
+
|
|
35
|
+
## 10 GB reference profile
|
|
36
|
+
|
|
37
|
+
A practical 10 GB RAM layout:
|
|
38
|
+
|
|
39
|
+
- FastContext Q4 weights: about 2.5 GB.
|
|
40
|
+
- 32K-64K KV cache: about 1-2 GB.
|
|
41
|
+
- Pi process: about 0.5 GB.
|
|
42
|
+
- Main model: cloud-hosted, or a local Qwen3-4B-Instruct-2507 Q4 model (about 2.5 GB more).
|
|
43
|
+
|
|
44
|
+
Expected peak for scout + pi is roughly 5-6 GB; adding a local 4B main model still fits on a 10 GB machine. Pi warns when a chosen local model's installed size exceeds about 90% of RAM.
|
|
45
|
+
|
|
46
|
+
## Qwen3 chat-template caveat
|
|
47
|
+
|
|
48
|
+
Ollama derives the chat template from the GGUF. Verify tool calling with `/fitness` before trusting the scout. If the probe shows tool-call failures, create a Modelfile with an explicit Qwen3 template and probe that model instead:
|
|
49
|
+
|
|
50
|
+
```modelfile
|
|
51
|
+
FROM hf.co/KikoCis/FastContext-1.0-4B-longctx-imatrix-GGUF:fastcontext4b.Q4_K_M.imx.gguf
|
|
52
|
+
TEMPLATE """{{- if .System }}<|im_start|>system
|
|
53
|
+
{{ .System }}<|im_end|>
|
|
54
|
+
{{ end }}{{- range .Messages }}<|im_start|>{{ .Role }}
|
|
55
|
+
{{ .Content }}<|im_end|>
|
|
56
|
+
{{ end }}<|im_start|>assistant
|
|
57
|
+
"""
|
|
58
|
+
PARAMETER temperature 0
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Then:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
ollama create fastcontext-qwen3-tools -f Modelfile
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Probe `ollama/fastcontext-qwen3-tools` with `/fitness` before assigning it.
|
|
68
|
+
|
|
69
|
+
## Router cheap-tier recipe
|
|
70
|
+
|
|
71
|
+
FastContext is a scout, not a solver. With `modelRouter.fitnessGate` enabled, a FastContext-shaped report that passes `research` + `toolCall` but fails `worker` remains eligible for the cheap tier and is structurally excluded from medium/expensive solver tiers. Mutating turns must still escalate out of the cheap tier before write/edit/bash changes; keep the medium or expensive tier on a solver model.
|
package/docs/settings.md
CHANGED
|
@@ -116,18 +116,29 @@ Hard stops still require explicit foreground approval even in `full`: publishing
|
|
|
116
116
|
|
|
117
117
|
| Setting | Type | Default | Description |
|
|
118
118
|
|---------|------|---------|-------------|
|
|
119
|
-
| `modelRouter.enabled` | boolean | `false` | Enable deterministic cheap/expensive model routing |
|
|
119
|
+
| `modelRouter.enabled` | boolean | `false` | Enable deterministic cheap/medium/expensive model routing |
|
|
120
|
+
| `modelRouter.fitnessGate` | boolean | `false` | Opt-in subtractive gate: when a tier model has a host-local failed probe for its router lanes, skip or fall back instead of routing to it; unprobed tier models still route |
|
|
120
121
|
| `modelRouter.cheapModel` | string | - | Model pattern for read-only, research, explanation, and question turns |
|
|
121
|
-
| `modelRouter.
|
|
122
|
+
| `modelRouter.mediumModel` | string | - | Model pattern for scoped implementation/planning turns |
|
|
123
|
+
| `modelRouter.expensiveModel` | string | - | Model pattern for high-impact, modify, implementation, and escalated tool-heavy turns |
|
|
122
124
|
| `modelRouter.learningModel` | string | `"active"` | Model pattern for background reflection, learn, and skill-creator work; `"active"` uses the current session model |
|
|
125
|
+
| `failover.subscriptionHop` | boolean | `true` | Allow subscription/OAuth quota failures to switch once to an authenticated provider default; metered/API-key quota failures always halt for explicit user choice |
|
|
123
126
|
|
|
124
|
-
Use `/settings` → **Model Router** to configure these fields globally or for the current project's `.pi/settings.json`. `/session` and `/usage` show the active router state and
|
|
127
|
+
Use `/settings` → **Model Router** to configure these fields globally or for the current project's `.pi/settings.json`. `/session` and `/usage` show the active router state, diagnostics, and per-tier fitness when the gate is enabled. Profile files can also include a `modelRouter` block so a situation can carry its own cheap, medium, expensive, and learning/reflection models together with its model, thinking level, soul, and resource filters.
|
|
128
|
+
|
|
129
|
+
Fitness applicability is intentionally split by autonomy level:
|
|
130
|
+
|
|
131
|
+
- Class A autonomous adoption requires proof on this host: executor direct uses `toolCall`, curation uses `digest`, and scout `"auto"` uses `research` + `toolCall`.
|
|
132
|
+
- Class B routed turns are subtractive and opt-in via `modelRouter.fitnessGate`: cheap uses `research` + `toolCall`; medium/expensive use `worker` + `toolCall`; the routing judge uses parsed `judge` output. Unprobed tier models pass.
|
|
133
|
+
- Class C explicit user choices are sovereign: explicit `/model` and explicit `scout.model` patterns are not router-gated, except for the existing all-lanes-failed adoption backstop and runtime output checks.
|
|
125
134
|
|
|
126
135
|
```json
|
|
127
136
|
{
|
|
128
137
|
"modelRouter": {
|
|
129
138
|
"enabled": true,
|
|
139
|
+
"fitnessGate": true,
|
|
130
140
|
"cheapModel": "openrouter/google/gemini-flash-latest",
|
|
141
|
+
"mediumModel": "anthropic/claude-sonnet-4-5",
|
|
131
142
|
"expensiveModel": "openai-codex/gpt-5.5",
|
|
132
143
|
"learningModel": "anthropic/claude-haiku-4-5"
|
|
133
144
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-extension-custom-provider",
|
|
3
|
-
"version": "0.81.
|
|
3
|
+
"version": "0.81.3",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pi-extension-custom-provider",
|
|
9
|
-
"version": "0.81.
|
|
9
|
+
"version": "0.81.3",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@anthropic-ai/sdk": "^0.52.0"
|
|
12
12
|
}
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-extension-sandbox",
|
|
3
|
-
"version": "0.81.
|
|
3
|
+
"version": "0.81.3",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pi-extension-sandbox",
|
|
9
|
-
"version": "0.81.
|
|
9
|
+
"version": "0.81.3",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@anthropic-ai/sandbox-runtime": "^0.0.26"
|
|
12
12
|
}
|