diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bab65d..5c3700a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,30 @@ All notable changes to this project are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.9.0] - 2026-10-27 + +### Added +- Every Claude model in OMP's bundled Anthropic catalog is registered, instead of + a hardcoded list: Opus 5.5, Opus 5, Sonnet 5.5, Haiku 5.5, Fable 5.1, + Mythos 5 / 5.1, Opus 4.5 and Sonnet 4.5 are now available, and future catalog + models appear without a code change. Dated snapshot aliases stay hidden. +- Opus 5.5 / Opus 5 / Sonnet 5.5 default to 1M (`[1m]`) with a `-200k` alternate. + Unmeasured 1M-capable models default to 200K with a `-1m` alternate. +- `max` thinking level, for both the provider and AskClaude's `thinking` parameter. + +### Changed +- Thinking levels map onto each model's catalog effort ladder (e.g. `xhigh` + stays `xhigh` on Opus 5.5), clamping down where a level is unsupported. +- AskClaude `opus` / `sonnet` / `haiku` shortcuts resolve to the newest model in + that family. +- OMP 18 compatibility: imports go through the host-shimmed `@earendil-works/*` + packages. + +### Fixed +- Unsuffixed picker entries whose preferred window has no runtime (Haiku 4.5 + under `"1m"`, Opus 4.7 under `"200k"`) no longer throw on request; they use + the model's only window, matching what the picker shows. + ## [0.8.1] - 2026-07-07 ### Fixed diff --git a/README.md b/README.md index d7c0f57..42cfd0b 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ --- -`omp-claude-bridge` lets you drive **Claude Code** — Opus, Sonnet, Haiku, and Fable — from inside Oh My Pi, with every tool call flowing through OMP's native TUI. It also exposes an **AskClaude** tool so any other provider can delegate a task or a second opinion to Claude Code, and it gives you **direct control over the context window** each model requests. +`omp-claude-bridge` lets you drive **Claude Code** — every Claude model in OMP's catalog (Opus, Sonnet, Haiku, Fable, Mythos) — from inside Oh My Pi, with every tool call flowing through OMP's native TUI. It also exposes an **AskClaude** tool so any other provider can delegate a task or a second opinion to Claude Code, and it gives you **direct control over the context window** each model requests. Authentication and billing run through Claude Code and your Anthropic subscription via the official [Claude Agent SDK](https://github.com/anthropics/claude-agent-sdk-typescript) — this extension never stores credentials. @@ -45,12 +45,12 @@ Authentication and billing run through Claude Code and your Anthropic subscripti ## Features -- **Claude Code as a provider** — pick Opus / Sonnet / Haiku / Fable from `/model`; tool calls render in OMP's TUI like any native provider. +- **Claude Code as a provider** — pick any Claude model (Opus 5.5, Sonnet 5.5, Haiku 5.5, Fable 5.1, …) from `/model`; tool calls render in OMP's TUI like any native provider. - **AskClaude delegation tool** — from any other provider, hand a task or question to Claude Code (read-only, no-tools, or full read/write/bash), optionally in an isolated session. - **Switchable context window** — force **1M** or **200K** globally, or leave it on measured per-model defaults. This is the headline addition in this fork. - **Session resume & persistence** — conversations survive across turns and reconnects. - **Skills + AGENTS.md forwarding** — your OMP skills and context files are passed into Claude Code's system prompt. -- **Thinking support** — effort levels map through to Claude Code, including `xhigh` on Sonnet models. +- **Thinking support** — effort levels map through to Claude Code, clamped to each model's effort ladder, including `xhigh` and `max`. - **MCP tool bridging** with strict-config isolation by default. ## Install @@ -114,18 +114,30 @@ Both windows stay in the picker regardless of this setting (wherever a runtime e ### Windows offered per model +Every Claude model in OMP's bundled Anthropic catalog is registered automatically — new releases show up without a code change. + | Model | 200K entry | 1M entry | `auto` default | | ----- | :--------: | :------: | :------------: | +| `claude-fable-5-1` | ✓ | ✓ | 200K | +| `claude-fable-5` | ✓ | ✓ | 200K | +| `claude-mythos-5-1` | ✓ | ✓ | 200K³ | +| `claude-mythos-5` | ✓ | ✓ | 200K³ | +| `claude-opus-5-5` | ✓ | ✓ | 1M | +| `claude-opus-5` | ✓ | ✓ | 1M | | `claude-opus-4-8` | ✓ | ✓ | 1M | | `claude-opus-4-7` | — | ✓ | 1M | | `claude-opus-4-6` | ✓ | ✓ | 200K¹ | -| `claude-fable-5` | ✓ | ✓ | 200K | +| `claude-opus-4-5` | ✓ | — | 200K | +| `claude-sonnet-5-5` | ✓ | ✓ | 1M | | `claude-sonnet-5` | ✓ | ✓ | 1M | | `claude-sonnet-4-6` | ✓ | ✓ | 200K² | +| `claude-sonnet-4-5` | ✓ | — | 200K | +| `claude-haiku-5-5` | ✓ | ✓ | 200K³ | | `claude-haiku-4-5` | ✓ | — | 200K | ¹ Opus 4.6's `auto` default is 1M when `plan: "max"` or `longContextExtraUsage: true`. ² Sonnet 4.6's `auto` default is 1M when `longContextExtraUsage: true`. +³ Not yet measured: models without a measured `[1m]` entitlement default to the bare id at 200K (an unentitled `[1m]` request fails outright). The 1M entry is still pickable. Catalog models not listed here follow the same rule: 1M offered when the catalog advertises it. The suffixed alternate exists only for the window that isn't the default — e.g. under `auto` you get `claude-opus-4-8` (1M) + `claude-opus-4-8-200k`, and under `"200k"` you get `claude-opus-4-8` (200K) + `claude-opus-4-8-1m`. @@ -139,19 +151,25 @@ Pick any of these from `/model` — each entry shows a `(1M)` or `(200K)` label. | Picker id (auto) | Window | | --------- | ------ | -| `claude-bridge/claude-fable-5` | 200K | -| `claude-bridge/claude-fable-5-1m` | 1M | -| `claude-bridge/claude-opus-4-8` | 1M | -| `claude-bridge/claude-opus-4-8-200k` | 200K | +| `claude-bridge/claude-fable-5-1` / `-1m` | 200K / 1M | +| `claude-bridge/claude-fable-5` / `-1m` | 200K / 1M | +| `claude-bridge/claude-mythos-5-1` / `-1m` | 200K / 1M | +| `claude-bridge/claude-mythos-5` / `-1m` | 200K / 1M | +| `claude-bridge/claude-opus-5-5` / `-200k` | 1M / 200K | +| `claude-bridge/claude-opus-5` / `-200k` | 1M / 200K | +| `claude-bridge/claude-opus-4-8` / `-200k` | 1M / 200K | | `claude-bridge/claude-opus-4-7` | 1M | -| `claude-bridge/claude-opus-4-6` | 200K (1M on Max / Extra Usage) | -| `claude-bridge/claude-opus-4-6-1m` | 1M | -| `claude-bridge/claude-sonnet-5` | 1M (supports `xhigh`) | -| `claude-bridge/claude-sonnet-5-200k` | 200K | -| `claude-bridge/claude-sonnet-4-6` | 200K (supports `xhigh`) | -| `claude-bridge/claude-sonnet-4-6-1m` | 1M | +| `claude-bridge/claude-opus-4-6` / `-1m` | 200K (1M on Max / Extra Usage) / 1M | +| `claude-bridge/claude-opus-4-5` | 200K | +| `claude-bridge/claude-sonnet-5-5` / `-200k` | 1M / 200K | +| `claude-bridge/claude-sonnet-5` / `-200k` | 1M / 200K | +| `claude-bridge/claude-sonnet-4-6` / `-1m` | 200K / 1M | +| `claude-bridge/claude-sonnet-4-5` | 200K | +| `claude-bridge/claude-haiku-5-5` / `-1m` | 200K / 1M | | `claude-bridge/claude-haiku-4-5` | 200K (cheapest) | +Thinking levels follow each model's effort ladder from the catalog, including `max`; a level a model lacks is clamped to the highest one it supports. + Bash commands issued by Claude Code get a 120-second default timeout (matching Claude Code's default), since OMP's bash has no timeout by default. ## AskClaude tool @@ -172,8 +190,8 @@ You can also bake it into a skill or AGENTS.md, e.g. *"Always call AskClaude to | --------- | ------ | ----------- | | `prompt` | string | The question or task for Claude Code. | | `mode` | `read` (default), `none`, `full` | `read` = read files + web; `full` = read/write/bash. Lock `full` out with `allowFullMode: false`. | -| `model` | `opus` (default), `sonnet`, `haiku`, or a full id | Which Claude model handles the delegation. | -| `thinking` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh` | Effort level. | +| `model` | `opus` (default), `sonnet`, `haiku`, or a full id | Which Claude model handles the delegation. Family shortcuts resolve to the newest model (e.g. `opus` → `claude-opus-5-5`). | +| `thinking` | `off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max` | Effort level. | | `isolated` | boolean (default `false`) | When `true`, Claude gets a clean session with no conversation history. | ## Configuration reference diff --git a/package.json b/package.json index ea22c96..a2f4abd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "omp-claude-bridge", - "version": "0.8.1", + "version": "0.9.0", "private": false, "description": "Oh My Pi extension that runs Claude Code (via the Claude Agent SDK) as a model provider, adds an AskClaude delegation tool, and lets you force the 1M / 200K context window per provider.", "keywords": [ diff --git a/src/config.ts b/src/config.ts index b38d27f..ce41878 100644 --- a/src/config.ts +++ b/src/config.ts @@ -5,7 +5,7 @@ import type { SettingSource } from "@anthropic-ai/claude-agent-sdk"; import type { ContextWindowMode } from "./models.js"; -import { CONFIG_DIR_NAME } from "@oh-my-pi/pi-utils"; +import { CONFIG_DIR_NAME } from "@earendil-works/pi-coding-agent"; import { existsSync, readFileSync } from "fs"; import { homedir } from "os"; import { join } from "path"; diff --git a/src/convert.ts b/src/convert.ts index 609358d..4af3013 100644 --- a/src/convert.ts +++ b/src/convert.ts @@ -1,7 +1,7 @@ // Pure pi→Anthropic message conversion helpers. // Extracted so they can be tested without pulling in the full extension runtime. -import type { Message as PiMessage } from "@oh-my-pi/pi-coding-agent/extensibility/legacy-pi-ai-shim"; +import type { Message as PiMessage } from "@earendil-works/pi-ai"; import type { Message as SessionMessage } from "cc-session-io"; import { pascalCase } from "change-case"; diff --git a/src/index.ts b/src/index.ts index 77e3b7f..07627cd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,19 +1,17 @@ -import { StringEnum, Type, getModels, type AssistantMessage, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions, type Tool, type Usage } from "@oh-my-pi/pi-coding-agent/extensibility/legacy-pi-ai-shim"; -import * as piAi from "@oh-my-pi/pi-coding-agent/extensibility/legacy-pi-ai-shim"; -import { type ExtensionAPI, type ExtensionUIContext } from "@oh-my-pi/pi-coding-agent"; -import { keyHint } from "@oh-my-pi/pi-coding-agent/modes/components/keybinding-hints"; -import { buildSessionContext } from "@oh-my-pi/pi-coding-agent/session/session-context"; -import type { CompactionEntry } from "@oh-my-pi/pi-coding-agent/session/session-entries"; -import { compact } from "@oh-my-pi/pi-agent-core/compaction"; +import { StringEnum, type AssistantMessage, type AssistantMessageEventStream, type Context, type Model, type SimpleStreamOptions, type Tool, type Usage } from "@earendil-works/pi-ai"; +import * as piAi from "@earendil-works/pi-ai"; +import { getModels } from "@earendil-works/pi-ai/compat"; +import { buildSessionContext, compact, keyHint, type CompactionEntry, type ExtensionAPI, type ExtensionUIContext } from "@earendil-works/pi-coding-agent"; import { createSdkMcpServer, query, type EffortLevel, type SDKMessage, type SDKUserMessage, type SettingSource } from "@anthropic-ai/claude-agent-sdk"; import type { Base64ImageSource, ContentBlockParam, MessageParam } from "@anthropic-ai/sdk/resources"; -import { Text } from "@oh-my-pi/pi-tui"; +import { Type } from "typebox"; +import { Text } from "@earendil-works/pi-tui"; import { createSession, deleteSession, repairToolPairing } from "cc-session-io"; import { appendFileSync, mkdirSync, realpathSync, statSync } from "fs"; import { homedir } from "os"; import { dirname, join } from "path"; import { PROVIDER_ID, messageContentToText, convertPiMessages } from "./convert.js"; -import { buildVariantModels, buildModels, claudeCodeModelId, type ContextWindowMode, type LongContextSettings, resolveModel as _resolveModel } from "./models.js"; +import { buildVariantModels, buildModels, claudeCodeEffort, claudeCodeModelId, type ContextWindowMode, type LongContextSettings, resolveModel as _resolveModel } from "./models.js"; import { MCP_SERVER_NAME, MCP_TOOL_PREFIX, extractSkillsBlock } from "./skills.js"; import { verifyWrittenSession as _verifyWrittenSession } from "./session-verify.js"; import { extractAllToolResults as _extractAllToolResults, type McpResult } from "./extract-tool-results.js"; @@ -784,13 +782,6 @@ function logServedContextWindow(label: string, message: SDKMessage, model: Model } } -// --- Effort level mapping --- -// OMP reasoning levels → CC SDK effort levels - -const REASONING_TO_EFFORT: Record = { - minimal: "low", low: "low", medium: "medium", high: "high", xhigh: "max", -}; - // --- Provider helpers: misc --- function mapStopReason(reason: string | undefined): "stop" | "length" | "toolUse" { @@ -1235,12 +1226,10 @@ function streamClaudeAgentSdk(model: Model, context: Context, options?: Sim const strictMcpConfigEnabled = providerSettings.strictMcpConfig !== false; const claudeExecutable = providerSettings.pathToClaudeCodeExecutable; - // Prefer the model's own thinkingLevelMap when present (pi-ai 0.72+ ships - // per-model overrides — e.g. opus-4-7 wants xhigh→xhigh, not xhigh→max). - // Fall back to our generic table for older pi-ai or unmapped levels. - const effort = options?.reasoning - ? ((model as any).thinkingLevelMap?.[options.reasoning] as EffortLevel | undefined) - ?? REASONING_TO_EFFORT[options.reasoning] + // OMP reasoning level → CC effort, clamped to the model's catalog effort ladder + // (see claudeCodeEffort; thinkingLevelMap overrides win). + const effort: EffortLevel | undefined = options?.reasoning + ? claudeCodeEffort(model as any, options.reasoning) : undefined; // cliModel is the actual id sent to Claude Code (may carry [1m]); model.id is the @@ -1485,8 +1474,8 @@ async function promptAndWait( ? extractSkillsBlock(options.systemPrompt) : undefined; // Effort - const effort = options?.thinking && options.thinking !== "off" - ? REASONING_TO_EFFORT[options.thinking] : undefined; + const effort: EffortLevel | undefined = options?.thinking + ? claudeCodeEffort(model ?? {}, options.thinking) : undefined; const claudeExecutable = providerSettings.pathToClaudeCodeExecutable; @@ -1766,7 +1755,7 @@ export default function (pi: ExtensionAPI) { prompt: Type.String({ description: "The question or task for Claude Code. By default Claude sees the full conversation history. Don't research up front, let Claude explore." }), mode: Type.Optional(StringEnum(modeValues, { description: modeDesc })), model: Type.Optional(Type.String({ description: 'Claude model (e.g. "opus", "sonnet", "haiku", or full ID). Defaults to "opus".' })), - thinking: Type.Optional(StringEnum(["off", "minimal", "low", "medium", "high", "xhigh"] as const, { description: "Thinking effort level. Omit to use Claude Code's default." })), + thinking: Type.Optional(StringEnum(["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const, { description: "Thinking effort level. Omit to use Claude Code's default." })), isolated: Type.Optional(Type.Boolean({ description: "When true, Claude sees only this prompt (clean session). When false (default), Claude sees the full conversation history." })), }); pi.registerTool({ diff --git a/src/models.ts b/src/models.ts index 3eff3e3..b540570 100644 --- a/src/models.ts +++ b/src/models.ts @@ -1,40 +1,101 @@ -// Canonical selection + display order for the model picker. -// `resolveModel` returns the first partial match, so `opus` resolves to the first-listed opus entry. -// Extracted from index.ts so tests can import without activating the extension. +// Model selection + display-order policy for the model picker. The picker is +// driven by the host's anthropic catalog: models appear (and disappear) with it, +// so new Claude releases show up without a code change. Extracted from index.ts +// so tests can import without activating the extension. +// `resolveModel` resolves family shortcuts (opus/sonnet/haiku) to the newest +// matching id regardless of sort order; sort order only drives picker display. -export const MODEL_IDS_IN_ORDER = ["claude-fable-5", "claude-opus-4-8", "claude-opus-4-7", "claude-opus-4-6", "claude-sonnet-5", "claude-sonnet-4-6", "claude-haiku-4-5"]; +const TWO_HUNDRED_K_CONTEXT = 200_000; +const ONE_M_CONTEXT = 1_000_000; + +// The catalog ships dated snapshot ids (claude-opus-4-5-20251101, ...) alongside +// the bare ids. They are never exposed - and must not steal partial-match +// shortcuts like "opus-4-5" from the bare id. +function isDatedAlias(id: string): boolean { + return /-20\d{6}$/.test(id); +} + +// Family tiers for display order: flagship families first; unknown families +// sink below all known ones. +const FAMILY_ORDER = ["fable", "mythos", "opus", "sonnet", "haiku"]; + +// Version rank of a claude id, e.g. claude-opus-4-7 -> ["opus", 4, 7]. Shared by +// the display sort and resolveModel's newest-first partial tiebreak. +function versionRank(id: string): { family: string; tuple: [number, number] } { + const [, family, major, minor] = id.split("-"); + return { family, tuple: [Number(major) || 0, Number(minor) || 0] }; +} + +function compareModelIds(a: string, b: string): number { + const fa = FAMILY_ORDER.indexOf(versionRank(a).family); + const fb = FAMILY_ORDER.indexOf(versionRank(b).family); + const ta = fa === -1 ? FAMILY_ORDER.length : fa; + const tb = fb === -1 ? FAMILY_ORDER.length : fb; + if (ta !== tb) return ta - tb; + const ra = versionRank(a).tuple; + const rb = versionRank(b).tuple; + if (ra[0] !== rb[0]) return rb[0] - ra[0]; + if (ra[1] !== rb[1]) return rb[1] - ra[1]; + return a.localeCompare(b); +} -// Workaround for models that ship without a thinkingLevelMap. Sonnet 5 and -// Sonnet 4.6 have no map, so getSupportedThinkingLevels hides xhigh (it's -// opt-in). Both models' top effort tier is "max" with no real xhigh (verified -// via Claude Code's supportedModels API), so xhigh->max matches opus-4-6. +// Workaround for models whose catalog entry over-advertises xhigh. Sonnet 5 and +// Sonnet 4.6 top out at "max" with no real xhigh (verified via Claude Code's +// supportedModels API), so xhigh->max matches opus-4-6. const DEFAULT_THINKING_LEVEL_MAPS: Record> = { "claude-sonnet-5": { xhigh: "max" }, "claude-sonnet-4-6": { xhigh: "max" }, }; -// Project pi-ai's model entries down to the fields OMP's registerProvider expects, -// and keep MODEL_IDS_IN_ORDER ordering. IDs missing from pi-ai are silently dropped. -// Context-dependent display labels are applied after plan/long-context config is known. +// Project the catalog's anthropic entries down to the fields OMP's registerProvider +// expects, newest generation first. Context-dependent display labels are applied +// after plan/long-context config is known. export function buildModels(piAiModels: T[]) { - return MODEL_IDS_IN_ORDER - .map((id) => piAiModels.find((m) => m.id === id)) - .filter((m) => m != null) - // Forward thinkingLevelMap so per-model overrides (e.g. opus-4-7 mapping - // xhigh->xhigh instead of xhigh->max) are visible to the effort lookup. - .map(({ id, name, reasoning, input, contextWindow, maxTokens, thinkingLevelMap }) => ({ + return piAiModels + .filter((m) => typeof m.id === "string" && m.id.startsWith("claude-") && !isDatedAlias(m.id)) + .sort((a, b) => compareModelIds(a.id, b.id)) + // Forward thinking + thinkingLevelMap: OMP derives the selectable effort + // ladder from `thinking.efforts`, and per-model overrides (e.g. opus-4-7 + // mapping xhigh->xhigh instead of xhigh->max) feed the effort lookup. + .map(({ id, name, reasoning, input, contextWindow, maxTokens, thinking, thinkingLevelMap }) => ({ id, name, - reasoning, input, contextWindow, maxTokens, + reasoning, input, contextWindow, maxTokens, thinking, thinkingLevelMap: thinkingLevelMap ?? DEFAULT_THINKING_LEVEL_MAPS[id], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }, })); } +// Effort levels Claude Code accepts, lowest to highest. +const CLAUDE_CODE_EFFORTS = ["low", "medium", "high", "xhigh", "max"] as const; +export type ClaudeCodeEffort = (typeof CLAUDE_CODE_EFFORTS)[number]; + +// Map an OMP thinking level onto a Claude Code effort for this model. An explicit +// thinkingLevelMap entry wins; otherwise use the level itself when the model's +// catalog ladder supports it, else the highest supported effort below it. +// Without a ladder, fall back to the legacy table (xhigh->max). +export function claudeCodeEffort( + model: { thinkingLevelMap?: Record | null; thinking?: { efforts?: readonly string[] } | null }, + level: string, +): ClaudeCodeEffort | undefined { + if (level === "off" || level === "inherit") return undefined; + const mapped = model.thinkingLevelMap?.[level]; + if (mapped != null) return mapped as ClaudeCodeEffort; + const wanted = level === "minimal" ? "low" : level; + const rank = CLAUDE_CODE_EFFORTS.indexOf(wanted as ClaudeCodeEffort); + if (rank === -1) return undefined; + const efforts = model.thinking?.efforts; + if (!efforts?.length) return wanted === "xhigh" ? "max" : wanted as ClaudeCodeEffort; + for (let i = rank; i >= 0; i--) { + if (efforts.includes(CLAUDE_CODE_EFFORTS[i])) return CLAUDE_CODE_EFFORTS[i]; + } + return "low"; +} + // User-selectable context-window policy (see provider.contextWindow in config). // "auto" - per-model default policy (measured SDK behavior). -// "1m" - force 1M: only register 1M-capable models, request [1m] where needed. -// "200k" - force 200K: only register 200K-capable models, request bare model ids. +// "1m" - prefer 1M: request [1m] where the model supports it. +// "200k" - prefer 200K: request bare model ids. export type ContextWindowMode = "auto" | "1m" | "200k"; export type LongContextSettings = { @@ -48,97 +109,96 @@ export type ClaudeCodeRuntimeModel = { contextWindow: number; }; -const TWO_HUNDRED_K_CONTEXT = 200_000; -const ONE_M_CONTEXT = 1_000_000; +// A model as seen by the runtime resolvers. contextWindow is the catalog window +// and only decides 1M capability for models without a measured row below. +type RuntimeModelInput = { id: string; contextWindow?: number | null }; + +// Measured Claude Agent SDK subscription/OAuth behavior. The `[1m]` suffix is the +// reliable way to request 1M; bare ids serve 200K, except bare Opus 4.7 which +// serves 1M and has no 200K runtime. Do not infer the default from the catalog's +// advertised contextWindow: an unentitled `[1m]` id is rejected outright (400/429), +// which is worse than serving 200K, so only measured-good ids default to 1M. +const ONE_M_ONLY_BARE = new Set(["claude-opus-4-7"]); + +// 1M-capable per measurement, even where an older catalog advertises 200K. +const MEASURED_ONE_M_CAPABLE = new Set([ + "claude-fable-5-1", + "claude-fable-5", + "claude-opus-5-5", + "claude-opus-5", + "claude-opus-4-8", + "claude-opus-4-7", + "claude-opus-4-6", + "claude-sonnet-5-5", + "claude-sonnet-5", + "claude-sonnet-4-6", +]); -// Measured Claude Agent SDK subscription/OAuth behavior. Do not infer this from -// pi-ai's advertised contextWindow: bare Opus 4.7 serves 1M, bare Opus 4.8 does -// not, bare Fable 5 serves 200K while claude-fable-5[1m] serves 1M, and [1m] -// entitlement differs by model. Returns null when a model has no runtime for the -// requested forced window (that model is hidden from the picker in that mode). -export function resolveClaudeCodeRuntimeModel(modelId: string, settings: LongContextSettings): ClaudeCodeRuntimeModel | null { +// 200K-only per measurement, even if a catalog advertises more. +const MEASURED_TWO_HUNDRED_K_ONLY = new Set(["claude-haiku-4-5"]); + +// "auto" defaults to 1M for these: [1m] measured to serve 1M on every plan. +const AUTO_ONE_M = new Set([ + "claude-opus-5-5", + "claude-opus-5", + "claude-opus-4-8", + "claude-opus-4-7", + "claude-sonnet-5-5", + "claude-sonnet-5", +]); + +// "auto" defaults to 1M only when the plan allows it. +const PLAN_GATED_ONE_M: Record boolean> = { + // [1m] measured 1M on Max plan / extra usage; 429 on Pro without it. + "claude-opus-4-6": (settings) => settings.plan === "max" || settings.longContextExtraUsage, + // [1m] measured 1M with extra usage only. + "claude-sonnet-4-6": (settings) => settings.longContextExtraUsage, +}; + +function supportsOneM(model: RuntimeModelInput): boolean { + if (MEASURED_TWO_HUNDRED_K_ONLY.has(model.id)) return false; + return MEASURED_ONE_M_CAPABLE.has(model.id) || (model.contextWindow ?? 0) >= ONE_M_CONTEXT; +} + +// Returns null when a model has no runtime for the requested window. +export function resolveClaudeCodeRuntimeModel(model: RuntimeModelInput, settings: LongContextSettings): ClaudeCodeRuntimeModel | null { switch (settings.contextWindow) { case "1m": - return resolveForcedOneMRuntimeModel(modelId); + return resolveForcedOneMRuntimeModel(model); case "200k": - return resolveForcedTwoHundredKRuntimeModel(modelId); + return resolveForcedTwoHundredKRuntimeModel(model); case "auto": - return resolveAutoRuntimeModel(modelId, settings); + return resolveAutoRuntimeModel(model, settings); } } -function resolveAutoRuntimeModel(modelId: string, settings: LongContextSettings): ClaudeCodeRuntimeModel { - switch (modelId) { - case "claude-opus-4-8": - return { cliModelId: "claude-opus-4-8[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-opus-4-7": - return { cliModelId: "claude-opus-4-7", contextWindow: ONE_M_CONTEXT }; - case "claude-opus-4-6": { - const useOneM = settings.plan === "max" || settings.longContextExtraUsage; - return { - cliModelId: useOneM ? "claude-opus-4-6[1m]" : "claude-opus-4-6", - contextWindow: useOneM ? ONE_M_CONTEXT : TWO_HUNDRED_K_CONTEXT, - }; - } - case "claude-fable-5": - return { cliModelId: "claude-fable-5", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-sonnet-5": - return { cliModelId: "claude-sonnet-5[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-sonnet-4-6": - return { - cliModelId: settings.longContextExtraUsage ? "claude-sonnet-4-6[1m]" : "claude-sonnet-4-6", - contextWindow: settings.longContextExtraUsage ? ONE_M_CONTEXT : TWO_HUNDRED_K_CONTEXT, - }; - case "claude-haiku-4-5": - return { cliModelId: "claude-haiku-4-5", contextWindow: TWO_HUNDRED_K_CONTEXT }; - default: - console.error(`claude-bridge: encountered model ${modelId} with no known context size, defaulting to 200K`); - return { cliModelId: modelId, contextWindow: TWO_HUNDRED_K_CONTEXT }; - } +function resolveAutoRuntimeModel(model: RuntimeModelInput, settings: LongContextSettings): ClaudeCodeRuntimeModel | null { + const planGate = PLAN_GATED_ONE_M[model.id]; + const preferOneM = ONE_M_ONLY_BARE.has(model.id) || AUTO_ONE_M.has(model.id) || (planGate != null && planGate(settings)); + return preferOneM + ? resolveForcedOneMRuntimeModel(model) + // Unmeasured models default to bare id at 200K, the safe default. + : resolveForcedTwoHundredKRuntimeModel(model); } -function resolveForcedOneMRuntimeModel(modelId: string): ClaudeCodeRuntimeModel | null { - switch (modelId) { - case "claude-opus-4-8": - return { cliModelId: "claude-opus-4-8[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-opus-4-7": - return { cliModelId: "claude-opus-4-7", contextWindow: ONE_M_CONTEXT }; - case "claude-opus-4-6": - return { cliModelId: "claude-opus-4-6[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-fable-5": - return { cliModelId: "claude-fable-5[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-sonnet-5": - return { cliModelId: "claude-sonnet-5[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-sonnet-4-6": - return { cliModelId: "claude-sonnet-4-6[1m]", contextWindow: ONE_M_CONTEXT }; - case "claude-haiku-4-5": - return null; - default: - console.error(`claude-bridge: encountered model ${modelId} with no known 1M runtime, hiding it`); - return null; - } +function resolveForcedOneMRuntimeModel(model: RuntimeModelInput): ClaudeCodeRuntimeModel | null { + if (!supportsOneM(model)) return null; + const cliModelId = ONE_M_ONLY_BARE.has(model.id) ? model.id : `${model.id}[1m]`; + return { cliModelId, contextWindow: ONE_M_CONTEXT }; } -function resolveForcedTwoHundredKRuntimeModel(modelId: string): ClaudeCodeRuntimeModel | null { - switch (modelId) { - case "claude-opus-4-8": - return { cliModelId: "claude-opus-4-8", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-opus-4-7": - return null; - case "claude-opus-4-6": - return { cliModelId: "claude-opus-4-6", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-fable-5": - return { cliModelId: "claude-fable-5", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-sonnet-5": - return { cliModelId: "claude-sonnet-5", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-sonnet-4-6": - return { cliModelId: "claude-sonnet-4-6", contextWindow: TWO_HUNDRED_K_CONTEXT }; - case "claude-haiku-4-5": - return { cliModelId: "claude-haiku-4-5", contextWindow: TWO_HUNDRED_K_CONTEXT }; - default: - console.error(`claude-bridge: encountered model ${modelId} with no known 200K runtime, hiding it`); - return null; - } +function resolveForcedTwoHundredKRuntimeModel(model: RuntimeModelInput): ClaudeCodeRuntimeModel | null { + if (ONE_M_ONLY_BARE.has(model.id)) return null; + return { cliModelId: model.id, contextWindow: TWO_HUNDRED_K_CONTEXT }; +} + +// The window the unsuffixed id maps to: the configured preference, or the sole +// available window when the preferred one has no runtime (e.g. Haiku 4.5 under +// "1m", Opus 4.7 under "200k"). +function resolveDefaultRuntimeModel(model: RuntimeModelInput, settings: LongContextSettings): ClaudeCodeRuntimeModel | null { + return resolveClaudeCodeRuntimeModel(model, settings) + ?? resolveForcedOneMRuntimeModel(model) + ?? resolveForcedTwoHundredKRuntimeModel(model); } // Split a registered picker id into its base model id and the forced window it @@ -151,13 +211,16 @@ export function parseVariantId(id: string): { baseId: string; forced?: "1m" | "2 return { baseId: id }; } -export function claudeCodeModelId(model: { id: string }, settings: LongContextSettings): string { +// model.contextWindow is the catalog window for base entries, or the variant's +// window for registered entries; either way it resolves the same runtime. +export function claudeCodeModelId(model: RuntimeModelInput, settings: LongContextSettings): string { const { baseId, forced } = parseVariantId(model.id); + const base = { id: baseId, contextWindow: model.contextWindow }; const runtimeModel = forced === "1m" - ? resolveForcedOneMRuntimeModel(baseId) + ? resolveForcedOneMRuntimeModel(base) : forced === "200k" - ? resolveForcedTwoHundredKRuntimeModel(baseId) - : resolveClaudeCodeRuntimeModel(baseId, settings); + ? resolveForcedTwoHundredKRuntimeModel(base) + : resolveDefaultRuntimeModel(base, settings); if (runtimeModel == null) { const requested = forced ?? settings.contextWindow; throw new Error(`claude-bridge: model ${model.id} has no Claude Code runtime (contextWindow=${requested})`); @@ -167,7 +230,19 @@ export function claudeCodeModelId(model: { id: string }, settings: LongContextSe export function resolveModel(models: T[], input: string): T | undefined { const lower = input.toLowerCase(); - return models.find((m) => m.id === lower || m.id.includes(lower)); + // Exact first, then the newest partial match, so "opus" means the newest Opus + // and a longer id (claude-fable-5-1) cannot shadow an exact one (claude-fable-5). + return models.find((m) => m.id === lower) + ?? newestPartialMatch(models.filter((m) => m.id.includes(lower))); +} + +function newestPartialMatch(candidates: T[]): T | undefined { + if (candidates.length === 0) return undefined; + return candidates.reduce((best, m) => { + const [vm, vbest] = [versionRank(m.id).tuple, versionRank(best.id).tuple]; + const newer = vm[0] !== vbest[0] ? vm[0] > vbest[0] : vm[1] > vbest[1]; + return newer ? m : best; + }); } function variantName(baseName: string, contextWindow: number): string { @@ -190,30 +265,14 @@ export function buildVariantModels = []; - if (resolveForcedOneMRuntimeModel(m.id) != null) available.push({ kind: "1m", contextWindow: ONE_M_CONTEXT }); - if (resolveForcedTwoHundredKRuntimeModel(m.id) != null) available.push({ kind: "200k", contextWindow: TWO_HUNDRED_K_CONTEXT }); - - // The config default decides which window is unsuffixed; fall back to the sole - // available window when the preferred one has no runtime (e.g. Haiku under - // "1m", Opus 4.7 under "200k"). - const defaultRuntime = resolveClaudeCodeRuntimeModel(m.id, settings); - const preferredKind: "1m" | "200k" | undefined = defaultRuntime == null - ? undefined - : defaultRuntime.contextWindow === ONE_M_CONTEXT ? "1m" : "200k"; - const defaultKind = preferredKind != null && available.some((a) => a.kind === preferredKind) - ? preferredKind - : available[0].kind; + if (resolveForcedOneMRuntimeModel(m) != null) available.push({ kind: "1m", contextWindow: ONE_M_CONTEXT }); + if (resolveForcedTwoHundredKRuntimeModel(m) != null) available.push({ kind: "200k", contextWindow: TWO_HUNDRED_K_CONTEXT }); + if (available.length === 0) continue; + + // The config default decides which window is unsuffixed. + const defaultRuntime = resolveDefaultRuntimeModel(m, settings); + const defaultKind: "1m" | "200k" = defaultRuntime?.contextWindow === ONE_M_CONTEXT ? "1m" : "200k"; const ordered = [ ...available.filter((a) => a.kind === defaultKind), diff --git a/src/query-state.ts b/src/query-state.ts index 00db691..1029fab 100644 --- a/src/query-state.ts +++ b/src/query-state.ts @@ -6,7 +6,7 @@ // // Extracted from index.ts so tests can import without activating the extension. -import type { AssistantMessage, AssistantMessageEventStream, Model } from "@oh-my-pi/pi-coding-agent/extensibility/legacy-pi-ai-shim"; +import type { AssistantMessage, AssistantMessageEventStream, Model } from "@earendil-works/pi-ai"; import type { McpResult } from "./extract-tool-results.js"; export interface PendingToolCall { diff --git a/tests/unit-context-window.mjs b/tests/unit-context-window.mjs index 8bbf7b9..ed84fa7 100644 --- a/tests/unit-context-window.mjs +++ b/tests/unit-context-window.mjs @@ -1,7 +1,7 @@ import test from "node:test"; import assert from "node:assert/strict"; -import { buildVariantModels, claudeCodeModelId, parseVariantId } from "../src/models.ts"; +import { buildModels, buildVariantModels, claudeCodeEffort, claudeCodeModelId, parseVariantId, resolveModel } from "../src/models.ts"; // Minimal stand-ins for pi-ai model entries (buildVariantModels reads id, name, // contextWindow and spreads the rest through to each variant). @@ -114,6 +114,77 @@ test("claudeCodeModelId: a suffixed id forces its window regardless of config", test("claudeCodeModelId throws when a model has no runtime for the requested window", () => { assert.throws(() => claudeCodeModelId({ id: "claude-haiku-4-5-1m" }, settings("auto"))); assert.throws(() => claudeCodeModelId({ id: "claude-opus-4-7-200k" }, settings("auto"))); - assert.throws(() => claudeCodeModelId({ id: "claude-haiku-4-5" }, settings("1m"))); - assert.throws(() => claudeCodeModelId({ id: "claude-opus-4-7" }, settings("200k"))); +}); + +test("claudeCodeModelId: unsuffixed id falls back to the sole window, matching the picker entry", () => { + assert.equal(claudeCodeModelId({ id: "claude-haiku-4-5" }, settings("1m")), "claude-haiku-4-5"); + assert.equal(claudeCodeModelId({ id: "claude-opus-4-7" }, settings("200k")), "claude-opus-4-7"); +}); + +// Shaped like the host catalog's anthropic entries (incl. a dated alias). +const CATALOG = [ + { id: "claude-haiku-4-5", name: "Claude Haiku 4.5", contextWindow: 200_000, thinking: { efforts: ["minimal", "low", "medium", "high", "xhigh"] } }, + { id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", contextWindow: 200_000 }, + { id: "claude-sonnet-5-5", name: "Claude Sonnet 5.5", contextWindow: 1_000_000, thinking: { efforts: ["low", "medium", "high", "xhigh", "max"] } }, + { id: "claude-opus-5", name: "Claude Opus 5", contextWindow: 1_000_000, thinking: { efforts: ["low", "medium", "high", "xhigh", "max"] } }, + { id: "claude-opus-5-5", name: "Claude Opus 5.5", contextWindow: 1_000_000, thinking: { efforts: ["low", "medium", "high", "xhigh", "max"] } }, + { id: "claude-haiku-5-5", name: "Claude Haiku 5.5", contextWindow: 1_000_000, thinking: { efforts: ["low", "medium", "high", "xhigh", "max"] } }, + { id: "claude-fable-5-1", name: "Claude Fable 5.1", contextWindow: 1_000_000 }, + { id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", contextWindow: 1_000_000, thinking: { efforts: ["low", "medium", "high"] } }, +]; + +test("buildModels: every catalog model is kept, dated aliases dropped, newest first per family", () => { + const ids = buildModels(CATALOG).map((m) => m.id); + assert.deepEqual(ids, [ + "claude-fable-5-1", + "claude-opus-5-5", "claude-opus-5", + "claude-sonnet-5-5", "claude-sonnet-4-6", + "claude-haiku-5-5", "claude-haiku-4-5", + ]); + assert.deepEqual(buildModels(CATALOG).find((m) => m.id === "claude-opus-5-5").thinking, CATALOG[4].thinking); +}); + +test("5.5 models: Opus/Sonnet 5.5 default to 1M with a 200K alternate", () => { + const m = Object.fromEntries(buildVariantModels(buildModels(CATALOG), settings("auto")).map((v) => [v.id, v])); + assert.equal(m["claude-opus-5-5"].contextWindow, 1_000_000); + assert.equal(m["claude-opus-5-5"].name, "Claude Opus 5.5 (1M)"); + assert.equal(m["claude-opus-5-5-200k"].contextWindow, 200_000); + assert.equal(m["claude-sonnet-5-5"].contextWindow, 1_000_000); + assert.equal(m["claude-sonnet-5-5-200k"].contextWindow, 200_000); + assert.equal(claudeCodeModelId(m["claude-opus-5-5"], settings("auto")), "claude-opus-5-5[1m]"); + assert.equal(claudeCodeModelId(m["claude-opus-5-5-200k"], settings("auto")), "claude-opus-5-5"); + assert.equal(claudeCodeModelId(m["claude-sonnet-5-5"], settings("auto")), "claude-sonnet-5-5[1m]"); +}); + +test("unmeasured 1M catalog models default to 200K and offer 1M as -1m", () => { + const m = Object.fromEntries(buildVariantModels(buildModels(CATALOG), settings("auto")).map((v) => [v.id, v])); + assert.equal(m["claude-haiku-5-5"].contextWindow, 200_000); + assert.equal(m["claude-haiku-5-5-1m"].contextWindow, 1_000_000); + assert.equal(claudeCodeModelId(m["claude-haiku-5-5"], settings("auto")), "claude-haiku-5-5"); + assert.equal(claudeCodeModelId(m["claude-haiku-5-5-1m"], settings("auto")), "claude-haiku-5-5[1m]"); + assert.equal(claudeCodeModelId(m["claude-fable-5-1-1m"], settings("auto")), "claude-fable-5-1[1m]"); +}); + +test("resolveModel: family shortcuts pick the newest model; exact ids win", () => { + const models = buildModels(CATALOG); + assert.equal(resolveModel(models, "opus").id, "claude-opus-5-5"); + assert.equal(resolveModel(models, "sonnet").id, "claude-sonnet-5-5"); + assert.equal(resolveModel(models, "haiku").id, "claude-haiku-5-5"); + assert.equal(resolveModel(models, "claude-opus-5").id, "claude-opus-5"); +}); + +test("claudeCodeEffort: clamps to the model's effort ladder and supports max", () => { + const [opus55] = buildModels(CATALOG).filter((m) => m.id === "claude-opus-5-5"); + const sonnet46 = buildModels(CATALOG).find((m) => m.id === "claude-sonnet-4-6"); + const haiku45 = buildModels(CATALOG).find((m) => m.id === "claude-haiku-4-5"); + assert.equal(claudeCodeEffort(opus55, "xhigh"), "xhigh"); + assert.equal(claudeCodeEffort(opus55, "max"), "max"); + assert.equal(claudeCodeEffort(opus55, "minimal"), "low"); + assert.equal(claudeCodeEffort(opus55, "off"), undefined); + // thinkingLevelMap override (sonnet-4-6 has no real xhigh). + assert.equal(claudeCodeEffort(sonnet46, "xhigh"), "max"); + assert.equal(claudeCodeEffort(haiku45, "max"), "xhigh"); + // No ladder: legacy table. + assert.equal(claudeCodeEffort({}, "xhigh"), "max"); + assert.equal(claudeCodeEffort({}, "high"), "high"); });