From c08fa5cacd47761c0be2c763b2d4d0baf4cd1b99 Mon Sep 17 00:00:00 2001 From: Rui Liang Date: Sat, 18 Jul 2026 21:33:45 +0800 Subject: [PATCH 1/3] update routing rules --- packages/coding-agent/src/core/router.ts | 200 ++++++++++++++++++----- 1 file changed, 159 insertions(+), 41 deletions(-) diff --git a/packages/coding-agent/src/core/router.ts b/packages/coding-agent/src/core/router.ts index 8dd5485..d8f7eff 100644 --- a/packages/coding-agent/src/core/router.ts +++ b/packages/coding-agent/src/core/router.ts @@ -16,16 +16,16 @@ import { export const ROUTE_PROVIDER_CHOICES = ["openai", "google", "anthropic"] as const; export type ProviderChoice = (typeof ROUTE_PROVIDER_CHOICES)[number]; -const DEFAULT_PROVIDER_CHOICE: ProviderChoice = "openai"; +const DEFAULT_PROVIDER_CHOICE: ProviderChoice = "anthropic"; const OPENROUTER_PROVIDER = "openrouter"; const CLASSIFIER_SYSTEM_PROMPT = "Classify the coding task into exactly one model provider."; const ROUTING_RULES: Record = { openai: - "General coding default — choose for simple edits, simple UI changes, tests, scripts, algorithms, code review, data analysis, and tasks that do not clearly fit another provider", + "Test and automation — choose for algorithms, code review, testing, data analysis, scripting, and CI/CD pipeline work", google: - "Google/mobile ecosystem — choose when the task specifically depends on Android, Flutter, Firebase, Google Cloud, Chrome extensions, Gradle, Kotlin, or Google APIs", + "Google ecosystem — choose when the task specifically depends on Android, Flutter, Firebase, Google Cloud, Chrome extensions, Gradle, Kotlin, or Google APIs", anthropic: - "Complex engineering — choose when the task requires deep repository context, architecture, refactoring, migrations, complex debugging, complex UI workflows, or broad code quality changes", + "General development — choose for all code writing, editing, debugging, architecture, refactoring, migrations, UI implementation, and any development task that does not specifically fit google or openai", }; export interface RouteSignal { @@ -62,6 +62,23 @@ export const ROUTING_ENTRY_TYPE = "openabcode-routing"; /** Per-provider keyword lists that extend the built-in heuristic tables. */ export type RouterHeuristicKeywords = Partial>; +/** + * All configurable router overrides, loaded from settings.json. + * When a field is set it fully replaces the corresponding built-in default. + */ +export interface RouterConfig { + /** LLM classifier descriptions per provider. Replaces ROUTING_RULES. */ + rules?: Partial>; + /** Per-provider keyword lists. Replaces HEURISTIC_KEYWORDS. */ + keywords?: RouterHeuristicKeywords; + /** File extension → provider mappings. Replaces HEURISTIC_FILE_EXTENSIONS. */ + fileExtensions?: Record; + /** Project marker → provider mappings. Replaces HEURISTIC_PROJECT_MARKERS. */ + projectMarkers?: Record; + /** Default fallback provider. Replaces DEFAULT_PROVIDER_CHOICE. */ + defaultProvider?: ProviderChoice; +} + export interface HeuristicRouteResult { choice: ProviderChoice; /** "high": multiple independent signals agree; "low": a single weak signal. */ @@ -83,22 +100,6 @@ const HEURISTIC_KEYWORDS: Record = { "firestore", "chrome extension", "play store", - "安卓", - "chrome 插件", - ], - anthropic: [ - "refactor", - "debug", - "architecture", - "migration", - "swift", - "ios", - "macos", - "xcode", - "重构", - "调试", - "架构", - "迁移", ], openai: [ "algorithm", @@ -106,27 +107,92 @@ const HEURISTIC_KEYWORDS: Record = { "unit test", "benchmark", "data analysis", - "devops", + "test coverage", + "ci/cd", "pipeline", - "算法", - "单元测试", - "代码审查", - "数据分析", + "multimodal", + ], + anthropic: [ + "refactor", + "debug", + "architecture", + "migration", + "implement", + "build", + "create", + "fix", + "feature", + "component", + "module", ], }; const HEURISTIC_FILE_EXTENSIONS: Record = { + // Google ecosystem ".kt": "google", ".kts": "google", ".dart": "google", ".gradle": "google", + // Anthropic / primary coding (all non-Google languages) ".swift": "anthropic", ".storyboard": "anthropic", ".xcodeproj": "anthropic", ".xcworkspace": "anthropic", + ".rs": "anthropic", + ".c": "anthropic", + ".h": "anthropic", + ".cpp": "anthropic", + ".cc": "anthropic", + ".cxx": "anthropic", + ".hpp": "anthropic", + ".hxx": "anthropic", + ".zig": "anthropic", + ".scala": "anthropic", + ".sc": "anthropic", + ".ex": "anthropic", + ".exs": "anthropic", + ".erl": "anthropic", + ".hrl": "anthropic", + ".hs": "anthropic", + ".ml": "anthropic", + ".mli": "anthropic", + ".clj": "anthropic", + ".cljs": "anthropic", + ".py": "anthropic", + ".js": "anthropic", + ".mjs": "anthropic", + ".cjs": "anthropic", + ".ts": "anthropic", + ".mts": "anthropic", + ".jsx": "anthropic", + ".tsx": "anthropic", + ".java": "anthropic", + ".go": "anthropic", + ".rb": "anthropic", + ".php": "anthropic", + ".cs": "anthropic", + ".lua": "anthropic", + ".r": "anthropic", + ".jl": "anthropic", + ".vue": "anthropic", + ".svelte": "anthropic", + ".proto": "anthropic", + ".css": "anthropic", + ".scss": "anthropic", + ".less": "anthropic", + ".html": "anthropic", + // OpenAI / test, automation, scripting, data + ".sh": "openai", + ".bash": "openai", + ".ps1": "openai", + ".sql": "openai", + ".tf": "openai", + ".graphql": "openai", + ".gql": "openai", }; const HEURISTIC_PROJECT_MARKERS: Record = { + // Google ecosystem "pubspec.yaml": "google", "build.gradle": "google", "build.gradle.kts": "google", @@ -134,8 +200,37 @@ const HEURISTIC_PROJECT_MARKERS: Record = { "settings.gradle.kts": "google", "androidmanifest.xml": "google", "firebase.json": "google", + // Anthropic / primary coding (all non-Google project types) "package.swift": "anthropic", podfile: "anthropic", + "cargo.toml": "anthropic", + "cmakelists.txt": "anthropic", + makefile: "anthropic", + "build.zig": "anthropic", + "build.sbt": "anthropic", + "mix.exs": "anthropic", + "rebar.config": "anthropic", + "stack.yaml": "anthropic", + "cabal.project": "anthropic", + "dune-project": "anthropic", + "project.clj": "anthropic", + "deps.edn": "anthropic", + "package.json": "anthropic", + "tsconfig.json": "anthropic", + "pyproject.toml": "anthropic", + "setup.py": "anthropic", + "requirements.txt": "anthropic", + pipfile: "anthropic", + "go.mod": "anthropic", + "pom.xml": "anthropic", + gemfile: "anthropic", + "composer.json": "anthropic", + "nuget.config": "anthropic", + // OpenAI / test, automation, infrastructure + "main.tf": "openai", + dockerfile: "openai", + "docker-compose.yml": "openai", + "docker-compose.yaml": "openai", }; function keywordMatches(keyword: string, text: string): boolean { @@ -151,20 +246,22 @@ function keywordMatches(keyword: string, text: string): boolean { * Zero-cost heuristic provider classification from prompt keywords, file * extensions, and project marker files. Returns undefined when no signal * matches or the top providers tie. + * + * When a config table is provided it fully replaces the corresponding built-in + * default; when absent the built-in table is used. */ -export function classifyProviderHeuristic( - input: RouteSignal, - customKeywords?: RouterHeuristicKeywords, -): HeuristicRouteResult | undefined { +export function classifyProviderHeuristic(input: RouteSignal, config?: RouterConfig): HeuristicRouteResult | undefined { const text = input.text.toLowerCase(); const fileNames = (input.fileNames ?? []).map((name) => name.toLowerCase()); const projectFiles = (input.projectFiles ?? []).map((name) => name.toLowerCase()); const matched: Record> = { openai: new Set(), google: new Set(), anthropic: new Set() }; + const effectiveKeywords: Record = config?.keywords + ? { openai: [], google: [], anthropic: [], ...config.keywords } + : HEURISTIC_KEYWORDS; for (const provider of ROUTE_PROVIDER_CHOICES) { - const keywords = [...HEURISTIC_KEYWORDS[provider], ...(customKeywords?.[provider] ?? [])]; - for (const keyword of keywords) { + for (const keyword of effectiveKeywords[provider]) { const normalized = keyword.toLowerCase(); if (normalized && keywordMatches(normalized, text)) { matched[provider].add(`keyword:${normalized}`); @@ -172,21 +269,23 @@ export function classifyProviderHeuristic( } } + const effectiveFileExtensions = config?.fileExtensions ?? HEURISTIC_FILE_EXTENSIONS; for (const fileName of fileNames) { - for (const [extension, provider] of Object.entries(HEURISTIC_FILE_EXTENSIONS)) { + for (const [extension, provider] of Object.entries(effectiveFileExtensions)) { if (fileName.endsWith(extension)) { matched[provider].add(`ext:${extension}`); } } } + const effectiveProjectMarkers = config?.projectMarkers ?? HEURISTIC_PROJECT_MARKERS; for (const projectFile of projectFiles) { - const provider = HEURISTIC_PROJECT_MARKERS[projectFile]; + const provider = effectiveProjectMarkers[projectFile]; if (provider) { matched[provider].add(`project:${projectFile}`); } // Bundle directories like MyApp.xcodeproj appear as project entries too. - for (const [extension, extProvider] of Object.entries(HEURISTIC_FILE_EXTENSIONS)) { + for (const [extension, extProvider] of Object.entries(effectiveFileExtensions)) { if (projectFile.endsWith(extension)) { matched[extProvider].add(`project:${extension}`); } @@ -199,6 +298,12 @@ export function classifyProviderHeuristic( const [top, runnerUp] = scores; if (top.score === 0 || top.score === runnerUp.score) return undefined; + // Signals pointing to the default provider are not distinctive — they just + // confirm "this is a normal project" which is already the fallback. Only + // non-default signals justify short-circuiting the LLM classifier. + const effectiveDefault = config?.defaultProvider ?? DEFAULT_PROVIDER_CHOICE; + if (top.provider === effectiveDefault) return undefined; + return { choice: top.provider, confidence: top.score >= 2 ? "high" : "low", @@ -214,13 +319,21 @@ function isProviderChoice(value: string): value is ProviderChoice { return ROUTE_PROVIDER_CHOICES.some((provider) => provider === value); } -function classifierPrompt(text: string, fileNames: string[], projectFiles: string[], recentContext: string[]): string { +function classifierPrompt( + text: string, + fileNames: string[], + projectFiles: string[], + recentContext: string[], + config?: RouterConfig, +): string { + const rules = config?.rules ?? ROUTING_RULES; + const defaultProvider = config?.defaultProvider ?? DEFAULT_PROVIDER_CHOICE; return `You are a coding task router. Given the project context and user request, choose which AI model provider should handle this task. Routing rules: -${ROUTE_PROVIDER_CHOICES.map((provider) => `- "${provider}": ${ROUTING_RULES[provider]}`).join("\n")} +${ROUTE_PROVIDER_CHOICES.map((provider) => `- "${provider}": ${rules[provider] ?? "(no rule)"}`).join("\n")} -Default to "${DEFAULT_PROVIDER_CHOICE}" if the task does not clearly fit another provider. +Default to "${defaultProvider}" if the task does not clearly fit another provider. ${projectFiles.length > 0 ? `Project root files: ${projectFiles.join(", ")}\n` : ""}${fileNames.length > 0 ? `Files involved: ${fileNames.join(", ")}\n` : ""}${recentContext.length > 0 ? `Recent conversation:\n${recentContext.map((snippet) => `- ${snippet}`).join("\n")}\n` : ""}Task: "${text}" @@ -235,7 +348,9 @@ export async function classifyProvider( model: Model, input: RouteSignal, options: SimpleStreamOptions, + config?: RouterConfig, ): Promise { + const defaultProvider = config?.defaultProvider ?? DEFAULT_PROVIDER_CHOICE; const fileNames = (input.fileNames ?? []).filter(Boolean); const projectFiles = input.projectFiles ?? []; const recentContext = (input.recentContext ?? []).filter(Boolean); @@ -251,7 +366,10 @@ export async function classifyProvider( { role: "user", content: [ - { type: "text", text: classifierPrompt(input.text, fileNames, projectFiles, recentContext) }, + { + type: "text", + text: classifierPrompt(input.text, fileNames, projectFiles, recentContext, config), + }, ], timestamp: Date.now(), }, @@ -260,7 +378,7 @@ export async function classifyProvider( { ...options, signal: controller.signal, temperature: 0, maxTokens: 16 }, ); - if (response.stopReason === "error" || response.stopReason === "aborted") return DEFAULT_PROVIDER_CHOICE; + if (response.stopReason === "error" || response.stopReason === "aborted") return defaultProvider; const raw = response.content .filter((part): part is { type: "text"; text: string } => part.type === "text") .map((part) => part.text) @@ -269,9 +387,9 @@ export async function classifyProvider( .toLowerCase() .replace(/"/g, ""); if (isProviderChoice(raw)) return raw; - return DEFAULT_PROVIDER_CHOICE; + return defaultProvider; } catch { - return DEFAULT_PROVIDER_CHOICE; + return defaultProvider; } finally { clearTimeout(timeout); } From 2b6820e1d4c9a77e1b2d1d192cae6cd543162018 Mon Sep 17 00:00:00 2001 From: Rui Liang Date: Sat, 18 Jul 2026 22:50:57 +0800 Subject: [PATCH 2/3] feat(router): enhance customization of routing rules and heuristics --- README.md | 37 +++++++++ .../coding-agent/src/core/agent-session.ts | 14 +++- .../coding-agent/src/core/settings-manager.ts | 44 +++++++--- .../test/settings-manager.test.ts | 64 +++++++++++++++ .../coding-agent/test/suite/router.test.ts | 80 ++++++++++++++----- 5 files changed, 208 insertions(+), 31 deletions(-) diff --git a/README.md b/README.md index 772af1c..fa46a48 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,43 @@ Inside the interactive CLI: When Route is on, the footer shows the configured execution models. Every completed routing decision is also stored in the session JSONL for audit. +## Customizing Route Rules + +Route rules, heuristic keywords, file extension mappings, project markers, and the default provider can all be customized in `~/.openabcode/agent/settings.json` (global) or `.openabcode/settings.json` (project-level). When a field is set, it fully replaces the corresponding built-in default. + +```json +{ + "router": { + "rules": { + "openai": "Test and automation — algorithms, code review, testing, data analysis, scripting", + "google": "Google ecosystem — Android, Flutter, Firebase, Google Cloud, Kotlin", + "anthropic": "General development — all code writing, editing, debugging, architecture, UI" + }, + "keywords": { + "openai": ["algorithm", "unit test", "benchmark", "data analysis", "pipeline"], + "google": ["android", "flutter", "dart", "firebase", "gcp"], + "anthropic": ["refactor", "debug", "architecture", "implement", "fix"] + }, + "fileExtensions": { + ".kt": "google", + ".dart": "google", + ".rs": "anthropic", + ".ts": "anthropic", + ".sh": "openai" + }, + "projectMarkers": { + "pubspec.yaml": "google", + "cargo.toml": "anthropic", + "package.json": "anthropic", + "main.tf": "openai" + }, + "defaultProvider": "anthropic" + } +} +``` + +Each field is optional and independent — only configure what you want to override. + ## Architecture ```text diff --git a/packages/coding-agent/src/core/agent-session.ts b/packages/coding-agent/src/core/agent-session.ts index d9a0dc4..8a7322f 100644 --- a/packages/coding-agent/src/core/agent-session.ts +++ b/packages/coding-agent/src/core/agent-session.ts @@ -98,6 +98,7 @@ import { pickRouteModel, ROUTE_PROVIDER_CHOICES, ROUTING_ENTRY_TYPE, + type RouterConfig, type RoutingDecision, type RoutingMethod, } from "./router.ts"; @@ -1613,10 +1614,14 @@ export class AgentSession { } const decisionID = `rtd_${randomUUID()}`; - const heuristic = classifyProviderHeuristic( - { text, projectFiles }, - this.settingsManager.getRouterHeuristicKeywords(), - ); + const routerConfig: RouterConfig = { + keywords: this.settingsManager.getRouterHeuristicKeywords(), + rules: this.settingsManager.getRouterHeuristicRules(), + fileExtensions: this.settingsManager.getRouterHeuristicFileExtensions() as RouterConfig["fileExtensions"], + projectMarkers: this.settingsManager.getRouterHeuristicProjectMarkers() as RouterConfig["projectMarkers"], + defaultProvider: this.settingsManager.getRouterDefaultProvider() as ProviderChoice | undefined, + }; + const heuristic = classifyProviderHeuristic({ text, projectFiles }, routerConfig); let choice: ProviderChoice; let method: RoutingMethod; @@ -1645,6 +1650,7 @@ export class AgentSession { : auth.headers, env: auth.env, }, + routerConfig, ); method = "classifier"; usedClassifier = true; diff --git a/packages/coding-agent/src/core/settings-manager.ts b/packages/coding-agent/src/core/settings-manager.ts index f2ce0de..1906d69 100644 --- a/packages/coding-agent/src/core/settings-manager.ts +++ b/packages/coding-agent/src/core/settings-manager.ts @@ -70,14 +70,24 @@ export interface RouterSettings { anthropic?: string; // "provider/modelId" preferred for anthropic-routed tasks openai?: string; // "provider/modelId" preferred for openai-routed tasks }; - heuristics?: { - // Extra keywords per provider that extend the built-in heuristic routing tables - keywords?: { - google?: string[]; - anthropic?: string[]; - openai?: string[]; - }; + // Per-provider keywords; replaces the built-in keyword table when set + keywords?: { + google?: string[]; + anthropic?: string[]; + openai?: string[]; + }; + // LLM classifier descriptions per provider; replaces the built-in rules when set + rules?: { + google?: string; + anthropic?: string; + openai?: string; }; + // File extension → provider mappings; replaces the built-in table when set + fileExtensions?: Record; + // Project marker file → provider mappings; replaces the built-in table when set + projectMarkers?: Record; + // Override the default fallback provider (default: "anthropic") + defaultProvider?: string; } export type TransportSetting = Transport; @@ -813,8 +823,24 @@ export class SettingsManager { return this.settings.router?.models ?? {}; } - getRouterHeuristicKeywords(): { google?: string[]; anthropic?: string[]; openai?: string[] } { - return this.settings.router?.heuristics?.keywords ?? {}; + getRouterHeuristicKeywords(): { google?: string[]; anthropic?: string[]; openai?: string[] } | undefined { + return this.settings.router?.keywords; + } + + getRouterHeuristicRules(): { google?: string; anthropic?: string; openai?: string } | undefined { + return this.settings.router?.rules; + } + + getRouterHeuristicFileExtensions(): Record | undefined { + return this.settings.router?.fileExtensions; + } + + getRouterHeuristicProjectMarkers(): Record | undefined { + return this.settings.router?.projectMarkers; + } + + getRouterDefaultProvider(): string | undefined { + return this.settings.router?.defaultProvider; } getDefaultThinkingLevel(): ThinkingLevel | undefined { diff --git a/packages/coding-agent/test/settings-manager.test.ts b/packages/coding-agent/test/settings-manager.test.ts index fed8d55..4ef45c3 100644 --- a/packages/coding-agent/test/settings-manager.test.ts +++ b/packages/coding-agent/test/settings-manager.test.ts @@ -558,5 +558,69 @@ describe("SettingsManager", () => { expect(saved.defaultModel).toBe("claude-sonnet-4-6"); expect(saved.router).toEqual({ enabled: false, setupCompleted: true }); }); + + it("returns heuristic rules from settings", () => { + writeFileSync( + join(agentDir, "settings.json"), + JSON.stringify({ + router: { rules: { openai: "Custom rule" } }, + }), + ); + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicRules()).toEqual({ openai: "Custom rule" }); + }); + + it("returns undefined when no heuristic rules are configured", () => { + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicRules()).toBeUndefined(); + }); + + it("returns heuristic file extensions from settings", () => { + writeFileSync( + join(agentDir, "settings.json"), + JSON.stringify({ + router: { fileExtensions: { ".rs": "anthropic" } }, + }), + ); + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicFileExtensions()).toEqual({ ".rs": "anthropic" }); + }); + + it("returns undefined when no file extensions are configured", () => { + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicFileExtensions()).toBeUndefined(); + }); + + it("returns heuristic project markers from settings", () => { + writeFileSync( + join(agentDir, "settings.json"), + JSON.stringify({ + router: { projectMarkers: { "Cargo.toml": "anthropic" } }, + }), + ); + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicProjectMarkers()).toEqual({ "Cargo.toml": "anthropic" }); + }); + + it("returns default provider from settings", () => { + writeFileSync( + join(agentDir, "settings.json"), + JSON.stringify({ + router: { defaultProvider: "anthropic" }, + }), + ); + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterDefaultProvider()).toBe("anthropic"); + }); + + it("returns undefined when no default provider is configured", () => { + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterDefaultProvider()).toBeUndefined(); + }); + + it("returns undefined for keywords when not configured", () => { + const manager = SettingsManager.create(projectDir, agentDir); + expect(manager.getRouterHeuristicKeywords()).toBeUndefined(); + }); }); }); diff --git a/packages/coding-agent/test/suite/router.test.ts b/packages/coding-agent/test/suite/router.test.ts index 87708c6..b7bae7f 100644 --- a/packages/coding-agent/test/suite/router.test.ts +++ b/packages/coding-agent/test/suite/router.test.ts @@ -119,16 +119,15 @@ describe("OpenABCode heuristic router", () => { expect(result?.matched).toContain("project:pubspec.yaml"); }); - it("classifies with low confidence on a single weak signal", () => { - const result = classifyProviderHeuristic({ text: "improve the algorithm here" }); - expect(result?.choice).toBe("openai"); - expect(result?.confidence).toBe("low"); + it("returns undefined for default-provider signals (defers to classifier)", () => { + // "refactor" matches anthropic, but anthropic is now the default — not distinctive + const result = classifyProviderHeuristic({ text: "refactor the auth module" }); + expect(result).toBeUndefined(); }); - it("matches Chinese keywords", () => { - const result = classifyProviderHeuristic({ text: "帮我重构这个模块的架构" }); - expect(result?.choice).toBe("anthropic"); - expect(result?.confidence).toBe("high"); + it("does not match Chinese text against ASCII-only keywords", () => { + // Chinese text falls through to the LLM classifier when no Chinese keywords are configured + expect(classifyProviderHeuristic({ text: "帮我重构这个模块的架构" })).toBeUndefined(); }); it("uses word boundaries for ASCII keywords", () => { @@ -138,11 +137,11 @@ describe("OpenABCode heuristic router", () => { it("scores file extensions and project bundle markers", () => { const result = classifyProviderHeuristic({ - text: "update the view", - fileNames: ["Sources/App/ContentView.swift"], - projectFiles: ["Package.swift", "MyApp.xcodeproj"], + text: "update the screen", + fileNames: ["lib/main.dart"], + projectFiles: ["pubspec.yaml", "README.md"], }); - expect(result?.choice).toBe("anthropic"); + expect(result?.choice).toBe("google"); expect(result?.confidence).toBe("high"); }); @@ -152,15 +151,60 @@ describe("OpenABCode heuristic router", () => { expect(result).toBeUndefined(); }); - it("extends the built-in tables with custom keywords from settings", () => { - const withoutCustom = classifyProviderHeuristic({ text: "tune the acme-widget renderer" }); - expect(withoutCustom).toBeUndefined(); + it("replaces the built-in keyword table when config.keywords is set", () => { + // "refactor" is a built-in anthropic keyword but anthropic is default so heuristic ignores it + const withBuiltin = classifyProviderHeuristic({ text: "refactor the auth module" }); + expect(withBuiltin).toBeUndefined(); + // Moving "refactor" to google (non-default) makes it a distinctive signal const result = classifyProviderHeuristic( - { text: "tune the acme-widget renderer and its acme runtime" }, - { anthropic: ["acme-widget", "acme runtime"] }, + { text: "refactor the auth module" }, + { keywords: { google: ["refactor"], anthropic: [], openai: [] } }, ); + expect(result?.choice).toBe("google"); + }); + + it("replaces the built-in file extension table when config.fileExtensions is set", () => { + // .dart is normally google (non-default); custom table maps only .rs to google + const withBuiltin = classifyProviderHeuristic({ + text: "update the screen", + fileNames: ["main.dart"], + }); + expect(withBuiltin?.choice).toBe("google"); + + const result = classifyProviderHeuristic( + { text: "update the screen", fileNames: ["main.dart"] }, + { fileExtensions: { ".rs": "google" } }, + ); + // .dart no longer matches anything in the custom table + expect(result).toBeUndefined(); + }); + + it("replaces the built-in project markers table when config.projectMarkers is set", () => { + // pubspec.yaml is normally google (non-default) + const withBuiltin = classifyProviderHeuristic({ + text: "update the config", + projectFiles: ["pubspec.yaml"], + }); + expect(withBuiltin?.choice).toBe("google"); + + const result = classifyProviderHeuristic( + { text: "update the config", projectFiles: ["pubspec.yaml"] }, + { projectMarkers: { "go.mod": "openai" } }, + ); + expect(result).toBeUndefined(); + }); + + it("returns undefined for default-provider-only signals (defers to classifier)", () => { + // anthropic is now the default; its signals should not short-circuit + const result = classifyProviderHeuristic({ text: "debug the module" }); + expect(result).toBeUndefined(); + }); + + it("allows default-provider signals when defaultProvider is overridden", () => { + // When defaultProvider is changed to google, anthropic signals become distinctive + const result = classifyProviderHeuristic({ text: "debug the handler" }, { defaultProvider: "google" }); expect(result?.choice).toBe("anthropic"); - expect(result?.confidence).toBe("high"); + expect(result?.confidence).toBe("low"); }); }); From b3fbc628887e4e79655fe99d471da4a36b5c82fb Mon Sep 17 00:00:00 2001 From: Rui Liang Date: Sun, 19 Jul 2026 00:04:49 +0800 Subject: [PATCH 3/3] fix(router): preserve explicit default-provider signals --- packages/coding-agent/src/core/router.ts | 9 +++++---- .../coding-agent/test/suite/router.test.ts | 18 ++++++++++-------- 2 files changed, 15 insertions(+), 12 deletions(-) diff --git a/packages/coding-agent/src/core/router.ts b/packages/coding-agent/src/core/router.ts index d8f7eff..66d7d0f 100644 --- a/packages/coding-agent/src/core/router.ts +++ b/packages/coding-agent/src/core/router.ts @@ -298,11 +298,12 @@ export function classifyProviderHeuristic(input: RouteSignal, config?: RouterCon const [top, runnerUp] = scores; if (top.score === 0 || top.score === runnerUp.score) return undefined; - // Signals pointing to the default provider are not distinctive — they just - // confirm "this is a normal project" which is already the fallback. Only - // non-default signals justify short-circuiting the LLM classifier. + // Project and file signals pointing to the default provider merely confirm + // the ambient ecosystem, so let the classifier evaluate task complexity. + // Explicit task keywords remain distinctive and may override sticky routing. const effectiveDefault = config?.defaultProvider ?? DEFAULT_PROVIDER_CHOICE; - if (top.provider === effectiveDefault) return undefined; + const hasTaskKeyword = [...matched[top.provider]].some((signal) => signal.startsWith("keyword:")); + if (top.provider === effectiveDefault && !hasTaskKeyword) return undefined; return { choice: top.provider, diff --git a/packages/coding-agent/test/suite/router.test.ts b/packages/coding-agent/test/suite/router.test.ts index b7bae7f..2398238 100644 --- a/packages/coding-agent/test/suite/router.test.ts +++ b/packages/coding-agent/test/suite/router.test.ts @@ -119,9 +119,11 @@ describe("OpenABCode heuristic router", () => { expect(result?.matched).toContain("project:pubspec.yaml"); }); - it("returns undefined for default-provider signals (defers to classifier)", () => { - // "refactor" matches anthropic, but anthropic is now the default — not distinctive - const result = classifyProviderHeuristic({ text: "refactor the auth module" }); + it("returns undefined for default-provider environment signals (defers to classifier)", () => { + const result = classifyProviderHeuristic({ + text: "update the application", + projectFiles: ["package.json", "tsconfig.json"], + }); expect(result).toBeUndefined(); }); @@ -152,9 +154,9 @@ describe("OpenABCode heuristic router", () => { }); it("replaces the built-in keyword table when config.keywords is set", () => { - // "refactor" is a built-in anthropic keyword but anthropic is default so heuristic ignores it + // Explicit task keywords remain actionable even when they target the default provider. const withBuiltin = classifyProviderHeuristic({ text: "refactor the auth module" }); - expect(withBuiltin).toBeUndefined(); + expect(withBuiltin?.choice).toBe("anthropic"); // Moving "refactor" to google (non-default) makes it a distinctive signal const result = classifyProviderHeuristic( @@ -195,10 +197,10 @@ describe("OpenABCode heuristic router", () => { expect(result).toBeUndefined(); }); - it("returns undefined for default-provider-only signals (defers to classifier)", () => { - // anthropic is now the default; its signals should not short-circuit + it("allows explicit task keywords to select the default provider", () => { const result = classifyProviderHeuristic({ text: "debug the module" }); - expect(result).toBeUndefined(); + expect(result?.choice).toBe("anthropic"); + expect(result?.confidence).toBe("high"); }); it("allows default-provider signals when defaultProvider is overridden", () => {