/** * Smart Router Extension - Intelligent model routing for different task types * * Uses sigma-agents SmartRouter for task classification and model recommendation. * Analyzes user input keywords and suggests the optimal model per task category. * * Configuration: ~/.phi/agent/routing.json * Command: /routing — show config, enable/disable, test, reload */ import { mkdir, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { type ExtensionAPI, getAgentDir } from "phi-code"; import type { RoutingConfig } from "sigma-agents"; import { SmartRouter } from "sigma-agents"; import { resolveModelRef } from "./providers/orchestrator-helpers.ts"; // ─── Extension Config ──────────────────────────────────────────────────── interface ExtensionConfig { enabled: boolean; /** * When false (default), the smart router never changes the chat model — it * only emits an informational notification per prompt. Use `/model` to * choose the chat model; that choice is now the single source of truth * and is persisted across sessions via the settings manager. * * When true (opt-in via `/routing autoswitch on`), the router switches * the chat model to the preferred route per prompt, matching the * pre-0.75.6 behavior. */ autoSwitch: boolean; notifyOnRecommendation: boolean; } // ─── Extension ─────────────────────────────────────────────────────────── export default function smartRouterExtension(pi: ExtensionAPI) { const configDir = getAgentDir(); const configPath = join(configDir, "routing.json"); let router = new SmartRouter(SmartRouter.defaultConfig()); const extConfig: ExtensionConfig = { enabled: true, autoSwitch: false, notifyOnRecommendation: false, }; /** * Load routing config from ~/.phi/agent/routing.json */ async function loadConfig() { try { const config = await SmartRouter.loadConfig(configPath); router = new SmartRouter(config); } catch { // No config file — use defaults, and save them for reference try { await mkdir(configDir, { recursive: true }); const defaultConfig = SmartRouter.defaultConfig(); await writeFile(configPath, JSON.stringify(defaultConfig, null, 2), "utf-8"); } catch { // Can't write, that's fine } } } // ─── Input Event ───────────────────────────────────────────────── pi.on("input", async (event, ctx) => { if (!extConfig.enabled || event.source === "extension") { return { action: "continue" }; } // Do NOT route during orchestration — the orchestrator manages models if ((globalThis as any).__phiOrchestrationActive) { return { action: "continue" }; } const recommendation = router.getRecommendation(event.text); if (recommendation.category !== "general") { // Find the recommended model in the registry. routing.json refs are // "provider/id" (written by /setup and /plan-models): comparing them to // a bare m.id never matched, so auto-switch could never fire. const available = ctx.modelRegistry?.getAvailable?.() || []; const targetModel = resolveModelRef(available, recommendation.model); const fallbackRoute = (router as any).config?.routes?.[recommendation.category]; const fallbackModel = fallbackRoute?.fallback ? resolveModelRef(available, fallbackRoute.fallback) : undefined; const modelToUse = targetModel || fallbackModel; if (!modelToUse) { if (extConfig.notifyOnRecommendation) { ctx.ui.notify( `Routing suggestion: ${recommendation.category} → \`${recommendation.model}\` (not in registry).`, "info", ); } } else if (modelToUse.id === ctx.model?.id && modelToUse.provider === ctx.model?.provider) { // Already on the recommended model — nothing to do. } else if (extConfig.autoSwitch) { // Legacy opt-in behavior: actually swap the chat model. const switched = await pi.setModel(modelToUse); if (switched && extConfig.notifyOnRecommendation) { ctx.ui.notify( `Auto-switched (${recommendation.category}) → \`${modelToUse.id}\`${modelToUse !== targetModel ? " (fallback)" : ""}`, "info", ); } } else if (extConfig.notifyOnRecommendation) { // Default behavior: never override the user's `/model` choice. Just // advertise the suggestion — the chat model stays sticky. ctx.ui.notify( `Routing suggestion: ${recommendation.category} → \`${modelToUse.id}\`. Stay on \`${ctx.model?.id}\` (use \`/routing autoswitch on\` to auto-apply, or \`/model\` to change manually).`, "info", ); } } return { action: "continue" }; }); // ─── /routing Command ──────────────────────────────────────────── pi.registerCommand("routing", { description: "Show or configure smart routing (enable/disable/test/reload)", handler: async (args, ctx) => { const arg = args.trim().toLowerCase(); if (!arg) { const routingConfig = (router as any).config as RoutingConfig; let output = `**Smart Router** (powered by sigma-agents)\n\n`; output += `Status: ${extConfig.enabled ? "enabled" : "disabled"}\n`; output += `Auto-switch: ${extConfig.autoSwitch ? "on (overrides /model per prompt)" : "off (suggestions only — /model is sticky)"}\n`; output += `Notifications: ${extConfig.notifyOnRecommendation ? "on" : "off"}\n\n`; output += `**Routes:**\n`; for (const [cat, route] of Object.entries(routingConfig.routes)) { output += ` **${cat}** → \`${route.preferredModel}\` (fallback: \`${route.fallback}\`) [agent: ${route.agent || "none"}]\n`; output += ` Keywords: ${route.keywords.slice(0, 6).join(", ")}${route.keywords.length > 6 ? "..." : ""}\n`; } output += `\n **default** → \`${routingConfig.default.model}\` (orchestrator fallback only; chat default comes from \`/model\`)\n`; output += `\nConfig: \`${configPath}\``; output += `\nCommands: \`/routing [enable|disable|autoswitch on|autoswitch off|notify-on|notify-off|reload|test]\``; ctx.ui.notify(output, "info"); return; } const tokens = arg.split(/\s+/); const head = tokens[0]; if (head === "autoswitch") { const flag = tokens[1]; if (flag === "on") { extConfig.autoSwitch = true; ctx.ui.notify( "Auto-switch enabled: the smart router will override the chat model per prompt. " + "Disable with `/routing autoswitch off` if it gets in your way.", "info", ); } else if (flag === "off") { extConfig.autoSwitch = false; ctx.ui.notify("Auto-switch disabled. The model selected via `/model` is now sticky.", "info"); } else { ctx.ui.notify("Usage: `/routing autoswitch on|off`", "warning"); } return; } switch (arg) { case "enable": extConfig.enabled = true; ctx.ui.notify("Smart routing enabled.", "info"); break; case "disable": extConfig.enabled = false; ctx.ui.notify("Smart routing disabled.", "info"); break; case "notify-on": extConfig.notifyOnRecommendation = true; ctx.ui.notify("Routing notifications enabled.", "info"); break; case "notify-off": extConfig.notifyOnRecommendation = false; ctx.ui.notify("Routing notifications disabled.", "info"); break; case "reload": await loadConfig(); ctx.ui.notify("Routing config reloaded from disk.", "info"); break; case "test": { const tests = [ "implement a new user authentication system", "fix the crash when uploading files larger than 10MB", "explain how the middleware chain works", "plan the migration from REST to GraphQL", "run all unit tests and check coverage", "review the PR for security vulnerabilities", "what time is it", ]; let output = "**🧪 Routing Test:**\n\n"; for (const input of tests) { const rec = router.getRecommendation(input); output += `"${input}"\n → **${rec.category}** → \`${rec.model}\`\n\n`; } ctx.ui.notify(output, "info"); break; } default: ctx.ui.notify("Usage: `/routing [enable|disable|notify-on|notify-off|reload|test]`", "warning"); } }, }); // ─── Session Start ─────────────────────────────────────────────── // One listener at a time: session_start fires again on /new, /resume and // /fork, and re-registering there stacked one more listener (one more // reload) per session switch. Released on session_shutdown. let unsubscribeRouting: (() => void) | undefined; pi.on("session_start", async (_event, _ctx) => { await loadConfig(); // Listen for routing.json file-watcher events (emitted by keys.ts extension). // This implements Q9 strategy A: auto-reload SmartRouter when routing.json // changes on disk, no /routing reload command needed. unsubscribeRouting ??= pi.events.on("routing_json_changed", () => { loadConfig().catch(() => { // If reload fails, keep the in-memory config rather than wiping it }); }); }); pi.on("session_shutdown", async () => { unsubscribeRouting?.(); unsubscribeRouting = undefined; }); }