@s-berdia/opencode-router 1.1.0 → 1.2.0

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/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/types.ts","../src/catalog.ts","../src/paths.ts","../node_modules/jsonc-parser/lib/esm/impl/scanner.js","../node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../node_modules/jsonc-parser/lib/esm/impl/format.js","../node_modules/jsonc-parser/lib/esm/impl/parser.js","../node_modules/jsonc-parser/lib/esm/impl/edit.js","../node_modules/jsonc-parser/lib/esm/main.js","../src/scoring.ts","../src/feeds.ts","../src/config.ts","../model-scores.json","../src/score-table.ts","../src/rank.ts","../src/engine.ts","../src/format.ts","../src/apply.ts","../src/ledger.ts","../src/install.ts","../src/commands.ts","../src/state.ts","../src/eval.ts","../src/update.ts","../src/bin.ts"],"sourcesContent":["import { parseArgs } from \"node:util\"\nimport { activeEntries, buildRoutingTable, statusRows, usagePercent } from \"./engine.js\"\nimport { formatScorecard, formatStatus } from \"./format.js\"\nimport { patchServerConfig, routingConfigBody, writeRoutingConfig } from \"./apply.js\"\nimport { LedgerStore } from \"./ledger.js\"\nimport { catalogMeta } from \"./catalog.js\"\nimport { installCommands } from \"./install.js\"\nimport { runEval } from \"./eval.js\"\nimport { editJsonFile, globalRouterConfigFile, isProjectDir, projectRouterConfigFile, readJson } from \"./paths.js\"\nimport { ledgerFile, readApplyMarker } from \"./state.js\"\nimport { PACKAGE_NAME, checkForUpdate, clearOutdatedCopies, fetchLatestVersion, updateNotice } from \"./update.js\"\nimport { isPlan, PLAN_PROFILES } from \"./types.js\"\nimport type { ConfigScope, PlanProfile } from \"./types.js\"\n\nconst HELP = `opencode-router - dynamic model routing for OpenCode Go / Go Plus / Free\n\nUsage:\n opencode-router refresh [options] Recompute the routing table and apply it\n opencode-router status [options] Show the model in use per role and its 5-hour quota use\n opencode-router plan <profile> Save the plan profile (go | go-plus | free) and rebuild\n opencode-router install [--scope] Write slash-command files and a starter config\n opencode-router cat Show catalog metadata (path, date, model count)\n opencode-router eval Run the scoring stress test\n opencode-router update Look for a newer version and clear OpenCode's cached copy\n\nOptions:\n --plan <go|go-plus|free> Plan profile for this run\n --scope <project|global> Which config files to write (default: project in a project folder, else global)\n --catalog <file> Path to an OpenCode models.json cache\n --dry-run Do not write opencode.json\n --no-apply Write opencode.json but do not send it to a running server\n --json Print machine-readable JSON\n --verbose Include score source tags\n -h, --help Show this help\n`\n\nconst PLAN_CHOICES = PLAN_PROFILES.join(\" | \")\n\n/** A mistake in the command line: exit code 2 with a short message, no stack trace. */\nclass UsageError extends Error {}\n\ninterface CommonOpts {\n plan?: PlanProfile\n scope: ConfigScope\n catalog?: string\n dryRun: boolean\n apply: boolean\n json: boolean\n verbose: boolean\n cwd: string\n}\n\n/**\n * Resolve the config scope. When the caller did not pass --scope and the\n * directory is not a real project (for example OpenCode's shell runs from the\n * home directory), fall back to the global config.\n */\nexport function resolveScope(explicit: boolean, value: ConfigScope, dir: string): ConfigScope {\n if (explicit) return value\n return isProjectDir(dir) ? \"project\" : \"global\"\n}\n\nfunction parsePlan(value: string | undefined): PlanProfile | undefined {\n if (value === undefined) return undefined\n if (!isPlan(value)) throw new UsageError(`--plan must be one of ${PLAN_CHOICES}, not \"${value}\"`)\n return value\n}\n\nfunction parseScope(value: string | undefined): ConfigScope | undefined {\n if (value === undefined || value === \"project\" || value === \"global\") return value\n throw new UsageError(`--scope must be project or global, not \"${value}\"`)\n}\n\nfunction parseCommandLine(argv: string[], cwd: string) {\n let parsed\n try {\n parsed = parseArgs({\n args: argv,\n options: {\n plan: { type: \"string\" },\n scope: { type: \"string\" },\n catalog: { type: \"string\" },\n \"dry-run\": { type: \"boolean\" },\n \"no-apply\": { type: \"boolean\" },\n json: { type: \"boolean\" },\n verbose: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n },\n allowPositionals: true,\n })\n } catch (error) {\n throw new UsageError(error instanceof Error ? error.message : String(error))\n }\n const { values, positionals } = parsed\n const scope = parseScope(values.scope)\n const opts: CommonOpts = {\n plan: parsePlan(values.plan),\n scope: resolveScope(scope !== undefined, scope ?? \"project\", cwd),\n catalog: values.catalog,\n dryRun: values[\"dry-run\"] === true,\n apply: values[\"no-apply\"] !== true,\n json: values.json === true,\n verbose: values.verbose === true,\n cwd,\n }\n return { command: positionals[0], args: positionals.slice(1), help: values.help === true, opts }\n}\n\nfunction build(opts: CommonOpts) {\n return buildRoutingTable({ plan: opts.plan, catalogFile: opts.catalog, projectDir: opts.cwd })\n}\n\nasync function writeUpdateNotice(opts: CommonOpts): Promise<void> {\n const update = await checkForUpdate({ projectDir: opts.cwd })\n if (update) process.stdout.write(`\\n${updateNotice(update)}\\n`)\n}\n\nasync function cmdRefresh(opts: CommonOpts): Promise<number> {\n const { table } = await build(opts)\n\n if (opts.json) {\n process.stdout.write(JSON.stringify({ table, routing: routingConfigBody(table) }, null, 2) + \"\\n\")\n } else {\n process.stdout.write(formatScorecard(table, { verbose: opts.verbose }) + \"\\n\")\n }\n\n let detail = \"dry-run: nothing written\"\n let applied = false\n if (!opts.dryRun) {\n const written = writeRoutingConfig(table, opts.scope, opts.cwd)\n detail = `${written.created ? \"created\" : \"updated\"} ${written.path}`\n // A slash command's plugin hook may have hot-applied the table already.\n const marker = readApplyMarker()\n if (marker) {\n detail += ` | ${marker.detail}`\n applied = marker.ok\n } else if (opts.apply) {\n const patch = await patchServerConfig(table)\n detail += patch.applied ? ` | hot-applied (${patch.detail})` : ` | ${patch.detail}`\n applied = patch.applied\n }\n }\n\n if (!opts.json) {\n process.stdout.write(`\\nApplied: ${detail}\\n`)\n if (!opts.dryRun && !applied) {\n process.stdout.write(\n \"A running OpenCode session recomputes routing on its next message (within 15 s). Restart to reload the UI display now.\\n\",\n )\n }\n await writeUpdateNotice(opts)\n }\n return 0\n}\n\nasync function cmdStatus(opts: CommonOpts): Promise<number> {\n const result = await build(opts)\n const ledger = new LedgerStore(ledgerFile())\n const rows = statusRows(result, ledger)\n\n if (opts.json) {\n const usage: Record<string, { pct: number }> = {}\n for (const entry of activeEntries(result.table)) usage[entry.id] = { pct: usagePercent(result, ledger, entry.id) }\n process.stdout.write(JSON.stringify({ table: result.table, rows, usage }, null, 2) + \"\\n\")\n } else {\n process.stdout.write(formatStatus(result.table, rows) + \"\\n\")\n await writeUpdateNotice(opts)\n }\n return 0\n}\n\nasync function cmdPlan(profile: string | undefined, opts: CommonOpts): Promise<number> {\n if (!isPlan(profile)) throw new UsageError(`plan must be one of ${PLAN_CHOICES}`)\n const file = opts.scope === \"global\" ? globalRouterConfigFile() : projectRouterConfigFile(opts.cwd)\n editJsonFile(file, [{ path: [\"plan\"], value: profile }])\n process.stdout.write(`Plan set to \"${profile}\" in ${file}\\n`)\n\n if (opts.scope === \"global\") {\n const projectFile = projectRouterConfigFile(opts.cwd)\n const projectPlan = readJson<{ plan?: unknown }>(projectFile)?.plan\n if (projectPlan !== undefined && projectPlan !== profile) {\n process.stdout.write(\n `Note: ${projectFile} sets \"plan\": ${JSON.stringify(projectPlan)}, which overrides the global plan in this project.\\n`,\n )\n }\n }\n\n process.stdout.write(\"\\n\")\n return cmdRefresh({ ...opts, plan: undefined })\n}\n\nfunction cmdCat(catalog?: string): number {\n const meta = catalogMeta(catalog)\n process.stdout.write(`Catalog: ${meta.path}\\n`)\n process.stdout.write(`Modified: ${meta.mtime ?? \"missing\"}\\n`)\n process.stdout.write(`Routed models: ${meta.total}\\n`)\n return 0\n}\n\nfunction cmdInstall(opts: CommonOpts): number {\n const result = installCommands(opts.scope, opts.cwd)\n process.stdout.write(`Wrote ${result.files.length} command files to ${result.commandDir}\\n`)\n process.stdout.write(\n result.configCreated ? `Wrote starter config: ${result.configPath}\\n` : `Kept existing config: ${result.configPath}\\n`,\n )\n return 0\n}\n\n/** Compare OpenCode's cached copies, not this process: `npx ...@latest update` is always the newest. */\nasync function cmdUpdate(): Promise<number> {\n const latest = await fetchLatestVersion()\n if (!latest) {\n process.stderr.write(\"error: could not reach the npm registry. Try again later.\\n\")\n return 1\n }\n\n const { removed, pinned, current, failed } = clearOutdatedCopies(latest)\n if (failed.length > 0) {\n for (const { dir, error } of failed) process.stderr.write(`error: could not remove ${dir} (${error})\\n`)\n process.stderr.write(`Close OpenCode, then run this command in a terminal: npx ${PACKAGE_NAME}@latest update\\n`)\n return 1\n }\n for (const dir of removed) process.stdout.write(`Removed the cached copy: ${dir}\\n`)\n if (removed.length > 0) {\n process.stdout.write(`Restart OpenCode. It then installs opencode-router ${latest}.\\n`)\n }\n if (pinned.length > 0) {\n process.stdout.write(\n `opencode.json pins an older version (${pinned.join(\", \")}). Change the plugin entry to \"${PACKAGE_NAME}@${latest}\", then restart OpenCode.\\n`,\n )\n }\n if (removed.length > 0 || pinned.length > 0) return 0\n\n if (current.length > 0) {\n process.stdout.write(`OpenCode has opencode-router ${latest}, the newest version.\\n`)\n } else {\n process.stdout.write(\n `OpenCode has no cached copy of opencode-router. The newest version is ${latest}. If you use a local build, run git pull and npm run build. If your OpenCode has the command \"opencode plugin update\", run it.\\n`,\n )\n }\n return 0\n}\n\nfunction usageError(error: Error): number {\n process.stderr.write(`error: ${error.message}\\n\\nRun \"opencode-router --help\" for usage.\\n`)\n return 2\n}\n\n/** Run one CLI command. Returns the exit code; never exits the process. */\nexport async function main(argv: string[], cwd: string = process.cwd()): Promise<number> {\n try {\n const { command, args, help, opts } = parseCommandLine(argv, cwd)\n if (!command || command === \"help\" || help) {\n process.stdout.write(HELP)\n return 0\n }\n switch (command) {\n case \"refresh\":\n return await cmdRefresh(opts)\n case \"status\":\n return await cmdStatus(opts)\n case \"plan\":\n return await cmdPlan(args[0], opts)\n case \"cat\":\n return cmdCat(opts.catalog)\n case \"install\":\n return cmdInstall(opts)\n case \"eval\":\n return await runEval({ plan: opts.plan, catalog: opts.catalog, json: opts.json, projectDir: opts.cwd })\n case \"update\":\n return await cmdUpdate()\n default:\n throw new UsageError(`unknown command \"${command}\"`)\n }\n } catch (error) {\n if (error instanceof UsageError) return usageError(error)\n throw error\n }\n}\n","// Shared types and the constant lists they are built from.\n\nexport const PLAN_PROFILES = [\"go\", \"go-plus\", \"free\"] as const\n\nexport type PlanProfile = (typeof PLAN_PROFILES)[number]\n\nexport function isPlan(value: unknown): value is PlanProfile {\n return typeof value === \"string\" && (PLAN_PROFILES as readonly string[]).includes(value)\n}\n\n/** Which config files a command reads and writes. */\nexport type ConfigScope = \"global\" | \"project\"\n\n/** OpenCode agents that the router switches per message. */\nexport const AGENT_ROLES = [\"plan\", \"build\", \"general\", \"explore\"] as const\n\n/** Helper models that OpenCode reads from the config only. */\nexport const INTERNAL_ROLES = [\"small_model\", \"title\", \"summary\", \"compaction\"] as const\n\nexport const ROLE_NAMES = [...AGENT_ROLES, ...INTERNAL_ROLES] as const\n\nexport type AgentRole = (typeof AGENT_ROLES)[number]\n\nexport type InternalRole = (typeof INTERNAL_ROLES)[number]\n\nexport type RoleName = AgentRole | InternalRole\n\nexport function isAgentRole(value: string | undefined): value is AgentRole {\n return value !== undefined && (AGENT_ROLES as readonly string[]).includes(value)\n}\n\nexport function isRoleName(value: string): value is RoleName {\n return (ROLE_NAMES as readonly string[]).includes(value)\n}\n\nexport type ScoreSource = \"override\" | \"cap\" | \"feed\" | \"heuristic\" | \"default\"\n\nexport type ModelClass = \"subscription\" | \"paid\" | \"free\"\n\nexport interface Weights {\n intelligence: number\n speed: number\n endurance: number\n}\n\n/** Intelligence and speed values from the score table, a feed, or the user. */\nexport interface MetricScores {\n intelligence?: number\n speed?: number\n}\n\nexport type Metric = keyof MetricScores\n\nexport interface RoleRequirement {\n toolCall?: boolean\n reasoning?: boolean\n minContext?: number\n minOutput?: number\n inputModalities?: string[]\n}\n\nexport interface RoleSpec {\n weights: Weights\n variant?: string\n chainDepth?: number\n requires?: RoleRequirement\n /** Prefer $0 models; adds a bonus to the score of free models. */\n preferFree?: boolean\n /** Avoid two adjacent picks from the same model family. */\n diversifyFamily?: boolean\n}\n\nexport interface ModelCost {\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n}\n\nexport interface CostTier {\n size: number\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n}\n\nexport interface CatalogModel {\n providerID: string\n modelID: string\n /** Full `provider/model` identifier. */\n id: string\n name: string\n family?: string\n releaseDate?: string\n status?: string\n reasoning: boolean\n toolCall: boolean\n attachment: boolean\n openWeights: boolean\n limit: { context: number; input?: number; output: number }\n cost: ModelCost\n tiers: CostTier[]\n inputModalities: string[]\n free: boolean\n}\n\nexport interface ScoredModel {\n model: CatalogModel\n intelligence: number\n speed: number\n endurance: number\n score: number\n intelligenceSource: ScoreSource\n speedSource: ScoreSource\n enduranceSource: ScoreSource\n blendedCost: number\n /** Estimated millions of tokens per 5h window; null means unlimited. */\n tokensPer5h: number | null\n /** Monthly dollar allowance; null means unlimited. */\n monthlyCapUSD: number | null\n}\n\nexport interface RankingEntry {\n rank: number\n providerID: string\n modelID: string\n id: string\n variant?: string\n score: number\n intelligence: number\n speed: number\n endurance: number\n tokensPer5h: number | null\n monthlyCapUSD: number | null\n sources: { intelligence: ScoreSource; speed: ScoreSource; endurance: ScoreSource }\n class: ModelClass\n}\n\nexport type RoleChains = Partial<Record<RoleName, RankingEntry[]>>\n\nexport interface RoutingTable {\n version: number\n createdAt: string\n plan: PlanProfile\n /** role -> ranked chain for the active plan. */\n active: RoleChains\n /** plan -> role -> ranked chain (all computed plans). */\n profiles: Partial<Record<PlanProfile, RoleChains>>\n notes: string[]\n}\n\nexport interface EnduranceScale {\n minTokensPer5h: number\n maxTokensPer5h: number\n}\n\nexport interface CostBlend {\n input: number\n output: number\n cacheRead: number\n}\n\nexport interface FeedConfig {\n enabled?: boolean\n url?: string\n timeoutMs?: number\n}\n\nexport interface RouterUserConfig {\n plan?: PlanProfile\n chainDepth?: number\n softThreshold?: number\n blend?: Partial<CostBlend>\n enduranceScale?: Partial<EnduranceScale>\n weights?: Partial<Record<RoleName, Partial<Weights>>>\n roles?: Partial<Record<RoleName, Partial<RoleSpec>>>\n denyModels?: string[]\n allowModels?: string[]\n privacy?: { freeModelsOk?: boolean }\n feeds?: FeedConfig\n /** Ask npm for a newer router version once per 24 hours (default true). */\n updateCheck?: boolean\n /** Explicit score overrides, keyed by `provider/model`. */\n scores?: Partial<Record<string, MetricScores>>\n}\n\nexport interface LedgerModelState {\n cost5h: number\n costWeek: number\n costMonth: number\n tokens5h: number\n tokensWeek: number\n tokensMonth: number\n window5hStart: number\n windowWeekStart: number\n windowMonthStart: number\n cooldownUntil?: number\n lastError?: string\n lastUsedAt?: number\n}\n\nexport interface Ledger {\n version: number\n updatedAt: string\n models: Record<string, LedgerModelState>\n}\n\nexport interface MonthlyCap {\n go: number | null\n goPlus: number | null\n}\n\nexport interface ScoreTable {\n version: number\n updated: string\n /** role -> weights/variant/requirements. */\n roles: Partial<Record<RoleName, RoleSpec>>\n /** `provider/model` -> fixed scores (wins over heuristics). */\n models: Record<string, MetricScores>\n /** Ordered family/substring patterns; first match wins. */\n heuristics: {\n patterns: Array<{ match: string; intelligence: number; speed: number }>\n defaultIntelligence: number\n defaultSpeed: number\n /** Penalty applied to models with no explicit entry in `models`. */\n unvettedPenalty?: number\n }\n /** Monthly USD allowance per model: { go, goPlus }. null = unlimited. */\n monthlyCaps: Record<string, MonthlyCap>\n /**\n * Score adjustment per plan and model class. On paid plans the subscription\n * models get an edge so the plan you pay for is used first and $0 models\n * remain the overflow fallback.\n */\n classPreference?: Partial<Record<PlanProfile, Partial<Record<ModelClass, number>>>>\n}\n\nexport interface ResolvedConfig extends RouterUserConfig {\n plan: PlanProfile\n chainDepth: number\n softThreshold: number\n blend: CostBlend\n enduranceScale: EnduranceScale\n denyModels: string[]\n allowModels: string[]\n privacy: { freeModelsOk: boolean }\n}\n","import fs from \"node:fs\"\nimport type { CatalogModel, CostTier } from \"./types.js\"\nimport { catalogCacheFile } from \"./paths.js\"\n\nexport interface RawModel {\n id: string\n name?: string\n family?: string\n attachment?: boolean\n reasoning?: boolean\n tool_call?: boolean\n open_weights?: boolean\n release_date?: string\n last_updated?: string\n modalities?: { input?: string[]; output?: string[] }\n limit?: { context?: number; input?: number; output?: number }\n cost?: {\n input?: number\n output?: number\n cache_read?: number\n cache_write?: number\n tiers?: Array<{\n input?: number\n output?: number\n cache_read?: number\n cache_write?: number\n tier?: { type?: string; size?: number }\n }>\n }\n}\n\nexport interface RawProvider {\n id: string\n name?: string\n models?: Record<string, RawModel>\n}\n\nexport type RawCatalog = Record<string, RawProvider>\n\n/** Providers this router understands. */\nexport const ROUTED_PROVIDERS = [\"opencode-go\", \"opencode\"] as const\n\nexport function readCatalogFile(file: string = catalogCacheFile()): RawCatalog | undefined {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n return JSON.parse(raw) as RawCatalog\n } catch {\n return undefined\n }\n}\n\nfunction toNumber(value: unknown, fallback = 0): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback\n}\n\nfunction mapTiers(raw: RawModel): CostTier[] {\n const tiers = raw.cost?.tiers\n if (!Array.isArray(tiers)) return []\n const out: CostTier[] = []\n for (const t of tiers) {\n const size = t?.tier?.size\n if (typeof size !== \"number\") continue\n out.push({\n size,\n input: toNumber(t.input),\n output: toNumber(t.output),\n cacheRead: t.cache_read !== undefined ? toNumber(t.cache_read) : undefined,\n cacheWrite: t.cache_write !== undefined ? toNumber(t.cache_write) : undefined,\n })\n }\n return out.sort((a, b) => a.size - b.size)\n}\n\nexport function isFreeModel(cost: { input: number; output: number }, tiers: CostTier[]): boolean {\n const baseFree = cost.input === 0 && cost.output === 0\n const tiersFree = tiers.every((t) => t.input === 0 && t.output === 0)\n return baseFree && tiersFree\n}\n\nexport function mapModel(providerID: string, raw: RawModel): CatalogModel {\n const cost = {\n input: toNumber(raw.cost?.input),\n output: toNumber(raw.cost?.output),\n cacheRead: raw.cost?.cache_read !== undefined ? toNumber(raw.cost.cache_read) : undefined,\n cacheWrite: raw.cost?.cache_write !== undefined ? toNumber(raw.cost.cache_write) : undefined,\n }\n const tiers = mapTiers(raw)\n const rawInputs = raw.modalities?.input\n const inputModalities = Array.isArray(rawInputs) ? rawInputs.map(String) : [\"text\"]\n return {\n providerID,\n modelID: raw.id,\n id: `${providerID}/${raw.id}`,\n name: raw.name ?? raw.id,\n family: raw.family,\n releaseDate: raw.release_date ?? raw.last_updated,\n reasoning: raw.reasoning === true,\n toolCall: raw.tool_call === true,\n attachment: raw.attachment === true,\n openWeights: raw.open_weights === true,\n limit: {\n context: toNumber(raw.limit?.context),\n input: raw.limit?.input !== undefined ? toNumber(raw.limit.input) : undefined,\n output: toNumber(raw.limit?.output),\n },\n cost,\n tiers,\n inputModalities,\n free: isFreeModel(cost, tiers),\n }\n}\n\n/**\n * Load every routed model from the OpenCode catalog cache.\n * Returns models from `opencode-go` and `opencode` only.\n */\nexport function loadCatalog(file: string = catalogCacheFile()): CatalogModel[] {\n const raw = readCatalogFile(file)\n if (!raw) return []\n const out: CatalogModel[] = []\n for (const providerID of ROUTED_PROVIDERS) {\n const provider = raw[providerID]\n if (!provider?.models) continue\n for (const rawModel of Object.values(provider.models)) {\n if (rawModel && typeof rawModel.id === \"string\") out.push(mapModel(providerID, rawModel))\n }\n }\n return out\n}\n\nexport function catalogMeta(file: string = catalogCacheFile()): { path: string; mtime: string | null; total: number } {\n let mtime: string | null = null\n try {\n mtime = fs.statSync(file).mtime.toISOString()\n } catch {\n mtime = null\n }\n return { path: file, mtime, total: loadCatalog(file).length }\n}\n","import os from \"node:os\"\nimport path from \"node:path\"\nimport fs from \"node:fs\"\nimport { applyEdits, findNodeAtLocation, modify, parse, parseTree, printParseErrorCode, type ParseError } from \"jsonc-parser\"\n\n/** Global OpenCode config directory. Honors XDG_CONFIG_HOME like OpenCode does. */\nexport function globalConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), \".config\")\n return path.join(base, \"opencode\")\n}\n\n/** OpenCode cache directory. Honors XDG_CACHE_HOME like OpenCode does. */\nexport function opencodeCacheDir(): string {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), \".cache\")\n return path.join(base, \"opencode\")\n}\n\n/** OpenCode model catalog cache written by the OpenCode CLI/desktop. */\nexport function catalogCacheFile(): string {\n return path.join(opencodeCacheDir(), \"models.json\")\n}\n\nexport function globalRouterConfigFile(): string {\n return path.join(globalConfigDir(), \"router.config.json\")\n}\n\nexport function projectRouterConfigFile(dir: string): string {\n return path.join(dir, \".opencode\", \"router.config.json\")\n}\n\n/** Candidate opencode.json paths, most specific first. */\nexport function opencodeConfigCandidates(dir: string): string[] {\n return [path.join(dir, \".opencode\", \"opencode.json\"), path.join(dir, \"opencode.jsonc\"), path.join(dir, \"opencode.json\")]\n}\n\nexport function globalOpencodeConfigCandidates(): string[] {\n return [path.join(globalConfigDir(), \"opencode.jsonc\"), path.join(globalConfigDir(), \"opencode.json\")]\n}\n\nexport function ensureDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true })\n}\n\nexport function fileExists(file: string): boolean {\n try {\n return fs.statSync(file).isFile()\n } catch {\n return false\n }\n}\n\nfunction pathExists(file: string): boolean {\n try {\n fs.statSync(file)\n return true\n } catch {\n return false\n }\n}\n\nconst PROJECT_MARKERS = [\n \".git\",\n \"package.json\",\n \"opencode.json\",\n \"opencode.jsonc\",\n \"pyproject.toml\",\n \"Cargo.toml\",\n \"go.mod\",\n]\n\n/** True when `dir` looks like a real project (used to pick the config scope). */\nexport function isProjectDir(dir: string): boolean {\n return PROJECT_MARKERS.some((marker) => pathExists(path.join(dir, marker)))\n}\n\nexport interface JsoncResult {\n value?: unknown\n /** The first parse problem and its line, when the text is not valid JSONC. */\n error?: string\n}\n\n/** Parse JSON that may contain comments and trailing commas. */\nexport function parseJsonc(text: string): JsoncResult {\n const errors: ParseError[] = []\n const value: unknown = parse(text, errors, { allowTrailingComma: true })\n const first = errors[0]\n if (first) return { error: `${printParseErrorCode(first.error)} at line ${lineAt(text, first.offset)}` }\n return { value }\n}\n\nfunction lineAt(text: string, offset: number): number {\n return text.slice(0, offset).split(\"\\n\").length\n}\n\nexport type JsonFile<T> = { status: \"absent\" } | { status: \"ok\"; value: T } | { status: \"invalid\"; error: string }\n\nfunction readText(file: string): string | undefined {\n try {\n // Strip a UTF-8 byte order mark: some Windows editors add one.\n return fs.readFileSync(file, \"utf8\").replace(/^/, \"\")\n } catch {\n return undefined\n }\n}\n\n/** Read a JSON(C) file. A missing or empty file is \"absent\"; a broken one is \"invalid\". */\nexport function readJsonFile<T = unknown>(file: string): JsonFile<T> {\n const text = readText(file)\n if (text === undefined || text.trim() === \"\") return { status: \"absent\" }\n const parsed = parseJsonc(text)\n if (parsed.error !== undefined) return { status: \"invalid\", error: parsed.error }\n return { status: \"ok\", value: parsed.value as T }\n}\n\n/** The parsed value of a JSON(C) file, or undefined when it is missing or broken. */\nexport function readJson<T = unknown>(file: string): T | undefined {\n const result = readJsonFile<T>(file)\n return result.status === \"ok\" ? result.value : undefined\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n/** Write through a temp file and a rename, so a crash never leaves half a file. */\nexport function writeTextAtomic(file: string, text: string): void {\n ensureDir(path.dirname(file))\n const temp = `${file}.${process.pid}.${Date.now()}.tmp`\n fs.writeFileSync(temp, text, \"utf8\")\n try {\n fs.renameSync(temp, file)\n } catch {\n // Windows can refuse the rename while another process has the file open.\n fs.writeFileSync(file, text, \"utf8\")\n fs.rmSync(temp, { force: true })\n }\n}\n\nexport function writeJson(file: string, value: unknown): void {\n writeTextAtomic(file, JSON.stringify(value, null, 2) + \"\\n\")\n}\n\n/** jsonc-parser throws when asked to remove a key whose parent is missing. */\nfunction hasPath(text: string, keyPath: string[]): boolean {\n const tree = parseTree(text)\n return tree !== undefined && findNodeAtLocation(tree, keyPath) !== undefined\n}\n\nexport interface JsonEdit {\n path: string[]\n /** `undefined` removes the key. */\n value: unknown\n}\n\n/**\n * Change some keys of a JSON(C) file and keep everything else, including\n * comments and formatting. Throws when the file is not a valid JSON object,\n * so a broken file is never replaced.\n */\nexport function editJsonFile(file: string, edits: JsonEdit[], initialText = \"{}\\n\"): { created: boolean } {\n const current = readJsonFile(file)\n if (current.status === \"invalid\") {\n throw new Error(`${file} has a JSON error (${current.error}). Fix the file and run the command again. The file was not changed.`)\n }\n if (current.status === \"ok\" && !isPlainObject(current.value)) {\n throw new Error(`${file} does not contain a JSON object. The file was not changed.`)\n }\n\n const created = !fileExists(file)\n let text = current.status === \"ok\" ? (readText(file) ?? initialText) : initialText\n const formattingOptions = {\n insertSpaces: !/^\\t/m.test(text),\n tabSize: 2,\n eol: text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\",\n }\n for (const edit of edits) {\n if (edit.value === undefined && !hasPath(text, edit.path)) continue\n text = applyEdits(text, modify(text, edit.path, edit.value, { formattingOptions }))\n }\n writeTextAtomic(file, text)\n return { created }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","import type {\n CatalogModel,\n Metric,\n MetricScores,\n ModelClass,\n PlanProfile,\n ResolvedConfig,\n RoleSpec,\n ScoreSource,\n ScoreTable,\n ScoredModel,\n} from \"./types.js\"\n\n/** Share of the monthly allowance that one 5-hour window may use. */\nexport const FIVE_HOUR_SHARE = 0.2\n\n/** Score bonus for a free model in a role that prefers free models. */\nconst FREE_ROLE_BONUS = 6\n\nconst DEFAULT_UNVETTED_PENALTY = 8\n\nexport function modelClass(model: CatalogModel): ModelClass {\n if (model.free) return \"free\"\n if (model.providerID === \"opencode-go\") return \"subscription\"\n return \"paid\"\n}\n\nexport interface FeedScores {\n /** keyed by lowercased family or `provider/model`. */\n byFamily: Map<string, MetricScores>\n byId: Map<string, MetricScores>\n}\n\nexport function emptyFeedScores(): FeedScores {\n return { byFamily: new Map(), byId: new Map() }\n}\n\nfunction clamp(value: number, min = 0, max = 100): number {\n return Math.max(min, Math.min(max, value))\n}\n\n/** Resolve one metric: score table/user override, then feed, then name pattern, then default. */\nfunction resolveMetric(\n model: CatalogModel,\n table: ScoreTable,\n feeds: FeedScores,\n metric: Metric,\n): { value: number; source: ScoreSource } {\n const override = table.models[model.id]?.[metric]\n if (override !== undefined) return { value: clamp(override), source: \"override\" }\n\n const fromId = feeds.byId.get(model.id.toLowerCase())?.[metric]\n if (fromId !== undefined) return { value: clamp(fromId), source: \"feed\" }\n const fromFamily = model.family ? feeds.byFamily.get(model.family.toLowerCase())?.[metric] : undefined\n if (fromFamily !== undefined) return { value: clamp(fromFamily), source: \"feed\" }\n\n const id = model.modelID.toLowerCase()\n const pattern = table.heuristics.patterns.find((p) => id.includes(p.match.toLowerCase()))\n if (pattern) return { value: clamp(pattern[metric]), source: \"heuristic\" }\n\n const fallback = metric === \"intelligence\" ? table.heuristics.defaultIntelligence : table.heuristics.defaultSpeed\n return { value: clamp(fallback), source: \"default\" }\n}\n\nexport function resolveIntelligence(model: CatalogModel, table: ScoreTable, feeds: FeedScores) {\n return resolveMetric(model, table, feeds, \"intelligence\")\n}\n\nexport function resolveSpeed(model: CatalogModel, table: ScoreTable, feeds: FeedScores) {\n return resolveMetric(model, table, feeds, \"speed\")\n}\n\n/** Blended USD cost per 1M tokens for a typical coding turn. */\nexport function blendedCost(model: CatalogModel, cfg: ResolvedConfig): number {\n const { input, output, cacheRead } = cfg.blend\n const c = model.cost\n return c.input * input + c.output * output + (c.cacheRead ?? 0) * cacheRead\n}\n\n/** Monthly USD allowance of a model on a plan; null means unlimited or unknown. */\nexport function monthlyCapFor(modelId: string, table: ScoreTable, plan: PlanProfile): number | null {\n if (plan === \"free\") return null\n const entry = table.monthlyCaps[modelId]\n if (!entry) return null\n return plan === \"go-plus\" ? entry.goPlus : entry.go\n}\n\nfunction logScale(value: number, min: number, max: number): number {\n const lo = Math.log10(Math.max(min, 1e-6))\n const hi = Math.log10(Math.max(max, min * 1.001))\n const v = Math.log10(Math.max(value, 1e-6))\n return clamp(((v - lo) / (hi - lo)) * 100)\n}\n\nexport interface EnduranceResult {\n score: number\n source: ScoreSource\n tokensPer5h: number | null\n monthlyCapUSD: number | null\n blendedCost: number\n}\n\nexport function resolveEndurance(model: CatalogModel, table: ScoreTable, cfg: ResolvedConfig): EnduranceResult {\n const bc = blendedCost(model, cfg)\n\n if (model.free) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: null, blendedCost: bc }\n }\n\n const cap = monthlyCapFor(model.id, table, cfg.plan)\n if (cap === null) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: null, blendedCost: bc }\n }\n\n if (bc <= 0) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: cap, blendedCost: bc }\n }\n\n const tokensPer5h = (cap * FIVE_HOUR_SHARE) / bc\n const score = logScale(tokensPer5h, cfg.enduranceScale.minTokensPer5h, cfg.enduranceScale.maxTokensPer5h)\n return { score, source: \"cap\", tokensPer5h, monthlyCapUSD: cap, blendedCost: bc }\n}\n\nexport function scoreModel(\n model: CatalogModel,\n role: RoleSpec,\n table: ScoreTable,\n cfg: ResolvedConfig,\n feeds: FeedScores,\n): ScoredModel {\n const intel = resolveIntelligence(model, table, feeds)\n const speed = resolveSpeed(model, table, feeds)\n const end = resolveEndurance(model, table, cfg)\n\n const w = role.weights\n let score = w.intelligence * intel.value + w.speed * speed.value + w.endurance * end.score\n\n // Plan/class preference: on paid plans keep the subscription models ahead of\n // the $0 overflow; for free-preferring roles do the opposite.\n const klass = modelClass(model)\n if (role.preferFree) {\n if (klass === \"free\") score += FREE_ROLE_BONUS\n } else {\n score += table.classPreference?.[cfg.plan]?.[klass] ?? 0\n }\n // Models we have never vetted score lower than ones with an explicit entry.\n if (table.models[model.id] === undefined) score -= table.heuristics.unvettedPenalty ?? DEFAULT_UNVETTED_PENALTY\n score = clamp(score)\n\n return {\n model,\n intelligence: intel.value,\n speed: speed.value,\n endurance: end.score,\n score,\n intelligenceSource: intel.source,\n speedSource: speed.source,\n enduranceSource: end.source,\n blendedCost: end.blendedCost,\n tokensPer5h: end.tokensPer5h,\n monthlyCapUSD: end.monthlyCapUSD,\n }\n}\n","import type { MetricScores, ResolvedConfig } from \"./types.js\"\nimport { emptyFeedScores, type FeedScores } from \"./scoring.js\"\n\nexport interface FeedRecord extends MetricScores {\n id?: string\n family?: string\n}\n\nexport interface FeedPayload {\n version?: number\n updated?: string\n models?: FeedRecord[]\n}\n\n/**\n * Optionally enrich intelligence/speed from a public benchmark feed.\n * Any failure returns the empty map: the router falls back to the committed\n * table and heuristics, so `/refresh-routing` never breaks on a bad network.\n */\nexport async function loadFeedScores(cfg: ResolvedConfig): Promise<{ feeds: FeedScores; note: string | null }> {\n const feeds = emptyFeedScores()\n if (!cfg.feeds?.enabled || !cfg.feeds.url) return { feeds, note: null }\n\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), cfg.feeds.timeoutMs ?? 5000)\n try {\n const res = await fetch(cfg.feeds.url, { signal: controller.signal })\n if (!res.ok) return { feeds, note: `feed ${cfg.feeds.url} returned ${res.status}; using table + heuristics` }\n const payload = (await res.json()) as FeedPayload\n const records = Array.isArray(payload.models) ? payload.models : []\n\n for (const rec of records) {\n if (!rec) continue\n const value: MetricScores = {}\n if (typeof rec.intelligence === \"number\") value.intelligence = rec.intelligence\n if (typeof rec.speed === \"number\") value.speed = rec.speed\n if (value.intelligence === undefined && value.speed === undefined) continue\n if (rec.id) feeds.byId.set(rec.id.toLowerCase(), value)\n if (rec.family) feeds.byFamily.set(rec.family.toLowerCase(), value)\n }\n return { feeds, note: `feed ${cfg.feeds.url}: ${records.length} records` }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { feeds, note: `feed unavailable (${message}); using table + heuristics` }\n } finally {\n clearTimeout(timeout)\n }\n}\n","import { isPlan, isRoleName, PLAN_PROFILES } from \"./types.js\"\nimport type { CatalogModel, PlanProfile, ResolvedConfig, RouterUserConfig } from \"./types.js\"\nimport { globalRouterConfigFile, isPlainObject, projectRouterConfigFile, readJsonFile } from \"./paths.js\"\n\nconst DEFAULT_SOFT_THRESHOLD = 0.85\nconst DEFAULT_CHAIN_DEPTH = 4\n\nexport interface LoadedUserConfig {\n config: RouterUserConfig\n /** Problems found in the files, shown in the scorecard notes. */\n notes: string[]\n}\n\n/** Read the global and project router.config.json. A bad file or value becomes a note, never a crash. */\nexport function loadUserConfig(projectDir?: string): LoadedUserConfig {\n const notes: string[] = []\n const global = readUserConfigFile(globalRouterConfigFile(), notes)\n const project = projectDir ? readUserConfigFile(projectRouterConfigFile(projectDir), notes) : {}\n return { config: mergeUserConfig(global, project), notes }\n}\n\nfunction readUserConfigFile(file: string, notes: string[]): RouterUserConfig {\n const result = readJsonFile(file)\n if (result.status === \"absent\") return {}\n if (result.status === \"invalid\") {\n notes.push(`${file} has a JSON error (${result.error}); it was ignored.`)\n return {}\n }\n if (!isPlainObject(result.value)) {\n notes.push(`${file} does not contain a JSON object; it was ignored.`)\n return {}\n }\n return sanitizeUserConfig(result.value, file, notes)\n}\n\n/** Remove values the router cannot use, with a note for each one. */\nfunction sanitizeUserConfig(raw: Record<string, unknown>, file: string, notes: string[]): RouterUserConfig {\n const config = { ...raw }\n const drop = (key: string, rule: string) => {\n notes.push(`${file}: \"${key}\" ${rule}, not ${JSON.stringify(config[key])}; it was ignored.`)\n delete config[key]\n }\n\n if (config.plan !== undefined && !isPlan(config.plan)) drop(\"plan\", `must be one of ${PLAN_PROFILES.join(\" | \")}`)\n const depth = config.chainDepth\n if (depth !== undefined && !(typeof depth === \"number\" && Number.isInteger(depth) && depth >= 1)) {\n drop(\"chainDepth\", \"must be a whole number of 1 or more\")\n }\n const threshold = config.softThreshold\n if (threshold !== undefined && !(typeof threshold === \"number\" && threshold > 0 && threshold <= 1)) {\n drop(\"softThreshold\", \"must be a number above 0 and at most 1\")\n }\n if (config.updateCheck !== undefined && typeof config.updateCheck !== \"boolean\") drop(\"updateCheck\", \"must be true or false\")\n for (const key of [\"denyModels\", \"allowModels\"]) {\n const list = config[key]\n if (list !== undefined && !(Array.isArray(list) && list.every((item) => typeof item === \"string\"))) {\n drop(key, \"must be a list of model IDs\")\n }\n }\n for (const key of [\"roles\", \"weights\"]) {\n const perRole = config[key]\n if (perRole === undefined) continue\n if (!isPlainObject(perRole)) {\n drop(key, \"must be an object keyed by role\")\n continue\n }\n const known: Record<string, unknown> = {}\n for (const [role, value] of Object.entries(perRole)) {\n if (isRoleName(role)) known[role] = value\n else notes.push(`${file}: unknown role \"${role}\" in \"${key}\"; it was ignored.`)\n }\n config[key] = known\n }\n return config as RouterUserConfig\n}\n\n/** Merge two `key -> object` maps one level deep, so project values add to global ones. */\nfunction mergeByKey<K extends string, V extends object>(\n base: Partial<Record<K, V>> = {},\n override: Partial<Record<K, V>> = {},\n): Partial<Record<K, V>> {\n const out: Partial<Record<K, V>> = { ...base }\n for (const key of Object.keys(override) as K[]) {\n out[key] = { ...base[key], ...override[key] } as V\n }\n return out\n}\n\nexport function mergeUserConfig(base: RouterUserConfig, override: RouterUserConfig): RouterUserConfig {\n return {\n ...base,\n ...override,\n blend: { ...base.blend, ...override.blend },\n enduranceScale: { ...base.enduranceScale, ...override.enduranceScale },\n weights: mergeByKey(base.weights, override.weights),\n roles: mergeByKey(base.roles, override.roles),\n scores: mergeByKey(base.scores, override.scores),\n privacy: { ...base.privacy, ...override.privacy },\n feeds: { ...base.feeds, ...override.feeds },\n denyModels: override.denyModels ?? base.denyModels,\n allowModels: override.allowModels ?? base.allowModels,\n }\n}\n\n/** Detect the best-matching plan profile from the models actually available. */\nexport function detectPlan(catalog: CatalogModel[]): PlanProfile {\n const hasGo = catalog.some((m) => m.providerID === \"opencode-go\" && !m.free)\n if (hasGo) return \"go\"\n const hasFree = catalog.some((m) => m.free)\n if (hasFree) return \"free\"\n return \"go\"\n}\n\nexport function resolveConfig(user: RouterUserConfig, catalog: CatalogModel[], cliPlan?: PlanProfile): ResolvedConfig {\n const plan = cliPlan ?? user.plan ?? detectPlan(catalog)\n return {\n ...user,\n plan,\n chainDepth: user.chainDepth ?? DEFAULT_CHAIN_DEPTH,\n softThreshold: user.softThreshold ?? DEFAULT_SOFT_THRESHOLD,\n blend: {\n input: user.blend?.input ?? 0.75,\n output: user.blend?.output ?? 0.25,\n cacheRead: user.blend?.cacheRead ?? 0.1,\n },\n enduranceScale: {\n minTokensPer5h: user.enduranceScale?.minTokensPer5h ?? 0.25,\n maxTokensPer5h: user.enduranceScale?.maxTokensPer5h ?? 40,\n },\n denyModels: user.denyModels ?? [],\n allowModels: user.allowModels ?? [],\n privacy: { freeModelsOk: user.privacy?.freeModelsOk ?? true },\n }\n}\n","{\n \"$comment\": \"Committed default score table for opencode-router. Safe to edit; user config (router.config.json) overrides these values.\",\n \"version\": 1,\n \"updated\": \"2026-10-18\",\n \"roles\": {\n \"plan\": {\n \"weights\": { \"intelligence\": 0.65, \"speed\": 0.1, \"endurance\": 0.25 },\n \"variant\": \"high\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"build\": {\n \"weights\": { \"intelligence\": 0.4, \"speed\": 0.25, \"endurance\": 0.35 },\n \"variant\": \"medium\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"general\": {\n \"weights\": { \"intelligence\": 0.35, \"speed\": 0.25, \"endurance\": 0.4 },\n \"variant\": \"medium\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"explore\": {\n \"weights\": { \"intelligence\": 0.15, \"speed\": 0.45, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 128000 },\n \"preferFree\": true\n },\n \"small_model\": {\n \"weights\": { \"intelligence\": 0.05, \"speed\": 0.55, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 100000 },\n \"preferFree\": true\n },\n \"title\": {\n \"weights\": { \"intelligence\": 0.05, \"speed\": 0.55, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 100000 },\n \"preferFree\": true\n },\n \"summary\": {\n \"weights\": { \"intelligence\": 0.3, \"speed\": 0.3, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"preferFree\": true\n },\n \"compaction\": {\n \"weights\": { \"intelligence\": 0.3, \"speed\": 0.2, \"endurance\": 0.5 },\n \"variant\": \"none\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 1000000 },\n \"preferFree\": true\n }\n },\n \"models\": {\n \"opencode-go/gemini-4-argon-contributor\": { \"intelligence\": 95, \"speed\": 25 },\n \"opencode-go/kimi-k3\": { \"intelligence\": 93, \"speed\": 20 },\n \"opencode-go/qwen3.8-max\": { \"intelligence\": 92, \"speed\": 35 },\n \"opencode-go/grok-4.7\": { \"intelligence\": 91, \"speed\": 40 },\n \"opencode-go/deepseek-v4-pro\": { \"intelligence\": 90, \"speed\": 30 },\n \"opencode-go/glm-5.3\": { \"intelligence\": 90, \"speed\": 45 },\n \"opencode-go/glm-5.2\": { \"intelligence\": 88, \"speed\": 45 },\n \"opencode-go/step-5-preview\": { \"intelligence\": 87, \"speed\": 40 },\n \"opencode-go/qwen3.7-plus\": { \"intelligence\": 86, \"speed\": 45 },\n \"opencode-go/kimi-k2.7-code\": { \"intelligence\": 85, \"speed\": 50 },\n \"opencode-go/gpt-6-luna\": { \"intelligence\": 85, \"speed\": 55 },\n \"opencode-go/gpt-5.6-luna\": { \"intelligence\": 84, \"speed\": 55 },\n \"opencode-go/minimax-m3\": { \"intelligence\": 84, \"speed\": 55 },\n \"opencode-go/hy4-preview\": { \"intelligence\": 82, \"speed\": 40 },\n \"opencode-go/qwen3.8-flash\": { \"intelligence\": 80, \"speed\": 70 },\n \"opencode-go/deepseek-v4.1-flash\": { \"intelligence\": 80, \"speed\": 65 },\n \"opencode-go/space-bunny\": { \"intelligence\": 79, \"speed\": 60 },\n \"opencode-go/glm-5.3-flash\": { \"intelligence\": 78, \"speed\": 72 },\n \"opencode-go/mimo-v2.6-pro\": { \"intelligence\": 78, \"speed\": 58 },\n \"opencode-go/muse-spark-1.3-contributor\": { \"intelligence\": 77, \"speed\": 62 },\n \"opencode-go/mimo-v2.5-pro\": { \"intelligence\": 76, \"speed\": 58 },\n \"opencode-go/longcat-2.0\": { \"intelligence\": 76, \"speed\": 55 },\n \"opencode-go/muse-spark-1.2-contributor\": { \"intelligence\": 75, \"speed\": 62 },\n \"opencode-go/longcat-2.5-preview-free\": { \"intelligence\": 75, \"speed\": 60 },\n \"opencode-go/hy3\": { \"intelligence\": 74, \"speed\": 60 },\n \"opencode-go/claude-haiku-5-5\": { \"intelligence\": 74, \"speed\": 78 },\n \"opencode-go/mimo-v2.6-flash\": { \"intelligence\": 73, \"speed\": 75 },\n \"opencode-go/mimo-v2.5\": { \"intelligence\": 72, \"speed\": 72 },\n \"opencode-go/beam-free\": { \"intelligence\": 72, \"speed\": 80 },\n\n \"opencode/deepseek-v4.1-flash-free\": { \"intelligence\": 80, \"speed\": 65 },\n \"opencode/space-bunny-free\": { \"intelligence\": 79, \"speed\": 60 },\n \"opencode/glm-5.3-flash-free\": { \"intelligence\": 78, \"speed\": 72 },\n \"opencode/longcat-2.5-preview-free\": { \"intelligence\": 75, \"speed\": 60 },\n \"opencode/nemotron-3-ultra-free\": { \"intelligence\": 74, \"speed\": 62 },\n \"opencode/mimo-v2.6-flash-free\": { \"intelligence\": 73, \"speed\": 75 },\n \"opencode/beam-free\": { \"intelligence\": 72, \"speed\": 80 },\n \"opencode/nemotron-3.5-super-vl-free\": { \"intelligence\": 72, \"speed\": 70 },\n \"opencode/nemotron-3.5-lightning-free\": { \"intelligence\": 68, \"speed\": 88 },\n \"opencode/big-pickle\": { \"intelligence\": 66, \"speed\": 70 }\n },\n \"heuristics\": {\n \"patterns\": [\n { \"match\": \"gemini-4-argon\", \"intelligence\": 95, \"speed\": 25 },\n { \"match\": \"kimi-k3\", \"intelligence\": 93, \"speed\": 20 },\n { \"match\": \"qwen3.8-max\", \"intelligence\": 92, \"speed\": 35 },\n { \"match\": \"opus\", \"intelligence\": 94, \"speed\": 30 },\n { \"match\": \"grok\", \"intelligence\": 91, \"speed\": 40 },\n { \"match\": \"deepseek-v4-pro\", \"intelligence\": 90, \"speed\": 30 },\n { \"match\": \"sonnet\", \"intelligence\": 88, \"speed\": 50 },\n { \"match\": \"step-5\", \"intelligence\": 87, \"speed\": 40 },\n { \"match\": \"gpt-6\", \"intelligence\": 85, \"speed\": 55 },\n { \"match\": \"kimi\", \"intelligence\": 85, \"speed\": 45 },\n { \"match\": \"gpt-5\", \"intelligence\": 84, \"speed\": 55 },\n { \"match\": \"minimax\", \"intelligence\": 84, \"speed\": 55 },\n { \"match\": \"hy4\", \"intelligence\": 82, \"speed\": 40 },\n { \"match\": \"claude\", \"intelligence\": 82, \"speed\": 60 },\n { \"match\": \"gpt\", \"intelligence\": 82, \"speed\": 55 },\n { \"match\": \"qwen\", \"intelligence\": 80, \"speed\": 55 },\n { \"match\": \"deepseek\", \"intelligence\": 80, \"speed\": 65 },\n { \"match\": \"glm\", \"intelligence\": 80, \"speed\": 55 },\n { \"match\": \"space-bunny\", \"intelligence\": 79, \"speed\": 60 },\n { \"match\": \"muse\", \"intelligence\": 77, \"speed\": 62 },\n { \"match\": \"longcat\", \"intelligence\": 76, \"speed\": 58 },\n { \"match\": \"hy3\", \"intelligence\": 74, \"speed\": 60 },\n { \"match\": \"haiku\", \"intelligence\": 74, \"speed\": 78 },\n { \"match\": \"mimo\", \"intelligence\": 74, \"speed\": 72 },\n { \"match\": \"nemotron\", \"intelligence\": 72, \"speed\": 75 },\n { \"match\": \"big-pickle\", \"intelligence\": 66, \"speed\": 70 },\n { \"match\": \"-max\", \"intelligence\": 90, \"speed\": 35 },\n { \"match\": \"-pro\", \"intelligence\": 88, \"speed\": 42 },\n { \"match\": \"-flash\", \"intelligence\": 78, \"speed\": 74 },\n { \"match\": \"-mini\", \"intelligence\": 74, \"speed\": 80 },\n { \"match\": \"-lite\", \"intelligence\": 70, \"speed\": 84 },\n { \"match\": \"-free\", \"intelligence\": 72, \"speed\": 70 },\n { \"match\": \"contributor\", \"intelligence\": 74, \"speed\": 62 }\n ],\n \"defaultIntelligence\": 60,\n \"defaultSpeed\": 60,\n \"unvettedPenalty\": 8\n },\n \"classPreference\": {\n \"go\": { \"subscription\": 0, \"paid\": -6, \"free\": -12 },\n \"go-plus\": { \"subscription\": 0, \"paid\": -6, \"free\": -12 },\n \"free\": { \"subscription\": 0, \"paid\": 0, \"free\": 0 }\n },\n \"monthlyCaps\": {\n \"opencode-go/longcat-2.5-preview-free\": { \"go\": null, \"goPlus\": null },\n \"opencode-go/beam-free\": { \"go\": null, \"goPlus\": null },\n \"opencode-go/deepseek-v4.1-flash\": { \"go\": 80, \"goPlus\": 160 },\n \"opencode-go/longcat-2.0\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/hy3\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/step-5-preview\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/gemini-4-argon-contributor\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/glm-5.3-flash\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/glm-5.2\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/kimi-k2.7-code\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/minimax-m3\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/qwen3.7-plus\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/mimo-v2.6-flash\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/mimo-v2.5\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/muse-spark-1.3-contributor\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/muse-spark-1.2-contributor\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/hy4-preview\": { \"go\": 30, \"goPlus\": 120 },\n \"opencode-go/space-bunny\": { \"go\": 30, \"goPlus\": 120 },\n \"opencode-go/qwen3.8-flash\": { \"go\": 30, \"goPlus\": 90 },\n \"opencode-go/glm-5.3\": { \"go\": 15, \"goPlus\": 120 },\n \"opencode-go/kimi-k3\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/mimo-v2.6-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/mimo-v2.5-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/qwen3.8-max\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/deepseek-v4-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/grok-4.7\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/gpt-6-luna\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/gpt-5.6-luna\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/claude-haiku-5-5\": { \"go\": 15, \"goPlus\": 60 }\n }\n}\n","import bundled from \"../model-scores.json\" with { type: \"json\" }\nimport { ROLE_NAMES } from \"./types.js\"\nimport type { RoleSpec, RouterUserConfig, ScoreTable } from \"./types.js\"\n\nconst DEFAULT_TABLE: ScoreTable = bundled\n\n/** A fresh copy of the committed default table (model-scores.json, bundled at build time). */\nexport function loadDefaultTable(): ScoreTable {\n return structuredClone(DEFAULT_TABLE)\n}\n\nfunction mergeRole(base: RoleSpec, override: Partial<RoleSpec>): RoleSpec {\n return {\n ...base,\n ...override,\n weights: { ...base.weights, ...override.weights },\n requires: { ...base.requires, ...override.requires },\n }\n}\n\n/**\n * Build the effective score table: committed defaults, then user overrides from\n * router.config.json. A top-level `chainDepth` applies to every role, and a\n * per-role value wins over it. Roles the router does not know are ignored.\n */\nexport function resolveTable(user: RouterUserConfig): ScoreTable {\n const table = loadDefaultTable()\n\n for (const role of ROLE_NAMES) {\n let spec = table.roles[role]\n if (!spec) continue\n if (user.chainDepth !== undefined) spec = { ...spec, chainDepth: user.chainDepth }\n const override = user.roles?.[role]\n if (override) spec = mergeRole(spec, override)\n const weights = user.weights?.[role]\n if (weights) spec = { ...spec, weights: { ...spec.weights, ...weights } }\n table.roles[role] = spec\n }\n\n for (const [id, score] of Object.entries(user.scores ?? {})) {\n table.models[id] = { ...table.models[id], ...score }\n }\n\n return table\n}\n","import type { CatalogModel, PlanProfile, RankingEntry, ResolvedConfig, RoleName, RoleSpec, ScoreTable, ScoredModel } from \"./types.js\"\nimport { modelClass, scoreModel, type FeedScores } from \"./scoring.js\"\n\nexport function globToRegex(glob: string): RegExp {\n const escaped = glob.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\").replace(/\\?/g, \".\")\n return new RegExp(`^${escaped}$`, \"i\")\n}\n\nexport function matchesAny(id: string, globs: string[]): boolean {\n return globs.some((g) => globToRegex(g).test(id))\n}\n\nfunction providerAllowed(model: CatalogModel, plan: PlanProfile): boolean {\n if (plan === \"free\") {\n // Without any subscription, only the OpenCode Zen `$0` tier is reachable.\n return model.providerID === \"opencode\" && model.free\n }\n if (plan === \"go\" || plan === \"go-plus\") {\n // OpenCode Go subscription models plus the $0 free tier from both providers.\n if (model.providerID === \"opencode-go\") return true\n if (model.providerID === \"opencode\") return model.free\n return false\n }\n return false\n}\n\nfunction requirementOk(model: CatalogModel, role: RoleSpec): boolean {\n const req = role.requires\n if (!req) return true\n if (req.toolCall && !model.toolCall) return false\n if (req.reasoning && !model.reasoning) return false\n if (req.minContext !== undefined && model.limit.context < req.minContext) return false\n if (req.minOutput !== undefined && model.limit.output < req.minOutput) return false\n if (req.inputModalities && req.inputModalities.length > 0) {\n const ok = req.inputModalities.every((m) => model.inputModalities.includes(m))\n if (!ok) return false\n }\n return true\n}\n\nexport function eligibleModels(\n catalog: CatalogModel[],\n role: RoleSpec,\n table: ScoreTable,\n cfg: ResolvedConfig,\n): CatalogModel[] {\n return catalog.filter((model) => {\n if (!providerAllowed(model, cfg.plan)) return false\n if (!requirementOk(model, role)) return false\n // On paid plans, a non-free Go model with no known allowance is treated as\n // unavailable (legacy/retired ids would otherwise look \"unlimited\").\n if ((cfg.plan === \"go\" || cfg.plan === \"go-plus\") && !model.free && !table.monthlyCaps[model.id]) return false\n if (cfg.denyModels.length > 0 && matchesAny(model.id, cfg.denyModels)) return false\n if (cfg.allowModels.length > 0 && !matchesAny(model.id, cfg.allowModels)) return false\n // Privacy: paid plans must not silently use data-collecting free models for real work.\n if (!cfg.privacy.freeModelsOk && model.free && !role.preferFree) return false\n return true\n })\n}\n\nexport function rankRole(\n catalog: CatalogModel[],\n roleName: RoleName,\n table: ScoreTable,\n cfg: ResolvedConfig,\n feeds: FeedScores,\n): RankingEntry[] {\n const role = table.roles[roleName]\n if (!role) return []\n\n const scored: ScoredModel[] = eligibleModels(catalog, role, table, cfg)\n .map((model) => scoreModel(model, role, table, cfg, feeds))\n .sort((a, b) => b.score - a.score || a.blendedCost - b.blendedCost)\n\n const depth = role.chainDepth ?? cfg.chainDepth\n const diversify = role.diversifyFamily ?? false\n\n const chosen: ScoredModel[] = []\n const seenFamilies = new Set<string>()\n\n for (const entry of scored) {\n if (chosen.length >= depth) break\n const family = (entry.model.family ?? entry.model.modelID).toLowerCase()\n if (diversify && seenFamilies.has(family) && chosen.length < depth) continue\n chosen.push(entry)\n seenFamilies.add(family)\n }\n // Backfill if diversification starved the chain.\n if (chosen.length < depth) {\n for (const entry of scored) {\n if (chosen.length >= depth) break\n if (chosen.includes(entry)) continue\n chosen.push(entry)\n }\n }\n\n return chosen.map((entry, index) => ({\n rank: index + 1,\n providerID: entry.model.providerID,\n modelID: entry.model.modelID,\n id: entry.model.id,\n variant: role.variant,\n score: round(entry.score),\n intelligence: round(entry.intelligence),\n speed: round(entry.speed),\n endurance: round(entry.endurance),\n tokensPer5h: entry.tokensPer5h === null ? null : round(entry.tokensPer5h, 3),\n monthlyCapUSD: entry.monthlyCapUSD,\n sources: {\n intelligence: entry.intelligenceSource,\n speed: entry.speedSource,\n endurance: entry.enduranceSource,\n },\n class: modelClass(entry.model),\n }))\n}\n\nfunction round(value: number, digits = 1): number {\n const f = Math.pow(10, digits)\n return Math.round(value * f) / f\n}\n","import { isAgentRole, PLAN_PROFILES, ROLE_NAMES } from \"./types.js\"\nimport type { CatalogModel, PlanProfile, RankingEntry, ResolvedConfig, RoleChains, RoleName, RoutingTable, ScoreTable } from \"./types.js\"\nimport { loadCatalog } from \"./catalog.js\"\nimport { loadFeedScores } from \"./feeds.js\"\nimport { loadUserConfig, resolveConfig } from \"./config.js\"\nimport { resolveTable } from \"./score-table.js\"\nimport { rankRole } from \"./rank.js\"\nimport { monthlyCapFor, type FeedScores } from \"./scoring.js\"\nimport { catalogCacheFile } from \"./paths.js\"\nimport type { LedgerStore } from \"./ledger.js\"\n\nexport interface BuildOptions {\n plan?: PlanProfile\n projectDir?: string\n catalogFile?: string\n catalog?: CatalogModel[]\n now?: Date\n feeds?: FeedScores\n notes?: string[]\n}\n\nexport interface BuildResult {\n table: RoutingTable\n cfg: ResolvedConfig\n scoreTable: ScoreTable\n catalog: CatalogModel[]\n}\n\nexport async function buildRoutingTable(opts: BuildOptions = {}): Promise<BuildResult> {\n const catalogFile = opts.catalogFile ?? catalogCacheFile()\n const catalog = opts.catalog ?? loadCatalog(catalogFile)\n const user = loadUserConfig(opts.projectDir)\n const notes: string[] = [...(opts.notes ?? []), ...user.notes]\n\n if (catalog.length === 0) {\n notes.push(`No models found in ${catalogFile}. Start OpenCode one time and sign in, then run this command again.`)\n }\n\n const cfg = resolveConfig(user.config, catalog, opts.plan)\n const scoreTable = resolveTable(user.config)\n\n let feeds = opts.feeds\n if (!feeds) {\n const loaded = await loadFeedScores(cfg)\n feeds = loaded.feeds\n if (loaded.note) notes.push(loaded.note)\n }\n\n const profiles: RoutingTable[\"profiles\"] = {}\n for (const plan of PLAN_PROFILES) {\n const planCfg: ResolvedConfig = { ...cfg, plan }\n const chains: RoleChains = {}\n for (const role of ROLE_NAMES) {\n chains[role] = rankRole(catalog, role, scoreTable, planCfg, feeds)\n }\n profiles[plan] = chains\n }\n\n const table: RoutingTable = {\n version: 1,\n createdAt: (opts.now ?? new Date()).toISOString(),\n plan: cfg.plan,\n active: profiles[cfg.plan] ?? {},\n profiles,\n notes,\n }\n\n return { table, cfg, scoreTable, catalog }\n}\n\n/** Every entry of every active chain. */\nexport function activeEntries(table: RoutingTable): RankingEntry[] {\n return ROLE_NAMES.flatMap((role) => table.active[role] ?? [])\n}\n\n/** The model a role should use right now, given the ledger's health flags. */\nexport function pickForRole(\n table: RoutingTable,\n role: RoleName,\n isHealthy: (modelId: string) => boolean,\n): RankingEntry | undefined {\n const chain = table.active[role]\n if (!chain || chain.length === 0) return undefined\n return chain.find((entry) => isHealthy(entry.id)) ?? chain[0]\n}\n\n/** Health check for one model id, from the ledger and the active plan's caps. */\nexport function healthCheck(result: BuildResult, ledger: LedgerStore): (modelId: string) => boolean {\n return (modelId) =>\n ledger.isHealthy(modelId, monthlyCapFor(modelId, result.scoreTable, result.cfg.plan), result.cfg.softThreshold)\n}\n\n/** Usage of each model in the 5-hour window, in percent of its 5-hour allowance. */\nexport function usagePercent(result: BuildResult, ledger: LedgerStore, modelId: string): number {\n return ledger.usage(modelId, monthlyCapFor(modelId, result.scoreTable, result.cfg.plan)).pct5h * 100\n}\n\nexport type RoleState = \"healthy\" | \"failover\" | \"limited\" | \"none\"\n\nexport interface StatusRow {\n role: RoleName\n /** The model in use now; undefined when the role has no eligible model. */\n entry?: RankingEntry\n pct5h: number\n state: RoleState\n}\n\n/** The model each role uses now, after failover, with its 5-hour use. */\nexport function statusRows(result: BuildResult, ledger: LedgerStore): StatusRow[] {\n const isHealthy = healthCheck(result, ledger)\n return ROLE_NAMES.map((role): StatusRow => {\n // Only the agent roles switch per message; the internal roles keep the first model.\n const entry = isAgentRole(role) ? pickForRole(result.table, role, isHealthy) : result.table.active[role]?.[0]\n if (!entry) return { role, pct5h: 0, state: \"none\" }\n const state: RoleState = !isHealthy(entry.id) ? \"limited\" : entry.rank > 1 ? \"failover\" : \"healthy\"\n return { role, entry, pct5h: usagePercent(result, ledger, entry.id), state }\n })\n}\n","import { ROLE_NAMES } from \"./types.js\"\nimport type { RankingEntry, RoutingTable } from \"./types.js\"\nimport type { StatusRow } from \"./engine.js\"\n\nfunction fmtTokens(value: number | null): string {\n if (value === null) return \"unlimited\"\n if (value >= 1) return `${value.toFixed(1)}M`\n return `${(value * 1000).toFixed(0)}K`\n}\n\nfunction fmtCap(value: number | null): string {\n return value === null ? \"inf\" : `$${value}`\n}\n\nfunction classTag(entry: RankingEntry): string {\n if (entry.class === \"free\") return \"free*\"\n if (entry.class === \"subscription\") return \"go\"\n return \"paid\"\n}\n\nexport function formatScorecard(table: RoutingTable, opts: { verbose?: boolean } = {}): string {\n const lines: string[] = []\n const when = table.createdAt.replace(\"T\", \" \").replace(/\\..*$/, \"\")\n lines.push(`## opencode-router scorecard`)\n lines.push(\"\")\n lines.push(`- Plan: **${table.plan}**`)\n lines.push(`- Updated: ${when} (UTC)`)\n lines.push(`- Legend: go = Go subscription, free* = $0 (data may be collected), paid = Zen pay-as-you-go`)\n lines.push(\"\")\n lines.push(\"| Role | # | Model | Var | Score | Intel | Speed | Endur | Tokens/5h | Cap/mo | Class |\")\n lines.push(\"| :-- | --: | :-- | :-- | --: | --: | --: | --: | --: | --: | :-- |\")\n\n for (const role of ROLE_NAMES) {\n const chain = table.active[role]\n if (!chain) continue\n if (chain.length === 0) {\n lines.push(`| ${role} | - | _no eligible model_ | | | | | | | | |`)\n continue\n }\n chain.forEach((entry, index) => {\n const roleCol = index === 0 ? role : \"\"\n const sources = opts.verbose\n ? ` (${entry.sources.intelligence}/${entry.sources.speed}/${entry.sources.endurance})`\n : \"\"\n lines.push(\n `| ${roleCol} | ${entry.rank} | \\`${entry.id}\\`${sources} | ${entry.variant ?? \"-\"} | ${entry.score} | ${entry.intelligence} | ${entry.speed} | ${entry.endurance} | ${fmtTokens(entry.tokensPer5h)} | ${fmtCap(entry.monthlyCapUSD)} | ${classTag(entry)} |`,\n )\n })\n }\n\n if (table.notes.length > 0) {\n lines.push(\"\")\n lines.push(\"**Notes**\")\n for (const note of table.notes) lines.push(`- ${note}`)\n }\n\n lines.push(\"\")\n lines.push(\n opts.verbose\n ? `_Sources (intel/speed/endur): override = committed/user table, feed = external benchmark, cap = computed from quota, heuristic = name pattern, default = no match._`\n : `_Run \\`opencode-router refresh --dry-run --verbose\\` in a terminal to see the source of each score._`,\n )\n return lines.join(\"\\n\")\n}\n\nexport function formatStatus(table: RoutingTable, rows: StatusRow[]): string {\n const lines: string[] = []\n lines.push(`## opencode-router status`)\n lines.push(\"\")\n lines.push(`- Plan: **${table.plan}**`)\n lines.push(\n `- State: healthy = first model; failover = a later model, because the first is limited; limited = the model in use is near its limit or in cooldown`,\n )\n lines.push(\"\")\n lines.push(\"| Role | Model in use | Rank | Usage (5h) | State |\")\n lines.push(\"| :-- | :-- | --: | --: | :-- |\")\n for (const row of rows) {\n if (!row.entry) {\n lines.push(`| ${row.role} | _none_ | - | - | - |`)\n continue\n }\n lines.push(`| ${row.role} | \\`${row.entry.id}\\` | ${row.entry.rank} | ${row.pct5h.toFixed(0)}% | ${row.state} |`)\n }\n return lines.join(\"\\n\")\n}\n","import path from \"node:path\"\nimport { AGENT_ROLES, isAgentRole } from \"./types.js\"\nimport type { ConfigScope, RoutingTable } from \"./types.js\"\nimport {\n editJsonFile,\n fileExists,\n globalConfigDir,\n globalOpencodeConfigCandidates,\n opencodeConfigCandidates,\n type JsonEdit,\n} from \"./paths.js\"\n\n/** Internal roles that OpenCode configures as agents (`small_model` is a top-level key). */\nconst INTERNAL_AGENTS = [\"compaction\", \"title\", \"summary\"] as const\n\nconst SCHEMA_URL = \"https://opencode.ai/config.json\"\n\n// Type aliases, not interfaces: OpenCode's Config type has index signatures,\n// and only an alias gets the implicit index signature that matches them.\nexport type AgentModel = {\n model: string\n variant?: string\n}\n\nexport type RoutingConfigBody = {\n model?: string\n small_model?: string\n agent: Record<string, AgentModel>\n}\n\n/** Build the OpenCode config fragment that expresses the routing table. */\nexport function routingConfigBody(table: RoutingTable): RoutingConfigBody {\n const agent: Record<string, AgentModel> = {}\n\n for (const role of AGENT_ROLES) {\n const entry = table.active[role]?.[0]\n if (!entry) continue\n agent[role] = entry.variant && entry.variant !== \"none\" ? { model: entry.id, variant: entry.variant } : { model: entry.id }\n }\n for (const role of INTERNAL_AGENTS) {\n const entry = table.active[role]?.[0]\n if (!entry) continue\n agent[role] = { model: entry.id }\n }\n\n const body: RoutingConfigBody = { agent }\n const build = table.active.build?.[0]\n const small = table.active.small_model?.[0]\n if (build) body.model = build.id\n if (small) body.small_model = small.id\n return body\n}\n\nexport interface WriteResult {\n path: string\n created: boolean\n}\n\n/** Pick the config file to write for the given scope. */\nexport function pickConfigPath(scope: ConfigScope, dir: string): string {\n const candidates = scope === \"global\" ? globalOpencodeConfigCandidates() : opencodeConfigCandidates(dir)\n for (const candidate of candidates) {\n if (fileExists(candidate)) return candidate\n }\n return scope === \"global\" ? path.join(globalConfigDir(), \"opencode.json\") : path.join(dir, \"opencode.json\")\n}\n\n/**\n * Write the routing table into the user's opencode.json(c). Only the keys the\n * router owns change: `model`, `small_model`, and `agent.<role>.model` (plus\n * `variant` for the agent roles). Comments and all other keys stay. A file\n * with a JSON error is never replaced: this throws and leaves it as it is.\n */\nexport function writeRoutingConfig(table: RoutingTable, scope: ConfigScope, dir: string): WriteResult {\n const target = pickConfigPath(scope, dir)\n const body = routingConfigBody(table)\n\n const edits: JsonEdit[] = []\n if (body.model) edits.push({ path: [\"model\"], value: body.model })\n if (body.small_model) edits.push({ path: [\"small_model\"], value: body.small_model })\n for (const [role, spec] of Object.entries(body.agent)) {\n edits.push({ path: [\"agent\", role, \"model\"], value: spec.model })\n if (isAgentRole(role)) edits.push({ path: [\"agent\", role, \"variant\"], value: spec.variant })\n }\n\n const { created } = editJsonFile(target, edits, `{\\n \"$schema\": \"${SCHEMA_URL}\"\\n}\\n`)\n return { path: target, created }\n}\n\nexport interface ServerPatchResult {\n applied: boolean\n detail: string\n}\n\n/**\n * Best-effort live apply from the CLI: PATCH the running OpenCode server's\n * config. Used only when OPENCODE_SERVER_URL (+ optional basic auth) is set.\n */\nexport async function patchServerConfig(table: RoutingTable): Promise<ServerPatchResult> {\n const base = process.env.OPENCODE_SERVER_URL ?? process.env.OPENCODE_SERVER\n if (!base) {\n return { applied: false, detail: \"live PATCH not attempted (no OPENCODE_SERVER_URL set)\" }\n }\n\n const url = base.replace(/\\/$/, \"\") + \"/config\"\n const headers: Record<string, string> = { \"content-type\": \"application/json\" }\n const user = process.env.OPENCODE_SERVER_USERNAME\n const pass = process.env.OPENCODE_SERVER_PASSWORD\n if (user && pass) headers.authorization = \"Basic \" + Buffer.from(`${user}:${pass}`).toString(\"base64\")\n\n try {\n const res = await fetch(url, { method: \"PATCH\", headers, body: JSON.stringify(routingConfigBody(table)) })\n if (!res.ok) return { applied: false, detail: `PATCH ${url} -> ${res.status}` }\n return { applied: true, detail: `PATCH ${url}` }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { applied: false, detail: `PATCH failed: ${message}` }\n }\n}\n","import fs from \"node:fs\"\nimport type { Ledger, LedgerModelState } from \"./types.js\"\nimport { isPlainObject, readJsonFile, writeJson } from \"./paths.js\"\nimport { FIVE_HOUR_SHARE } from \"./scoring.js\"\n\nconst HOUR = 3_600_000\nconst DAY = 24 * HOUR\nexport const WINDOW_5H = 5 * HOUR\nexport const WINDOW_WEEK = 7 * DAY\nexport const WINDOW_MONTH = 30 * DAY\n\n/** A model is unhealthy once it has used this share of its monthly allowance. */\nconst MONTHLY_LIMIT = 0.95\n\nfunction emptyState(now: number): LedgerModelState {\n return {\n cost5h: 0,\n costWeek: 0,\n costMonth: 0,\n tokens5h: 0,\n tokensWeek: 0,\n tokensMonth: 0,\n window5hStart: now,\n windowWeekStart: now,\n windowMonthStart: now,\n }\n}\n\nfunction emptyLedger(now: number): Ledger {\n return { version: 1, updatedAt: new Date(now).toISOString(), models: {} }\n}\n\nfunction isLedger(value: unknown): value is Ledger {\n return isPlainObject(value) && value.version === 1 && isPlainObject(value.models)\n}\n\nfunction mtimeOf(file: string): number {\n try {\n return fs.statSync(file).mtimeMs\n } catch {\n return -1\n }\n}\n\nexport interface ModelUsage {\n cost5h: number\n costMonth: number\n tokens5h: number\n tokensMonth: number\n pct5h: number\n pctMonth: number\n cooldownUntil: number | null\n}\n\n/**\n * Rolling spend per model, stored in one JSON file. Several OpenCode sessions\n * can share the file: each call reloads it when another process changed it.\n */\nexport class LedgerStore {\n private data: Ledger\n private loadedMtime = -1\n\n constructor(\n private readonly file: string,\n private readonly now: () => number = Date.now,\n ) {\n this.data = this.load()\n }\n\n /** Read the file. A corrupt file is kept as `<file>.corrupt-<time>` and a new ledger starts. */\n private load(): Ledger {\n this.loadedMtime = mtimeOf(this.file)\n const result = readJsonFile(this.file)\n if (result.status === \"ok\" && isLedger(result.value)) return result.value\n if (result.status !== \"absent\") {\n try {\n fs.renameSync(this.file, `${this.file}.corrupt-${this.now()}`)\n } catch {\n /* keep going with an empty ledger */\n }\n this.loadedMtime = -1\n }\n return emptyLedger(this.now())\n }\n\n private sync(): void {\n if (mtimeOf(this.file) !== this.loadedMtime) this.data = this.load()\n }\n\n /** Reset each window that has ended. */\n private roll(state: LedgerModelState, now: number): LedgerModelState {\n if (now - state.window5hStart >= WINDOW_5H) {\n state.cost5h = 0\n state.tokens5h = 0\n state.window5hStart = now\n }\n if (now - state.windowWeekStart >= WINDOW_WEEK) {\n state.costWeek = 0\n state.tokensWeek = 0\n state.windowWeekStart = now\n }\n if (now - state.windowMonthStart >= WINDOW_MONTH) {\n state.costMonth = 0\n state.tokensMonth = 0\n state.windowMonthStart = now\n }\n return state\n }\n\n private state(modelId: string): LedgerModelState {\n this.sync()\n const now = this.now()\n let entry = this.data.models[modelId]\n if (!entry) {\n entry = emptyState(now)\n this.data.models[modelId] = entry\n }\n return this.roll(entry, now)\n }\n\n record(modelId: string, costUSD: number, tokens: number): void {\n const state = this.state(modelId)\n state.cost5h += costUSD\n state.costWeek += costUSD\n state.costMonth += costUSD\n state.tokens5h += tokens\n state.tokensWeek += tokens\n state.tokensMonth += tokens\n state.lastUsedAt = this.now()\n this.save()\n }\n\n cooldown(modelId: string, durationMs: number, reason?: string): void {\n const state = this.state(modelId)\n state.cooldownUntil = this.now() + durationMs\n if (reason) state.lastError = reason\n this.save()\n }\n\n clearCooldown(modelId: string): void {\n const state = this.state(modelId)\n state.cooldownUntil = undefined\n this.save()\n }\n\n usage(modelId: string, monthlyCapUSD: number | null): ModelUsage {\n return usageOf(this.state(modelId), monthlyCapUSD)\n }\n\n /** Healthy = not cooling down, under the soft threshold for 5 hours, and under the monthly limit. */\n isHealthy(modelId: string, monthlyCapUSD: number | null, softThreshold: number): boolean {\n const state = this.state(modelId)\n if (state.cooldownUntil && this.now() < state.cooldownUntil) return false\n const u = usageOf(state, monthlyCapUSD)\n return u.pct5h < softThreshold && u.pctMonth < MONTHLY_LIMIT\n }\n\n snapshot(): Ledger {\n return structuredClone(this.data)\n }\n\n save(): void {\n this.data.updatedAt = new Date(this.now()).toISOString()\n writeJson(this.file, this.data)\n this.loadedMtime = mtimeOf(this.file)\n }\n}\n\nfunction usageOf(state: LedgerModelState, monthlyCapUSD: number | null): ModelUsage {\n const cap5h = monthlyCapUSD === null ? null : monthlyCapUSD * FIVE_HOUR_SHARE\n return {\n cost5h: state.cost5h,\n costMonth: state.costMonth,\n tokens5h: state.tokens5h,\n tokensMonth: state.tokensMonth,\n pct5h: cap5h === null || cap5h <= 0 ? 0 : state.cost5h / cap5h,\n pctMonth: monthlyCapUSD === null || monthlyCapUSD <= 0 ? 0 : state.costMonth / monthlyCapUSD,\n cooldownUntil: state.cooldownUntil ?? null,\n }\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport type { ConfigScope } from \"./types.js\"\nimport { SLASH_COMMANDS, commandTemplate, type SlashCommand } from \"./commands.js\"\nimport { ensureDir, fileExists, globalConfigDir, writeJson } from \"./paths.js\"\n\nfunction commandFile(command: SlashCommand): string {\n return [\"---\", `description: ${command.description}`, \"agent: build\", \"---\", \"\", commandTemplate(command.args), \"\"].join(\"\\n\")\n}\n\nexport interface InstallResult {\n commandDir: string\n configPath: string\n /** False when a router.config.json already existed; it is never replaced. */\n configCreated: boolean\n files: string[]\n}\n\n/** Write on-disk slash-command files, plus an empty router.config.json when there is none. */\nexport function installCommands(scope: ConfigScope, dir: string): InstallResult {\n const base = scope === \"global\" ? globalConfigDir() : path.join(dir, \".opencode\")\n const commandDir = path.join(base, \"command\")\n ensureDir(commandDir)\n\n const files = SLASH_COMMANDS.map((command) => {\n const file = path.join(commandDir, `${command.name}.md`)\n fs.writeFileSync(file, commandFile(command), \"utf8\")\n return file\n })\n\n const configPath = path.join(base, \"router.config.json\")\n const configCreated = !fileExists(configPath)\n if (configCreated) writeJson(configPath, {})\n\n return { commandDir, configPath, configCreated, files }\n}\n","import { fileURLToPath } from \"node:url\"\n\nexport interface SlashCommand {\n name: string\n description: string\n /** CLI arguments; OpenCode replaces $1 with the first word the user types. */\n args: string\n}\n\n/** The slash commands, shared by the plugin and `opencode-router install`. */\nexport const SLASH_COMMANDS: readonly SlashCommand[] = [\n { name: \"refresh-routing\", description: \"Recompute and apply OpenCode model routing\", args: \"refresh\" },\n { name: \"routing-status\", description: \"Show the model in use per role and its 5-hour quota use\", args: \"status\" },\n { name: \"routing-plan\", description: \"Switch the routing plan (go | go-plus | free) and rebuild\", args: \"plan $1\" },\n { name: \"routing-eval\", description: \"Run the router scoring stress test\", args: \"eval\" },\n { name: \"routing-update\", description: \"Update opencode-router to the newest version\", args: \"update\" },\n]\n\nconst OUTPUT_BEGIN = \"---BEGIN ROUTER OUTPUT---\"\n\n/** True for the prompt of a router slash command. */\nexport function isRouterCommandPrompt(parts: readonly { type: string; text?: string }[]): boolean {\n return parts.some((part) => part.type === \"text\" && part.text?.includes(OUTPUT_BEGIN) === true)\n}\n\n/** Absolute path of the CLI script that ships next to this module in dist/. */\nfunction cliScriptPath(): string {\n return fileURLToPath(new URL(\"./bin.js\", import.meta.url)).replace(/\\\\/g, \"/\")\n}\n\n/** Command body. OpenCode runs the !`...` part and puts its output in the prompt. */\nexport function commandTemplate(args: string): string {\n return [\n \"opencode-router already ran. Its output is between the markers below.\",\n \"\",\n \"Rules:\",\n \"1. Do not run any command, script, or tool. Do not search for opencode-router on PATH.\",\n \"2. Present the text between the markers to the user exactly as written.\",\n \"3. Do not summarize, reformat, shorten, or reorganize it.\",\n \"\",\n OUTPUT_BEGIN,\n `!\\`node \"${cliScriptPath()}\" ${args} --scope global\\``,\n \"---END ROUTER OUTPUT---\",\n ].join(\"\\n\")\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport { globalConfigDir, readJson, writeJson } from \"./paths.js\"\n\n// Usage caps are per OpenCode account, not per project, so all runtime state\n// lives in one global folder that the plugin and the CLI share.\n\nexport function stateDir(): string {\n return path.join(globalConfigDir(), \"router\")\n}\n\nexport function ledgerFile(): string {\n return path.join(stateDir(), \"ledger.json\")\n}\n\nexport function routingTableFile(): string {\n return path.join(stateDir(), \"routing-table.json\")\n}\n\nexport function evalReportFile(): string {\n return path.join(stateDir(), \"eval-report.md\")\n}\n\nexport function updateCheckFile(): string {\n return path.join(stateDir(), \"update-check.json\")\n}\n\nfunction applyMarkerFile(): string {\n return path.join(stateDir(), \"last-apply.json\")\n}\n\n/** The plugin's hot-apply and the CLI it starts run within milliseconds of each other. */\nconst MARKER_MAX_AGE_MS = 10_000\n\nexport interface ApplyMarker {\n ok: boolean\n detail: string\n}\n\n/** Record the result of the plugin's last hot-apply, for the CLI to report. */\nexport function writeApplyMarker(marker: ApplyMarker): void {\n writeJson(applyMarkerFile(), { at: new Date().toISOString(), ...marker })\n}\n\nexport function readApplyMarker(maxAgeMs = MARKER_MAX_AGE_MS): ApplyMarker | null {\n const marker = readJson<{ at?: string; ok?: boolean; detail?: string }>(applyMarkerFile())\n if (!marker?.at || !marker.detail) return null\n const at = Date.parse(marker.at)\n if (!Number.isFinite(at) || Date.now() - at > maxAgeMs) return null\n return { ok: marker.ok === true, detail: marker.detail }\n}\n\nexport function clearApplyMarker(): void {\n fs.rmSync(applyMarkerFile(), { force: true })\n}\n","import type { PlanProfile, RankingEntry } from \"./types.js\"\nimport { buildRoutingTable } from \"./engine.js\"\nimport { writeTextAtomic } from \"./paths.js\"\nimport { FIVE_HOUR_SHARE } from \"./scoring.js\"\nimport { evalReportFile } from \"./state.js\"\n\nexport interface EvalOptions {\n plan?: PlanProfile\n catalog?: string\n json?: boolean\n projectDir?: string\n}\n\nconst ROLE = \"build\"\nconst CHAIN_LIMIT = 4\n\nconst PROMPT = `In a fixture repo, build a CLI named \\`todo\\` with \\`add\\`, \\`list\\`, \\`done <id>\\`, and \\`rm <id>\\` subcommands backed by a JSON file. Include input validation, a \\`--json\\` output flag, and a test suite. Then fix any failing tests.`\n\nconst GO_URL = \"https://opencode.ai/inference/go/openai/v1\"\nconst ZEN_URL = \"https://opencode.ai/inference/openai/v1\"\n\ninterface CallResult {\n ok: boolean\n latencyMs: number\n inputTokens: number\n outputTokens: number\n costUSD: number\n text: string\n error?: string\n}\n\nfunction staticGrade(text: string): { passed: number; checks: Record<string, boolean> } {\n const lower = text.toLowerCase()\n const checks: Record<string, boolean> = {\n add: /\\badd\\b/.test(lower),\n list: /\\blist\\b/.test(lower),\n done: /\\bdone\\b/.test(lower),\n rm: /\\brm\\b|\\bremove\\b|\\bdelete\\b/.test(lower),\n jsonFlag: /--json/.test(text),\n validation: /invalid|validat|error/.test(lower),\n tests: /\\btest\\b|\\bdescribe\\(|\\bit\\(|assert/.test(lower),\n }\n const passed = Object.values(checks).filter(Boolean).length\n return { passed, checks }\n}\n\nasync function callModel(entry: RankingEntry, apiKey: string): Promise<CallResult> {\n const base = entry.providerID === \"opencode-go\" ? GO_URL : ZEN_URL\n const started = Date.now()\n try {\n const res = await fetch(`${base}/chat/completions`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n model: entry.modelID,\n messages: [{ role: \"user\", content: PROMPT }],\n max_tokens: 2000,\n }),\n })\n const latencyMs = Date.now() - started\n if (!res.ok) {\n return { ok: false, latencyMs, inputTokens: 0, outputTokens: 0, costUSD: 0, text: \"\", error: `HTTP ${res.status}` }\n }\n const json = (await res.json()) as {\n choices?: Array<{ message?: { content?: string } }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const text = json.choices?.[0]?.message?.content ?? \"\"\n return {\n ok: true,\n latencyMs,\n inputTokens: json.usage?.prompt_tokens ?? 0,\n outputTokens: json.usage?.completion_tokens ?? 0,\n costUSD: estimateCost(entry, json.usage?.prompt_tokens ?? 0, json.usage?.completion_tokens ?? 0),\n text,\n }\n } catch (error) {\n return {\n ok: false,\n latencyMs: Date.now() - started,\n inputTokens: 0,\n outputTokens: 0,\n costUSD: 0,\n text: \"\",\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\nfunction estimateCost(entry: RankingEntry, inputTokens: number, outputTokens: number): number {\n // Rough: derived from the score table's blended cost when present.\n const per1M = entry.tokensPer5h && entry.monthlyCapUSD ? (entry.monthlyCapUSD * FIVE_HOUR_SHARE) / entry.tokensPer5h : 1\n return ((inputTokens + outputTokens) / 1_000_000) * per1M\n}\n\nexport async function runEval(opts: EvalOptions = {}): Promise<number> {\n const { table } = await buildRoutingTable({ plan: opts.plan, catalogFile: opts.catalog, projectDir: opts.projectDir })\n const chain = (table.active[ROLE] ?? []).slice(0, CHAIN_LIMIT)\n\n if (chain.length === 0) {\n process.stderr.write(`error: no candidate models for role \"${ROLE}\"\\n`)\n return 1\n }\n\n const apiKey = process.env.OPENCODE_API_KEY\n const reportPath = evalReportFile()\n\n const lines: string[] = []\n lines.push(`# opencode-router eval report`)\n lines.push(\"\")\n lines.push(`- Role: **${ROLE}**`)\n lines.push(`- Plan: **${table.plan}**`)\n lines.push(`- Generated: ${new Date().toISOString()}`)\n lines.push(\"\")\n lines.push(`## Prompt`)\n lines.push(\"\")\n lines.push(\"> \" + PROMPT.replace(/\\r?\\n/g, \" \"))\n lines.push(\"\")\n\n if (!apiKey) {\n lines.push(\"## Result\")\n lines.push(\"\")\n lines.push(\"`OPENCODE_API_KEY` is not set. Nothing was called. The predicted ranking is below.\")\n lines.push(\"\")\n lines.push(\"| Rank | Model | Score | Intel | Speed | Endur | Tokens/5h | Class |\")\n lines.push(\"| --: | :-- | --: | --: | --: | --: | --: | :-- |\")\n for (const e of chain) {\n lines.push(`| ${e.rank} | \\`${e.id}\\` | ${e.score} | ${e.intelligence} | ${e.speed} | ${e.endurance} | ${e.tokensPer5h ?? \"inf\"} | ${e.class} |`)\n }\n lines.push(\"\")\n lines.push(\"Set `OPENCODE_API_KEY` and re-run `opencode-router eval` to measure real latency, tokens, and pass rate.\")\n writeTextAtomic(reportPath, lines.join(\"\\n\") + \"\\n\")\n if (opts.json) process.stdout.write(JSON.stringify({ role: ROLE, predicted: chain }, null, 2) + \"\\n\")\n else process.stdout.write(`Wrote ${reportPath} (predicted only; set OPENCODE_API_KEY for live results)\\n`)\n return 0\n }\n\n lines.push(\"## Result\")\n lines.push(\"\")\n lines.push(\"| Predicted rank | Model | Latency (ms) | Tokens | Cost (USD) | Checks | Static pass | Error |\")\n lines.push(\"| --: | :-- | --: | --: | --: | --: | --: | :-- |\")\n\n const results: Array<{ entry: RankingEntry; result: CallResult; pass: number }> = []\n for (const entry of chain) {\n const result = await callModel(entry, apiKey)\n const grade = staticGrade(result.text)\n results.push({ entry, result, pass: grade.passed })\n lines.push(\n `| ${entry.rank} | \\`${entry.id}\\` | ${result.latencyMs} | ${result.inputTokens + result.outputTokens} | ${result.costUSD.toFixed(5)} | ${grade.passed}/7 | ${result.ok ? (grade.passed >= 5 ? \"PASS\" : \"WEAK\") : \"FAIL\"} | ${result.error ?? \"\"} |`,\n )\n }\n\n const measured = [...results].sort((a, b) => b.pass - a.pass || a.result.latencyMs - b.result.latencyMs)\n lines.push(\"\")\n lines.push(\"## Predicted vs measured\")\n lines.push(\"\")\n lines.push(\"| Predicted rank | Measured rank | Model |\")\n lines.push(\"| --: | --: | :-- |\")\n for (const { entry } of results) {\n const measuredRank = measured.findIndex((m) => m.entry.id === entry.id) + 1\n lines.push(`| ${entry.rank} | ${measuredRank} | \\`${entry.id}\\` |`)\n }\n lines.push(\"\")\n lines.push(\"Feed the measured ranks back into `model-scores.json` (or `router.config.json` -> `scores`) to tune accuracy.\")\n\n writeTextAtomic(reportPath, lines.join(\"\\n\") + \"\\n\")\n if (opts.json) process.stdout.write(JSON.stringify({ role: ROLE, results }, null, 2) + \"\\n\")\n else process.stdout.write(`Wrote ${reportPath}\\n`)\n return 0\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { loadUserConfig } from \"./config.js\"\nimport { opencodeCacheDir, readJson, writeJson } from \"./paths.js\"\nimport { updateCheckFile } from \"./state.js\"\n\n// OpenCode 1.19 installs an npm plugin one time and then reuses its cached\n// copy. It does not look for a newer version, so the router does.\n\nexport const PACKAGE_NAME = \"@s-berdia/opencode-router\"\nconst LATEST_URL = `https://registry.npmjs.org/${PACKAGE_NAME.replace(\"/\", \"%2f\")}/latest`\nconst CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\nconst TIMEOUT_MS = 3000\n\nexport interface UpdateInfo {\n current: string\n latest: string\n}\n\ninterface UpdateCheckState {\n checkedAt: number\n latest?: string\n}\n\nfunction parseVersion(version: string): number[] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version)\n return match ? match.slice(1).map(Number) : null\n}\n\n/** True when version `a` is higher than version `b`. Compares major.minor.patch only. */\nexport function isNewerVersion(a: string, b: string): boolean {\n const left = parseVersion(a)\n const right = parseVersion(b)\n if (!left || !right) return false\n for (let i = 0; i < 3; i++) {\n if (left[i]! !== right[i]!) return left[i]! > right[i]!\n }\n return false\n}\n\n/** The version in this package's package.json, one folder above dist/ (or src/ in tests). */\nexport function installedVersion(): string {\n const file = fileURLToPath(new URL(\"../package.json\", import.meta.url))\n return readJson<{ version?: string }>(file)?.version ?? \"0.0.0\"\n}\n\n/** The `latest` version on npm, or undefined when npm cannot be reached. */\nexport async function fetchLatestVersion(): Promise<string | undefined> {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS)\n try {\n const res = await fetch(LATEST_URL, { signal: controller.signal, headers: { accept: \"application/json\" } })\n if (!res.ok) return undefined\n const body = (await res.json()) as { version?: unknown }\n return typeof body.version === \"string\" ? body.version : undefined\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\nexport interface UpdateCheckOptions {\n projectDir?: string\n /** Installed version; default: this package's version. */\n current?: string\n now?: number\n}\n\n/**\n * The newer version on npm, or null. Asks npm at most once per 24 hours and\n * never when `updateCheck` is false. Never throws.\n */\nexport async function checkForUpdate(opts: UpdateCheckOptions = {}): Promise<UpdateInfo | null> {\n try {\n if (loadUserConfig(opts.projectDir).config.updateCheck === false) return null\n const current = opts.current ?? installedVersion()\n const now = opts.now ?? Date.now()\n const state = readJson<UpdateCheckState>(updateCheckFile())\n let latest = state?.latest\n const fresh = state !== undefined && now >= state.checkedAt && now - state.checkedAt < CHECK_INTERVAL_MS\n if (!fresh) {\n // Record failed checks too, so an offline machine asks once per day, not at each start.\n latest = (await fetchLatestVersion()) ?? latest\n writeJson(updateCheckFile(), { checkedAt: now, latest })\n }\n return latest && isNewerVersion(latest, current) ? { current, latest } : null\n } catch {\n return null\n }\n}\n\n/** One line for the end of the status and the scorecard. */\nexport function updateNotice(update: UpdateInfo): string {\n return `opencode-router ${update.latest} is available (installed: ${update.current}). To update, type /routing-update in OpenCode.`\n}\n\nexport interface ClearResult {\n /** Removed cache folders. OpenCode installs the newest version into them at its next start. */\n removed: string[]\n /** Cache folders of an older version that opencode.json pins, for example `opencode-router@1.0.1`. */\n pinned: string[]\n /** Cache folders that already have the newest version. */\n current: string[]\n /** Old cache folders that could not be removed, for example because Windows locks a file. */\n failed: Array<{ dir: string; error: string }>\n}\n\n/**\n * Remove OpenCode's cached copies of this package that are older than `latest`.\n * OpenCode 1.19 keeps them in <cache>/packages/@s-berdia/<spec>/node_modules/.\n */\nexport function clearOutdatedCopies(latest: string): ClearResult {\n const [scope, name] = PACKAGE_NAME.split(\"/\") as [string, string]\n const scopeDir = path.join(opencodeCacheDir(), \"packages\", scope)\n const result: ClearResult = { removed: [], pinned: [], current: [], failed: [] }\n let entries: string[] = []\n try {\n entries = fs.readdirSync(scopeDir)\n } catch {\n return result\n }\n for (const entry of entries) {\n const dir = path.join(scopeDir, entry)\n if (entry === name || entry === `${name}@latest`) {\n const manifest = path.join(dir, \"node_modules\", scope, name, \"package.json\")\n const version = readJson<{ version?: string }>(manifest)?.version ?? \"0.0.0\"\n if (!isNewerVersion(latest, version)) {\n result.current.push(dir)\n continue\n }\n try {\n fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 })\n result.removed.push(dir)\n } catch (error) {\n result.failed.push({ dir, error: error instanceof Error ? error.message : String(error) })\n }\n } else if (entry.startsWith(`${name}@`) && isNewerVersion(latest, entry.slice(name.length + 1))) {\n result.pinned.push(entry)\n }\n }\n return result\n}\n","#!/usr/bin/env node\nimport { main } from \"./cli.js\"\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code\n },\n (error: unknown) => {\n process.stderr.write(`opencode-router failed: ${error instanceof Error ? error.message : String(error)}\\n`)\n process.exitCode = 1\n },\n)\n"],"mappings":";;;AAAA,SAAS,iBAAiB;;;ACEnB,IAAM,gBAAgB,CAAC,MAAM,WAAW,MAAM;AAI9C,SAAS,OAAO,OAAsC;AAC3D,SAAO,OAAO,UAAU,YAAa,cAAoC,SAAS,KAAK;AACzF;AAMO,IAAM,cAAc,CAAC,QAAQ,SAAS,WAAW,SAAS;AAG1D,IAAM,iBAAiB,CAAC,eAAe,SAAS,WAAW,YAAY;AAEvE,IAAM,aAAa,CAAC,GAAG,aAAa,GAAG,cAAc;AAQrD,SAAS,YAAY,OAA+C;AACzE,SAAO,UAAU,UAAc,YAAkC,SAAS,KAAK;AACjF;AAEO,SAAS,WAAW,OAAkC;AAC3D,SAAQ,WAAiC,SAAS,KAAK;AACzD;;;ACjCA,OAAOA,SAAQ;;;ACAf,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,QAAQ;;;ACOR,SAAS,cAAc,MAAM,eAAe,OAAO;AACtD,QAAM,MAAM,KAAK;AACjB,MAAI,MAAM,GAAG,QAAQ,IAAI,cAAc,GAAG,QAAQ,IAA6B,aAAa,GAAG,kBAAkB,GAAG,uBAAuB,GAAG,2BAA2B,GAAG,YAAY;AACxL,WAAS,cAAc,OAAO,OAAO;AACjC,QAAI,SAAS;AACb,QAAIC,SAAQ;AACZ,WAAO,SAAS,SAAS,CAAC,OAAO;AAC7B,UAAI,KA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AAM,QAAQ,EAAE,MAAM,KAAK,MAAM,SAAS,KAAK,SAAS,MAAM,KAAK,MAAM,YAAY,KAAK,IAAI,CAAC;AAAA,MACxG,KAAK;AACH,eAAO,MAAM,UAAU;AAAA,MACzB;AACE,cAAM,IAAI,WAAW,oBAAoB,OAAO,GAAG;AAAA,IACvD;AAAA,EACF,SAAS,OAAO;AACd,QAAI,iBAAiB,WAAY,QAAO,WAAW,KAAK;AACxD,UAAM;AAAA,EACR;AACF;;;AyBnRA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAC1B,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,OAAO,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAC1G,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["fs","value","CharacterCodes","ParseOptions","path","path","edit","ScanError","SyntaxKind","parse","parseTree","findNodeAtLocation","ParseErrorCode","path","parse","parseTree","findNodeAtLocation","fs","path","build","path","fs","fs","fs","path","path","fs","fs","path","path","path","fs","path","fileURLToPath","fileURLToPath","path","fs"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/types.ts","../src/catalog.ts","../src/paths.ts","../node_modules/jsonc-parser/lib/esm/impl/scanner.js","../node_modules/jsonc-parser/lib/esm/impl/string-intern.js","../node_modules/jsonc-parser/lib/esm/impl/format.js","../node_modules/jsonc-parser/lib/esm/impl/parser.js","../node_modules/jsonc-parser/lib/esm/impl/edit.js","../node_modules/jsonc-parser/lib/esm/main.js","../src/scoring.ts","../src/feeds.ts","../src/config.ts","../model-scores.json","../src/score-table.ts","../src/rank.ts","../src/engine.ts","../src/format.ts","../src/apply.ts","../src/ledger.ts","../src/install.ts","../src/commands.ts","../src/state.ts","../src/eval.ts","../src/update.ts","../src/bin.ts"],"sourcesContent":["import { parseArgs } from \"node:util\"\nimport { buildRoutingTable, statusRows } from \"./engine.js\"\nimport { formatScorecard, formatStatus } from \"./format.js\"\nimport { patchServerConfig, routingConfigBody, writeRoutingConfig } from \"./apply.js\"\nimport { LedgerStore } from \"./ledger.js\"\nimport { catalogMeta } from \"./catalog.js\"\nimport { installCommands } from \"./install.js\"\nimport { runEval } from \"./eval.js\"\nimport { editJsonFile, globalRouterConfigFile, isProjectDir, projectRouterConfigFile, readJson } from \"./paths.js\"\nimport { ledgerFile, readApplyMarker } from \"./state.js\"\nimport { PACKAGE_NAME, checkForUpdate, clearOutdatedCopies, fetchLatestVersion, updateNotice } from \"./update.js\"\nimport { isPlan, PLAN_PROFILES } from \"./types.js\"\nimport type { ConfigScope, PlanProfile } from \"./types.js\"\n\nconst HELP = `opencode-router - dynamic model routing for OpenCode Go / Go Plus / Free\n\nUsage:\n opencode-router refresh [options] Recompute the routing table and apply it\n opencode-router status [options] Show the model in use per role and its 5-hour quota use\n opencode-router plan <profile> Save the plan profile (go | go-plus | free) and rebuild\n opencode-router install [--scope] Write slash-command files and a starter config\n opencode-router cat Show catalog metadata (path, date, model count)\n opencode-router eval Run the scoring stress test\n opencode-router update Look for a newer version and clear OpenCode's cached copy\n\nOptions:\n --plan <go|go-plus|free> Plan profile for this run\n --scope <project|global> Which config files to write (default: project in a project folder, else global)\n --catalog <file> Path to an OpenCode models.json cache\n --dry-run Do not write opencode.json\n --no-apply Write opencode.json but do not send it to a running server\n --json Print machine-readable JSON\n --verbose Include score source tags\n -h, --help Show this help\n`\n\nconst PLAN_CHOICES = PLAN_PROFILES.join(\" | \")\n\n/** A mistake in the command line: exit code 2 with a short message, no stack trace. */\nclass UsageError extends Error {}\n\ninterface CommonOpts {\n plan?: PlanProfile\n scope: ConfigScope\n catalog?: string\n dryRun: boolean\n apply: boolean\n json: boolean\n verbose: boolean\n cwd: string\n}\n\n/**\n * Resolve the config scope. When the caller did not pass --scope and the\n * directory is not a real project (for example OpenCode's shell runs from the\n * home directory), fall back to the global config.\n */\nexport function resolveScope(explicit: boolean, value: ConfigScope, dir: string): ConfigScope {\n if (explicit) return value\n return isProjectDir(dir) ? \"project\" : \"global\"\n}\n\nfunction parsePlan(value: string | undefined): PlanProfile | undefined {\n if (value === undefined) return undefined\n if (!isPlan(value)) throw new UsageError(`--plan must be one of ${PLAN_CHOICES}, not \"${value}\"`)\n return value\n}\n\nfunction parseScope(value: string | undefined): ConfigScope | undefined {\n if (value === undefined || value === \"project\" || value === \"global\") return value\n throw new UsageError(`--scope must be project or global, not \"${value}\"`)\n}\n\nfunction parseCommandLine(argv: string[], cwd: string) {\n let parsed\n try {\n parsed = parseArgs({\n args: argv,\n options: {\n plan: { type: \"string\" },\n scope: { type: \"string\" },\n catalog: { type: \"string\" },\n \"dry-run\": { type: \"boolean\" },\n \"no-apply\": { type: \"boolean\" },\n json: { type: \"boolean\" },\n verbose: { type: \"boolean\" },\n help: { type: \"boolean\", short: \"h\" },\n },\n allowPositionals: true,\n })\n } catch (error) {\n throw new UsageError(error instanceof Error ? error.message : String(error))\n }\n const { values, positionals } = parsed\n const scope = parseScope(values.scope)\n const opts: CommonOpts = {\n plan: parsePlan(values.plan),\n scope: resolveScope(scope !== undefined, scope ?? \"project\", cwd),\n catalog: values.catalog,\n dryRun: values[\"dry-run\"] === true,\n apply: values[\"no-apply\"] !== true,\n json: values.json === true,\n verbose: values.verbose === true,\n cwd,\n }\n return { command: positionals[0], args: positionals.slice(1), help: values.help === true, opts }\n}\n\nfunction build(opts: CommonOpts) {\n return buildRoutingTable({ plan: opts.plan, catalogFile: opts.catalog, projectDir: opts.cwd })\n}\n\nasync function writeUpdateNotice(opts: CommonOpts): Promise<void> {\n const update = await checkForUpdate({ projectDir: opts.cwd })\n if (update) process.stdout.write(`\\n${updateNotice(update)}\\n`)\n}\n\nasync function cmdRefresh(opts: CommonOpts): Promise<number> {\n const { table } = await build(opts)\n\n if (opts.json) {\n process.stdout.write(JSON.stringify({ table, routing: routingConfigBody(table) }, null, 2) + \"\\n\")\n } else {\n process.stdout.write(formatScorecard(table, { verbose: opts.verbose }) + \"\\n\")\n }\n\n let detail = \"dry-run: nothing written\"\n let applied = false\n if (!opts.dryRun) {\n const written = writeRoutingConfig(table, opts.scope, opts.cwd)\n detail = `${written.created ? \"created\" : \"updated\"} ${written.path}`\n // A slash command's plugin hook may have hot-applied the table already.\n const marker = readApplyMarker()\n if (marker) {\n detail += ` | ${marker.detail}`\n applied = marker.ok\n } else if (opts.apply) {\n const patch = await patchServerConfig(table)\n detail += patch.applied ? ` | hot-applied (${patch.detail})` : ` | ${patch.detail}`\n applied = patch.applied\n }\n }\n\n if (!opts.json) {\n process.stdout.write(`\\nApplied: ${detail}\\n`)\n if (!opts.dryRun && !applied) {\n process.stdout.write(\n \"A running OpenCode session recomputes routing on its next message (within 15 s). Restart to reload the UI display now.\\n\",\n )\n }\n await writeUpdateNotice(opts)\n }\n return 0\n}\n\nasync function cmdStatus(opts: CommonOpts): Promise<number> {\n const result = await build(opts)\n const ledger = new LedgerStore(ledgerFile())\n const rows = statusRows(result, ledger)\n\n // The free plan has no Go allowance.\n const allowance = result.cfg.plan === \"free\" ? undefined : ledger.allowance()\n\n if (opts.json) {\n process.stdout.write(JSON.stringify({ table: result.table, rows, allowance: allowance ?? null }, null, 2) + \"\\n\")\n } else {\n const status = allowance && { usage: allowance, softThreshold: result.cfg.softThreshold }\n process.stdout.write(formatStatus(result.table, rows, status) + \"\\n\")\n await writeUpdateNotice(opts)\n }\n return 0\n}\n\nasync function cmdPlan(profile: string | undefined, opts: CommonOpts): Promise<number> {\n if (!isPlan(profile)) throw new UsageError(`plan must be one of ${PLAN_CHOICES}`)\n const file = opts.scope === \"global\" ? globalRouterConfigFile() : projectRouterConfigFile(opts.cwd)\n editJsonFile(file, [{ path: [\"plan\"], value: profile }])\n process.stdout.write(`Plan set to \"${profile}\" in ${file}\\n`)\n\n if (opts.scope === \"global\") {\n const projectFile = projectRouterConfigFile(opts.cwd)\n const projectPlan = readJson<{ plan?: unknown }>(projectFile)?.plan\n if (projectPlan !== undefined && projectPlan !== profile) {\n process.stdout.write(\n `Note: ${projectFile} sets \"plan\": ${JSON.stringify(projectPlan)}, which overrides the global plan in this project.\\n`,\n )\n }\n }\n\n process.stdout.write(\"\\n\")\n return cmdRefresh({ ...opts, plan: undefined })\n}\n\nfunction cmdCat(catalog?: string): number {\n const meta = catalogMeta(catalog)\n process.stdout.write(`Catalog: ${meta.path}\\n`)\n process.stdout.write(`Modified: ${meta.mtime ?? \"missing\"}\\n`)\n process.stdout.write(`Routed models: ${meta.total}\\n`)\n return 0\n}\n\nfunction cmdInstall(opts: CommonOpts): number {\n const result = installCommands(opts.scope, opts.cwd)\n process.stdout.write(`Wrote ${result.files.length} command files to ${result.commandDir}\\n`)\n process.stdout.write(\n result.configCreated ? `Wrote starter config: ${result.configPath}\\n` : `Kept existing config: ${result.configPath}\\n`,\n )\n return 0\n}\n\n/** Compare OpenCode's cached copies, not this process: `npx ...@latest update` is always the newest. */\nasync function cmdUpdate(): Promise<number> {\n const latest = await fetchLatestVersion()\n if (!latest) {\n process.stderr.write(\"error: could not reach the npm registry. Try again later.\\n\")\n return 1\n }\n\n const { removed, pinned, current, failed } = clearOutdatedCopies(latest)\n if (failed.length > 0) {\n for (const { dir, error } of failed) process.stderr.write(`error: could not remove ${dir} (${error})\\n`)\n process.stderr.write(`Close OpenCode, then run this command in a terminal: npx ${PACKAGE_NAME}@latest update\\n`)\n return 1\n }\n for (const dir of removed) process.stdout.write(`Removed the cached copy: ${dir}\\n`)\n if (removed.length > 0) {\n process.stdout.write(`Restart OpenCode. It then installs opencode-router ${latest}.\\n`)\n }\n if (pinned.length > 0) {\n process.stdout.write(\n `opencode.json pins an older version (${pinned.join(\", \")}). Change the plugin entry to \"${PACKAGE_NAME}@${latest}\", then restart OpenCode.\\n`,\n )\n }\n if (removed.length > 0 || pinned.length > 0) return 0\n\n if (current.length > 0) {\n process.stdout.write(`OpenCode has opencode-router ${latest}, the newest version.\\n`)\n } else {\n process.stdout.write(\n `OpenCode has no cached copy of opencode-router. The newest version is ${latest}. If you use a local build, run git pull and npm run build. If your OpenCode has the command \"opencode plugin update\", run it.\\n`,\n )\n }\n return 0\n}\n\nfunction usageError(error: Error): number {\n process.stderr.write(`error: ${error.message}\\n\\nRun \"opencode-router --help\" for usage.\\n`)\n return 2\n}\n\n/** Run one CLI command. Returns the exit code; never exits the process. */\nexport async function main(argv: string[], cwd: string = process.cwd()): Promise<number> {\n try {\n const { command, args, help, opts } = parseCommandLine(argv, cwd)\n if (!command || command === \"help\" || help) {\n process.stdout.write(HELP)\n return 0\n }\n switch (command) {\n case \"refresh\":\n return await cmdRefresh(opts)\n case \"status\":\n return await cmdStatus(opts)\n case \"plan\":\n return await cmdPlan(args[0], opts)\n case \"cat\":\n return cmdCat(opts.catalog)\n case \"install\":\n return cmdInstall(opts)\n case \"eval\":\n return await runEval({ plan: opts.plan, catalog: opts.catalog, json: opts.json, projectDir: opts.cwd })\n case \"update\":\n return await cmdUpdate()\n default:\n throw new UsageError(`unknown command \"${command}\"`)\n }\n } catch (error) {\n if (error instanceof UsageError) return usageError(error)\n throw error\n }\n}\n","// Shared types and the constant lists they are built from.\n\nexport const PLAN_PROFILES = [\"go\", \"go-plus\", \"free\"] as const\n\nexport type PlanProfile = (typeof PLAN_PROFILES)[number]\n\nexport function isPlan(value: unknown): value is PlanProfile {\n return typeof value === \"string\" && (PLAN_PROFILES as readonly string[]).includes(value)\n}\n\n/** Which config files a command reads and writes. */\nexport type ConfigScope = \"global\" | \"project\"\n\n/** OpenCode agents that the router switches per message. */\nexport const AGENT_ROLES = [\"plan\", \"build\", \"general\", \"explore\"] as const\n\n/** Helper models that OpenCode reads from the config only. */\nexport const INTERNAL_ROLES = [\"small_model\", \"title\", \"summary\", \"compaction\"] as const\n\nexport const ROLE_NAMES = [...AGENT_ROLES, ...INTERNAL_ROLES] as const\n\nexport type AgentRole = (typeof AGENT_ROLES)[number]\n\nexport type InternalRole = (typeof INTERNAL_ROLES)[number]\n\nexport type RoleName = AgentRole | InternalRole\n\nexport function isAgentRole(value: string | undefined): value is AgentRole {\n return value !== undefined && (AGENT_ROLES as readonly string[]).includes(value)\n}\n\nexport function isRoleName(value: string): value is RoleName {\n return (ROLE_NAMES as readonly string[]).includes(value)\n}\n\nexport type ScoreSource = \"override\" | \"cap\" | \"feed\" | \"heuristic\" | \"default\"\n\nexport type ModelClass = \"subscription\" | \"paid\" | \"free\"\n\nexport interface Weights {\n intelligence: number\n speed: number\n endurance: number\n}\n\n/** Intelligence and speed values from the score table, a feed, or the user. */\nexport interface MetricScores {\n intelligence?: number\n speed?: number\n}\n\nexport type Metric = keyof MetricScores\n\nexport interface RoleRequirement {\n toolCall?: boolean\n reasoning?: boolean\n minContext?: number\n minOutput?: number\n inputModalities?: string[]\n}\n\nexport interface RoleSpec {\n weights: Weights\n variant?: string\n chainDepth?: number\n requires?: RoleRequirement\n /** Prefer $0 models; adds a bonus to the score of free models. */\n preferFree?: boolean\n /** Avoid two adjacent picks from the same model family. */\n diversifyFamily?: boolean\n}\n\nexport interface ModelCost {\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n}\n\nexport interface CostTier {\n size: number\n input: number\n output: number\n cacheRead?: number\n cacheWrite?: number\n}\n\nexport interface CatalogModel {\n providerID: string\n modelID: string\n /** Full `provider/model` identifier. */\n id: string\n name: string\n family?: string\n releaseDate?: string\n status?: string\n reasoning: boolean\n toolCall: boolean\n attachment: boolean\n openWeights: boolean\n limit: { context: number; input?: number; output: number }\n cost: ModelCost\n tiers: CostTier[]\n inputModalities: string[]\n free: boolean\n}\n\nexport interface ScoredModel {\n model: CatalogModel\n intelligence: number\n speed: number\n endurance: number\n score: number\n intelligenceSource: ScoreSource\n speedSource: ScoreSource\n enduranceSource: ScoreSource\n blendedCost: number\n /** Estimated millions of tokens per 5h window; null means unlimited. */\n tokensPer5h: number | null\n /** Monthly dollar allowance; null means unlimited. */\n monthlyCapUSD: number | null\n}\n\nexport interface RankingEntry {\n rank: number\n providerID: string\n modelID: string\n id: string\n variant?: string\n score: number\n intelligence: number\n speed: number\n endurance: number\n tokensPer5h: number | null\n monthlyCapUSD: number | null\n sources: { intelligence: ScoreSource; speed: ScoreSource; endurance: ScoreSource }\n class: ModelClass\n}\n\nexport type RoleChains = Partial<Record<RoleName, RankingEntry[]>>\n\nexport interface RoutingTable {\n version: number\n createdAt: string\n plan: PlanProfile\n /** role -> ranked chain for the active plan. */\n active: RoleChains\n /** plan -> role -> ranked chain (all computed plans). */\n profiles: Partial<Record<PlanProfile, RoleChains>>\n notes: string[]\n}\n\nexport interface EnduranceScale {\n minTokensPer5h: number\n maxTokensPer5h: number\n}\n\nexport interface CostBlend {\n input: number\n output: number\n cacheRead: number\n}\n\nexport interface FeedConfig {\n enabled?: boolean\n url?: string\n timeoutMs?: number\n}\n\nexport interface RouterUserConfig {\n plan?: PlanProfile\n chainDepth?: number\n softThreshold?: number\n blend?: Partial<CostBlend>\n enduranceScale?: Partial<EnduranceScale>\n weights?: Partial<Record<RoleName, Partial<Weights>>>\n roles?: Partial<Record<RoleName, Partial<RoleSpec>>>\n denyModels?: string[]\n allowModels?: string[]\n privacy?: { freeModelsOk?: boolean }\n feeds?: FeedConfig\n /** Ask npm for a newer router version once per 24 hours (default true). */\n updateCheck?: boolean\n /** Explicit score overrides, keyed by `provider/model`. */\n scores?: Partial<Record<string, MetricScores>>\n}\n\nexport interface LedgerModelState {\n cost5h: number\n costWeek: number\n costMonth: number\n tokens5h: number\n tokensWeek: number\n tokensMonth: number\n window5hStart: number\n windowWeekStart: number\n windowMonthStart: number\n cooldownUntil?: number\n lastError?: string\n lastUsedAt?: number\n}\n\n/**\n * The Go usage allowance. All subscription models share it: a message adds its\n * cost divided by the monthly limit of its model.\n */\nexport interface LedgerAllowance {\n /** [start of the hour in ms, share of the monthly allowance used in that hour] */\n buckets: Array<[number, number]>\n cooldownUntil?: number\n lastError?: string\n}\n\nexport interface Ledger {\n version: number\n updatedAt: string\n models: Record<string, LedgerModelState>\n allowance?: LedgerAllowance\n}\n\nexport interface MonthlyCap {\n go: number | null\n goPlus: number | null\n}\n\nexport interface ScoreTable {\n version: number\n updated: string\n /** role -> weights/variant/requirements. */\n roles: Partial<Record<RoleName, RoleSpec>>\n /** `provider/model` -> fixed scores (wins over heuristics). */\n models: Record<string, MetricScores>\n /** Ordered family/substring patterns; first match wins. */\n heuristics: {\n patterns: Array<{ match: string; intelligence: number; speed: number }>\n defaultIntelligence: number\n defaultSpeed: number\n /** Penalty applied to models with no explicit entry in `models`. */\n unvettedPenalty?: number\n }\n /** Monthly USD allowance per model: { go, goPlus }. null = unlimited. */\n monthlyCaps: Record<string, MonthlyCap>\n /**\n * Score adjustment per plan and model class. On paid plans the subscription\n * models get an edge so the plan you pay for is used first and $0 models\n * remain the overflow fallback.\n */\n classPreference?: Partial<Record<PlanProfile, Partial<Record<ModelClass, number>>>>\n}\n\nexport interface ResolvedConfig extends RouterUserConfig {\n plan: PlanProfile\n chainDepth: number\n softThreshold: number\n blend: CostBlend\n enduranceScale: EnduranceScale\n denyModels: string[]\n allowModels: string[]\n privacy: { freeModelsOk: boolean }\n}\n","import fs from \"node:fs\"\nimport type { CatalogModel, CostTier } from \"./types.js\"\nimport { catalogCacheFile } from \"./paths.js\"\n\nexport interface RawModel {\n id: string\n name?: string\n family?: string\n attachment?: boolean\n reasoning?: boolean\n tool_call?: boolean\n open_weights?: boolean\n release_date?: string\n last_updated?: string\n modalities?: { input?: string[]; output?: string[] }\n limit?: { context?: number; input?: number; output?: number }\n cost?: {\n input?: number\n output?: number\n cache_read?: number\n cache_write?: number\n tiers?: Array<{\n input?: number\n output?: number\n cache_read?: number\n cache_write?: number\n tier?: { type?: string; size?: number }\n }>\n }\n}\n\nexport interface RawProvider {\n id: string\n name?: string\n models?: Record<string, RawModel>\n}\n\nexport type RawCatalog = Record<string, RawProvider>\n\n/** Providers this router understands. */\nexport const ROUTED_PROVIDERS = [\"opencode-go\", \"opencode\"] as const\n\nexport function readCatalogFile(file: string = catalogCacheFile()): RawCatalog | undefined {\n try {\n const raw = fs.readFileSync(file, \"utf8\")\n return JSON.parse(raw) as RawCatalog\n } catch {\n return undefined\n }\n}\n\nfunction toNumber(value: unknown, fallback = 0): number {\n return typeof value === \"number\" && Number.isFinite(value) ? value : fallback\n}\n\nfunction mapTiers(raw: RawModel): CostTier[] {\n const tiers = raw.cost?.tiers\n if (!Array.isArray(tiers)) return []\n const out: CostTier[] = []\n for (const t of tiers) {\n const size = t?.tier?.size\n if (typeof size !== \"number\") continue\n out.push({\n size,\n input: toNumber(t.input),\n output: toNumber(t.output),\n cacheRead: t.cache_read !== undefined ? toNumber(t.cache_read) : undefined,\n cacheWrite: t.cache_write !== undefined ? toNumber(t.cache_write) : undefined,\n })\n }\n return out.sort((a, b) => a.size - b.size)\n}\n\nexport function isFreeModel(cost: { input: number; output: number }, tiers: CostTier[]): boolean {\n const baseFree = cost.input === 0 && cost.output === 0\n const tiersFree = tiers.every((t) => t.input === 0 && t.output === 0)\n return baseFree && tiersFree\n}\n\nexport function mapModel(providerID: string, raw: RawModel): CatalogModel {\n const cost = {\n input: toNumber(raw.cost?.input),\n output: toNumber(raw.cost?.output),\n cacheRead: raw.cost?.cache_read !== undefined ? toNumber(raw.cost.cache_read) : undefined,\n cacheWrite: raw.cost?.cache_write !== undefined ? toNumber(raw.cost.cache_write) : undefined,\n }\n const tiers = mapTiers(raw)\n const rawInputs = raw.modalities?.input\n const inputModalities = Array.isArray(rawInputs) ? rawInputs.map(String) : [\"text\"]\n return {\n providerID,\n modelID: raw.id,\n id: `${providerID}/${raw.id}`,\n name: raw.name ?? raw.id,\n family: raw.family,\n releaseDate: raw.release_date ?? raw.last_updated,\n reasoning: raw.reasoning === true,\n toolCall: raw.tool_call === true,\n attachment: raw.attachment === true,\n openWeights: raw.open_weights === true,\n limit: {\n context: toNumber(raw.limit?.context),\n input: raw.limit?.input !== undefined ? toNumber(raw.limit.input) : undefined,\n output: toNumber(raw.limit?.output),\n },\n cost,\n tiers,\n inputModalities,\n free: isFreeModel(cost, tiers),\n }\n}\n\n/**\n * Load every routed model from the OpenCode catalog cache.\n * Returns models from `opencode-go` and `opencode` only.\n */\nexport function loadCatalog(file: string = catalogCacheFile()): CatalogModel[] {\n const raw = readCatalogFile(file)\n if (!raw) return []\n const out: CatalogModel[] = []\n for (const providerID of ROUTED_PROVIDERS) {\n const provider = raw[providerID]\n if (!provider?.models) continue\n for (const rawModel of Object.values(provider.models)) {\n if (rawModel && typeof rawModel.id === \"string\") out.push(mapModel(providerID, rawModel))\n }\n }\n return out\n}\n\nexport function catalogMeta(file: string = catalogCacheFile()): { path: string; mtime: string | null; total: number } {\n let mtime: string | null = null\n try {\n mtime = fs.statSync(file).mtime.toISOString()\n } catch {\n mtime = null\n }\n return { path: file, mtime, total: loadCatalog(file).length }\n}\n","import os from \"node:os\"\nimport path from \"node:path\"\nimport fs from \"node:fs\"\nimport { applyEdits, findNodeAtLocation, modify, parse, parseTree, printParseErrorCode, type ParseError } from \"jsonc-parser\"\n\n/** Global OpenCode config directory. Honors XDG_CONFIG_HOME like OpenCode does. */\nexport function globalConfigDir(): string {\n const xdg = process.env.XDG_CONFIG_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), \".config\")\n return path.join(base, \"opencode\")\n}\n\n/** OpenCode cache directory. Honors XDG_CACHE_HOME like OpenCode does. */\nexport function opencodeCacheDir(): string {\n const xdg = process.env.XDG_CACHE_HOME\n const base = xdg && xdg.length > 0 ? xdg : path.join(os.homedir(), \".cache\")\n return path.join(base, \"opencode\")\n}\n\n/** OpenCode model catalog cache written by the OpenCode CLI/desktop. */\nexport function catalogCacheFile(): string {\n return path.join(opencodeCacheDir(), \"models.json\")\n}\n\nexport function globalRouterConfigFile(): string {\n return path.join(globalConfigDir(), \"router.config.json\")\n}\n\nexport function projectRouterConfigFile(dir: string): string {\n return path.join(dir, \".opencode\", \"router.config.json\")\n}\n\n/** Candidate opencode.json paths, most specific first. */\nexport function opencodeConfigCandidates(dir: string): string[] {\n return [path.join(dir, \".opencode\", \"opencode.json\"), path.join(dir, \"opencode.jsonc\"), path.join(dir, \"opencode.json\")]\n}\n\nexport function globalOpencodeConfigCandidates(): string[] {\n return [path.join(globalConfigDir(), \"opencode.jsonc\"), path.join(globalConfigDir(), \"opencode.json\")]\n}\n\nexport function ensureDir(dir: string): void {\n fs.mkdirSync(dir, { recursive: true })\n}\n\nexport function fileExists(file: string): boolean {\n try {\n return fs.statSync(file).isFile()\n } catch {\n return false\n }\n}\n\nfunction pathExists(file: string): boolean {\n try {\n fs.statSync(file)\n return true\n } catch {\n return false\n }\n}\n\nconst PROJECT_MARKERS = [\n \".git\",\n \"package.json\",\n \"opencode.json\",\n \"opencode.jsonc\",\n \"pyproject.toml\",\n \"Cargo.toml\",\n \"go.mod\",\n]\n\n/** True when `dir` looks like a real project (used to pick the config scope). */\nexport function isProjectDir(dir: string): boolean {\n return PROJECT_MARKERS.some((marker) => pathExists(path.join(dir, marker)))\n}\n\nexport interface JsoncResult {\n value?: unknown\n /** The first parse problem and its line, when the text is not valid JSONC. */\n error?: string\n}\n\n/** Parse JSON that may contain comments and trailing commas. */\nexport function parseJsonc(text: string): JsoncResult {\n const errors: ParseError[] = []\n const value: unknown = parse(text, errors, { allowTrailingComma: true })\n const first = errors[0]\n if (first) return { error: `${printParseErrorCode(first.error)} at line ${lineAt(text, first.offset)}` }\n return { value }\n}\n\nfunction lineAt(text: string, offset: number): number {\n return text.slice(0, offset).split(\"\\n\").length\n}\n\nexport type JsonFile<T> = { status: \"absent\" } | { status: \"ok\"; value: T } | { status: \"invalid\"; error: string }\n\nfunction readText(file: string): string | undefined {\n try {\n // Strip a UTF-8 byte order mark: some Windows editors add one.\n return fs.readFileSync(file, \"utf8\").replace(/^/, \"\")\n } catch {\n return undefined\n }\n}\n\n/** Read a JSON(C) file. A missing or empty file is \"absent\"; a broken one is \"invalid\". */\nexport function readJsonFile<T = unknown>(file: string): JsonFile<T> {\n const text = readText(file)\n if (text === undefined || text.trim() === \"\") return { status: \"absent\" }\n const parsed = parseJsonc(text)\n if (parsed.error !== undefined) return { status: \"invalid\", error: parsed.error }\n return { status: \"ok\", value: parsed.value as T }\n}\n\n/** The parsed value of a JSON(C) file, or undefined when it is missing or broken. */\nexport function readJson<T = unknown>(file: string): T | undefined {\n const result = readJsonFile<T>(file)\n return result.status === \"ok\" ? result.value : undefined\n}\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n/** Write through a temp file and a rename, so a crash never leaves half a file. */\nexport function writeTextAtomic(file: string, text: string): void {\n ensureDir(path.dirname(file))\n const temp = `${file}.${process.pid}.${Date.now()}.tmp`\n fs.writeFileSync(temp, text, \"utf8\")\n try {\n fs.renameSync(temp, file)\n } catch {\n // Windows can refuse the rename while another process has the file open.\n fs.writeFileSync(file, text, \"utf8\")\n fs.rmSync(temp, { force: true })\n }\n}\n\nexport function writeJson(file: string, value: unknown): void {\n writeTextAtomic(file, JSON.stringify(value, null, 2) + \"\\n\")\n}\n\n/** jsonc-parser throws when asked to remove a key whose parent is missing. */\nfunction hasPath(text: string, keyPath: string[]): boolean {\n const tree = parseTree(text)\n return tree !== undefined && findNodeAtLocation(tree, keyPath) !== undefined\n}\n\nexport interface JsonEdit {\n path: string[]\n /** `undefined` removes the key. */\n value: unknown\n}\n\n/**\n * Change some keys of a JSON(C) file and keep everything else, including\n * comments and formatting. Throws when the file is not a valid JSON object,\n * so a broken file is never replaced.\n */\nexport function editJsonFile(file: string, edits: JsonEdit[], initialText = \"{}\\n\"): { created: boolean } {\n const current = readJsonFile(file)\n if (current.status === \"invalid\") {\n throw new Error(`${file} has a JSON error (${current.error}). Fix the file and run the command again. The file was not changed.`)\n }\n if (current.status === \"ok\" && !isPlainObject(current.value)) {\n throw new Error(`${file} does not contain a JSON object. The file was not changed.`)\n }\n\n const created = !fileExists(file)\n let text = current.status === \"ok\" ? (readText(file) ?? initialText) : initialText\n const formattingOptions = {\n insertSpaces: !/^\\t/m.test(text),\n tabSize: 2,\n eol: text.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\",\n }\n for (const edit of edits) {\n if (edit.value === undefined && !hasPath(text, edit.path)) continue\n text = applyEdits(text, modify(text, edit.path, edit.value, { formattingOptions }))\n }\n writeTextAtomic(file, text)\n return { created }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport function createScanner(text, ignoreTrivia = false) {\n const len = text.length;\n let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */;\n function scanHexDigits(count, exact) {\n let digits = 0;\n let value = 0;\n while (digits < count || !exact) {\n let ch = text.charCodeAt(pos);\n if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) {\n value = value * 16 + ch - 48 /* CharacterCodes._0 */;\n }\n else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) {\n value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10;\n }\n else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) {\n value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10;\n }\n else {\n break;\n }\n pos++;\n digits++;\n }\n if (digits < count) {\n value = -1;\n }\n return value;\n }\n function setPosition(newPosition) {\n pos = newPosition;\n value = '';\n tokenOffset = 0;\n token = 16 /* SyntaxKind.Unknown */;\n scanError = 0 /* ScanError.None */;\n }\n function scanNumber() {\n let start = pos;\n if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) {\n pos++;\n }\n else {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) {\n pos++;\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n return text.substring(start, pos);\n }\n }\n let end = pos;\n if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) {\n pos++;\n if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) {\n pos++;\n }\n if (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n while (pos < text.length && isDigit(text.charCodeAt(pos))) {\n pos++;\n }\n end = pos;\n }\n else {\n scanError = 3 /* ScanError.UnexpectedEndOfNumber */;\n }\n }\n return text.substring(start, end);\n }\n function scanString() {\n let result = '', start = pos;\n while (true) {\n if (pos >= len) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch = text.charCodeAt(pos);\n if (ch === 34 /* CharacterCodes.doubleQuote */) {\n result += text.substring(start, pos);\n pos++;\n break;\n }\n if (ch === 92 /* CharacterCodes.backslash */) {\n result += text.substring(start, pos);\n pos++;\n if (pos >= len) {\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n const ch2 = text.charCodeAt(pos++);\n switch (ch2) {\n case 34 /* CharacterCodes.doubleQuote */:\n result += '\\\"';\n break;\n case 92 /* CharacterCodes.backslash */:\n result += '\\\\';\n break;\n case 47 /* CharacterCodes.slash */:\n result += '/';\n break;\n case 98 /* CharacterCodes.b */:\n result += '\\b';\n break;\n case 102 /* CharacterCodes.f */:\n result += '\\f';\n break;\n case 110 /* CharacterCodes.n */:\n result += '\\n';\n break;\n case 114 /* CharacterCodes.r */:\n result += '\\r';\n break;\n case 116 /* CharacterCodes.t */:\n result += '\\t';\n break;\n case 117 /* CharacterCodes.u */:\n const ch3 = scanHexDigits(4, true);\n if (ch3 >= 0) {\n result += String.fromCharCode(ch3);\n }\n else {\n scanError = 4 /* ScanError.InvalidUnicode */;\n }\n break;\n default:\n scanError = 5 /* ScanError.InvalidEscapeCharacter */;\n }\n start = pos;\n continue;\n }\n if (ch >= 0 && ch <= 0x1f) {\n if (isLineBreak(ch)) {\n result += text.substring(start, pos);\n scanError = 2 /* ScanError.UnexpectedEndOfString */;\n break;\n }\n else {\n scanError = 6 /* ScanError.InvalidCharacter */;\n // mark as error but continue with string\n }\n }\n pos++;\n }\n return result;\n }\n function scanNext() {\n value = '';\n scanError = 0 /* ScanError.None */;\n tokenOffset = pos;\n lineStartOffset = lineNumber;\n prevTokenLineStartOffset = tokenLineStartOffset;\n if (pos >= len) {\n // at the end\n tokenOffset = len;\n return token = 17 /* SyntaxKind.EOF */;\n }\n let code = text.charCodeAt(pos);\n // trivia: whitespace\n if (isWhiteSpace(code)) {\n do {\n pos++;\n value += String.fromCharCode(code);\n code = text.charCodeAt(pos);\n } while (isWhiteSpace(code));\n return token = 15 /* SyntaxKind.Trivia */;\n }\n // trivia: newlines\n if (isLineBreak(code)) {\n pos++;\n value += String.fromCharCode(code);\n if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n value += '\\n';\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n return token = 14 /* SyntaxKind.LineBreakTrivia */;\n }\n switch (code) {\n // tokens: []{}:,\n case 123 /* CharacterCodes.openBrace */:\n pos++;\n return token = 1 /* SyntaxKind.OpenBraceToken */;\n case 125 /* CharacterCodes.closeBrace */:\n pos++;\n return token = 2 /* SyntaxKind.CloseBraceToken */;\n case 91 /* CharacterCodes.openBracket */:\n pos++;\n return token = 3 /* SyntaxKind.OpenBracketToken */;\n case 93 /* CharacterCodes.closeBracket */:\n pos++;\n return token = 4 /* SyntaxKind.CloseBracketToken */;\n case 58 /* CharacterCodes.colon */:\n pos++;\n return token = 6 /* SyntaxKind.ColonToken */;\n case 44 /* CharacterCodes.comma */:\n pos++;\n return token = 5 /* SyntaxKind.CommaToken */;\n // strings\n case 34 /* CharacterCodes.doubleQuote */:\n pos++;\n value = scanString();\n return token = 10 /* SyntaxKind.StringLiteral */;\n // comments\n case 47 /* CharacterCodes.slash */:\n const start = pos - 1;\n // Single-line comment\n if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n while (pos < len) {\n if (isLineBreak(text.charCodeAt(pos))) {\n break;\n }\n pos++;\n }\n value = text.substring(start, pos);\n return token = 12 /* SyntaxKind.LineCommentTrivia */;\n }\n // Multi-line comment\n if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) {\n pos += 2;\n const safeLength = len - 1; // For lookahead.\n let commentClosed = false;\n while (pos < safeLength) {\n const ch = text.charCodeAt(pos);\n if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) {\n pos += 2;\n commentClosed = true;\n break;\n }\n pos++;\n if (isLineBreak(ch)) {\n if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) {\n pos++;\n }\n lineNumber++;\n tokenLineStartOffset = pos;\n }\n }\n if (!commentClosed) {\n pos++;\n scanError = 1 /* ScanError.UnexpectedEndOfComment */;\n }\n value = text.substring(start, pos);\n return token = 13 /* SyntaxKind.BlockCommentTrivia */;\n }\n // just a single slash\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n // numbers\n case 45 /* CharacterCodes.minus */:\n value += String.fromCharCode(code);\n pos++;\n if (pos === len || !isDigit(text.charCodeAt(pos))) {\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // found a minus, followed by a number so\n // we fall through to proceed with scanning\n // numbers\n case 48 /* CharacterCodes._0 */:\n case 49 /* CharacterCodes._1 */:\n case 50 /* CharacterCodes._2 */:\n case 51 /* CharacterCodes._3 */:\n case 52 /* CharacterCodes._4 */:\n case 53 /* CharacterCodes._5 */:\n case 54 /* CharacterCodes._6 */:\n case 55 /* CharacterCodes._7 */:\n case 56 /* CharacterCodes._8 */:\n case 57 /* CharacterCodes._9 */:\n value += scanNumber();\n return token = 11 /* SyntaxKind.NumericLiteral */;\n // literals and unknown symbols\n default:\n // is a literal? Read the full word.\n while (pos < len && isUnknownContentCharacter(code)) {\n pos++;\n code = text.charCodeAt(pos);\n }\n if (tokenOffset !== pos) {\n value = text.substring(tokenOffset, pos);\n // keywords: true, false, null\n switch (value) {\n case 'true': return token = 8 /* SyntaxKind.TrueKeyword */;\n case 'false': return token = 9 /* SyntaxKind.FalseKeyword */;\n case 'null': return token = 7 /* SyntaxKind.NullKeyword */;\n }\n return token = 16 /* SyntaxKind.Unknown */;\n }\n // some\n value += String.fromCharCode(code);\n pos++;\n return token = 16 /* SyntaxKind.Unknown */;\n }\n }\n function isUnknownContentCharacter(code) {\n if (isWhiteSpace(code) || isLineBreak(code)) {\n return false;\n }\n switch (code) {\n case 125 /* CharacterCodes.closeBrace */:\n case 93 /* CharacterCodes.closeBracket */:\n case 123 /* CharacterCodes.openBrace */:\n case 91 /* CharacterCodes.openBracket */:\n case 34 /* CharacterCodes.doubleQuote */:\n case 58 /* CharacterCodes.colon */:\n case 44 /* CharacterCodes.comma */:\n case 47 /* CharacterCodes.slash */:\n return false;\n }\n return true;\n }\n function scanNextNonTrivia() {\n let result;\n do {\n result = scanNext();\n } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */);\n return result;\n }\n return {\n setPosition: setPosition,\n getPosition: () => pos,\n scan: ignoreTrivia ? scanNextNonTrivia : scanNext,\n getToken: () => token,\n getTokenValue: () => value,\n getTokenOffset: () => tokenOffset,\n getTokenLength: () => pos - tokenOffset,\n getTokenStartLine: () => lineStartOffset,\n getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,\n getTokenError: () => scanError,\n };\n}\nfunction isWhiteSpace(ch) {\n return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;\n}\nfunction isLineBreak(ch) {\n return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;\n}\nfunction isDigit(ch) {\n return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;\n}\nvar CharacterCodes;\n(function (CharacterCodes) {\n CharacterCodes[CharacterCodes[\"lineFeed\"] = 10] = \"lineFeed\";\n CharacterCodes[CharacterCodes[\"carriageReturn\"] = 13] = \"carriageReturn\";\n CharacterCodes[CharacterCodes[\"space\"] = 32] = \"space\";\n CharacterCodes[CharacterCodes[\"_0\"] = 48] = \"_0\";\n CharacterCodes[CharacterCodes[\"_1\"] = 49] = \"_1\";\n CharacterCodes[CharacterCodes[\"_2\"] = 50] = \"_2\";\n CharacterCodes[CharacterCodes[\"_3\"] = 51] = \"_3\";\n CharacterCodes[CharacterCodes[\"_4\"] = 52] = \"_4\";\n CharacterCodes[CharacterCodes[\"_5\"] = 53] = \"_5\";\n CharacterCodes[CharacterCodes[\"_6\"] = 54] = \"_6\";\n CharacterCodes[CharacterCodes[\"_7\"] = 55] = \"_7\";\n CharacterCodes[CharacterCodes[\"_8\"] = 56] = \"_8\";\n CharacterCodes[CharacterCodes[\"_9\"] = 57] = \"_9\";\n CharacterCodes[CharacterCodes[\"a\"] = 97] = \"a\";\n CharacterCodes[CharacterCodes[\"b\"] = 98] = \"b\";\n CharacterCodes[CharacterCodes[\"c\"] = 99] = \"c\";\n CharacterCodes[CharacterCodes[\"d\"] = 100] = \"d\";\n CharacterCodes[CharacterCodes[\"e\"] = 101] = \"e\";\n CharacterCodes[CharacterCodes[\"f\"] = 102] = \"f\";\n CharacterCodes[CharacterCodes[\"g\"] = 103] = \"g\";\n CharacterCodes[CharacterCodes[\"h\"] = 104] = \"h\";\n CharacterCodes[CharacterCodes[\"i\"] = 105] = \"i\";\n CharacterCodes[CharacterCodes[\"j\"] = 106] = \"j\";\n CharacterCodes[CharacterCodes[\"k\"] = 107] = \"k\";\n CharacterCodes[CharacterCodes[\"l\"] = 108] = \"l\";\n CharacterCodes[CharacterCodes[\"m\"] = 109] = \"m\";\n CharacterCodes[CharacterCodes[\"n\"] = 110] = \"n\";\n CharacterCodes[CharacterCodes[\"o\"] = 111] = \"o\";\n CharacterCodes[CharacterCodes[\"p\"] = 112] = \"p\";\n CharacterCodes[CharacterCodes[\"q\"] = 113] = \"q\";\n CharacterCodes[CharacterCodes[\"r\"] = 114] = \"r\";\n CharacterCodes[CharacterCodes[\"s\"] = 115] = \"s\";\n CharacterCodes[CharacterCodes[\"t\"] = 116] = \"t\";\n CharacterCodes[CharacterCodes[\"u\"] = 117] = \"u\";\n CharacterCodes[CharacterCodes[\"v\"] = 118] = \"v\";\n CharacterCodes[CharacterCodes[\"w\"] = 119] = \"w\";\n CharacterCodes[CharacterCodes[\"x\"] = 120] = \"x\";\n CharacterCodes[CharacterCodes[\"y\"] = 121] = \"y\";\n CharacterCodes[CharacterCodes[\"z\"] = 122] = \"z\";\n CharacterCodes[CharacterCodes[\"A\"] = 65] = \"A\";\n CharacterCodes[CharacterCodes[\"B\"] = 66] = \"B\";\n CharacterCodes[CharacterCodes[\"C\"] = 67] = \"C\";\n CharacterCodes[CharacterCodes[\"D\"] = 68] = \"D\";\n CharacterCodes[CharacterCodes[\"E\"] = 69] = \"E\";\n CharacterCodes[CharacterCodes[\"F\"] = 70] = \"F\";\n CharacterCodes[CharacterCodes[\"G\"] = 71] = \"G\";\n CharacterCodes[CharacterCodes[\"H\"] = 72] = \"H\";\n CharacterCodes[CharacterCodes[\"I\"] = 73] = \"I\";\n CharacterCodes[CharacterCodes[\"J\"] = 74] = \"J\";\n CharacterCodes[CharacterCodes[\"K\"] = 75] = \"K\";\n CharacterCodes[CharacterCodes[\"L\"] = 76] = \"L\";\n CharacterCodes[CharacterCodes[\"M\"] = 77] = \"M\";\n CharacterCodes[CharacterCodes[\"N\"] = 78] = \"N\";\n CharacterCodes[CharacterCodes[\"O\"] = 79] = \"O\";\n CharacterCodes[CharacterCodes[\"P\"] = 80] = \"P\";\n CharacterCodes[CharacterCodes[\"Q\"] = 81] = \"Q\";\n CharacterCodes[CharacterCodes[\"R\"] = 82] = \"R\";\n CharacterCodes[CharacterCodes[\"S\"] = 83] = \"S\";\n CharacterCodes[CharacterCodes[\"T\"] = 84] = \"T\";\n CharacterCodes[CharacterCodes[\"U\"] = 85] = \"U\";\n CharacterCodes[CharacterCodes[\"V\"] = 86] = \"V\";\n CharacterCodes[CharacterCodes[\"W\"] = 87] = \"W\";\n CharacterCodes[CharacterCodes[\"X\"] = 88] = \"X\";\n CharacterCodes[CharacterCodes[\"Y\"] = 89] = \"Y\";\n CharacterCodes[CharacterCodes[\"Z\"] = 90] = \"Z\";\n CharacterCodes[CharacterCodes[\"asterisk\"] = 42] = \"asterisk\";\n CharacterCodes[CharacterCodes[\"backslash\"] = 92] = \"backslash\";\n CharacterCodes[CharacterCodes[\"closeBrace\"] = 125] = \"closeBrace\";\n CharacterCodes[CharacterCodes[\"closeBracket\"] = 93] = \"closeBracket\";\n CharacterCodes[CharacterCodes[\"colon\"] = 58] = \"colon\";\n CharacterCodes[CharacterCodes[\"comma\"] = 44] = \"comma\";\n CharacterCodes[CharacterCodes[\"dot\"] = 46] = \"dot\";\n CharacterCodes[CharacterCodes[\"doubleQuote\"] = 34] = \"doubleQuote\";\n CharacterCodes[CharacterCodes[\"minus\"] = 45] = \"minus\";\n CharacterCodes[CharacterCodes[\"openBrace\"] = 123] = \"openBrace\";\n CharacterCodes[CharacterCodes[\"openBracket\"] = 91] = \"openBracket\";\n CharacterCodes[CharacterCodes[\"plus\"] = 43] = \"plus\";\n CharacterCodes[CharacterCodes[\"slash\"] = 47] = \"slash\";\n CharacterCodes[CharacterCodes[\"formFeed\"] = 12] = \"formFeed\";\n CharacterCodes[CharacterCodes[\"tab\"] = 9] = \"tab\";\n})(CharacterCodes || (CharacterCodes = {}));\n","export const cachedSpaces = new Array(20).fill(0).map((_, index) => {\n return ' '.repeat(index);\n});\nconst maxCachedValues = 200;\nexport const cachedBreakLinesWithSpaces = {\n ' ': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + ' '.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + ' '.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + ' '.repeat(index);\n }),\n },\n '\\t': {\n '\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\n' + '\\t'.repeat(index);\n }),\n '\\r': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r' + '\\t'.repeat(index);\n }),\n '\\r\\n': new Array(maxCachedValues).fill(0).map((_, index) => {\n return '\\r\\n' + '\\t'.repeat(index);\n }),\n }\n};\nexport const supportedEols = ['\\n', '\\r', '\\r\\n'];\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nimport { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';\nexport function format(documentText, range, options) {\n let initialIndentLevel;\n let formatText;\n let formatTextStart;\n let rangeStart;\n let rangeEnd;\n if (range) {\n rangeStart = range.offset;\n rangeEnd = rangeStart + range.length;\n formatTextStart = rangeStart;\n while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) {\n formatTextStart--;\n }\n let endOffset = rangeEnd;\n while (endOffset < documentText.length && !isEOL(documentText, endOffset)) {\n endOffset++;\n }\n formatText = documentText.substring(formatTextStart, endOffset);\n initialIndentLevel = computeIndentLevel(formatText, options);\n }\n else {\n formatText = documentText;\n initialIndentLevel = 0;\n formatTextStart = 0;\n rangeStart = 0;\n rangeEnd = documentText.length;\n }\n const eol = getEOL(options, documentText);\n const eolFastPathSupported = supportedEols.includes(eol);\n let numberLineBreaks = 0;\n let indentLevel = 0;\n let indentValue;\n if (options.insertSpaces) {\n indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4);\n }\n else {\n indentValue = '\\t';\n }\n const indentType = indentValue === '\\t' ? '\\t' : ' ';\n let scanner = createScanner(formatText, false);\n let hasError = false;\n function newLinesAndIndent() {\n if (numberLineBreaks > 1) {\n return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel);\n if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) {\n return eol + repeat(indentValue, initialIndentLevel + indentLevel);\n }\n if (amountOfSpaces <= 0) {\n return eol;\n }\n return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces];\n }\n function scanNext() {\n let token = scanner.scan();\n numberLineBreaks = 0;\n while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) {\n if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) {\n numberLineBreaks += 1;\n }\n else if (token === 14 /* SyntaxKind.LineBreakTrivia */) {\n numberLineBreaks = 1;\n }\n token = scanner.scan();\n }\n hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */;\n return token;\n }\n const editOperations = [];\n function addEdit(text, startOffset, endOffset) {\n if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) {\n editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text });\n }\n }\n let firstToken = scanNext();\n if (options.keepLines && numberLineBreaks > 0) {\n addEdit(repeat(eol, numberLineBreaks), 0, 0);\n }\n if (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenStart = scanner.getTokenOffset() + formatTextStart;\n let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces\n ? cachedSpaces[indentValue.length * initialIndentLevel]\n : repeat(indentValue, initialIndentLevel);\n addEdit(initialIndent, formatTextStart, firstTokenStart);\n }\n while (firstToken !== 17 /* SyntaxKind.EOF */) {\n let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n let secondToken = scanNext();\n let replaceContent = '';\n let needsLineBreak = false;\n while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n let commentTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart);\n firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart;\n needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */;\n replaceContent = needsLineBreak ? newLinesAndIndent() : '';\n secondToken = scanNext();\n }\n if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) {\n if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) {\n if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n indentLevel--;\n }\n ;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) {\n replaceContent = newLinesAndIndent();\n }\n else if (options.keepLines) {\n replaceContent = cachedSpaces[1];\n }\n }\n else {\n switch (firstToken) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n case 1 /* SyntaxKind.OpenBraceToken */:\n indentLevel++;\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 5 /* SyntaxKind.CommaToken */:\n if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 12 /* SyntaxKind.LineCommentTrivia */:\n replaceContent = newLinesAndIndent();\n break;\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 6 /* SyntaxKind.ColonToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (!needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n break;\n case 10 /* SyntaxKind.StringLiteral */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) {\n replaceContent = '';\n }\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n case 8 /* SyntaxKind.TrueKeyword */:\n case 9 /* SyntaxKind.FalseKeyword */:\n case 11 /* SyntaxKind.NumericLiteral */:\n case 2 /* SyntaxKind.CloseBraceToken */:\n case 4 /* SyntaxKind.CloseBracketToken */:\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) {\n replaceContent = cachedSpaces[1];\n }\n else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) {\n hasError = true;\n }\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n hasError = true;\n break;\n }\n if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) {\n replaceContent = newLinesAndIndent();\n }\n }\n if (secondToken === 17 /* SyntaxKind.EOF */) {\n if (options.keepLines && numberLineBreaks > 0) {\n replaceContent = newLinesAndIndent();\n }\n else {\n replaceContent = options.insertFinalNewline ? eol : '';\n }\n }\n const secondTokenStart = scanner.getTokenOffset() + formatTextStart;\n addEdit(replaceContent, firstTokenEnd, secondTokenStart);\n firstToken = secondToken;\n }\n return editOperations;\n}\nfunction repeat(s, count) {\n let result = '';\n for (let i = 0; i < count; i++) {\n result += s;\n }\n return result;\n}\nfunction computeIndentLevel(content, options) {\n let i = 0;\n let nChars = 0;\n const tabSize = options.tabSize || 4;\n while (i < content.length) {\n let ch = content.charAt(i);\n if (ch === cachedSpaces[1]) {\n nChars++;\n }\n else if (ch === '\\t') {\n nChars += tabSize;\n }\n else {\n break;\n }\n i++;\n }\n return Math.floor(nChars / tabSize);\n}\nfunction getEOL(options, text) {\n for (let i = 0; i < text.length; i++) {\n const ch = text.charAt(i);\n if (ch === '\\r') {\n if (i + 1 < text.length && text.charAt(i + 1) === '\\n') {\n return '\\r\\n';\n }\n return '\\r';\n }\n else if (ch === '\\n') {\n return '\\n';\n }\n }\n return (options && options.eol) || '\\n';\n}\nexport function isEOL(text, offset) {\n return '\\r\\n'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { createScanner } from './scanner';\nvar ParseOptions;\n(function (ParseOptions) {\n ParseOptions.DEFAULT = {\n allowTrailingComma: false\n };\n})(ParseOptions || (ParseOptions = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport function getLocation(text, position) {\n const segments = []; // strings or numbers\n const earlyReturnException = new Object();\n let previousNode = undefined;\n const previousNodeInst = {\n value: {},\n offset: 0,\n length: 0,\n type: 'object',\n parent: undefined\n };\n let isAtPropertyKey = false;\n function setPreviousNode(value, offset, length, type) {\n previousNodeInst.value = value;\n previousNodeInst.offset = offset;\n previousNodeInst.length = length;\n previousNodeInst.type = type;\n previousNodeInst.colonOffset = undefined;\n previousNode = previousNodeInst;\n }\n try {\n visit(text, {\n onObjectBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n isAtPropertyKey = position > offset;\n segments.push(''); // push a placeholder (will be replaced)\n },\n onObjectProperty: (name, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(name, offset, length, 'property');\n segments[segments.length - 1] = name;\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onObjectEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onArrayBegin: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.push(0);\n },\n onArrayEnd: (offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n previousNode = undefined;\n segments.pop();\n },\n onLiteralValue: (value, offset, length) => {\n if (position < offset) {\n throw earlyReturnException;\n }\n setPreviousNode(value, offset, length, getNodeType(value));\n if (position <= offset + length) {\n throw earlyReturnException;\n }\n },\n onSeparator: (sep, offset, length) => {\n if (position <= offset) {\n throw earlyReturnException;\n }\n if (sep === ':' && previousNode && previousNode.type === 'property') {\n previousNode.colonOffset = offset;\n isAtPropertyKey = false;\n previousNode = undefined;\n }\n else if (sep === ',') {\n const last = segments[segments.length - 1];\n if (typeof last === 'number') {\n segments[segments.length - 1] = last + 1;\n }\n else {\n isAtPropertyKey = true;\n segments[segments.length - 1] = '';\n }\n previousNode = undefined;\n }\n }\n });\n }\n catch (e) {\n if (e !== earlyReturnException) {\n throw e;\n }\n }\n return {\n path: segments,\n previousNode,\n isAtPropertyKey,\n matches: (pattern) => {\n let k = 0;\n for (let i = 0; k < pattern.length && i < segments.length; i++) {\n if (pattern[k] === segments[i] || pattern[k] === '*') {\n k++;\n }\n else if (pattern[k] !== '**') {\n return false;\n }\n }\n return k === pattern.length;\n }\n };\n}\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore always check the errors list to find out if the input was valid.\n */\nexport function parse(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentProperty = null;\n let currentParent = [];\n const previousParents = [];\n function onValue(value) {\n if (Array.isArray(currentParent)) {\n currentParent.push(value);\n }\n else if (currentProperty !== null) {\n currentParent[currentProperty] = value;\n }\n }\n const visitor = {\n onObjectBegin: () => {\n const object = {};\n onValue(object);\n previousParents.push(currentParent);\n currentParent = object;\n currentProperty = null;\n },\n onObjectProperty: (name) => {\n currentProperty = name;\n },\n onObjectEnd: () => {\n currentParent = previousParents.pop();\n },\n onArrayBegin: () => {\n const array = [];\n onValue(array);\n previousParents.push(currentParent);\n currentParent = array;\n currentProperty = null;\n },\n onArrayEnd: () => {\n currentParent = previousParents.pop();\n },\n onLiteralValue: onValue,\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n return currentParent[0];\n}\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport function parseTree(text, errors = [], options = ParseOptions.DEFAULT) {\n let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root\n function ensurePropertyComplete(endOffset) {\n if (currentParent.type === 'property') {\n currentParent.length = endOffset - currentParent.offset;\n currentParent = currentParent.parent;\n }\n }\n function onValue(valueNode) {\n currentParent.children.push(valueNode);\n return valueNode;\n }\n const visitor = {\n onObjectBegin: (offset) => {\n currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] });\n },\n onObjectProperty: (name, offset, length) => {\n currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] });\n currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent });\n },\n onObjectEnd: (offset, length) => {\n ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onArrayBegin: (offset, length) => {\n currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] });\n },\n onArrayEnd: (offset, length) => {\n currentParent.length = offset + length - currentParent.offset;\n currentParent = currentParent.parent;\n ensurePropertyComplete(offset + length);\n },\n onLiteralValue: (value, offset, length) => {\n onValue({ type: getNodeType(value), offset, length, parent: currentParent, value });\n ensurePropertyComplete(offset + length);\n },\n onSeparator: (sep, offset, length) => {\n if (currentParent.type === 'property') {\n if (sep === ':') {\n currentParent.colonOffset = offset;\n }\n else if (sep === ',') {\n ensurePropertyComplete(offset);\n }\n }\n },\n onError: (error, offset, length) => {\n errors.push({ error, offset, length });\n }\n };\n visit(text, visitor, options);\n const result = currentParent.children[0];\n if (result) {\n delete result.parent;\n }\n return result;\n}\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport function findNodeAtLocation(root, path) {\n if (!root) {\n return undefined;\n }\n let node = root;\n for (let segment of path) {\n if (typeof segment === 'string') {\n if (node.type !== 'object' || !Array.isArray(node.children)) {\n return undefined;\n }\n let found = false;\n for (const propertyNode of node.children) {\n if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) {\n node = propertyNode.children[1];\n found = true;\n break;\n }\n }\n if (!found) {\n return undefined;\n }\n }\n else {\n const index = segment;\n if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) {\n return undefined;\n }\n node = node.children[index];\n }\n }\n return node;\n}\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport function getNodePath(node) {\n if (!node.parent || !node.parent.children) {\n return [];\n }\n const path = getNodePath(node.parent);\n if (node.parent.type === 'property') {\n const key = node.parent.children[0].value;\n path.push(key);\n }\n else if (node.parent.type === 'array') {\n const index = node.parent.children.indexOf(node);\n if (index !== -1) {\n path.push(index);\n }\n }\n return path;\n}\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport function getNodeValue(node) {\n switch (node.type) {\n case 'array':\n return node.children.map(getNodeValue);\n case 'object':\n const obj = Object.create(null);\n for (let prop of node.children) {\n const valueNode = prop.children[1];\n if (valueNode) {\n obj[prop.children[0].value] = getNodeValue(valueNode);\n }\n }\n return obj;\n case 'null':\n case 'string':\n case 'number':\n case 'boolean':\n return node.value;\n default:\n return undefined;\n }\n}\nexport function contains(node, offset, includeRightBound = false) {\n return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));\n}\n/**\n * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport function findNodeAtOffset(node, offset, includeRightBound = false) {\n if (contains(node, offset, includeRightBound)) {\n const children = node.children;\n if (Array.isArray(children)) {\n for (let i = 0; i < children.length && children[i].offset <= offset; i++) {\n const item = findNodeAtOffset(children[i], offset, includeRightBound);\n if (item) {\n return item;\n }\n }\n }\n return node;\n }\n return undefined;\n}\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport function visit(text, visitor, options = ParseOptions.DEFAULT) {\n const _scanner = createScanner(text, false);\n // Important: Only pass copies of this to visitor functions to prevent accidental modification, and\n // to not affect visitor functions which stored a reference to a previous JSONPath\n const _jsonPath = [];\n // Depth of onXXXBegin() callbacks suppressed. onXXXEnd() decrements this if it isn't 0 already.\n // Callbacks are only called when this value is 0.\n let suppressedCallbacks = 0;\n function toNoArgVisit(visitFunction) {\n return visitFunction ? () => suppressedCallbacks === 0 && visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisit(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;\n }\n function toOneArgVisitWithPath(visitFunction) {\n return visitFunction ? (arg) => suppressedCallbacks === 0 && visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;\n }\n function toBeginVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks++;\n }\n else {\n let cbReturn = visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice());\n if (cbReturn === false) {\n suppressedCallbacks = 1;\n }\n }\n }\n : () => true;\n }\n function toEndVisit(visitFunction) {\n return visitFunction ?\n () => {\n if (suppressedCallbacks > 0) {\n suppressedCallbacks--;\n }\n if (suppressedCallbacks === 0) {\n visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter());\n }\n }\n : () => true;\n }\n const onObjectBegin = toBeginVisit(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toEndVisit(visitor.onObjectEnd), onArrayBegin = toBeginVisit(visitor.onArrayBegin), onArrayEnd = toEndVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);\n const disallowComments = options && options.disallowComments;\n const allowTrailingComma = options && options.allowTrailingComma;\n function scanNext() {\n while (true) {\n const token = _scanner.scan();\n switch (_scanner.getTokenError()) {\n case 4 /* ScanError.InvalidUnicode */:\n handleError(14 /* ParseErrorCode.InvalidUnicode */);\n break;\n case 5 /* ScanError.InvalidEscapeCharacter */:\n handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */);\n break;\n case 3 /* ScanError.UnexpectedEndOfNumber */:\n handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */);\n break;\n case 1 /* ScanError.UnexpectedEndOfComment */:\n if (!disallowComments) {\n handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */);\n }\n break;\n case 2 /* ScanError.UnexpectedEndOfString */:\n handleError(12 /* ParseErrorCode.UnexpectedEndOfString */);\n break;\n case 6 /* ScanError.InvalidCharacter */:\n handleError(16 /* ParseErrorCode.InvalidCharacter */);\n break;\n }\n switch (token) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n if (disallowComments) {\n handleError(10 /* ParseErrorCode.InvalidCommentToken */);\n }\n else {\n onComment();\n }\n break;\n case 16 /* SyntaxKind.Unknown */:\n handleError(1 /* ParseErrorCode.InvalidSymbol */);\n break;\n case 15 /* SyntaxKind.Trivia */:\n case 14 /* SyntaxKind.LineBreakTrivia */:\n break;\n default:\n return token;\n }\n }\n }\n function handleError(error, skipUntilAfter = [], skipUntil = []) {\n onError(error);\n if (skipUntilAfter.length + skipUntil.length > 0) {\n let token = _scanner.getToken();\n while (token !== 17 /* SyntaxKind.EOF */) {\n if (skipUntilAfter.indexOf(token) !== -1) {\n scanNext();\n break;\n }\n else if (skipUntil.indexOf(token) !== -1) {\n break;\n }\n token = scanNext();\n }\n }\n }\n function parseString(isValue) {\n const value = _scanner.getTokenValue();\n if (isValue) {\n onLiteralValue(value);\n }\n else {\n onObjectProperty(value);\n // add property name afterwards\n _jsonPath.push(value);\n }\n scanNext();\n return true;\n }\n function parseLiteral() {\n switch (_scanner.getToken()) {\n case 11 /* SyntaxKind.NumericLiteral */:\n const tokenValue = _scanner.getTokenValue();\n let value = Number(tokenValue);\n if (isNaN(value)) {\n handleError(2 /* ParseErrorCode.InvalidNumberFormat */);\n value = 0;\n }\n onLiteralValue(value);\n break;\n case 7 /* SyntaxKind.NullKeyword */:\n onLiteralValue(null);\n break;\n case 8 /* SyntaxKind.TrueKeyword */:\n onLiteralValue(true);\n break;\n case 9 /* SyntaxKind.FalseKeyword */:\n onLiteralValue(false);\n break;\n default:\n return false;\n }\n scanNext();\n return true;\n }\n function parseProperty() {\n if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) {\n handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n return false;\n }\n parseString(false);\n if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) {\n onSeparator(':');\n scanNext(); // consume colon\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n }\n else {\n handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n _jsonPath.pop(); // remove processed property name\n return true;\n }\n function parseObject() {\n onObjectBegin();\n scanNext(); // consume open brace\n let needsComma = false;\n while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (!parseProperty()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onObjectEnd();\n if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) {\n handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []);\n }\n else {\n scanNext(); // consume close brace\n }\n return true;\n }\n function parseArray() {\n onArrayBegin();\n scanNext(); // consume open bracket\n let isFirstElement = true;\n let needsComma = false;\n while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) {\n if (!needsComma) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n }\n onSeparator(',');\n scanNext(); // consume comma\n if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) {\n break;\n }\n }\n else if (needsComma) {\n handleError(6 /* ParseErrorCode.CommaExpected */, [], []);\n }\n if (isFirstElement) {\n _jsonPath.push(0);\n isFirstElement = false;\n }\n else {\n _jsonPath[_jsonPath.length - 1]++;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]);\n }\n needsComma = true;\n }\n onArrayEnd();\n if (!isFirstElement) {\n _jsonPath.pop(); // remove array index\n }\n if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) {\n handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []);\n }\n else {\n scanNext(); // consume close bracket\n }\n return true;\n }\n function parseValue() {\n switch (_scanner.getToken()) {\n case 3 /* SyntaxKind.OpenBracketToken */:\n return parseArray();\n case 1 /* SyntaxKind.OpenBraceToken */:\n return parseObject();\n case 10 /* SyntaxKind.StringLiteral */:\n return parseString(true);\n default:\n return parseLiteral();\n }\n }\n scanNext();\n if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) {\n if (options.allowEmptyContent) {\n return true;\n }\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (!parseValue()) {\n handleError(4 /* ParseErrorCode.ValueExpected */, [], []);\n return false;\n }\n if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) {\n handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []);\n }\n return true;\n}\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport function stripComments(text, replaceCh) {\n let _scanner = createScanner(text), parts = [], kind, offset = 0, pos;\n do {\n pos = _scanner.getPosition();\n kind = _scanner.scan();\n switch (kind) {\n case 12 /* SyntaxKind.LineCommentTrivia */:\n case 13 /* SyntaxKind.BlockCommentTrivia */:\n case 17 /* SyntaxKind.EOF */:\n if (offset !== pos) {\n parts.push(text.substring(offset, pos));\n }\n if (replaceCh !== undefined) {\n parts.push(_scanner.getTokenValue().replace(/[^\\r\\n]/g, replaceCh));\n }\n offset = _scanner.getPosition();\n break;\n }\n } while (kind !== 17 /* SyntaxKind.EOF */);\n return parts.join('');\n}\nexport function getNodeType(value) {\n switch (typeof value) {\n case 'boolean': return 'boolean';\n case 'number': return 'number';\n case 'string': return 'string';\n case 'object': {\n if (!value) {\n return 'null';\n }\n else if (Array.isArray(value)) {\n return 'array';\n }\n return 'object';\n }\n default: return 'null';\n }\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport { format, isEOL } from './format';\nimport { parseTree, findNodeAtLocation } from './parser';\nexport function removeProperty(text, path, options) {\n return setProperty(text, path, void 0, options);\n}\nexport function setProperty(text, originalPath, value, options) {\n const path = originalPath.slice();\n const errors = [];\n const root = parseTree(text, errors);\n let parent = void 0;\n let lastSegment = void 0;\n while (path.length > 0) {\n lastSegment = path.pop();\n parent = findNodeAtLocation(root, path);\n if (parent === void 0 && value !== void 0) {\n if (typeof lastSegment === 'string') {\n value = { [lastSegment]: value };\n }\n else {\n value = [value];\n }\n }\n else {\n break;\n }\n }\n if (!parent) {\n // empty document\n if (value === void 0) { // delete\n throw new Error('Can not delete in empty document');\n }\n return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options);\n }\n else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) {\n const existing = findNodeAtLocation(parent, [lastSegment]);\n if (existing !== void 0) {\n if (value === void 0) { // delete\n if (!existing.parent) {\n throw new Error('Malformed AST');\n }\n const propertyIndex = parent.children.indexOf(existing.parent);\n let removeBegin;\n let removeEnd = existing.parent.offset + existing.parent.length;\n if (propertyIndex > 0) {\n // remove the comma of the previous node\n let previous = parent.children[propertyIndex - 1];\n removeBegin = previous.offset + previous.length;\n }\n else {\n removeBegin = parent.offset + 1;\n if (parent.children.length > 1) {\n // remove the comma of the next node\n let next = parent.children[1];\n removeEnd = next.offset;\n }\n }\n return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options);\n }\n else {\n // set value of existing property\n return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options);\n }\n }\n else {\n if (value === void 0) { // delete\n return []; // property does not exist, nothing to do\n }\n const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`;\n const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length;\n let edit;\n if (index > 0) {\n let previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n else if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' };\n }\n return withFormatting(text, edit, options);\n }\n }\n else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) {\n const insertIndex = lastSegment;\n if (insertIndex === -1) {\n // Insert\n const newProperty = `${JSON.stringify(value)}`;\n let edit;\n if (parent.children.length === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: newProperty };\n }\n else {\n const previous = parent.children[parent.children.length - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else if (value === void 0 && parent.children.length >= 0) {\n // Removal\n const removalIndex = lastSegment;\n const toRemove = parent.children[removalIndex];\n let edit;\n if (parent.children.length === 1) {\n // only item\n edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' };\n }\n else if (parent.children.length - 1 === removalIndex) {\n // last item\n let previous = parent.children[removalIndex - 1];\n let offset = previous.offset + previous.length;\n let parentEndOffset = parent.offset + parent.length;\n edit = { offset, length: parentEndOffset - 2 - offset, content: '' };\n }\n else {\n edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' };\n }\n return withFormatting(text, edit, options);\n }\n else if (value !== void 0) {\n let edit;\n const newProperty = `${JSON.stringify(value)}`;\n if (!options.isArrayInsertion && parent.children.length > lastSegment) {\n const toModify = parent.children[lastSegment];\n edit = { offset: toModify.offset, length: toModify.length, content: newProperty };\n }\n else if (parent.children.length === 0 || lastSegment === 0) {\n edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' };\n }\n else {\n const index = lastSegment > parent.children.length ? parent.children.length : lastSegment;\n const previous = parent.children[index - 1];\n edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty };\n }\n return withFormatting(text, edit, options);\n }\n else {\n throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`);\n }\n }\n else {\n throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`);\n }\n}\nfunction withFormatting(text, edit, options) {\n if (!options.formattingOptions) {\n return [edit];\n }\n // apply the edit\n let newText = applyEdit(text, edit);\n // format the new text\n let begin = edit.offset;\n let end = edit.offset + edit.content.length;\n if (edit.length === 0 || edit.content.length === 0) { // insert or remove\n while (begin > 0 && !isEOL(newText, begin - 1)) {\n begin--;\n }\n while (end < newText.length && !isEOL(newText, end)) {\n end++;\n }\n }\n const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false });\n // apply the formatting edits and track the begin and end offsets of the changes\n for (let i = edits.length - 1; i >= 0; i--) {\n const edit = edits[i];\n newText = applyEdit(newText, edit);\n begin = Math.min(begin, edit.offset);\n end = Math.max(end, edit.offset + edit.length);\n end += edit.content.length - edit.length;\n }\n // create a single edit with all changes\n const editLength = text.length - (newText.length - end) - begin;\n return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];\n}\nexport function applyEdit(text, edit) {\n return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);\n}\nexport function isWS(text, offset) {\n return '\\r\\n \\t'.indexOf(text.charAt(offset)) !== -1;\n}\n","/*---------------------------------------------------------------------------------------------\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License. See License.txt in the project root for license information.\n *--------------------------------------------------------------------------------------------*/\n'use strict';\nimport * as formatter from './impl/format';\nimport * as edit from './impl/edit';\nimport * as scanner from './impl/scanner';\nimport * as parser from './impl/parser';\n/**\n * Creates a JSON scanner on the given text.\n * If ignoreTrivia is set, whitespaces or comments are ignored.\n */\nexport const createScanner = scanner.createScanner;\nexport var ScanError;\n(function (ScanError) {\n ScanError[ScanError[\"None\"] = 0] = \"None\";\n ScanError[ScanError[\"UnexpectedEndOfComment\"] = 1] = \"UnexpectedEndOfComment\";\n ScanError[ScanError[\"UnexpectedEndOfString\"] = 2] = \"UnexpectedEndOfString\";\n ScanError[ScanError[\"UnexpectedEndOfNumber\"] = 3] = \"UnexpectedEndOfNumber\";\n ScanError[ScanError[\"InvalidUnicode\"] = 4] = \"InvalidUnicode\";\n ScanError[ScanError[\"InvalidEscapeCharacter\"] = 5] = \"InvalidEscapeCharacter\";\n ScanError[ScanError[\"InvalidCharacter\"] = 6] = \"InvalidCharacter\";\n})(ScanError || (ScanError = {}));\nexport var SyntaxKind;\n(function (SyntaxKind) {\n SyntaxKind[SyntaxKind[\"OpenBraceToken\"] = 1] = \"OpenBraceToken\";\n SyntaxKind[SyntaxKind[\"CloseBraceToken\"] = 2] = \"CloseBraceToken\";\n SyntaxKind[SyntaxKind[\"OpenBracketToken\"] = 3] = \"OpenBracketToken\";\n SyntaxKind[SyntaxKind[\"CloseBracketToken\"] = 4] = \"CloseBracketToken\";\n SyntaxKind[SyntaxKind[\"CommaToken\"] = 5] = \"CommaToken\";\n SyntaxKind[SyntaxKind[\"ColonToken\"] = 6] = \"ColonToken\";\n SyntaxKind[SyntaxKind[\"NullKeyword\"] = 7] = \"NullKeyword\";\n SyntaxKind[SyntaxKind[\"TrueKeyword\"] = 8] = \"TrueKeyword\";\n SyntaxKind[SyntaxKind[\"FalseKeyword\"] = 9] = \"FalseKeyword\";\n SyntaxKind[SyntaxKind[\"StringLiteral\"] = 10] = \"StringLiteral\";\n SyntaxKind[SyntaxKind[\"NumericLiteral\"] = 11] = \"NumericLiteral\";\n SyntaxKind[SyntaxKind[\"LineCommentTrivia\"] = 12] = \"LineCommentTrivia\";\n SyntaxKind[SyntaxKind[\"BlockCommentTrivia\"] = 13] = \"BlockCommentTrivia\";\n SyntaxKind[SyntaxKind[\"LineBreakTrivia\"] = 14] = \"LineBreakTrivia\";\n SyntaxKind[SyntaxKind[\"Trivia\"] = 15] = \"Trivia\";\n SyntaxKind[SyntaxKind[\"Unknown\"] = 16] = \"Unknown\";\n SyntaxKind[SyntaxKind[\"EOF\"] = 17] = \"EOF\";\n})(SyntaxKind || (SyntaxKind = {}));\n/**\n * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.\n */\nexport const getLocation = parser.getLocation;\n/**\n * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n * Therefore, always check the errors list to find out if the input was valid.\n */\nexport const parse = parser.parse;\n/**\n * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.\n */\nexport const parseTree = parser.parseTree;\n/**\n * Finds the node at the given path in a JSON DOM.\n */\nexport const findNodeAtLocation = parser.findNodeAtLocation;\n/**\n * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset.\n */\nexport const findNodeAtOffset = parser.findNodeAtOffset;\n/**\n * Gets the JSON path of the given JSON DOM node\n */\nexport const getNodePath = parser.getNodePath;\n/**\n * Evaluates the JavaScript object of the given JSON DOM node\n */\nexport const getNodeValue = parser.getNodeValue;\n/**\n * Parses the given text and invokes the visitor functions for each object, array and literal reached.\n */\nexport const visit = parser.visit;\n/**\n * Takes JSON with JavaScript-style comments and remove\n * them. Optionally replaces every none-newline character\n * of comments with a replaceCharacter\n */\nexport const stripComments = parser.stripComments;\nexport var ParseErrorCode;\n(function (ParseErrorCode) {\n ParseErrorCode[ParseErrorCode[\"InvalidSymbol\"] = 1] = \"InvalidSymbol\";\n ParseErrorCode[ParseErrorCode[\"InvalidNumberFormat\"] = 2] = \"InvalidNumberFormat\";\n ParseErrorCode[ParseErrorCode[\"PropertyNameExpected\"] = 3] = \"PropertyNameExpected\";\n ParseErrorCode[ParseErrorCode[\"ValueExpected\"] = 4] = \"ValueExpected\";\n ParseErrorCode[ParseErrorCode[\"ColonExpected\"] = 5] = \"ColonExpected\";\n ParseErrorCode[ParseErrorCode[\"CommaExpected\"] = 6] = \"CommaExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBraceExpected\"] = 7] = \"CloseBraceExpected\";\n ParseErrorCode[ParseErrorCode[\"CloseBracketExpected\"] = 8] = \"CloseBracketExpected\";\n ParseErrorCode[ParseErrorCode[\"EndOfFileExpected\"] = 9] = \"EndOfFileExpected\";\n ParseErrorCode[ParseErrorCode[\"InvalidCommentToken\"] = 10] = \"InvalidCommentToken\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfComment\"] = 11] = \"UnexpectedEndOfComment\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfString\"] = 12] = \"UnexpectedEndOfString\";\n ParseErrorCode[ParseErrorCode[\"UnexpectedEndOfNumber\"] = 13] = \"UnexpectedEndOfNumber\";\n ParseErrorCode[ParseErrorCode[\"InvalidUnicode\"] = 14] = \"InvalidUnicode\";\n ParseErrorCode[ParseErrorCode[\"InvalidEscapeCharacter\"] = 15] = \"InvalidEscapeCharacter\";\n ParseErrorCode[ParseErrorCode[\"InvalidCharacter\"] = 16] = \"InvalidCharacter\";\n})(ParseErrorCode || (ParseErrorCode = {}));\nexport function printParseErrorCode(code) {\n switch (code) {\n case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol';\n case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat';\n case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected';\n case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected';\n case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected';\n case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected';\n case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected';\n case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected';\n case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected';\n case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken';\n case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment';\n case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString';\n case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber';\n case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode';\n case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter';\n case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter';\n }\n return '<unknown ParseErrorCode>';\n}\n/**\n * Computes the edit operations needed to format a JSON document.\n *\n * @param documentText The input text\n * @param range The range to format or `undefined` to format the full content\n * @param options The formatting options\n * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function format(documentText, range, options) {\n return formatter.format(documentText, range, options);\n}\n/**\n * Computes the edit operations needed to modify a value in the JSON document.\n *\n * @param documentText The input text\n * @param path The path of the value to change. The path represents either to the document root, a property or an array item.\n * If the path points to an non-existing property or item, it will be created.\n * @param value The new value for the specified property or item. If the value is undefined,\n * the property or item will be removed.\n * @param options Options\n * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}.\n * To apply the edit operations to the input, use {@linkcode applyEdits}.\n */\nexport function modify(text, path, value, options) {\n return edit.setProperty(text, path, value, options);\n}\n/**\n * Applies edits to an input string.\n * @param text The input text\n * @param edits Edit operations following the format described in {@linkcode EditResult}.\n * @returns The text with the applied edits.\n * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}.\n */\nexport function applyEdits(text, edits) {\n let sortedEdits = edits.slice(0).sort((a, b) => {\n const diff = a.offset - b.offset;\n if (diff === 0) {\n return a.length - b.length;\n }\n return diff;\n });\n let lastModifiedOffset = text.length;\n for (let i = sortedEdits.length - 1; i >= 0; i--) {\n let e = sortedEdits[i];\n if (e.offset + e.length <= lastModifiedOffset) {\n text = edit.applyEdit(text, e);\n }\n else {\n throw new Error('Overlapping edit');\n }\n lastModifiedOffset = e.offset;\n }\n return text;\n}\n","import type {\n CatalogModel,\n Metric,\n MetricScores,\n ModelClass,\n PlanProfile,\n ResolvedConfig,\n RoleSpec,\n ScoreSource,\n ScoreTable,\n ScoredModel,\n} from \"./types.js\"\n\n/** Share of the monthly allowance that one 5-hour window may use. */\nexport const FIVE_HOUR_SHARE = 0.2\n/** Share of the monthly allowance that one 7-day window may use. */\nexport const WEEK_SHARE = 0.5\n\n/** Score bonus for a free model in a role that prefers free models. */\nconst FREE_ROLE_BONUS = 6\n\nconst DEFAULT_UNVETTED_PENALTY = 8\n\nexport function modelClass(model: CatalogModel): ModelClass {\n if (model.free) return \"free\"\n if (model.providerID === \"opencode-go\") return \"subscription\"\n return \"paid\"\n}\n\nexport interface FeedScores {\n /** keyed by lowercased family or `provider/model`. */\n byFamily: Map<string, MetricScores>\n byId: Map<string, MetricScores>\n}\n\nexport function emptyFeedScores(): FeedScores {\n return { byFamily: new Map(), byId: new Map() }\n}\n\nfunction clamp(value: number, min = 0, max = 100): number {\n return Math.max(min, Math.min(max, value))\n}\n\n/** Resolve one metric: score table/user override, then feed, then name pattern, then default. */\nfunction resolveMetric(\n model: CatalogModel,\n table: ScoreTable,\n feeds: FeedScores,\n metric: Metric,\n): { value: number; source: ScoreSource } {\n const override = table.models[model.id]?.[metric]\n if (override !== undefined) return { value: clamp(override), source: \"override\" }\n\n const fromId = feeds.byId.get(model.id.toLowerCase())?.[metric]\n if (fromId !== undefined) return { value: clamp(fromId), source: \"feed\" }\n const fromFamily = model.family ? feeds.byFamily.get(model.family.toLowerCase())?.[metric] : undefined\n if (fromFamily !== undefined) return { value: clamp(fromFamily), source: \"feed\" }\n\n const id = model.modelID.toLowerCase()\n const pattern = table.heuristics.patterns.find((p) => id.includes(p.match.toLowerCase()))\n if (pattern) return { value: clamp(pattern[metric]), source: \"heuristic\" }\n\n const fallback = metric === \"intelligence\" ? table.heuristics.defaultIntelligence : table.heuristics.defaultSpeed\n return { value: clamp(fallback), source: \"default\" }\n}\n\nexport function resolveIntelligence(model: CatalogModel, table: ScoreTable, feeds: FeedScores) {\n return resolveMetric(model, table, feeds, \"intelligence\")\n}\n\nexport function resolveSpeed(model: CatalogModel, table: ScoreTable, feeds: FeedScores) {\n return resolveMetric(model, table, feeds, \"speed\")\n}\n\n/** Blended USD cost per 1M tokens for a typical coding turn. */\nexport function blendedCost(model: CatalogModel, cfg: ResolvedConfig): number {\n const { input, output, cacheRead } = cfg.blend\n const c = model.cost\n return c.input * input + c.output * output + (c.cacheRead ?? 0) * cacheRead\n}\n\n/** Monthly USD allowance of a model on a plan; null means unlimited or unknown. */\nexport function monthlyCapFor(modelId: string, table: ScoreTable, plan: PlanProfile): number | null {\n if (plan === \"free\") return null\n const entry = table.monthlyCaps[modelId]\n if (!entry) return null\n return plan === \"go-plus\" ? entry.goPlus : entry.go\n}\n\nfunction logScale(value: number, min: number, max: number): number {\n const lo = Math.log10(Math.max(min, 1e-6))\n const hi = Math.log10(Math.max(max, min * 1.001))\n const v = Math.log10(Math.max(value, 1e-6))\n return clamp(((v - lo) / (hi - lo)) * 100)\n}\n\nexport interface EnduranceResult {\n score: number\n source: ScoreSource\n tokensPer5h: number | null\n monthlyCapUSD: number | null\n blendedCost: number\n}\n\nexport function resolveEndurance(model: CatalogModel, table: ScoreTable, cfg: ResolvedConfig): EnduranceResult {\n const bc = blendedCost(model, cfg)\n\n if (model.free) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: null, blendedCost: bc }\n }\n\n const cap = monthlyCapFor(model.id, table, cfg.plan)\n if (cap === null) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: null, blendedCost: bc }\n }\n\n if (bc <= 0) {\n return { score: 100, source: \"cap\", tokensPer5h: null, monthlyCapUSD: cap, blendedCost: bc }\n }\n\n const tokensPer5h = (cap * FIVE_HOUR_SHARE) / bc\n const score = logScale(tokensPer5h, cfg.enduranceScale.minTokensPer5h, cfg.enduranceScale.maxTokensPer5h)\n return { score, source: \"cap\", tokensPer5h, monthlyCapUSD: cap, blendedCost: bc }\n}\n\nexport function scoreModel(\n model: CatalogModel,\n role: RoleSpec,\n table: ScoreTable,\n cfg: ResolvedConfig,\n feeds: FeedScores,\n): ScoredModel {\n const intel = resolveIntelligence(model, table, feeds)\n const speed = resolveSpeed(model, table, feeds)\n const end = resolveEndurance(model, table, cfg)\n\n const w = role.weights\n let score = w.intelligence * intel.value + w.speed * speed.value + w.endurance * end.score\n\n // Plan/class preference: on paid plans keep the subscription models ahead of\n // the $0 overflow; for free-preferring roles do the opposite.\n const klass = modelClass(model)\n if (role.preferFree) {\n if (klass === \"free\") score += FREE_ROLE_BONUS\n } else {\n score += table.classPreference?.[cfg.plan]?.[klass] ?? 0\n }\n // Models we have never vetted score lower than ones with an explicit entry.\n if (table.models[model.id] === undefined) score -= table.heuristics.unvettedPenalty ?? DEFAULT_UNVETTED_PENALTY\n score = clamp(score)\n\n return {\n model,\n intelligence: intel.value,\n speed: speed.value,\n endurance: end.score,\n score,\n intelligenceSource: intel.source,\n speedSource: speed.source,\n enduranceSource: end.source,\n blendedCost: end.blendedCost,\n tokensPer5h: end.tokensPer5h,\n monthlyCapUSD: end.monthlyCapUSD,\n }\n}\n","import type { MetricScores, ResolvedConfig } from \"./types.js\"\nimport { emptyFeedScores, type FeedScores } from \"./scoring.js\"\n\nexport interface FeedRecord extends MetricScores {\n id?: string\n family?: string\n}\n\nexport interface FeedPayload {\n version?: number\n updated?: string\n models?: FeedRecord[]\n}\n\n/**\n * Optionally enrich intelligence/speed from a public benchmark feed.\n * Any failure returns the empty map: the router falls back to the committed\n * table and heuristics, so `/refresh-routing` never breaks on a bad network.\n */\nexport async function loadFeedScores(cfg: ResolvedConfig): Promise<{ feeds: FeedScores; note: string | null }> {\n const feeds = emptyFeedScores()\n if (!cfg.feeds?.enabled || !cfg.feeds.url) return { feeds, note: null }\n\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), cfg.feeds.timeoutMs ?? 5000)\n try {\n const res = await fetch(cfg.feeds.url, { signal: controller.signal })\n if (!res.ok) return { feeds, note: `feed ${cfg.feeds.url} returned ${res.status}; using table + heuristics` }\n const payload = (await res.json()) as FeedPayload\n const records = Array.isArray(payload.models) ? payload.models : []\n\n for (const rec of records) {\n if (!rec) continue\n const value: MetricScores = {}\n if (typeof rec.intelligence === \"number\") value.intelligence = rec.intelligence\n if (typeof rec.speed === \"number\") value.speed = rec.speed\n if (value.intelligence === undefined && value.speed === undefined) continue\n if (rec.id) feeds.byId.set(rec.id.toLowerCase(), value)\n if (rec.family) feeds.byFamily.set(rec.family.toLowerCase(), value)\n }\n return { feeds, note: `feed ${cfg.feeds.url}: ${records.length} records` }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { feeds, note: `feed unavailable (${message}); using table + heuristics` }\n } finally {\n clearTimeout(timeout)\n }\n}\n","import { isPlan, isRoleName, PLAN_PROFILES } from \"./types.js\"\nimport type { CatalogModel, PlanProfile, ResolvedConfig, RouterUserConfig } from \"./types.js\"\nimport { globalRouterConfigFile, isPlainObject, projectRouterConfigFile, readJsonFile } from \"./paths.js\"\n\nconst DEFAULT_SOFT_THRESHOLD = 0.85\nconst DEFAULT_CHAIN_DEPTH = 4\n\nexport interface LoadedUserConfig {\n config: RouterUserConfig\n /** Problems found in the files, shown in the scorecard notes. */\n notes: string[]\n}\n\n/** Read the global and project router.config.json. A bad file or value becomes a note, never a crash. */\nexport function loadUserConfig(projectDir?: string): LoadedUserConfig {\n const notes: string[] = []\n const global = readUserConfigFile(globalRouterConfigFile(), notes)\n const project = projectDir ? readUserConfigFile(projectRouterConfigFile(projectDir), notes) : {}\n return { config: mergeUserConfig(global, project), notes }\n}\n\nfunction readUserConfigFile(file: string, notes: string[]): RouterUserConfig {\n const result = readJsonFile(file)\n if (result.status === \"absent\") return {}\n if (result.status === \"invalid\") {\n notes.push(`${file} has a JSON error (${result.error}); it was ignored.`)\n return {}\n }\n if (!isPlainObject(result.value)) {\n notes.push(`${file} does not contain a JSON object; it was ignored.`)\n return {}\n }\n return sanitizeUserConfig(result.value, file, notes)\n}\n\n/** Remove values the router cannot use, with a note for each one. */\nfunction sanitizeUserConfig(raw: Record<string, unknown>, file: string, notes: string[]): RouterUserConfig {\n const config = { ...raw }\n const drop = (key: string, rule: string) => {\n notes.push(`${file}: \"${key}\" ${rule}, not ${JSON.stringify(config[key])}; it was ignored.`)\n delete config[key]\n }\n\n if (config.plan !== undefined && !isPlan(config.plan)) drop(\"plan\", `must be one of ${PLAN_PROFILES.join(\" | \")}`)\n const depth = config.chainDepth\n if (depth !== undefined && !(typeof depth === \"number\" && Number.isInteger(depth) && depth >= 1)) {\n drop(\"chainDepth\", \"must be a whole number of 1 or more\")\n }\n const threshold = config.softThreshold\n if (threshold !== undefined && !(typeof threshold === \"number\" && threshold > 0 && threshold <= 1)) {\n drop(\"softThreshold\", \"must be a number above 0 and at most 1\")\n }\n if (config.updateCheck !== undefined && typeof config.updateCheck !== \"boolean\") drop(\"updateCheck\", \"must be true or false\")\n for (const key of [\"denyModels\", \"allowModels\"]) {\n const list = config[key]\n if (list !== undefined && !(Array.isArray(list) && list.every((item) => typeof item === \"string\"))) {\n drop(key, \"must be a list of model IDs\")\n }\n }\n for (const key of [\"roles\", \"weights\"]) {\n const perRole = config[key]\n if (perRole === undefined) continue\n if (!isPlainObject(perRole)) {\n drop(key, \"must be an object keyed by role\")\n continue\n }\n const known: Record<string, unknown> = {}\n for (const [role, value] of Object.entries(perRole)) {\n if (isRoleName(role)) known[role] = value\n else notes.push(`${file}: unknown role \"${role}\" in \"${key}\"; it was ignored.`)\n }\n config[key] = known\n }\n return config as RouterUserConfig\n}\n\n/** Merge two `key -> object` maps one level deep, so project values add to global ones. */\nfunction mergeByKey<K extends string, V extends object>(\n base: Partial<Record<K, V>> = {},\n override: Partial<Record<K, V>> = {},\n): Partial<Record<K, V>> {\n const out: Partial<Record<K, V>> = { ...base }\n for (const key of Object.keys(override) as K[]) {\n out[key] = { ...base[key], ...override[key] } as V\n }\n return out\n}\n\nexport function mergeUserConfig(base: RouterUserConfig, override: RouterUserConfig): RouterUserConfig {\n return {\n ...base,\n ...override,\n blend: { ...base.blend, ...override.blend },\n enduranceScale: { ...base.enduranceScale, ...override.enduranceScale },\n weights: mergeByKey(base.weights, override.weights),\n roles: mergeByKey(base.roles, override.roles),\n scores: mergeByKey(base.scores, override.scores),\n privacy: { ...base.privacy, ...override.privacy },\n feeds: { ...base.feeds, ...override.feeds },\n denyModels: override.denyModels ?? base.denyModels,\n allowModels: override.allowModels ?? base.allowModels,\n }\n}\n\n/** Detect the best-matching plan profile from the models actually available. */\nexport function detectPlan(catalog: CatalogModel[]): PlanProfile {\n const hasGo = catalog.some((m) => m.providerID === \"opencode-go\" && !m.free)\n if (hasGo) return \"go\"\n const hasFree = catalog.some((m) => m.free)\n if (hasFree) return \"free\"\n return \"go\"\n}\n\nexport function resolveConfig(user: RouterUserConfig, catalog: CatalogModel[], cliPlan?: PlanProfile): ResolvedConfig {\n const plan = cliPlan ?? user.plan ?? detectPlan(catalog)\n return {\n ...user,\n plan,\n chainDepth: user.chainDepth ?? DEFAULT_CHAIN_DEPTH,\n softThreshold: user.softThreshold ?? DEFAULT_SOFT_THRESHOLD,\n blend: {\n input: user.blend?.input ?? 0.75,\n output: user.blend?.output ?? 0.25,\n cacheRead: user.blend?.cacheRead ?? 0.1,\n },\n enduranceScale: {\n minTokensPer5h: user.enduranceScale?.minTokensPer5h ?? 0.25,\n maxTokensPer5h: user.enduranceScale?.maxTokensPer5h ?? 40,\n },\n denyModels: user.denyModels ?? [],\n allowModels: user.allowModels ?? [],\n privacy: { freeModelsOk: user.privacy?.freeModelsOk ?? true },\n }\n}\n","{\n \"$comment\": \"Committed default score table for opencode-router. Safe to edit; user config (router.config.json) overrides these values.\",\n \"version\": 1,\n \"updated\": \"2026-10-18\",\n \"roles\": {\n \"plan\": {\n \"weights\": { \"intelligence\": 0.65, \"speed\": 0.1, \"endurance\": 0.25 },\n \"variant\": \"high\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"build\": {\n \"weights\": { \"intelligence\": 0.4, \"speed\": 0.25, \"endurance\": 0.35 },\n \"variant\": \"medium\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"general\": {\n \"weights\": { \"intelligence\": 0.35, \"speed\": 0.25, \"endurance\": 0.4 },\n \"variant\": \"medium\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"diversifyFamily\": true\n },\n \"explore\": {\n \"weights\": { \"intelligence\": 0.15, \"speed\": 0.45, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 4,\n \"requires\": { \"toolCall\": true, \"minContext\": 128000 },\n \"preferFree\": true\n },\n \"small_model\": {\n \"weights\": { \"intelligence\": 0.05, \"speed\": 0.55, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 100000 },\n \"preferFree\": true\n },\n \"title\": {\n \"weights\": { \"intelligence\": 0.05, \"speed\": 0.55, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 100000 },\n \"preferFree\": true\n },\n \"summary\": {\n \"weights\": { \"intelligence\": 0.3, \"speed\": 0.3, \"endurance\": 0.4 },\n \"variant\": \"low\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 200000 },\n \"preferFree\": true\n },\n \"compaction\": {\n \"weights\": { \"intelligence\": 0.3, \"speed\": 0.2, \"endurance\": 0.5 },\n \"variant\": \"none\",\n \"chainDepth\": 3,\n \"requires\": { \"toolCall\": true, \"minContext\": 1000000 },\n \"preferFree\": true\n }\n },\n \"models\": {\n \"opencode-go/gemini-4-argon-contributor\": { \"intelligence\": 95, \"speed\": 25 },\n \"opencode-go/kimi-k3\": { \"intelligence\": 93, \"speed\": 20 },\n \"opencode-go/qwen3.8-max\": { \"intelligence\": 92, \"speed\": 35 },\n \"opencode-go/grok-4.7\": { \"intelligence\": 91, \"speed\": 40 },\n \"opencode-go/deepseek-v4-pro\": { \"intelligence\": 90, \"speed\": 30 },\n \"opencode-go/glm-5.3\": { \"intelligence\": 90, \"speed\": 45 },\n \"opencode-go/glm-5.2\": { \"intelligence\": 88, \"speed\": 45 },\n \"opencode-go/step-5-preview\": { \"intelligence\": 87, \"speed\": 40 },\n \"opencode-go/qwen3.7-plus\": { \"intelligence\": 86, \"speed\": 45 },\n \"opencode-go/kimi-k2.7-code\": { \"intelligence\": 85, \"speed\": 50 },\n \"opencode-go/gpt-6-luna\": { \"intelligence\": 85, \"speed\": 55 },\n \"opencode-go/gpt-5.6-luna\": { \"intelligence\": 84, \"speed\": 55 },\n \"opencode-go/minimax-m3\": { \"intelligence\": 84, \"speed\": 55 },\n \"opencode-go/hy4-preview\": { \"intelligence\": 82, \"speed\": 40 },\n \"opencode-go/qwen3.8-flash\": { \"intelligence\": 80, \"speed\": 70 },\n \"opencode-go/deepseek-v4.1-flash\": { \"intelligence\": 80, \"speed\": 65 },\n \"opencode-go/space-bunny\": { \"intelligence\": 79, \"speed\": 60 },\n \"opencode-go/glm-5.3-flash\": { \"intelligence\": 78, \"speed\": 72 },\n \"opencode-go/mimo-v2.6-pro\": { \"intelligence\": 78, \"speed\": 58 },\n \"opencode-go/muse-spark-1.3-contributor\": { \"intelligence\": 77, \"speed\": 62 },\n \"opencode-go/mimo-v2.5-pro\": { \"intelligence\": 76, \"speed\": 58 },\n \"opencode-go/longcat-2.0\": { \"intelligence\": 76, \"speed\": 55 },\n \"opencode-go/muse-spark-1.2-contributor\": { \"intelligence\": 75, \"speed\": 62 },\n \"opencode-go/longcat-2.5-preview-free\": { \"intelligence\": 75, \"speed\": 60 },\n \"opencode-go/hy3\": { \"intelligence\": 74, \"speed\": 60 },\n \"opencode-go/claude-haiku-5-5\": { \"intelligence\": 74, \"speed\": 78 },\n \"opencode-go/mimo-v2.6-flash\": { \"intelligence\": 73, \"speed\": 75 },\n \"opencode-go/mimo-v2.5\": { \"intelligence\": 72, \"speed\": 72 },\n \"opencode-go/beam-free\": { \"intelligence\": 72, \"speed\": 80 },\n\n \"opencode/deepseek-v4.1-flash-free\": { \"intelligence\": 80, \"speed\": 65 },\n \"opencode/space-bunny-free\": { \"intelligence\": 79, \"speed\": 60 },\n \"opencode/glm-5.3-flash-free\": { \"intelligence\": 78, \"speed\": 72 },\n \"opencode/longcat-2.5-preview-free\": { \"intelligence\": 75, \"speed\": 60 },\n \"opencode/nemotron-3-ultra-free\": { \"intelligence\": 74, \"speed\": 62 },\n \"opencode/mimo-v2.6-flash-free\": { \"intelligence\": 73, \"speed\": 75 },\n \"opencode/beam-free\": { \"intelligence\": 72, \"speed\": 80 },\n \"opencode/nemotron-3.5-super-vl-free\": { \"intelligence\": 72, \"speed\": 70 },\n \"opencode/nemotron-3.5-lightning-free\": { \"intelligence\": 68, \"speed\": 88 },\n \"opencode/big-pickle\": { \"intelligence\": 66, \"speed\": 70 }\n },\n \"heuristics\": {\n \"patterns\": [\n { \"match\": \"gemini-4-argon\", \"intelligence\": 95, \"speed\": 25 },\n { \"match\": \"kimi-k3\", \"intelligence\": 93, \"speed\": 20 },\n { \"match\": \"qwen3.8-max\", \"intelligence\": 92, \"speed\": 35 },\n { \"match\": \"opus\", \"intelligence\": 94, \"speed\": 30 },\n { \"match\": \"grok\", \"intelligence\": 91, \"speed\": 40 },\n { \"match\": \"deepseek-v4-pro\", \"intelligence\": 90, \"speed\": 30 },\n { \"match\": \"sonnet\", \"intelligence\": 88, \"speed\": 50 },\n { \"match\": \"step-5\", \"intelligence\": 87, \"speed\": 40 },\n { \"match\": \"gpt-6\", \"intelligence\": 85, \"speed\": 55 },\n { \"match\": \"kimi\", \"intelligence\": 85, \"speed\": 45 },\n { \"match\": \"gpt-5\", \"intelligence\": 84, \"speed\": 55 },\n { \"match\": \"minimax\", \"intelligence\": 84, \"speed\": 55 },\n { \"match\": \"hy4\", \"intelligence\": 82, \"speed\": 40 },\n { \"match\": \"claude\", \"intelligence\": 82, \"speed\": 60 },\n { \"match\": \"gpt\", \"intelligence\": 82, \"speed\": 55 },\n { \"match\": \"qwen\", \"intelligence\": 80, \"speed\": 55 },\n { \"match\": \"deepseek\", \"intelligence\": 80, \"speed\": 65 },\n { \"match\": \"glm\", \"intelligence\": 80, \"speed\": 55 },\n { \"match\": \"space-bunny\", \"intelligence\": 79, \"speed\": 60 },\n { \"match\": \"muse\", \"intelligence\": 77, \"speed\": 62 },\n { \"match\": \"longcat\", \"intelligence\": 76, \"speed\": 58 },\n { \"match\": \"hy3\", \"intelligence\": 74, \"speed\": 60 },\n { \"match\": \"haiku\", \"intelligence\": 74, \"speed\": 78 },\n { \"match\": \"mimo\", \"intelligence\": 74, \"speed\": 72 },\n { \"match\": \"nemotron\", \"intelligence\": 72, \"speed\": 75 },\n { \"match\": \"big-pickle\", \"intelligence\": 66, \"speed\": 70 },\n { \"match\": \"-max\", \"intelligence\": 90, \"speed\": 35 },\n { \"match\": \"-pro\", \"intelligence\": 88, \"speed\": 42 },\n { \"match\": \"-flash\", \"intelligence\": 78, \"speed\": 74 },\n { \"match\": \"-mini\", \"intelligence\": 74, \"speed\": 80 },\n { \"match\": \"-lite\", \"intelligence\": 70, \"speed\": 84 },\n { \"match\": \"-free\", \"intelligence\": 72, \"speed\": 70 },\n { \"match\": \"contributor\", \"intelligence\": 74, \"speed\": 62 }\n ],\n \"defaultIntelligence\": 60,\n \"defaultSpeed\": 60,\n \"unvettedPenalty\": 8\n },\n \"classPreference\": {\n \"go\": { \"subscription\": 0, \"paid\": -6, \"free\": -12 },\n \"go-plus\": { \"subscription\": 0, \"paid\": -6, \"free\": -12 },\n \"free\": { \"subscription\": 0, \"paid\": 0, \"free\": 0 }\n },\n \"monthlyCaps\": {\n \"opencode-go/longcat-2.5-preview-free\": { \"go\": null, \"goPlus\": null },\n \"opencode-go/beam-free\": { \"go\": null, \"goPlus\": null },\n \"opencode-go/deepseek-v4.1-flash\": { \"go\": 80, \"goPlus\": 160 },\n \"opencode-go/longcat-2.0\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/hy3\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/step-5-preview\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/gemini-4-argon-contributor\": { \"go\": 60, \"goPlus\": 240 },\n \"opencode-go/glm-5.3-flash\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/glm-5.2\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/kimi-k2.7-code\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/minimax-m3\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/qwen3.7-plus\": { \"go\": 60, \"goPlus\": 180 },\n \"opencode-go/mimo-v2.6-flash\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/mimo-v2.5\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/muse-spark-1.3-contributor\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/muse-spark-1.2-contributor\": { \"go\": 60, \"goPlus\": 120 },\n \"opencode-go/hy4-preview\": { \"go\": 30, \"goPlus\": 120 },\n \"opencode-go/space-bunny\": { \"go\": 30, \"goPlus\": 120 },\n \"opencode-go/qwen3.8-flash\": { \"go\": 30, \"goPlus\": 90 },\n \"opencode-go/glm-5.3\": { \"go\": 15, \"goPlus\": 120 },\n \"opencode-go/kimi-k3\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/mimo-v2.6-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/mimo-v2.5-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/qwen3.8-max\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/deepseek-v4-pro\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/grok-4.7\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/gpt-6-luna\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/gpt-5.6-luna\": { \"go\": 15, \"goPlus\": 60 },\n \"opencode-go/claude-haiku-5-5\": { \"go\": 15, \"goPlus\": 60 }\n }\n}\n","import bundled from \"../model-scores.json\" with { type: \"json\" }\nimport { ROLE_NAMES } from \"./types.js\"\nimport type { RoleSpec, RouterUserConfig, ScoreTable } from \"./types.js\"\n\nconst DEFAULT_TABLE: ScoreTable = bundled\n\n/** A fresh copy of the committed default table (model-scores.json, bundled at build time). */\nexport function loadDefaultTable(): ScoreTable {\n return structuredClone(DEFAULT_TABLE)\n}\n\nfunction mergeRole(base: RoleSpec, override: Partial<RoleSpec>): RoleSpec {\n return {\n ...base,\n ...override,\n weights: { ...base.weights, ...override.weights },\n requires: { ...base.requires, ...override.requires },\n }\n}\n\n/**\n * Build the effective score table: committed defaults, then user overrides from\n * router.config.json. A top-level `chainDepth` applies to every role, and a\n * per-role value wins over it. Roles the router does not know are ignored.\n */\nexport function resolveTable(user: RouterUserConfig): ScoreTable {\n const table = loadDefaultTable()\n\n for (const role of ROLE_NAMES) {\n let spec = table.roles[role]\n if (!spec) continue\n if (user.chainDepth !== undefined) spec = { ...spec, chainDepth: user.chainDepth }\n const override = user.roles?.[role]\n if (override) spec = mergeRole(spec, override)\n const weights = user.weights?.[role]\n if (weights) spec = { ...spec, weights: { ...spec.weights, ...weights } }\n table.roles[role] = spec\n }\n\n for (const [id, score] of Object.entries(user.scores ?? {})) {\n table.models[id] = { ...table.models[id], ...score }\n }\n\n return table\n}\n","import type { CatalogModel, PlanProfile, RankingEntry, ResolvedConfig, RoleName, RoleSpec, ScoreTable, ScoredModel } from \"./types.js\"\nimport { modelClass, scoreModel, type FeedScores } from \"./scoring.js\"\n\nexport function globToRegex(glob: string): RegExp {\n const escaped = glob.replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\").replace(/\\?/g, \".\")\n return new RegExp(`^${escaped}$`, \"i\")\n}\n\nexport function matchesAny(id: string, globs: string[]): boolean {\n return globs.some((g) => globToRegex(g).test(id))\n}\n\nfunction providerAllowed(model: CatalogModel, plan: PlanProfile): boolean {\n if (plan === \"free\") {\n // Without any subscription, only the OpenCode Zen `$0` tier is reachable.\n return model.providerID === \"opencode\" && model.free\n }\n if (plan === \"go\" || plan === \"go-plus\") {\n // OpenCode Go subscription models plus the $0 free tier from both providers.\n if (model.providerID === \"opencode-go\") return true\n if (model.providerID === \"opencode\") return model.free\n return false\n }\n return false\n}\n\nfunction requirementOk(model: CatalogModel, role: RoleSpec): boolean {\n const req = role.requires\n if (!req) return true\n if (req.toolCall && !model.toolCall) return false\n if (req.reasoning && !model.reasoning) return false\n if (req.minContext !== undefined && model.limit.context < req.minContext) return false\n if (req.minOutput !== undefined && model.limit.output < req.minOutput) return false\n if (req.inputModalities && req.inputModalities.length > 0) {\n const ok = req.inputModalities.every((m) => model.inputModalities.includes(m))\n if (!ok) return false\n }\n return true\n}\n\nexport function eligibleModels(\n catalog: CatalogModel[],\n role: RoleSpec,\n table: ScoreTable,\n cfg: ResolvedConfig,\n): CatalogModel[] {\n return catalog.filter((model) => {\n if (!providerAllowed(model, cfg.plan)) return false\n if (!requirementOk(model, role)) return false\n // On paid plans, a non-free Go model with no known allowance is treated as\n // unavailable (legacy/retired ids would otherwise look \"unlimited\").\n if ((cfg.plan === \"go\" || cfg.plan === \"go-plus\") && !model.free && !table.monthlyCaps[model.id]) return false\n if (cfg.denyModels.length > 0 && matchesAny(model.id, cfg.denyModels)) return false\n if (cfg.allowModels.length > 0 && !matchesAny(model.id, cfg.allowModels)) return false\n // Privacy: paid plans must not silently use data-collecting free models for real work.\n if (!cfg.privacy.freeModelsOk && model.free && !role.preferFree) return false\n return true\n })\n}\n\nexport function rankRole(\n catalog: CatalogModel[],\n roleName: RoleName,\n table: ScoreTable,\n cfg: ResolvedConfig,\n feeds: FeedScores,\n): RankingEntry[] {\n const role = table.roles[roleName]\n if (!role) return []\n\n const scored: ScoredModel[] = eligibleModels(catalog, role, table, cfg)\n .map((model) => scoreModel(model, role, table, cfg, feeds))\n .sort((a, b) => b.score - a.score || a.blendedCost - b.blendedCost)\n\n const depth = role.chainDepth ?? cfg.chainDepth\n const diversify = role.diversifyFamily ?? false\n\n const chosen: ScoredModel[] = []\n const seenFamilies = new Set<string>()\n\n for (const entry of scored) {\n if (chosen.length >= depth) break\n const family = (entry.model.family ?? entry.model.modelID).toLowerCase()\n if (diversify && seenFamilies.has(family) && chosen.length < depth) continue\n chosen.push(entry)\n seenFamilies.add(family)\n }\n // Backfill if diversification starved the chain.\n if (chosen.length < depth) {\n for (const entry of scored) {\n if (chosen.length >= depth) break\n if (chosen.includes(entry)) continue\n chosen.push(entry)\n }\n }\n // All Go subscription models share one usage allowance, so another\n // subscription model does not help when it runs out. End the chain with the\n // best free model (if the privacy setting allows one).\n if (cfg.plan !== \"free\" && !chosen.some((entry) => entry.model.free)) {\n const free = scored.find((entry) => entry.model.free)\n if (free) {\n if (chosen.length >= depth && chosen.length > 1) chosen.pop()\n chosen.push(free)\n }\n }\n\n return chosen.map((entry, index) => ({\n rank: index + 1,\n providerID: entry.model.providerID,\n modelID: entry.model.modelID,\n id: entry.model.id,\n variant: role.variant,\n score: round(entry.score),\n intelligence: round(entry.intelligence),\n speed: round(entry.speed),\n endurance: round(entry.endurance),\n tokensPer5h: entry.tokensPer5h === null ? null : round(entry.tokensPer5h, 3),\n monthlyCapUSD: entry.monthlyCapUSD,\n sources: {\n intelligence: entry.intelligenceSource,\n speed: entry.speedSource,\n endurance: entry.enduranceSource,\n },\n class: modelClass(entry.model),\n }))\n}\n\nfunction round(value: number, digits = 1): number {\n const f = Math.pow(10, digits)\n return Math.round(value * f) / f\n}\n","import { isAgentRole, PLAN_PROFILES, ROLE_NAMES } from \"./types.js\"\nimport type { CatalogModel, PlanProfile, RankingEntry, ResolvedConfig, RoleChains, RoleName, RoutingTable, ScoreTable } from \"./types.js\"\nimport { loadCatalog } from \"./catalog.js\"\nimport { loadFeedScores } from \"./feeds.js\"\nimport { loadUserConfig, resolveConfig } from \"./config.js\"\nimport { resolveTable } from \"./score-table.js\"\nimport { rankRole } from \"./rank.js\"\nimport { monthlyCapFor, type FeedScores } from \"./scoring.js\"\nimport { catalogCacheFile } from \"./paths.js\"\nimport type { LedgerStore } from \"./ledger.js\"\n\nexport interface BuildOptions {\n plan?: PlanProfile\n projectDir?: string\n catalogFile?: string\n catalog?: CatalogModel[]\n now?: Date\n feeds?: FeedScores\n notes?: string[]\n}\n\nexport interface BuildResult {\n table: RoutingTable\n cfg: ResolvedConfig\n scoreTable: ScoreTable\n catalog: CatalogModel[]\n}\n\nexport async function buildRoutingTable(opts: BuildOptions = {}): Promise<BuildResult> {\n const catalogFile = opts.catalogFile ?? catalogCacheFile()\n const catalog = opts.catalog ?? loadCatalog(catalogFile)\n const user = loadUserConfig(opts.projectDir)\n const notes: string[] = [...(opts.notes ?? []), ...user.notes]\n\n if (catalog.length === 0) {\n notes.push(`No models found in ${catalogFile}. Start OpenCode one time and sign in, then run this command again.`)\n }\n\n const cfg = resolveConfig(user.config, catalog, opts.plan)\n const scoreTable = resolveTable(user.config)\n\n let feeds = opts.feeds\n if (!feeds) {\n const loaded = await loadFeedScores(cfg)\n feeds = loaded.feeds\n if (loaded.note) notes.push(loaded.note)\n }\n\n const profiles: RoutingTable[\"profiles\"] = {}\n for (const plan of PLAN_PROFILES) {\n const planCfg: ResolvedConfig = { ...cfg, plan }\n const chains: RoleChains = {}\n for (const role of ROLE_NAMES) {\n chains[role] = rankRole(catalog, role, scoreTable, planCfg, feeds)\n }\n profiles[plan] = chains\n }\n\n const table: RoutingTable = {\n version: 1,\n createdAt: (opts.now ?? new Date()).toISOString(),\n plan: cfg.plan,\n active: profiles[cfg.plan] ?? {},\n profiles,\n notes,\n }\n\n return { table, cfg, scoreTable, catalog }\n}\n\n/** The model a role should use right now: the first usable model of its chain. */\nexport function pickForRole(\n table: RoutingTable,\n role: RoleName,\n isUsable: (entry: RankingEntry) => boolean,\n): RankingEntry | undefined {\n const chain = table.active[role]\n if (!chain || chain.length === 0) return undefined\n return chain.find(isUsable) ?? chain[0]\n}\n\n/**\n * Usable = the model is not in cooldown, and, for a Go subscription model, the\n * shared allowance is under the soft threshold.\n */\nexport function healthCheck(result: BuildResult, ledger: LedgerStore): (entry: RankingEntry) => boolean {\n const allowanceOk = ledger.allowanceAvailable(result.cfg.softThreshold)\n return (entry) => !ledger.inCooldown(entry.id) && (allowanceOk || entry.class !== \"subscription\")\n}\n\n/** True when the model's use counts toward the shared Go allowance. */\nexport function usesAllowance(result: BuildResult, modelId: string): boolean {\n const cap = monthlyCapFor(modelId, result.scoreTable, result.cfg.plan)\n return cap !== null && cap > 0\n}\n\n/** The part of the monthly Go allowance that `costUSD` on this model uses. */\nexport function allowanceShare(result: BuildResult, modelId: string, costUSD: number): number {\n const cap = monthlyCapFor(modelId, result.scoreTable, result.cfg.plan)\n return cap !== null && cap > 0 ? costUSD / cap : 0\n}\n\n/**\n * healthy = first model; failover = a later model, because an earlier one is in\n * cooldown; free-fallback = a free model, because the Go allowance is near its\n * limit; limited = no usable model.\n */\nexport type RoleState = \"healthy\" | \"failover\" | \"free-fallback\" | \"limited\" | \"none\"\n\nexport interface StatusRow {\n role: RoleName\n /** The model in use now; undefined when the role has no eligible model. */\n entry?: RankingEntry\n state: RoleState\n}\n\n/** The model each role uses now, after failover. */\nexport function statusRows(result: BuildResult, ledger: LedgerStore): StatusRow[] {\n const isUsable = healthCheck(result, ledger)\n const allowanceOk = ledger.allowanceAvailable(result.cfg.softThreshold)\n return ROLE_NAMES.map((role): StatusRow => {\n // Only the agent roles switch per message; the internal roles keep the first model.\n const entry = isAgentRole(role) ? pickForRole(result.table, role, isUsable) : result.table.active[role]?.[0]\n if (!entry) return { role, state: \"none\" }\n const first = result.table.active[role]?.[0]\n let state: RoleState = \"healthy\"\n if (!isUsable(entry)) state = \"limited\"\n else if (entry.rank > 1 && entry.class === \"free\" && first?.class === \"subscription\" && !allowanceOk) state = \"free-fallback\"\n else if (entry.rank > 1) state = \"failover\"\n return { role, entry, state }\n })\n}\n","import { ROLE_NAMES } from \"./types.js\"\nimport type { RankingEntry, RoutingTable } from \"./types.js\"\nimport type { StatusRow } from \"./engine.js\"\nimport type { AllowanceUsage } from \"./ledger.js\"\n\nfunction fmtTokens(value: number | null): string {\n if (value === null) return \"unlimited\"\n if (value >= 1) return `${value.toFixed(1)}M`\n return `${(value * 1000).toFixed(0)}K`\n}\n\nfunction fmtCap(value: number | null): string {\n return value === null ? \"inf\" : `$${value}`\n}\n\nfunction classTag(entry: RankingEntry): string {\n if (entry.class === \"free\") return \"free*\"\n if (entry.class === \"subscription\") return \"go\"\n return \"paid\"\n}\n\nexport function formatScorecard(table: RoutingTable, opts: { verbose?: boolean } = {}): string {\n const lines: string[] = []\n const when = table.createdAt.replace(\"T\", \" \").replace(/\\..*$/, \"\")\n lines.push(`## opencode-router scorecard`)\n lines.push(\"\")\n lines.push(`- Plan: **${table.plan}**`)\n lines.push(`- Updated: ${when} (UTC)`)\n lines.push(`- Legend: go = Go subscription, free* = $0 (data may be collected), paid = Zen pay-as-you-go`)\n if (table.plan !== \"free\") {\n lines.push(\n \"- All `go` models share one usage allowance. When it is near its limit, each agent uses the free model at the end of its list.\",\n )\n }\n lines.push(\"\")\n lines.push(\"| Role | # | Model | Var | Score | Intel | Speed | Endur | Tokens/5h | Cap/mo | Class |\")\n lines.push(\"| :-- | --: | :-- | :-- | --: | --: | --: | --: | --: | --: | :-- |\")\n\n for (const role of ROLE_NAMES) {\n const chain = table.active[role]\n if (!chain) continue\n if (chain.length === 0) {\n lines.push(`| ${role} | - | _no eligible model_ | | | | | | | | |`)\n continue\n }\n chain.forEach((entry, index) => {\n const roleCol = index === 0 ? role : \"\"\n const sources = opts.verbose\n ? ` (${entry.sources.intelligence}/${entry.sources.speed}/${entry.sources.endurance})`\n : \"\"\n lines.push(\n `| ${roleCol} | ${entry.rank} | \\`${entry.id}\\`${sources} | ${entry.variant ?? \"-\"} | ${entry.score} | ${entry.intelligence} | ${entry.speed} | ${entry.endurance} | ${fmtTokens(entry.tokensPer5h)} | ${fmtCap(entry.monthlyCapUSD)} | ${classTag(entry)} |`,\n )\n })\n }\n\n if (table.notes.length > 0) {\n lines.push(\"\")\n lines.push(\"**Notes**\")\n for (const note of table.notes) lines.push(`- ${note}`)\n }\n\n lines.push(\"\")\n lines.push(\n opts.verbose\n ? `_Sources (intel/speed/endur): override = committed/user table, feed = external benchmark, cap = computed from quota, heuristic = name pattern, default = no match._`\n : `_Run \\`opencode-router refresh --dry-run --verbose\\` in a terminal to see the source of each score._`,\n )\n return lines.join(\"\\n\")\n}\n\nfunction percent(part: number): string {\n return `${(part * 100).toFixed(0)}%`\n}\n\n/** The shared Go allowance; omitted on the free plan. */\nexport interface AllowanceStatus {\n usage: AllowanceUsage\n softThreshold: number\n}\n\nexport function formatStatus(table: RoutingTable, rows: StatusRow[], allowance?: AllowanceStatus): string {\n const lines: string[] = []\n lines.push(`## opencode-router status`)\n lines.push(\"\")\n lines.push(`- Plan: **${table.plan}**`)\n if (allowance) {\n const { usage } = allowance\n lines.push(\n `- Go allowance used (estimate): 5 hours ${percent(usage.pct5h)}, 7 days ${percent(usage.pctWeek)}, 30 days ${percent(usage.pctMonth)}`,\n )\n if (usage.cooldownUntil !== null) {\n const until = new Date(usage.cooldownUntil).toISOString().slice(11, 16)\n lines.push(`- Go allowance cooldown until ${until} UTC (${usage.cooldownReason ?? \"usage limit\"})`)\n }\n }\n const freeFallback = allowance\n ? `free-fallback = a free model, because the Go allowance is at ${percent(allowance.softThreshold)} or more or in cooldown; `\n : \"\"\n lines.push(\n `- State: healthy = first model; failover = a later model, because an earlier model is in cooldown; ${freeFallback}limited = no usable model`,\n )\n lines.push(\"\")\n lines.push(\"| Role | Model in use | Rank | State |\")\n lines.push(\"| :-- | :-- | --: | :-- |\")\n for (const row of rows) {\n if (!row.entry) {\n lines.push(`| ${row.role} | _none_ | - | - |`)\n continue\n }\n lines.push(`| ${row.role} | \\`${row.entry.id}\\` | ${row.entry.rank} | ${row.state} |`)\n }\n return lines.join(\"\\n\")\n}\n","import path from \"node:path\"\nimport { AGENT_ROLES, isAgentRole } from \"./types.js\"\nimport type { ConfigScope, RoutingTable } from \"./types.js\"\nimport {\n editJsonFile,\n fileExists,\n globalConfigDir,\n globalOpencodeConfigCandidates,\n opencodeConfigCandidates,\n type JsonEdit,\n} from \"./paths.js\"\n\n/** Internal roles that OpenCode configures as agents (`small_model` is a top-level key). */\nconst INTERNAL_AGENTS = [\"compaction\", \"title\", \"summary\"] as const\n\nconst SCHEMA_URL = \"https://opencode.ai/config.json\"\n\n// Type aliases, not interfaces: OpenCode's Config type has index signatures,\n// and only an alias gets the implicit index signature that matches them.\nexport type AgentModel = {\n model: string\n variant?: string\n}\n\nexport type RoutingConfigBody = {\n model?: string\n small_model?: string\n agent: Record<string, AgentModel>\n}\n\n/** Build the OpenCode config fragment that expresses the routing table. */\nexport function routingConfigBody(table: RoutingTable): RoutingConfigBody {\n const agent: Record<string, AgentModel> = {}\n\n for (const role of AGENT_ROLES) {\n const entry = table.active[role]?.[0]\n if (!entry) continue\n agent[role] = entry.variant && entry.variant !== \"none\" ? { model: entry.id, variant: entry.variant } : { model: entry.id }\n }\n for (const role of INTERNAL_AGENTS) {\n const entry = table.active[role]?.[0]\n if (!entry) continue\n agent[role] = { model: entry.id }\n }\n\n const body: RoutingConfigBody = { agent }\n const build = table.active.build?.[0]\n const small = table.active.small_model?.[0]\n if (build) body.model = build.id\n if (small) body.small_model = small.id\n return body\n}\n\nexport interface WriteResult {\n path: string\n created: boolean\n}\n\n/** Pick the config file to write for the given scope. */\nexport function pickConfigPath(scope: ConfigScope, dir: string): string {\n const candidates = scope === \"global\" ? globalOpencodeConfigCandidates() : opencodeConfigCandidates(dir)\n for (const candidate of candidates) {\n if (fileExists(candidate)) return candidate\n }\n return scope === \"global\" ? path.join(globalConfigDir(), \"opencode.json\") : path.join(dir, \"opencode.json\")\n}\n\n/**\n * Write the routing table into the user's opencode.json(c). Only the keys the\n * router owns change: `model`, `small_model`, and `agent.<role>.model` (plus\n * `variant` for the agent roles). Comments and all other keys stay. A file\n * with a JSON error is never replaced: this throws and leaves it as it is.\n */\nexport function writeRoutingConfig(table: RoutingTable, scope: ConfigScope, dir: string): WriteResult {\n const target = pickConfigPath(scope, dir)\n const body = routingConfigBody(table)\n\n const edits: JsonEdit[] = []\n if (body.model) edits.push({ path: [\"model\"], value: body.model })\n if (body.small_model) edits.push({ path: [\"small_model\"], value: body.small_model })\n for (const [role, spec] of Object.entries(body.agent)) {\n edits.push({ path: [\"agent\", role, \"model\"], value: spec.model })\n if (isAgentRole(role)) edits.push({ path: [\"agent\", role, \"variant\"], value: spec.variant })\n }\n\n const { created } = editJsonFile(target, edits, `{\\n \"$schema\": \"${SCHEMA_URL}\"\\n}\\n`)\n return { path: target, created }\n}\n\nexport interface ServerPatchResult {\n applied: boolean\n detail: string\n}\n\n/**\n * Best-effort live apply from the CLI: PATCH the running OpenCode server's\n * config. Used only when OPENCODE_SERVER_URL (+ optional basic auth) is set.\n */\nexport async function patchServerConfig(table: RoutingTable): Promise<ServerPatchResult> {\n const base = process.env.OPENCODE_SERVER_URL ?? process.env.OPENCODE_SERVER\n if (!base) {\n return { applied: false, detail: \"live PATCH not attempted (no OPENCODE_SERVER_URL set)\" }\n }\n\n const url = base.replace(/\\/$/, \"\") + \"/config\"\n const headers: Record<string, string> = { \"content-type\": \"application/json\" }\n const user = process.env.OPENCODE_SERVER_USERNAME\n const pass = process.env.OPENCODE_SERVER_PASSWORD\n if (user && pass) headers.authorization = \"Basic \" + Buffer.from(`${user}:${pass}`).toString(\"base64\")\n\n try {\n const res = await fetch(url, { method: \"PATCH\", headers, body: JSON.stringify(routingConfigBody(table)) })\n if (!res.ok) return { applied: false, detail: `PATCH ${url} -> ${res.status}` }\n return { applied: true, detail: `PATCH ${url}` }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return { applied: false, detail: `PATCH failed: ${message}` }\n }\n}\n","import fs from \"node:fs\"\nimport type { Ledger, LedgerAllowance, LedgerModelState } from \"./types.js\"\nimport { isPlainObject, readJsonFile, writeJson } from \"./paths.js\"\nimport { FIVE_HOUR_SHARE, WEEK_SHARE } from \"./scoring.js\"\n\nconst HOUR = 3_600_000\nconst DAY = 24 * HOUR\nexport const WINDOW_5H = 5 * HOUR\nexport const WINDOW_WEEK = 7 * DAY\nexport const WINDOW_MONTH = 30 * DAY\n\n\nfunction emptyState(now: number): LedgerModelState {\n return {\n cost5h: 0,\n costWeek: 0,\n costMonth: 0,\n tokens5h: 0,\n tokensWeek: 0,\n tokensMonth: 0,\n window5hStart: now,\n windowWeekStart: now,\n windowMonthStart: now,\n }\n}\n\nfunction emptyLedger(now: number): Ledger {\n return { version: 1, updatedAt: new Date(now).toISOString(), models: {} }\n}\n\nfunction isLedger(value: unknown): value is Ledger {\n return isPlainObject(value) && value.version === 1 && isPlainObject(value.models)\n}\n\nfunction mtimeOf(file: string): number {\n try {\n return fs.statSync(file).mtimeMs\n } catch {\n return -1\n }\n}\n\nexport interface ModelUsage {\n cost5h: number\n costMonth: number\n tokens5h: number\n tokensMonth: number\n cooldownUntil: number | null\n}\n\n/** Use of the shared Go allowance, as a part of each window's limit (1 = 100%). */\nexport interface AllowanceUsage {\n pct5h: number\n pctWeek: number\n pctMonth: number\n cooldownUntil: number | null\n /** Why the cooldown started; null without a cooldown. */\n cooldownReason: string | null\n}\n\n/**\n * Rolling spend per model, stored in one JSON file. Several OpenCode sessions\n * can share the file: each call reloads it when another process changed it.\n */\nexport class LedgerStore {\n private data: Ledger\n private loadedMtime = -1\n\n constructor(\n private readonly file: string,\n private readonly now: () => number = Date.now,\n ) {\n this.data = this.load()\n }\n\n /** Read the file. A corrupt file is kept as `<file>.corrupt-<time>` and a new ledger starts. */\n private load(): Ledger {\n this.loadedMtime = mtimeOf(this.file)\n const result = readJsonFile(this.file)\n if (result.status === \"ok\" && isLedger(result.value)) return result.value\n if (result.status !== \"absent\") {\n try {\n fs.renameSync(this.file, `${this.file}.corrupt-${this.now()}`)\n } catch {\n /* keep going with an empty ledger */\n }\n this.loadedMtime = -1\n }\n return emptyLedger(this.now())\n }\n\n private sync(): void {\n if (mtimeOf(this.file) !== this.loadedMtime) this.data = this.load()\n }\n\n /** Reset each window that has ended. */\n private roll(state: LedgerModelState, now: number): LedgerModelState {\n if (now - state.window5hStart >= WINDOW_5H) {\n state.cost5h = 0\n state.tokens5h = 0\n state.window5hStart = now\n }\n if (now - state.windowWeekStart >= WINDOW_WEEK) {\n state.costWeek = 0\n state.tokensWeek = 0\n state.windowWeekStart = now\n }\n if (now - state.windowMonthStart >= WINDOW_MONTH) {\n state.costMonth = 0\n state.tokensMonth = 0\n state.windowMonthStart = now\n }\n return state\n }\n\n private state(modelId: string): LedgerModelState {\n this.sync()\n const now = this.now()\n let entry = this.data.models[modelId]\n if (!entry) {\n entry = emptyState(now)\n this.data.models[modelId] = entry\n }\n return this.roll(entry, now)\n }\n\n /** `allowanceShare`: the cost divided by the model's monthly limit; 0 for a model outside the Go allowance. */\n record(modelId: string, costUSD: number, tokens: number, allowanceShare = 0): void {\n const state = this.state(modelId)\n state.cost5h += costUSD\n state.costWeek += costUSD\n state.costMonth += costUSD\n state.tokens5h += tokens\n state.tokensWeek += tokens\n state.tokensMonth += tokens\n state.lastUsedAt = this.now()\n if (allowanceShare > 0) this.addShare(allowanceShare)\n this.save()\n }\n\n /** Call after sync() or state(), never before: a reload would drop changes to the old data. */\n private sharedAllowance(): LedgerAllowance {\n if (!this.data.allowance || !Array.isArray(this.data.allowance.buckets)) this.data.allowance = { buckets: [] }\n return this.data.allowance\n }\n\n private addShare(share: number): void {\n const allowance = this.sharedAllowance()\n const now = this.now()\n const hour = Math.floor(now / HOUR) * HOUR\n allowance.buckets = allowance.buckets.filter(([start]) => start + HOUR > now - WINDOW_MONTH)\n const bucket = allowance.buckets.find(([start]) => start === hour)\n if (bucket) bucket[1] += share\n else allowance.buckets.push([hour, share])\n }\n\n cooldown(modelId: string, durationMs: number, reason?: string): void {\n const state = this.state(modelId)\n state.cooldownUntil = this.now() + durationMs\n if (reason) state.lastError = reason\n this.save()\n }\n\n clearCooldown(modelId: string): void {\n const state = this.state(modelId)\n state.cooldownUntil = undefined\n this.save()\n }\n\n inCooldown(modelId: string): boolean {\n const until = this.state(modelId).cooldownUntil\n return until !== undefined && this.now() < until\n }\n\n /** After a usage-limit error: every model that uses the shared allowance is limited. */\n cooldownAllowance(durationMs: number, reason?: string): void {\n this.sync()\n const allowance = this.sharedAllowance()\n allowance.cooldownUntil = this.now() + durationMs\n if (reason) allowance.lastError = reason\n this.save()\n }\n\n usage(modelId: string): ModelUsage {\n const state = this.state(modelId)\n return {\n cost5h: state.cost5h,\n costMonth: state.costMonth,\n tokens5h: state.tokens5h,\n tokensMonth: state.tokensMonth,\n cooldownUntil: state.cooldownUntil ?? null,\n }\n }\n\n /** Rolling use of the shared allowance in the last 5 hours, 7 days, and 30 days. */\n allowance(): AllowanceUsage {\n this.sync()\n const allowance = this.sharedAllowance()\n const now = this.now()\n const cooldownUntil = allowance.cooldownUntil !== undefined && now < allowance.cooldownUntil ? allowance.cooldownUntil : null\n return {\n pct5h: windowShare(allowance.buckets, now, WINDOW_5H) / FIVE_HOUR_SHARE,\n pctWeek: windowShare(allowance.buckets, now, WINDOW_WEEK) / WEEK_SHARE,\n pctMonth: windowShare(allowance.buckets, now, WINDOW_MONTH),\n cooldownUntil,\n cooldownReason: cooldownUntil === null ? null : (allowance.lastError ?? null),\n }\n }\n\n /** True when no window has reached `softThreshold` and no usage-limit cooldown is active. */\n allowanceAvailable(softThreshold: number): boolean {\n const u = this.allowance()\n return u.cooldownUntil === null && u.pct5h < softThreshold && u.pctWeek < softThreshold && u.pctMonth < softThreshold\n }\n\n snapshot(): Ledger {\n return structuredClone(this.data)\n }\n\n save(): void {\n this.data.updatedAt = new Date(this.now()).toISOString()\n writeJson(this.file, this.data)\n this.loadedMtime = mtimeOf(this.file)\n }\n}\n\n/**\n * Sum of the shares in the last `windowMs`. The use in one hour is taken as\n * even, so an hour that is partly inside the window counts in part.\n */\nfunction windowShare(buckets: Array<[number, number]>, now: number, windowMs: number): number {\n const from = now - windowMs\n let sum = 0\n for (const [start, share] of buckets) {\n const end = Math.min(start + HOUR, now)\n if (end <= from || start > now) continue\n const span = end - start\n sum += span <= 0 ? share : (share * (end - Math.max(start, from))) / span\n }\n return sum\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport type { ConfigScope } from \"./types.js\"\nimport { SLASH_COMMANDS, commandTemplate, type SlashCommand } from \"./commands.js\"\nimport { ensureDir, fileExists, globalConfigDir, writeJson } from \"./paths.js\"\n\nfunction commandFile(command: SlashCommand): string {\n return [\"---\", `description: ${command.description}`, \"agent: build\", \"---\", \"\", commandTemplate(command.args), \"\"].join(\"\\n\")\n}\n\nexport interface InstallResult {\n commandDir: string\n configPath: string\n /** False when a router.config.json already existed; it is never replaced. */\n configCreated: boolean\n files: string[]\n}\n\n/** Write on-disk slash-command files, plus an empty router.config.json when there is none. */\nexport function installCommands(scope: ConfigScope, dir: string): InstallResult {\n const base = scope === \"global\" ? globalConfigDir() : path.join(dir, \".opencode\")\n const commandDir = path.join(base, \"command\")\n ensureDir(commandDir)\n\n const files = SLASH_COMMANDS.map((command) => {\n const file = path.join(commandDir, `${command.name}.md`)\n fs.writeFileSync(file, commandFile(command), \"utf8\")\n return file\n })\n\n const configPath = path.join(base, \"router.config.json\")\n const configCreated = !fileExists(configPath)\n if (configCreated) writeJson(configPath, {})\n\n return { commandDir, configPath, configCreated, files }\n}\n","import { fileURLToPath } from \"node:url\"\n\nexport interface SlashCommand {\n name: string\n description: string\n /** CLI arguments; OpenCode replaces $1 with the first word the user types. */\n args: string\n}\n\n/** The slash commands, shared by the plugin and `opencode-router install`. */\nexport const SLASH_COMMANDS: readonly SlashCommand[] = [\n { name: \"refresh-routing\", description: \"Recompute and apply OpenCode model routing\", args: \"refresh\" },\n { name: \"routing-status\", description: \"Show the model in use per role and its 5-hour quota use\", args: \"status\" },\n { name: \"routing-plan\", description: \"Switch the routing plan (go | go-plus | free) and rebuild\", args: \"plan $1\" },\n { name: \"routing-eval\", description: \"Run the router scoring stress test\", args: \"eval\" },\n { name: \"routing-update\", description: \"Update opencode-router to the newest version\", args: \"update\" },\n]\n\nconst OUTPUT_BEGIN = \"---BEGIN ROUTER OUTPUT---\"\n\n/** True for the prompt of a router slash command. */\nexport function isRouterCommandPrompt(parts: readonly { type: string; text?: string }[]): boolean {\n return parts.some((part) => part.type === \"text\" && part.text?.includes(OUTPUT_BEGIN) === true)\n}\n\n/** Absolute path of the CLI script that ships next to this module in dist/. */\nfunction cliScriptPath(): string {\n return fileURLToPath(new URL(\"./bin.js\", import.meta.url)).replace(/\\\\/g, \"/\")\n}\n\n/** Command body. OpenCode runs the !`...` part and puts its output in the prompt. */\nexport function commandTemplate(args: string): string {\n return [\n \"opencode-router already ran. Its output is between the markers below.\",\n \"\",\n \"Rules:\",\n \"1. Do not run any command, script, or tool. Do not search for opencode-router on PATH.\",\n \"2. Present the text between the markers to the user exactly as written.\",\n \"3. Do not summarize, reformat, shorten, or reorganize it.\",\n \"\",\n OUTPUT_BEGIN,\n `!\\`node \"${cliScriptPath()}\" ${args} --scope global\\``,\n \"---END ROUTER OUTPUT---\",\n ].join(\"\\n\")\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport { globalConfigDir, readJson, writeJson } from \"./paths.js\"\n\n// Usage caps are per OpenCode account, not per project, so all runtime state\n// lives in one global folder that the plugin and the CLI share.\n\nexport function stateDir(): string {\n return path.join(globalConfigDir(), \"router\")\n}\n\nexport function ledgerFile(): string {\n return path.join(stateDir(), \"ledger.json\")\n}\n\nexport function routingTableFile(): string {\n return path.join(stateDir(), \"routing-table.json\")\n}\n\nexport function evalReportFile(): string {\n return path.join(stateDir(), \"eval-report.md\")\n}\n\nexport function updateCheckFile(): string {\n return path.join(stateDir(), \"update-check.json\")\n}\n\nfunction applyMarkerFile(): string {\n return path.join(stateDir(), \"last-apply.json\")\n}\n\n/** The plugin's hot-apply and the CLI it starts run within milliseconds of each other. */\nconst MARKER_MAX_AGE_MS = 10_000\n\nexport interface ApplyMarker {\n ok: boolean\n detail: string\n}\n\n/** Record the result of the plugin's last hot-apply, for the CLI to report. */\nexport function writeApplyMarker(marker: ApplyMarker): void {\n writeJson(applyMarkerFile(), { at: new Date().toISOString(), ...marker })\n}\n\nexport function readApplyMarker(maxAgeMs = MARKER_MAX_AGE_MS): ApplyMarker | null {\n const marker = readJson<{ at?: string; ok?: boolean; detail?: string }>(applyMarkerFile())\n if (!marker?.at || !marker.detail) return null\n const at = Date.parse(marker.at)\n if (!Number.isFinite(at) || Date.now() - at > maxAgeMs) return null\n return { ok: marker.ok === true, detail: marker.detail }\n}\n\nexport function clearApplyMarker(): void {\n fs.rmSync(applyMarkerFile(), { force: true })\n}\n","import type { PlanProfile, RankingEntry } from \"./types.js\"\nimport { buildRoutingTable } from \"./engine.js\"\nimport { writeTextAtomic } from \"./paths.js\"\nimport { FIVE_HOUR_SHARE } from \"./scoring.js\"\nimport { evalReportFile } from \"./state.js\"\n\nexport interface EvalOptions {\n plan?: PlanProfile\n catalog?: string\n json?: boolean\n projectDir?: string\n}\n\nconst ROLE = \"build\"\nconst CHAIN_LIMIT = 4\n\nconst PROMPT = `In a fixture repo, build a CLI named \\`todo\\` with \\`add\\`, \\`list\\`, \\`done <id>\\`, and \\`rm <id>\\` subcommands backed by a JSON file. Include input validation, a \\`--json\\` output flag, and a test suite. Then fix any failing tests.`\n\nconst GO_URL = \"https://opencode.ai/inference/go/openai/v1\"\nconst ZEN_URL = \"https://opencode.ai/inference/openai/v1\"\n\ninterface CallResult {\n ok: boolean\n latencyMs: number\n inputTokens: number\n outputTokens: number\n costUSD: number\n text: string\n error?: string\n}\n\nfunction staticGrade(text: string): { passed: number; checks: Record<string, boolean> } {\n const lower = text.toLowerCase()\n const checks: Record<string, boolean> = {\n add: /\\badd\\b/.test(lower),\n list: /\\blist\\b/.test(lower),\n done: /\\bdone\\b/.test(lower),\n rm: /\\brm\\b|\\bremove\\b|\\bdelete\\b/.test(lower),\n jsonFlag: /--json/.test(text),\n validation: /invalid|validat|error/.test(lower),\n tests: /\\btest\\b|\\bdescribe\\(|\\bit\\(|assert/.test(lower),\n }\n const passed = Object.values(checks).filter(Boolean).length\n return { passed, checks }\n}\n\nasync function callModel(entry: RankingEntry, apiKey: string): Promise<CallResult> {\n const base = entry.providerID === \"opencode-go\" ? GO_URL : ZEN_URL\n const started = Date.now()\n try {\n const res = await fetch(`${base}/chat/completions`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\", authorization: `Bearer ${apiKey}` },\n body: JSON.stringify({\n model: entry.modelID,\n messages: [{ role: \"user\", content: PROMPT }],\n max_tokens: 2000,\n }),\n })\n const latencyMs = Date.now() - started\n if (!res.ok) {\n return { ok: false, latencyMs, inputTokens: 0, outputTokens: 0, costUSD: 0, text: \"\", error: `HTTP ${res.status}` }\n }\n const json = (await res.json()) as {\n choices?: Array<{ message?: { content?: string } }>\n usage?: { prompt_tokens?: number; completion_tokens?: number }\n }\n const text = json.choices?.[0]?.message?.content ?? \"\"\n return {\n ok: true,\n latencyMs,\n inputTokens: json.usage?.prompt_tokens ?? 0,\n outputTokens: json.usage?.completion_tokens ?? 0,\n costUSD: estimateCost(entry, json.usage?.prompt_tokens ?? 0, json.usage?.completion_tokens ?? 0),\n text,\n }\n } catch (error) {\n return {\n ok: false,\n latencyMs: Date.now() - started,\n inputTokens: 0,\n outputTokens: 0,\n costUSD: 0,\n text: \"\",\n error: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\nfunction estimateCost(entry: RankingEntry, inputTokens: number, outputTokens: number): number {\n // Rough: derived from the score table's blended cost when present.\n const per1M = entry.tokensPer5h && entry.monthlyCapUSD ? (entry.monthlyCapUSD * FIVE_HOUR_SHARE) / entry.tokensPer5h : 1\n return ((inputTokens + outputTokens) / 1_000_000) * per1M\n}\n\nexport async function runEval(opts: EvalOptions = {}): Promise<number> {\n const { table } = await buildRoutingTable({ plan: opts.plan, catalogFile: opts.catalog, projectDir: opts.projectDir })\n const chain = (table.active[ROLE] ?? []).slice(0, CHAIN_LIMIT)\n\n if (chain.length === 0) {\n process.stderr.write(`error: no candidate models for role \"${ROLE}\"\\n`)\n return 1\n }\n\n const apiKey = process.env.OPENCODE_API_KEY\n const reportPath = evalReportFile()\n\n const lines: string[] = []\n lines.push(`# opencode-router eval report`)\n lines.push(\"\")\n lines.push(`- Role: **${ROLE}**`)\n lines.push(`- Plan: **${table.plan}**`)\n lines.push(`- Generated: ${new Date().toISOString()}`)\n lines.push(\"\")\n lines.push(`## Prompt`)\n lines.push(\"\")\n lines.push(\"> \" + PROMPT.replace(/\\r?\\n/g, \" \"))\n lines.push(\"\")\n\n if (!apiKey) {\n lines.push(\"## Result\")\n lines.push(\"\")\n lines.push(\"`OPENCODE_API_KEY` is not set. Nothing was called. The predicted ranking is below.\")\n lines.push(\"\")\n lines.push(\"| Rank | Model | Score | Intel | Speed | Endur | Tokens/5h | Class |\")\n lines.push(\"| --: | :-- | --: | --: | --: | --: | --: | :-- |\")\n for (const e of chain) {\n lines.push(`| ${e.rank} | \\`${e.id}\\` | ${e.score} | ${e.intelligence} | ${e.speed} | ${e.endurance} | ${e.tokensPer5h ?? \"inf\"} | ${e.class} |`)\n }\n lines.push(\"\")\n lines.push(\"Set `OPENCODE_API_KEY` and re-run `opencode-router eval` to measure real latency, tokens, and pass rate.\")\n writeTextAtomic(reportPath, lines.join(\"\\n\") + \"\\n\")\n if (opts.json) process.stdout.write(JSON.stringify({ role: ROLE, predicted: chain }, null, 2) + \"\\n\")\n else process.stdout.write(`Wrote ${reportPath} (predicted only; set OPENCODE_API_KEY for live results)\\n`)\n return 0\n }\n\n lines.push(\"## Result\")\n lines.push(\"\")\n lines.push(\"| Predicted rank | Model | Latency (ms) | Tokens | Cost (USD) | Checks | Static pass | Error |\")\n lines.push(\"| --: | :-- | --: | --: | --: | --: | --: | :-- |\")\n\n const results: Array<{ entry: RankingEntry; result: CallResult; pass: number }> = []\n for (const entry of chain) {\n const result = await callModel(entry, apiKey)\n const grade = staticGrade(result.text)\n results.push({ entry, result, pass: grade.passed })\n lines.push(\n `| ${entry.rank} | \\`${entry.id}\\` | ${result.latencyMs} | ${result.inputTokens + result.outputTokens} | ${result.costUSD.toFixed(5)} | ${grade.passed}/7 | ${result.ok ? (grade.passed >= 5 ? \"PASS\" : \"WEAK\") : \"FAIL\"} | ${result.error ?? \"\"} |`,\n )\n }\n\n const measured = [...results].sort((a, b) => b.pass - a.pass || a.result.latencyMs - b.result.latencyMs)\n lines.push(\"\")\n lines.push(\"## Predicted vs measured\")\n lines.push(\"\")\n lines.push(\"| Predicted rank | Measured rank | Model |\")\n lines.push(\"| --: | --: | :-- |\")\n for (const { entry } of results) {\n const measuredRank = measured.findIndex((m) => m.entry.id === entry.id) + 1\n lines.push(`| ${entry.rank} | ${measuredRank} | \\`${entry.id}\\` |`)\n }\n lines.push(\"\")\n lines.push(\"Feed the measured ranks back into `model-scores.json` (or `router.config.json` -> `scores`) to tune accuracy.\")\n\n writeTextAtomic(reportPath, lines.join(\"\\n\") + \"\\n\")\n if (opts.json) process.stdout.write(JSON.stringify({ role: ROLE, results }, null, 2) + \"\\n\")\n else process.stdout.write(`Wrote ${reportPath}\\n`)\n return 0\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport { fileURLToPath } from \"node:url\"\nimport { loadUserConfig } from \"./config.js\"\nimport { opencodeCacheDir, readJson, writeJson } from \"./paths.js\"\nimport { updateCheckFile } from \"./state.js\"\n\n// OpenCode 1.19 installs an npm plugin one time and then reuses its cached\n// copy. It does not look for a newer version, so the router does.\n\nexport const PACKAGE_NAME = \"@s-berdia/opencode-router\"\nconst LATEST_URL = `https://registry.npmjs.org/${PACKAGE_NAME.replace(\"/\", \"%2f\")}/latest`\nconst CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000\nconst TIMEOUT_MS = 3000\n\nexport interface UpdateInfo {\n current: string\n latest: string\n}\n\ninterface UpdateCheckState {\n checkedAt: number\n latest?: string\n}\n\nfunction parseVersion(version: string): number[] | null {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version)\n return match ? match.slice(1).map(Number) : null\n}\n\n/** True when version `a` is higher than version `b`. Compares major.minor.patch only. */\nexport function isNewerVersion(a: string, b: string): boolean {\n const left = parseVersion(a)\n const right = parseVersion(b)\n if (!left || !right) return false\n for (let i = 0; i < 3; i++) {\n if (left[i]! !== right[i]!) return left[i]! > right[i]!\n }\n return false\n}\n\n/** The version in this package's package.json, one folder above dist/ (or src/ in tests). */\nexport function installedVersion(): string {\n const file = fileURLToPath(new URL(\"../package.json\", import.meta.url))\n return readJson<{ version?: string }>(file)?.version ?? \"0.0.0\"\n}\n\n/** The `latest` version on npm, or undefined when npm cannot be reached. */\nexport async function fetchLatestVersion(): Promise<string | undefined> {\n const controller = new AbortController()\n const timeout = setTimeout(() => controller.abort(), TIMEOUT_MS)\n try {\n const res = await fetch(LATEST_URL, { signal: controller.signal, headers: { accept: \"application/json\" } })\n if (!res.ok) return undefined\n const body = (await res.json()) as { version?: unknown }\n return typeof body.version === \"string\" ? body.version : undefined\n } catch {\n return undefined\n } finally {\n clearTimeout(timeout)\n }\n}\n\nexport interface UpdateCheckOptions {\n projectDir?: string\n /** Installed version; default: this package's version. */\n current?: string\n now?: number\n}\n\n/**\n * The newer version on npm, or null. Asks npm at most once per 24 hours and\n * never when `updateCheck` is false. Never throws.\n */\nexport async function checkForUpdate(opts: UpdateCheckOptions = {}): Promise<UpdateInfo | null> {\n try {\n if (loadUserConfig(opts.projectDir).config.updateCheck === false) return null\n const current = opts.current ?? installedVersion()\n const now = opts.now ?? Date.now()\n const state = readJson<UpdateCheckState>(updateCheckFile())\n let latest = state?.latest\n const fresh = state !== undefined && now >= state.checkedAt && now - state.checkedAt < CHECK_INTERVAL_MS\n if (!fresh) {\n // Record failed checks too, so an offline machine asks once per day, not at each start.\n latest = (await fetchLatestVersion()) ?? latest\n writeJson(updateCheckFile(), { checkedAt: now, latest })\n }\n return latest && isNewerVersion(latest, current) ? { current, latest } : null\n } catch {\n return null\n }\n}\n\n/** One line for the end of the status and the scorecard. */\nexport function updateNotice(update: UpdateInfo): string {\n return `opencode-router ${update.latest} is available (installed: ${update.current}). To update, type /routing-update in OpenCode.`\n}\n\nexport interface ClearResult {\n /** Removed cache folders. OpenCode installs the newest version into them at its next start. */\n removed: string[]\n /** Cache folders of an older version that opencode.json pins, for example `opencode-router@1.0.1`. */\n pinned: string[]\n /** Cache folders that already have the newest version. */\n current: string[]\n /** Old cache folders that could not be removed, for example because Windows locks a file. */\n failed: Array<{ dir: string; error: string }>\n}\n\n/**\n * Remove OpenCode's cached copies of this package that are older than `latest`.\n * OpenCode 1.19 keeps them in <cache>/packages/@s-berdia/<spec>/node_modules/.\n */\nexport function clearOutdatedCopies(latest: string): ClearResult {\n const [scope, name] = PACKAGE_NAME.split(\"/\") as [string, string]\n const scopeDir = path.join(opencodeCacheDir(), \"packages\", scope)\n const result: ClearResult = { removed: [], pinned: [], current: [], failed: [] }\n let entries: string[] = []\n try {\n entries = fs.readdirSync(scopeDir)\n } catch {\n return result\n }\n for (const entry of entries) {\n const dir = path.join(scopeDir, entry)\n if (entry === name || entry === `${name}@latest`) {\n const manifest = path.join(dir, \"node_modules\", scope, name, \"package.json\")\n const version = readJson<{ version?: string }>(manifest)?.version ?? \"0.0.0\"\n if (!isNewerVersion(latest, version)) {\n result.current.push(dir)\n continue\n }\n try {\n fs.rmSync(dir, { recursive: true, force: true, maxRetries: 3 })\n result.removed.push(dir)\n } catch (error) {\n result.failed.push({ dir, error: error instanceof Error ? error.message : String(error) })\n }\n } else if (entry.startsWith(`${name}@`) && isNewerVersion(latest, entry.slice(name.length + 1))) {\n result.pinned.push(entry)\n }\n }\n return result\n}\n","#!/usr/bin/env node\nimport { main } from \"./cli.js\"\n\nmain(process.argv.slice(2)).then(\n (code) => {\n process.exitCode = code\n },\n (error: unknown) => {\n process.stderr.write(`opencode-router failed: ${error instanceof Error ? error.message : String(error)}\\n`)\n process.exitCode = 1\n },\n)\n"],"mappings":";;;AAAA,SAAS,iBAAiB;;;ACEnB,IAAM,gBAAgB,CAAC,MAAM,WAAW,MAAM;AAI9C,SAAS,OAAO,OAAsC;AAC3D,SAAO,OAAO,UAAU,YAAa,cAAoC,SAAS,KAAK;AACzF;AAMO,IAAM,cAAc,CAAC,QAAQ,SAAS,WAAW,SAAS;AAG1D,IAAM,iBAAiB,CAAC,eAAe,SAAS,WAAW,YAAY;AAEvE,IAAM,aAAa,CAAC,GAAG,aAAa,GAAG,cAAc;AAQrD,SAAS,YA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AAW,IAAI;AAAA,MAC9B,KAAK;AACH,eAAO,MAAM,UAAU,IAAI;AAAA,MAC7B,KAAK;AACH,eAAO,MAAM,QAAQ,KAAK,CAAC,GAAG,IAAI;AAAA,MACpC,KAAK;AACH,eAAO,OAAO,KAAK,OAAO;AAAA,MAC5B,KAAK;AACH,eAAO,WAAW,IAAI;AAAA,MACxB,KAAK;AACH,eAAO,MAAM,QAAQ,EAAE,MAAM,KAAK,MAAM,SAAS,KAAK,SAAS,MAAM,KAAK,MAAM,YAAY,KAAK,IAAI,CAAC;AAAA,MACxG,KAAK;AACH,eAAO,MAAM,UAAU;AAAA,MACzB;AACE,cAAM,IAAI,WAAW,oBAAoB,OAAO,GAAG;AAAA,IACvD;AAAA,EACF,SAAS,OAAO;AACd,QAAI,iBAAiB,WAAY,QAAO,WAAW,KAAK;AACxD,UAAM;AAAA,EACR;AACF;;;AyBrRA,KAAK,QAAQ,KAAK,MAAM,CAAC,CAAC,EAAE;AAAA,EAC1B,CAAC,SAAS;AACR,YAAQ,WAAW;AAAA,EACrB;AAAA,EACA,CAAC,UAAmB;AAClB,YAAQ,OAAO,MAAM,2BAA2B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,CAAI;AAC1G,YAAQ,WAAW;AAAA,EACrB;AACF;","names":["fs","value","CharacterCodes","ParseOptions","path","path","edit","ScanError","SyntaxKind","parse","parseTree","findNodeAtLocation","ParseErrorCode","path","parse","parseTree","findNodeAtLocation","fs","path","build","path","fs","fs","fs","path","path","fs","fs","path","path","path","fs","path","fileURLToPath","fileURLToPath","path","fs"]}