Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
refactor(pi): migrate model and runtime authority to Pi 0.99.1
vastsab72ff6759255
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 5d0b0bac3..e21de2c8a 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -299,11 +299,7 @@ const updater = new AppUpdaterController({* this process; the renderer sees progress events and the sidecar sees only* resolved request auth.*/-const modelsDevCatalog = new ModelsDevCatalog({- catalogPath: app.isPackaged- ? join(process.resourcesPath, "models.dev", "api.json")- : join(app.getAppPath(), "resources", "models.dev", "api.json"),-});+const modelsDevCatalog = new ModelsDevCatalog();const vendorOAuth = new VendorOAuth({call: <T,>(method: string, params?: unknown): Promise<T> => {@@ -316,9 +312,12 @@ const vendorOAuth = new VendorOAuth({await safeOpenExternal(url);},log: (level, message, data) => logger.app("provider", level, message, { data }),- modelConfigFor: async ({ vendorKey, option }) => {+ onAccountModels: (id, models) => modelsDevCatalog.setAccountModels(id, models),+ onAccountRemoved: (id) => modelsDevCatalog.deleteAccount(id),+ modelConfigFor: async ({ providerId, vendorKey, option }) => {await modelsDevCatalog.ensureLoaded();return catalogModelConfigFor(modelsDevCatalog, {+ providerId,vendorKey,baseUrl: option.baseUrl,apiStyle: option.apiStyle,diff --git a/apps/desktop/electron/main/installation-identity.ts b/apps/desktop/electron/main/installation-identity.tsnew file mode 100644index 000000000..6d68eaf1a--- /dev/null+++ b/apps/desktop/electron/main/installation-identity.ts@@ -0,0 +1,40 @@+import { randomUUID } from "node:crypto";++/** Local-only: never include this ref in portable configuration or account data. */+const INSTALLATION_ID_REF = "secret:installation:oauth-device-id";+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;++type HostCall = <T = unknown>(method: string, params?: unknown) => Promise<T>;++/** Owned by the main-process OAuth service, not by a provider/account. */+export function createInstallationIdentity(+ call: HostCall,+ newId: () => string = randomUUID,+): () => Promise<string> {+ let pending: Promise<string> | undefined;+ return () => {+ pending ??= Promise.resolve().then(async () => {+ try {+ const { value } = await call<{ value?: string | null }>(+ "secrets.getForRuntime",+ { secretRef: INSTALLATION_ID_REF },+ );+ if (value != null) {+ if (!UUID.test(value)) throw new Error("invalid installation identity");+ return value;+ }+ const id = newId();+ if (!UUID.test(id)) throw new Error("invalid generated installation identity");+ // Never expose an identity to a flow until persistence has succeeded.+ await call("secrets.set", { secretRef: INSTALLATION_ID_REF, value: id });+ return id;+ } catch {+ // Host/backend errors may contain values. Keep failure observable but+ // do not pass their text to OAuth's renderer events or ordinary logs.+ pending = undefined;+ throw new Error("Could not load or persist the OAuth installation identity");+ }+ });+ return pending;+ };+}diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.tsindex 06bf85bee..806387b91 100644--- a/apps/desktop/electron/main/ipc/provider-ipc.ts+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts@@ -3,7 +3,6 @@ import {ErrorCodes,inferEndpointProfile,normalizeApiStyle,- resolveBindingLimits,type ModelBinding,type ProviderReorderInput,type OAuthRespondInput,@@ -14,10 +13,10 @@ import {probeDiscoveryCandidates,type DiscoveryAttempt,} from "../provider-endpoint-probe";-import { modelConfigWithBinding } from "@pi-desktop/agent-runtime";import {catalogModelConfigFor,modelInfoFromModelsDev,+ modelConfigFromModelsDev,type ModelsDevCatalog,} from "../models-dev-catalog";import type { HostProcess } from "../host-process";@@ -68,8 +67,12 @@ export type ProviderIpcDependencies = {| "loadLocal"| "getStatus"| "findModel"- | "anthropicThinkingFor"| "modelsForProvider"+ | "configureAccount"+ | "deleteAccount"+ | "modelConfigFor"+ | "settingsMetadataFor"+ | "publishedModelFor">;vendorOAuth: VendorOAuth;logger: Pick<Logger, "app">;@@ -152,7 +155,8 @@ export function registerProviderIpc({: typeof input?.baseUrl === "string" && input.baseUrl? (inferEndpointProfile({ baseUrl: input.baseUrl })?.providerKey ?? declaredKey): declaredKey;- const model = modelsDevCatalog.findModel({+ const model = (modelsDevCatalog.publishedModelFor?.bind(modelsDevCatalog) ?? modelsDevCatalog.findModel.bind(modelsDevCatalog))({+ providerId: input?.providerId,vendorKey: lookupVendorKey,baseUrl: input?.baseUrl,modelId,@@ -160,7 +164,7 @@ export function registerProviderIpc({return {info: model? modelInfoFromModelsDev(model, input?.providerId ?? "")- : null,+ : modelsDevCatalog.settingsMetadataFor?.({ providerId: input?.providerId, vendorKey: lookupVendorKey, baseUrl: input?.baseUrl, modelId }) ?? null,};},);@@ -206,6 +210,7 @@ export function registerProviderIpc({handle(IPC.invoke.providersDelete, async (id: string) => {if (!host) throw new Error("host unavailable");const result = await host.call("providers.delete", { id });+ modelsDevCatalog.deleteAccount(id);await onProviderInvalidated?.(id);return result;});@@ -342,6 +347,7 @@ export function registerProviderIpc({const provider = req.providerId? providers.find((p) => p.id === req.providerId): undefined;+ if (provider) modelsDevCatalog.configureAccount(provider);const baseUrl = (req.baseUrl ?? provider?.baseUrl ?? "").trim();const apiStyle = req.apiStyle ?? provider?.apiStyle ?? "chat_completions";/*@@ -401,31 +407,29 @@ export function registerProviderIpc({modelApiStyle: string = apiStyle,catalogBaseUrl: string = endpointBaseUrl,) => {- const modelsDevModel = modelsDevCatalog.findModel({+ const modelsDevModel = (modelsDevCatalog.publishedModelFor?.bind(modelsDevCatalog) ?? modelsDevCatalog.findModel.bind(modelsDevCatalog))({+ providerId: provider?.id,vendorKey: catalogVendorKey,baseUrl: catalogBaseUrl,modelId: model.modelId,});- const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {+ const catalogModelConfig = modelsDevModel ? modelConfigFromModelsDev(modelsDevModel, catalogBaseUrl) : catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider?.id,vendorKey: catalogVendorKey,baseUrl: catalogBaseUrl,apiStyle: modelApiStyle,modelId: model.modelId,});- const storedModel = provider ? bindingForModel(provider, model.modelId) : undefined;- const resolvedModel = resolveBindingLimits(catalogModelConfig, storedModel);- const modelConfig = modelConfigWithBinding(- resolvedModel.catalogConfig,- resolvedModel.binding,- );+ const modelConfig = catalogModelConfig;+ const operationMetadata = modelsDevCatalog.settingsMetadataFor?.({ providerId: provider?.id, vendorKey: catalogVendorKey, baseUrl: catalogBaseUrl, modelId: model.modelId });const info = modelsDevModel? modelInfoFromModelsDev(modelsDevModel, provider?.id ?? "")- : {+ : operationMetadata ?? {modelId: model.modelId,displayName: model.displayName,providerId: provider?.id ?? "",modalities: modelConfig.modalities,- reasoning: catalogModelConfig.reasoning,+ reasoning: catalogModelConfig.source === "generic" ? false : catalogModelConfig.reasoning,...(catalogModelConfig.reasoningOptions? { reasoningOptions: catalogModelConfig.reasoningOptions }: {}),@@ -434,7 +438,7 @@ export function registerProviderIpc({: {}),capabilities: ["text",- ...(catalogModelConfig.reasoning ? ["reasoning" as const] : []),+ ...(catalogModelConfig.source !== "generic" && catalogModelConfig.reasoning ? ["reasoning" as const] : []),] as Array<"text" | "tools" | "vision" | "reasoning" | "json">,supportedThinkingLevels: [...(catalogModelConfig.supportedThinkingLevels ?? [])],source: model.source ?? ("discovered" as const),@@ -444,18 +448,18 @@ export function registerProviderIpc({modelId: model.modelId,displayName: info.displayName || modelConfig.name,providerId: provider?.id ?? "",- contextWindow: modelConfig.contextWindow,- maxTokens: modelConfig.maxTokens,+ contextWindow: operationMetadata?.contextWindow ?? modelConfig.contextWindow,+ maxTokens: operationMetadata?.maxTokens ?? modelConfig.maxTokens,// Published modalities, taken before the binding is applied. This// record is what the settings panel compares its checkboxes against,// so letting a stored override shape it would make the override its// own justification and the panel could never show what models.dev// actually says.- modalities: catalogModelConfig.modalities ?? { input: ["text"], output: ["text"] },+ modalities: operationMetadata?.modalities ?? catalogModelConfig.modalities ?? { input: ["text"], output: ["text"] },// ModelInfo is catalog metadata. Keep its published reasoning fields// intact; Composer and runtime resolve the exact user binding when// they need effective per-provider capabilities.- ...(modelsDevModel ? { catalogSource: "models.dev" as const } : {}),+ ...(modelsDevModel ? { catalogSource: "pi" as const } : {}),};};diff --git a/apps/desktop/electron/main/logger.ts b/apps/desktop/electron/main/logger.tsindex 323fe83e2..7f19fa44d 100644--- a/apps/desktop/electron/main/logger.ts+++ b/apps/desktop/electron/main/logger.ts@@ -37,6 +37,7 @@ export type LogFields = {turnId?: string;toolCallId?: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;pluginId?: string;executionId?: string;@@ -59,6 +60,7 @@ export type LogRecord = {turnId?: string;toolCallId?: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;pluginId?: string;executionId?: string;diff --git a/apps/desktop/electron/main/models-dev-catalog.ts b/apps/desktop/electron/main/models-dev-catalog.tsindex a12384ec1..43da4a331 100644--- a/apps/desktop/electron/main/models-dev-catalog.ts+++ b/apps/desktop/electron/main/models-dev-catalog.ts@@ -1,103 +1,22 @@-import { readFile } from "node:fs/promises";+import { PI_VENDOR_ALIASES, relayChatMetadata, settingsOperationMetadata } from "./pi-model-metadata.ts";import {- MODEL_VENDOR_PREFIXES,- NAMED_ENDPOINT_PRESETS,- catalogModelIdsMatch,- stripReleaseSuffix,- stripVariantSuffix,-} from "@pi-desktop/shared";-import type {- ModelCost,- ModelCostTier,- ModelExperimentalMetadata,- ModelInfo,- ModelInterleaved,- ModelLimit,- ModelModalities,- ModelModality,- ModelProviderMetadata,- ModelReasoningOption,- ThinkingLevel,- ThinkingProtocol,-} from "@pi-desktop/shared";-import { genericModelConfig, type ModelConfig } from "@pi-desktop/agent-runtime";--export const MODELS_DEV_API_URL = "https://models.dev/api.json";-export const MODELS_DEV_TIMEOUT_MS = 10_000;-const LOOKUP_MEMO_LIMIT = 1_024;-const DEFAULT_CONTEXT_WINDOW = 128_000;-const DEFAULT_MAX_TOKENS = 8_192;-const DEFAULT_THINKING_LEVELS: ThinkingLevel[] = ["low", "medium", "high"];-const THINKING_LEVELS: readonly ThinkingLevel[] = [- "off",- "minimal",- "low",- "medium",- "high",- "xhigh",- "max",-];-const MODEL_MODALITIES: readonly ModelModality[] = [- "text",- "image",- "audio",- "video",- "pdf",-];--type JsonRecord = Record<string, unknown>;--export type ModelsDevProvider = {- providerKey: string;- name: string;- api?: string;- /** Published adapter package, the most reliable wire-API signal. */- npm?: string;- /** Published environment variable names that carry this provider's key. */- env: string[];- /** Provider documentation URL, when published. */- doc?: string;- models: ModelsDevModel[];-};--export type ModelsDevModel = {- providerKey: string;- providerName: string;- providerApi?: string;- /**- * Wire API published for this model (e.g. "openai-responses").- * models.dev omits it; modelFromRaw fills known ids from RESPONSES_ONLY_MODEL_IDS.- */- modelApi?: string;- modelId: string;- displayName: string;- description?: string;- family?: string;- attachment?: boolean;- reasoning: boolean;- reasoningPublished: boolean;- reasoningOptions?: ModelReasoningOption[];- thinkingProtocol?: ThinkingProtocol;- thinkingLevels: ThinkingLevel[];- modalities: ModelModalities;- modalitiesPublished: boolean;- inputPublished: boolean;- outputPublished: boolean;- toolCall?: boolean;- structuredOutput?: boolean;- temperature?: boolean;- knowledge?: string;- releaseDate?: string;- lastUpdated?: string;- openWeights?: boolean;- limit: ModelLimit;- cost?: ModelCost;- interleaved?: ModelInterleaved;- status?: string;- experimental?: ModelExperimentalMetadata;- provider?: ModelProviderMetadata;-};-+ createModels,+ getSupportedThinkingLevels,+ InMemoryModelsStore,+ type Api,+ type Model,+ type Models,+ type MutableModels,+ type ModelType,+ type ModelTypeMap,+ type Provider,+} from "@earendil-works/pi-ai";+import { builtinProviders } from "@earendil-works/pi-ai/providers/all";+import { matchNamedPreset, resolveBindingLimits, THINKING_LEVELS, type ModelBinding, type ModelInfo } from "@pi-desktop/shared";+import { genericModelConfig, modelConfigFromPi, modelConfigWithBinding, type ModelConfig } from "@pi-desktop/agent-runtime";++/** Compatibility type names only. The independent models.dev catalog is removed. */+export type ModelsDevModel = Model<Api>;export type ModelsDevCatalogStatus = {loaded: boolean;source: "bundled" | "remote" | "empty";@@ -107,1480 +26,274 @@ export type ModelsDevCatalogStatus = {modelCount: number;lastError?: string;};-export type ModelsDevCatalogOptions = {- /** Checked-in/release-packaged api.json; never a user-data path. */- catalogPath: string;- fetchImpl?: typeof fetch;- timeoutMs?: number;+ /** Accepted for existing boot callers; Pi packages own the offline catalog. */+ catalogPath?: string;+ providers?: readonly Provider[];now?: () => number;};+export type CatalogAccount = { id: string; vendorKey?: string; baseUrl?: string; apiStyle?: string; models?: ModelBinding[] };+type CatalogTarget = { providerId?: string; vendorKey?: string; baseUrl?: string; modelId: string };-function asRecord(value: unknown): JsonRecord | null {- return value && typeof value === "object" && !Array.isArray(value)- ? (value as JsonRecord)- : null;-}--function nonEmptyString(value: unknown): string | undefined {- return typeof value === "string" && value.trim() ? value.trim() : undefined;-}--function stringArray(value: unknown): string[] {- if (!Array.isArray(value)) return [];- return [- ...new Set(- value- .map((entry) => nonEmptyString(entry))- .filter((entry): entry is string => entry !== undefined),- ),- ];-}--function publishedMetadata(value: unknown): ModelProviderMetadata | undefined {- if (typeof value === "string") return nonEmptyString(value);- return asRecord(value) ?? undefined;-}--function publishedExperimental(value: unknown): ModelExperimentalMetadata | undefined {- if (typeof value === "boolean") return value;- return asRecord(value) ?? undefined;-}--function nonNegativeNumber(value: unknown): number | undefined {- return typeof value === "number" && Number.isFinite(value) && value >= 0- ? value- : undefined;-}--function nonNegativeInteger(value: unknown): number | undefined {- return typeof value === "number" &&- Number.isSafeInteger(value) &&- value >= 0 &&- value <= 0xffff_ffff- ? value- : undefined;-}--function positiveInteger(value: unknown): number | undefined {- const number = nonNegativeInteger(value);- return number !== undefined && number > 0 ? number : undefined;-}--function parseModality(value: unknown): ModelModality | undefined {- return typeof value === "string" && MODEL_MODALITIES.includes(value as ModelModality)- ? (value as ModelModality)- : undefined;-}--function parseModalities(value: unknown): {- modalities: ModelModalities;- published: boolean;- inputPublished: boolean;- outputPublished: boolean;-} {- const record = asRecord(value);- const rawInput = Array.isArray(record?.input) ? record.input : undefined;- const rawOutput = Array.isArray(record?.output) ? record.output : undefined;- const input = rawInput?.map(parseModality).filter(- (item): item is ModelModality => item !== undefined,- ) ?? [];- const output = rawOutput?.map(parseModality).filter(- (item): item is ModelModality => item !== undefined,- ) ?? [];- return {- modalities: {- input: input.length > 0 ? [...new Set(input)] : ["text"],- output: output.length > 0 ? [...new Set(output)] : ["text"],- },- published: rawInput !== undefined || rawOutput !== undefined,- inputPublished: rawInput !== undefined && input.length > 0,- outputPublished: rawOutput !== undefined && output.length > 0,- };-}--function normalizeThinkingValue(value: unknown): ThinkingLevel | undefined {- if (value === "none") return "off";- return typeof value === "string" &&- (THINKING_LEVELS as readonly string[]).includes(value)- ? (value as ThinkingLevel)- : undefined;-}--function parseReasoningOptions(value: unknown): ModelReasoningOption[] | undefined {- if (!Array.isArray(value)) return undefined;- const options = value.flatMap((entry) => {- const record = asRecord(entry);- const type = nonEmptyString(record?.type);- if (!type) return [];- const values = Array.isArray(record?.values)- ? record.values.filter(- (item): item is string | null => typeof item === "string" || item === null,- )- : undefined;- const min = nonNegativeNumber(record?.min);- const max = nonNegativeNumber(record?.max);- return [{- type,- ...(values ? { values } : {}),- ...(min !== undefined ? { min } : {}),- ...(max !== undefined ? { max } : {}),- }];- });- return options;-}--/** Convert models.dev reasoning options into the canonical UI levels. */-export function thinkingLevelsFromModelsDev(- reasoning: boolean,- options: unknown,-): ThinkingLevel[] {- if (!reasoning) return [];- const levels = new Set<ThinkingLevel>();- if (Array.isArray(options)) {- for (const option of options) {- const record = asRecord(option);- const type = nonEmptyString(record?.type);- if (type === "toggle" || type === "budget_tokens") {- levels.add("off");- levels.add("medium");- }- if (Array.isArray(record?.values)) {- for (const value of record.values) {- const level = normalizeThinkingValue(value);- if (level) levels.add(level);- }- }- }- }- return levels.size > 0- ? THINKING_LEVELS.filter((level) => levels.has(level))- : [...DEFAULT_THINKING_LEVELS];-}--function thinkingLevelMapFromModelsDev(- options: ModelReasoningOption[] | undefined,- levels: ThinkingLevel[],-): Partial<Record<ThinkingLevel, string | null>> | undefined {- if (!options?.length) return undefined;- const map: Partial<Record<ThinkingLevel, string | null>> = {};- for (const option of options) {- if (option.type === "toggle" || option.type === "budget_tokens") {- if (levels.includes("off")) map.off = "none";- if (levels.includes("medium")) map.medium = "medium";- }- for (const value of option.values ?? []) {- const level = normalizeThinkingValue(value);- if (level && typeof value === "string") map[level] = value;- }- }- // models.dev effort ladders often omit an off/none value (e.g. grok-4.6).- // Pin off=null so adapters omit reasoning when thinking is turned off,- // instead of synthesizing effort: "none" which upstream rejects (#603).- if (- Object.keys(map).length > 0 &&- map.off === undefined &&- !levels.includes("off")- ) {- map.off = null;- }- return Object.keys(map).length > 0 ? map : undefined;-}--function parseLimit(value: unknown): ModelLimit {- const record = asRecord(value);- const context = nonNegativeInteger(record?.context);- const input = nonNegativeInteger(record?.input);- const output = nonNegativeInteger(record?.output);- return {- ...(context !== undefined ? { context } : {}),- ...(input !== undefined ? { input } : {}),- ...(output !== undefined ? { output } : {}),- };-}--function parseCostTier(value: unknown): ModelCostTier | undefined {- const record = asRecord(value);- if (!record) return undefined;- const input = nonNegativeNumber(record.input);- const output = nonNegativeNumber(record.output);- const cacheRead = nonNegativeNumber(record.cache_read);- const cacheWrite = nonNegativeNumber(record.cache_write);- const tierRecord = asRecord(record.tier);- const tierType = nonEmptyString(tierRecord?.type);- const tierSize = positiveInteger(tierRecord?.size);- if (- input === undefined &&- output === undefined &&- cacheRead === undefined &&- cacheWrite === undefined &&- !tierType &&- tierSize === undefined- ) return undefined;- return {- ...(input !== undefined ? { input } : {}),- ...(output !== undefined ? { output } : {}),- ...(cacheRead !== undefined ? { cacheRead } : {}),- ...(cacheWrite !== undefined ? { cacheWrite } : {}),- ...(tierType || tierSize !== undefined- ? {- tier: {- ...(tierType ? { type: tierType } : {}),- ...(tierSize !== undefined ? { size: tierSize } : {}),- },- }- : {}),- };-}--function parseCost(value: unknown): ModelCost | undefined {- const record = asRecord(value);- if (!record) return undefined;- const input = nonNegativeNumber(record.input);- const output = nonNegativeNumber(record.output);- const cacheRead = nonNegativeNumber(record.cache_read);- const cacheWrite = nonNegativeNumber(record.cache_write);- const reasoning = nonNegativeNumber(record.reasoning);- const inputAudio = nonNegativeNumber(record.input_audio);- const outputAudio = nonNegativeNumber(record.output_audio);- const contextOver = asRecord(record.context_over_200k);- const contextOver200k = contextOver- ? {- ...(nonNegativeNumber(contextOver.input) !== undefined- ? { input: nonNegativeNumber(contextOver.input) }- : {}),- ...(nonNegativeNumber(contextOver.output) !== undefined- ? { output: nonNegativeNumber(contextOver.output) }- : {}),- ...(nonNegativeNumber(contextOver.cache_read) !== undefined- ? { cacheRead: nonNegativeNumber(contextOver.cache_read) }- : {}),- ...(nonNegativeNumber(contextOver.cache_write) !== undefined- ? { cacheWrite: nonNegativeNumber(contextOver.cache_write) }- : {}),- }- : undefined;- const tiers = Array.isArray(record.tiers)- ? record.tiers- .map(parseCostTier)- .filter((item): item is ModelCostTier => item !== undefined)- : undefined;- if (- input === undefined &&- output === undefined &&- cacheRead === undefined &&- cacheWrite === undefined &&- reasoning === undefined &&- inputAudio === undefined &&- outputAudio === undefined &&- !contextOver200k &&- !tiers?.length- ) return undefined;- return {- ...(input !== undefined ? { input } : {}),- ...(output !== undefined ? { output } : {}),- ...(cacheRead !== undefined ? { cacheRead } : {}),- ...(cacheWrite !== undefined ? { cacheWrite } : {}),- ...(reasoning !== undefined ? { reasoning } : {}),- ...(inputAudio !== undefined ? { inputAudio } : {}),- ...(outputAudio !== undefined ? { outputAudio } : {}),- ...(contextOver200k ? { contextOver200k } : {}),- ...(tiers?.length ? { tiers } : {}),- };-}--function parseInterleaved(value: unknown): ModelInterleaved | undefined {- if (typeof value === "boolean") return value;- const record = asRecord(value);- const field = nonEmptyString(record?.field);- return field ? { field } : undefined;-}--/**- * models.dev publishes no per-model wire API, yet some models only serve one.- * Keep this list to verified responses-only ids; everything else falls back- * to the provider-wide style (see #105).- */-const RESPONSES_ONLY_MODEL_IDS: ReadonlySet<string> = new Set([- "muse-spark-1.2-contributor",- "muse-spark-1.3-contributor",-]);--function modelFromRaw(- providerKey: string,- provider: JsonRecord,- modelKey: string,- raw: JsonRecord,-): ModelsDevModel | undefined {- const modelId = nonEmptyString(raw.id) ?? modelKey.trim();- if (!modelId) return undefined;- const modalityResult = parseModalities(raw.modalities);- const reasoningPublished = typeof raw.reasoning === "boolean";- const reasoning = raw.reasoning === true;- const reasoningOptions = parseReasoningOptions(raw.reasoning_options);- const thinkingProtocol: ThinkingProtocol | undefined =- providerKey === "anthropic" && reasoning &&- reasoningOptions?.some((option) => option.type === "effort") &&- !reasoningOptions.some((option) => option.type === "budget_tokens")- ? "adaptive"- : undefined;- const limit = parseLimit(raw.limit);- const experimental = publishedExperimental(raw.experimental);- const providerMetadata = publishedMetadata(raw.provider);- // Scoped to opencode-go on purpose: the same model ids exist under other- // providers (e.g. meta, llmgateway) where the completions path is correct- // and must not be rerouted (see #105).- const modelApi =- nonEmptyString(raw.api) ??- (providerKey === "opencode-go" && RESPONSES_ONLY_MODEL_IDS.has(modelId.toLowerCase())- ? "openai-responses"- : undefined);- const displayName = nonEmptyString(raw.name) ?? modelId;- const inputPublished = modalityResult.inputPublished;- const outputPublished = modalityResult.outputPublished;- return {- providerKey,- providerName: nonEmptyString(provider.name) ?? providerKey,- ...(nonEmptyString(provider.api) ? { providerApi: nonEmptyString(provider.api) } : {}),- modelId,- displayName,- ...(nonEmptyString(raw.description) ? { description: nonEmptyString(raw.description) } : {}),- ...(nonEmptyString(raw.family) ? { family: nonEmptyString(raw.family) } : {}),- ...(typeof raw.attachment === "boolean" ? { attachment: raw.attachment } : {}),- reasoning,- reasoningPublished,- ...(reasoningOptions ? { reasoningOptions } : {}),- ...(thinkingProtocol ? { thinkingProtocol } : {}),- thinkingLevels: thinkingLevelsFromModelsDev(reasoning, raw.reasoning_options),- modalities: modalityResult.modalities,- modalitiesPublished: modalityResult.published,- inputPublished,- outputPublished,- ...(typeof raw.tool_call === "boolean" ? { toolCall: raw.tool_call } : {}),- ...(typeof raw.structured_output === "boolean" ? { structuredOutput: raw.structured_output } : {}),- ...(typeof raw.temperature === "boolean" ? { temperature: raw.temperature } : {}),- ...(nonEmptyString(raw.knowledge) ? { knowledge: nonEmptyString(raw.knowledge) } : {}),- ...(nonEmptyString(raw.release_date) ? { releaseDate: nonEmptyString(raw.release_date) } : {}),- ...(nonEmptyString(raw.last_updated) ? { lastUpdated: nonEmptyString(raw.last_updated) } : {}),- ...(typeof raw.open_weights === "boolean" ? { openWeights: raw.open_weights } : {}),- limit,- ...(parseCost(raw.cost) ? { cost: parseCost(raw.cost) } : {}),- ...(parseInterleaved(raw.interleaved) !== undefined- ? { interleaved: parseInterleaved(raw.interleaved) }- : {}),- ...(nonEmptyString(raw.status) ? { status: nonEmptyString(raw.status) } : {}),- ...(experimental !== undefined ? { experimental } : {}),- ...(providerMetadata !== undefined ? { provider: providerMetadata } : {}),- ...(modelApi !== undefined ? { modelApi } : {}),- };-}--/** Parse the public models.dev document without network access. */-export function parseModelsDevCatalog(body: unknown): ModelsDevProvider[] {- const root = asRecord(body);- if (!root) throw new Error("models.dev catalog must be an object");- const providers: ModelsDevProvider[] = [];- for (const [providerKey, value] of Object.entries(root)) {- const provider = asRecord(value);- const rawModels = asRecord(provider?.models);- if (!provider || !rawModels) continue;- const parsedModels = Object.entries(rawModels).flatMap(([modelKey, modelValue]) => {- const model = asRecord(modelValue);- const parsed = model ? modelFromRaw(providerKey, provider, modelKey, model) : undefined;- return parsed ? [parsed] : [];- });- const models = [- ...new Map(parsedModels.map((model) => [model.modelId.toLowerCase(), model])).values(),- ]- .sort((a, b) => a.modelId.localeCompare(b.modelId));- if (models.length > 0) {- providers.push({- providerKey,- name: nonEmptyString(provider.name) ?? providerKey,- ...(nonEmptyString(provider.api) ? { api: nonEmptyString(provider.api) } : {}),- ...(nonEmptyString(provider.npm) ? { npm: nonEmptyString(provider.npm) } : {}),- env: stringArray(provider.env),- ...(nonEmptyString(provider.doc) ? { doc: nonEmptyString(provider.doc) } : {}),- models,- });- }- }- return providers;-}--function normalizedProviderKey(value: string | undefined): string {- return (value ?? "").trim().toLowerCase().replace(/_/g, "-");-}--function normalizedModelId(value: string): string {- return value.trim().toLowerCase();-}---function modelVendorPrefixes(model: ModelsDevModel): string[] {- const prefixes = new Set<string>();- const add = (value: unknown) => {- if (typeof value !== "string") return;- const normalized = normalizedProviderKey(value);- if (normalized) prefixes.add(normalized);- };- add(model.providerKey);- if (typeof model.provider === "string") add(model.provider);- const providerRecord = typeof model.provider === "object" ? model.provider : undefined;- add(providerRecord?.id);- const npmProvider = nonEmptyString(providerRecord?.npm);- if (npmProvider) add(npmProvider.split("/").at(-1)?.replace(/^@ai-sdk-/, ""));- const modelId = normalizedModelId(model.modelId);- for (const prefix of MODEL_VENDOR_PREFIXES) {- if (- modelId.startsWith(`${prefix}/`) ||- modelId.startsWith(`${prefix}-`) ||- modelId.startsWith(`${prefix}.`)- ) {- prefixes.add(prefix);- }- }- return [...prefixes];-}--function modelMatchesProvider(model: ModelsDevModel, vendorKey?: string): boolean {- const candidates = new Set(providerKeyCandidates(vendorKey));- if (candidates.size === 0 || candidates.has("custom")) return false;- return modelVendorPrefixes(model).some((prefix) => candidates.has(prefix));-}--const KNOWN_PROVIDER_BASE_URLS: Record<string, string[]> = {- openai: ["https://api.openai.com/v1", "https://chatgpt.com/backend-api"],- anthropic: ["https://api.anthropic.com"],- google: ["https://generativelanguage.googleapis.com/v1beta"],- mistral: ["https://api.mistral.ai/v1"],- xai: ["https://api.x.ai/v1"],- groq: ["https://api.groq.com/openai/v1"],- togetherai: ["https://api.together.xyz/v1"],- deepseek: ["https://api.deepseek.com"],- openrouter: ["https://openrouter.ai/api/v1"],- "fireworks-ai": ["https://api.fireworks.ai/inference/v1"],- "alibaba-cn": ["https://dashscope.aliyuncs.com/compatible-mode/v1"],- "moonshotai-cn": ["https://api.moonshot.cn/v1"],- "siliconflow-cn": ["https://api.siliconflow.cn/v1"],- volcengine: ["https://ark.cn-beijing.volces.com/api/v3"],- // MiniMax exposes both an Anthropic endpoint (the published models.dev- // URL) and an OpenAI-compatible `/v1` endpoint. Treat the latter as the- // same provider so a custom OpenAI-style row still inherits M3's vision- // metadata instead of falling back to a text-only generic model.- "minimax-cn": [- "https://api.minimaxi.com/v1",- "https://api.minimaxi.com/anthropic/v1",- ],- minimax: [- "https://api.minimax.io/v1",- "https://api.minimax.io/anthropic/v1",- ],-};--const PROVIDER_ALIASES: Record<string, string[]> = {- // pi-ai names the ChatGPT subscription adapter `openai-codex`, while- // models.dev publishes its model metadata under `openai`. Keep the- // transport identity in provider config, but resolve metadata through the- // corresponding public catalog provider.- "openai-codex": ["openai", "openai-codex"],- "openai-codex-responses": ["openai", "openai-codex"],- together: ["together", "togetherai"],- "together-ai": ["together", "togetherai"],- fireworks: ["fireworks", "fireworks-ai"],- "fireworks-ai": ["fireworks", "fireworks-ai"],- kimi: ["kimi-for-coding", "kimi-coding"],- "kimi-coding": ["kimi-coding", "kimi-for-coding"],- "google-vertex": ["google-vertex"],- "azure-openai-responses": ["azure", "azure-cognitive-services"],- "vercel-ai-gateway": ["vercel"],- "zai-coding-cn": ["zhipuai-coding-plan", "zai-coding-cn"],- "zhipuai-coding-plan": ["zhipuai-coding-plan", "zai-coding-cn"],- zhipu: ["zhipuai"],- bigmodel: ["zhipuai"],- dashscope: ["alibaba-cn"],- qwen: ["alibaba-cn"],- moonshot: ["moonshotai-cn", "moonshotai"],- doubao: ["volcengine"],- ark: ["volcengine"],- minimax: ["minimax-cn", "minimax"],- "lm-studio": ["lmstudio", "lm-studio"],- lmstudio: ["lmstudio", "lm-studio"],-};--function providerKeyCandidates(value: string | undefined): string[] {- const key = normalizedProviderKey(value);- return [...new Set([key, ...(PROVIDER_ALIASES[key] ?? [])])].filter(Boolean);-}--/**- * Publishers this app ships a provider for: the models.dev keys behind the- * first-class presets and the known endpoints, which mirror the providers pi-ai- * supports.- *- * They are the publishers read first when nothing identifies the row's own- * publisher. A relay's list can name an id a hundred arbitrary resellers also- * carry, and a reseller's own flags describe *its* deployment, not the one this- * row talks to; the vendors and gateways the app actually ships describe the- * model. Resellers outside this set are still read when none of these states the- * id, because the alternative is dropping a published model to the generic- * 128k text-only shape.- */-const SUPPORTED_PUBLISHER_KEYS: ReadonlySet<string> = new Set(- [- ...NAMED_ENDPOINT_PRESETS.map((preset) => preset.vendorKey),- ...Object.keys(KNOWN_PROVIDER_BASE_URLS),- ].flatMap((key) => providerKeyCandidates(key)),-);--/**- * Canonical form of a provider base URL: lowercase origin without a trailing- * slash and without the trailing API version segment, so a row configured with- * `.../v1` still matches the documented models.dev endpoint.- */export function normalizedApiUrl(value: string | undefined): string | undefined {- const raw = nonEmptyString(value);- if (!raw) return undefined;+ if (!value?.trim()) return undefined;try {- const parsed = new URL(raw);- const pathname = parsed.pathname- .replace(/\/+$/, "")- .replace(/\/(?:v1|v1beta|v1alpha)$/i, "");- return `${parsed.protocol.toLowerCase()}//${parsed.host.toLowerCase()}${pathname}`;+ const url = new URL(value);+ return `${url.origin}${url.pathname.replace(/\/+$/, "")}`.toLowerCase();} catch {return undefined;}}--/** Whether two base URLs address the same provider endpoint. */export function apiMatches(left: string | undefined, right: string | undefined): boolean {- const normalizedLeft = normalizedApiUrl(left);- const normalizedRight = normalizedApiUrl(right);- return Boolean(normalizedLeft && normalizedRight && normalizedLeft === normalizedRight);-}---/**- * Hostname of a base URL, lowercased, or undefined when it has none.- *- * Only the host is read: two paths on one host can be the same publisher's- * different API surfaces, which is exactly what `apiMatches` cannot see.- */-function hostOfUrl(value: string | undefined): string | undefined {- const raw = nonEmptyString(value);- if (!raw) return undefined;- try {- return new URL(raw).host.toLowerCase() || undefined;- } catch {- return undefined;- }-}-function isTextAgentModel(model: ModelsDevModel): boolean {- return model.modalities.input.includes("text") && model.modalities.output.includes("text");-}--function adapterInput(modalities: ModelModalities): Array<"text" | "image"> {- const input = modalities.input.filter(- (item): item is "text" | "image" => item === "text" || item === "image",- );- return input.includes("text") ? input : ["text"];-}--function capabilityList(model: ModelsDevModel): ModelInfo["capabilities"] {- const capabilities = new Set<ModelInfo["capabilities"][number]>(["text"]);- if (model.attachment === true) capabilities.add("attachments");- if (model.temperature === true) capabilities.add("temperature");- if (model.toolCall === true) capabilities.add("tools");- if (model.reasoning) capabilities.add("reasoning");- if (model.structuredOutput === true) capabilities.add("json");- for (const modality of model.modalities.input) {- if (modality === "image") capabilities.add("vision");- if (modality === "audio") capabilities.add("audio");- if (modality === "video") capabilities.add("video");- if (modality === "pdf") capabilities.add("pdf");- }- for (const modality of model.modalities.output) {- if (modality === "audio") capabilities.add("audio");- if (modality === "video") capabilities.add("video");- if (modality === "pdf") capabilities.add("pdf");- }- return [...capabilities];+ const value = normalizedApiUrl(left);+ return value !== undefined && value === normalizedApiUrl(right);}-export function modelInfoFromModelsDev(- model: ModelsDevModel,- providerId: string,-): ModelInfo {- const contextWindow = positiveInteger(model.limit.context);- const maxTokens = positiveInteger(model.limit.output);- const thinkingLevelMap = thinkingLevelMapFromModelsDev(- model.reasoningOptions,- model.thinkingLevels,- );+/** A projection, not a second metadata source. Non-chat operations never reach this shape. */+export function modelInfoFromModelsDev(model: Model<Api>, providerId: string): ModelInfo {return {- modelId: model.modelId,- displayName: model.displayName,providerId,- ...(model.description !== undefined ? { description: model.description } : {}),- ...(model.family !== undefined ? { family: model.family } : {}),- ...(model.attachment !== undefined ? { attachment: model.attachment } : {}),+ modelId: model.id,+ displayName: model.name,reasoning: model.reasoning,- ...(model.reasoningOptions !== undefined ? { reasoningOptions: model.reasoningOptions } : {}),- ...(model.thinkingProtocol !== undefined ? { thinkingProtocol: model.thinkingProtocol } : {}),- ...(thinkingLevelMap !== undefined ? { thinkingLevelMap } : {}),- ...(model.toolCall !== undefined ? { toolCall: model.toolCall } : {}),- ...(model.structuredOutput !== undefined ? { structuredOutput: model.structuredOutput } : {}),- ...(model.temperature !== undefined ? { temperature: model.temperature } : {}),- ...(model.knowledge !== undefined ? { knowledge: model.knowledge } : {}),- ...(model.releaseDate !== undefined ? { releaseDate: model.releaseDate } : {}),- ...(model.lastUpdated !== undefined ? { lastUpdated: model.lastUpdated } : {}),- modalities: model.modalities,- ...(model.openWeights !== undefined ? { openWeights: model.openWeights } : {}),- ...(Object.keys(model.limit).length > 0 ? { limit: model.limit } : {}),- ...(model.cost !== undefined ? { cost: model.cost } : {}),- ...(model.interleaved !== undefined ? { interleaved: model.interleaved } : {}),- ...(model.status !== undefined ? { status: model.status } : {}),- ...(model.experimental !== undefined ? { experimental: model.experimental } : {}),- ...(model.provider !== undefined ? { provider: model.provider } : {}),- ...(contextWindow !== undefined ? { contextWindow } : {}),- ...(maxTokens !== undefined ? { maxTokens } : {}),- capabilities: capabilityList(model),- supportedThinkingLevels: [...model.thinkingLevels],+ supportedThinkingLevels: getSupportedThinkingLevels(model),+ thinkingLevelMap: model.thinkingLevelMap,+ contextWindow: model.contextWindow,+ maxTokens: model.maxTokens,+ modalities: { input: [...model.input], output: ["text"] },+ limit: { context: model.contextWindow, output: model.maxTokens },+ // Pi's request-wide tier format is not the historical display-tier format.+ cost: {+ input: model.cost.input,+ output: model.cost.output,+ cacheRead: model.cost.cacheRead,+ cacheWrite: model.cost.cacheWrite,+ },+ capabilities: ["text", "tools", ...(model.reasoning ? ["reasoning" as const] : []), ...(model.input.includes("image") ? ["vision" as const] : [])],source: "discovered",- catalogSource: "models.dev",+ catalogSource: "pi",};}--/** Convert one complete models.dev record into the sidecar model config. */-export function modelConfigFromModelsDev(- model: ModelsDevModel,- baseUrl?: string,-): ModelConfig {- const contextWindow = positiveInteger(model.limit.context) ?? DEFAULT_CONTEXT_WINDOW;- const maxTokens = positiveInteger(model.limit.output) ?? DEFAULT_MAX_TOKENS;- const reasoning = model.reasoningPublished ? model.reasoning : false;- const thinkingLevels = reasoning ? [...model.thinkingLevels] : [];- const cost: NonNullable<ModelConfig["cost"]> = {- input: model.cost?.input ?? 0,- output: model.cost?.output ?? 0,- cacheRead: model.cost?.cacheRead ?? 0,- cacheWrite: model.cost?.cacheWrite ?? 0,- ...(model.cost?.reasoning !== undefined ? { reasoning: model.cost.reasoning } : {}),- ...(model.cost?.inputAudio !== undefined ? { inputAudio: model.cost.inputAudio } : {}),- ...(model.cost?.outputAudio !== undefined ? { outputAudio: model.cost.outputAudio } : {}),- ...(model.cost?.contextOver200k ? { contextOver200k: model.cost.contextOver200k } : {}),- ...(model.cost?.tiers ? { tiers: model.cost.tiers } : {}),- };- const config: ModelConfig = {- source: "models.dev",- name: model.displayName,- baseUrl: baseUrl ?? model.providerApi ?? "",- reasoning,- supportedThinkingLevels: thinkingLevels,- modalities: model.modalities,- limit: {- ...model.limit,- context: model.limit.context ?? contextWindow,- input: model.limit.input ?? contextWindow,- output: model.limit.output ?? maxTokens,- },- cost,- input: adapterInput(model.modalities),- contextWindow,- maxTokens,- };- if (model.description !== undefined) config.description = model.description;- if (model.family !== undefined) config.family = model.family;- if (model.attachment !== undefined) config.attachment = model.attachment;- if (model.reasoningOptions !== undefined) config.reasoningOptions = model.reasoningOptions;- if (model.thinkingProtocol !== undefined) config.thinkingProtocol = model.thinkingProtocol;- const thinkingLevelMap = thinkingLevelMapFromModelsDev(model.reasoningOptions, thinkingLevels);- if (thinkingLevelMap) config.thinkingLevelMap = thinkingLevelMap;- if (model.toolCall !== undefined) config.toolCall = model.toolCall;- if (model.structuredOutput !== undefined) config.structuredOutput = model.structuredOutput;- if (model.temperature !== undefined) config.temperature = model.temperature;- if (model.knowledge !== undefined) config.knowledge = model.knowledge;- if (model.releaseDate !== undefined) config.releaseDate = model.releaseDate;- if (model.lastUpdated !== undefined) config.lastUpdated = model.lastUpdated;- if (model.openWeights !== undefined) config.openWeights = model.openWeights;- if (model.interleaved !== undefined) config.interleaved = model.interleaved;- if (model.status !== undefined) config.status = model.status;- if (model.experimental !== undefined) config.experimental = model.experimental;- if (model.provider !== undefined) {- config.provider = model.provider;- config.catalogProvider = model.provider;- }- if (model.modelApi !== undefined) config.api = model.modelApi;- return config;+export function modelConfigFromModelsDev(model: Model<Api>, baseUrl?: string): ModelConfig {+ return { ...modelConfigFromPi(model), ...(baseUrl ? { baseUrl } : {}) };}-/**- * Sidecar model config for one provider row: the catalog record when the- * lookup resolves one, otherwise the generic shape.- *- * An Anthropic Messages row the catalog cannot identify (a custom gateway URL- * serving an id several publishers list) still needs the right thinking wire- * shape: Opus 4.7+ and the Claude 5 family reject budget thinking with a 400.- * Whether a Claude id takes adaptive or budget thinking is a property of the- * model, which Anthropic's own record states, not of the deployment. So only- * the exact Anthropic id's reasoning options transfer; limits and modalities- * stay generic because they describe the deployment (#990).- */export function catalogModelConfigFor(- catalog: Pick<ModelsDevCatalog, "findModel" | "anthropicThinkingFor">,- input: { vendorKey?: string; baseUrl?: string; apiStyle?: string; modelId: string },+ catalog: Pick<ModelsDevCatalog, "findModel"> & Partial<Pick<ModelsDevCatalog, "modelConfigFor">>,+ input: CatalogTarget & { apiStyle?: string },): ModelConfig {+ if (catalog.modelConfigFor) return catalog.modelConfigFor(input);const model = catalog.findModel(input);- if (!model) {- const generic = genericModelConfig(input.modelId, input.baseUrl ?? "");- const thinking = input.apiStyle === "anthropic_messages"- ? catalog.anthropicThinkingFor(input.modelId)- : undefined;- return thinking ? { ...generic, ...thinking } : generic;- }- const config = modelConfigFromModelsDev(model, input.baseUrl);- /*- A record that states no reasoning shape cannot speak for an Anthropic- Messages row: a record borrowed from another publisher has its own options- dropped, and a reseller's record describes the reseller's API. Anthropic's- own record is what says whether this id takes adaptive or budget thinking,- and losing that would put a rejected shape on the wire (#990).- */- const thinking = input.apiStyle === "anthropic_messages" && !config.reasoningOptions?.length- ? catalog.anthropicThinkingFor(input.modelId)- : undefined;- return thinking ? { ...config, ...thinking } : config;+ return model ? modelConfigFromModelsDev(model, input.baseUrl) : genericModelConfig(input.modelId, input.baseUrl ?? "");}-type IndexedModel = { model: ModelsDevModel; provider: ModelsDevProvider };-/**- * Per-generation candidate index built from a loaded catalog. Bounding the- * lookup by the number of distinct model ids in the catalog (not by the number- * of distinct queries) keeps the work of a single session-list read constant- * regardless of how many distinct bindings it contains: no per-query eviction- * can force an earlier key to be rescanned. It is rebuilt only when the- * provider map is replaced and is cleared on a failed or fresh load.+ * Pi catalog/Models adapter. Startup is cache-only. Each OAuth/account collection+ * remains owned by its existing account owner and can be attached without copying+ * credentials or introducing a second refresh authority. Public discovery IDs+ * still live in Rust's chat-only cache, not in a second metadata database.*/-class ModelsDevLookupIndex {- private readonly byModelId = new Map<string, IndexedModel[]>();+export class ModelsDevCatalog {+ private readonly models;+ private readonly accounts = new Map<string, MutableModels>();+ private readonly removedAccounts = new Set<string>();+ private readonly accountRows = new Map<string, CatalogAccount>();+ private readonly originalProviders = new WeakMap<Provider, Provider>();+ private readonly publishedModels = new WeakMap<Model<Api>, Model<Api>>();+ private readonly effectiveConfigs = new WeakMap<Model<Api>, ModelConfig>();+ private readonly now: () => number;+ private loaded = false;+ private fetchedAt?: string;+ private lastError?: string;+ private loading?: Promise<boolean>;++ constructor(options: ModelsDevCatalogOptions = {}) {+ this.now = options.now ?? Date.now;+ this.models = createModels({+ modelsStore: new InMemoryModelsStore(),+ // Catalog reads must never discover ambient credentials or user files.+ authContext: { env: async () => undefined, fileExists: async () => false },+ });+ for (const provider of options.providers ?? builtinProviders()) this.models.setProvider(provider);+ }- constructor(providers: ReadonlyMap<string, ModelsDevProvider>) {- for (const provider of providers.values()) {- for (const model of provider.models) {- /*- Every published model is indexed, including the audio-only ones the- listing drops: `modelsForProvider` decides which models a row- *offers*, while this index answers for an ID a row already lists, and- an endpoint that serves a TTS or ASR id has a published record for- it. Filtering here is what left such a row on the generic seed.- */- const entry: IndexedModel = { model, provider };- for (const key of registrationKeys(model.modelId)) {- let bucket = this.byModelId.get(key);- if (!bucket) {- bucket = [];- this.byModelId.set(key, bucket);- }- if (!bucket.includes(entry)) bucket.push(entry);- }- }- }+ /** Attach the account owner's existing Models; never replace its auth/store. */+ setAccountModels(providerId: string, models: MutableModels): void {+ if (this.removedAccounts.has(providerId)) return;+ this.accounts.set(providerId, models);+ const row = this.accountRows.get(providerId);+ if (row) { this.accountRows.delete(providerId); this.configureAccount(row); }+ }+ deleteAccount(providerId: string): void {+ this.removedAccounts.add(providerId);+ this.accounts.delete(providerId);+ this.accountRows.delete(providerId);}- candidates(requested: string): readonly IndexedModel[] {- const keys = lookupCandidateKeys(requested);- if (keys.length === 0) return EMPTY_CANDIDATES;- if (keys.length === 1) {- return this.byModelId.get(keys[0]) ?? EMPTY_CANDIDATES;+ /** Apply persisted explicit overrides at the Pi provider boundary, not per consumer.+ * The wrapper retains upstream auth, refresh and non-chat operations unchanged.+ * Its cache is keyed by the upstream model identity, so refresh replaces stale+ * projections and deleting an override restores the untouched upstream record.+ */+ configureAccount(row: CatalogAccount): void {+ if (this.removedAccounts.has(row.id)) return;+ const previous = this.accountRows.get(row.id);+ const signature = (value: CatalogAccount) => JSON.stringify([value.vendorKey, value.baseUrl, value.apiStyle, value.models]);+ if (previous && signature(previous) === signature(row) && this.accounts.has(row.id)) return;+ row = structuredClone(row);+ this.accountRows.set(row.id, row);+ let collection = this.accounts.get(row.id);+ if (!collection) {+ collection = createModels({ modelsStore: new InMemoryModelsStore(), authContext: { env: async () => undefined, fileExists: async () => false } });+ for (const provider of this.models.getProviders()) collection.setProvider(provider);+ this.accounts.set(row.id, collection);}- const result: IndexedModel[] = [];- const seen = new Set<IndexedModel>();- for (const key of keys) {- const bucket = this.byModelId.get(key);- if (!bucket) continue;- for (const entry of bucket) {- if (!seen.has(entry)) {- seen.add(entry);- result.push(entry);+ const key = this.providerKeyForRow(row) ?? row.vendorKey;+ const current = key ? collection.getProvider(key) : undefined;+ if (!current) return;+ const original = this.originalProviders.get(current) ?? current;+ const cache = new WeakMap<Model<Api>, Model<Api>>();+ const project = (model: Model<Api>): Model<Api> => {+ const cached = cache.get(model);+ if (cached) return cached;+ const binding = row.models?.find((entry) => entry.id.trim().toLowerCase() === model.id.trim().toLowerCase());+ const baseline = modelConfigFromPi(model);+ const limits = resolveBindingLimits(baseline, binding);+ const configured = modelConfigWithBinding(limits.catalogConfig, limits.binding);+ const selected = binding?.thinkingLevels.filter((level) => baseline.supportedThinkingLevels?.includes(level));+ const thinkingLevelMap = { ...configured.thinkingLevelMap };+ if (selected?.length) {+ for (const level of THINKING_LEVELS) {+ if (!selected.includes(level)) thinkingLevelMap[level] = null;}}- }- return result;+ // A saved unsupported level never re-enables a native null mapping (Sol+ // cannot send off/none). Keep the persisted request, normalize execution.+ for (const level of THINKING_LEVELS) {+ if (model.thinkingLevelMap?.[level] === null) thinkingLevelMap[level] = null;+ }+ const reasoning = selected?.length+ ? selected.some((level) => level !== "off")+ : model.reasoning;+ const supportedThinkingLevels = getSupportedThinkingLevels({ ...model, reasoning, thinkingLevelMap });+ const config = { ...configured, reasoning, thinkingLevelMap, supportedThinkingLevels };+ const effective = {+ ...model,+ ...config,+ id: model.id,+ provider: model.provider,+ cost: model.cost,+ };+ cache.set(model, effective);+ this.publishedModels.set(effective, model);+ this.effectiveConfigs.set(effective, config);+ return effective;+ };+ const wrapped: Provider = {+ ...original,+ getModels: () => original.getModels().map(project),+ getAllModels: () => (original.getAllModels?.() ?? original.getModels()).map((model) =>+ !model.type || model.type === "chat" ? project(model) : model),+ };+ this.originalProviders.set(wrapped, original);+ collection.setProvider(wrapped);}-}-/** Generate the exact lowercase last `/`-segment used by the catalog matcher. */-function candidateKeys(modelId: string): string[] {- const normalized = normalizedModelId(modelId);- if (!normalized) return [];- const slash = normalized.lastIndexOf("/");- const leaf = slash >= 0 ? normalized.slice(slash + 1) : normalized;- return leaf ? [leaf] : [];-}--function registrationKeys(modelId: string): string[] {- return candidateKeys(modelId);-}--function lookupCandidateKeys(requested: string): string[] {- return candidateKeys(requested);-}--const EMPTY_CANDIDATES: readonly IndexedModel[] = [];--type OfficialProviderFamily = "anthropic" | "openai" | "google" | "xai";--const OFFICIAL_PROVIDER_FAMILIES: Readonly<Record<string, OfficialProviderFamily>> = {- anthropic: "anthropic",- openai: "openai",- google: "google",- "google-ai-studio": "google",- "google-vertex": "google",- xai: "xai",- "x-ai": "xai",-};--function explicitModelSourceFamily(modelId: string): OfficialProviderFamily | undefined {- const firstSegment = normalizedModelId(modelId).split("/", 1)[0];- return OFFICIAL_PROVIDER_FAMILIES[firstSegment];-}--function isOfficialSourceProvider(entry: IndexedModel): boolean {- const providerFamily = OFFICIAL_PROVIDER_FAMILIES[normalizedProviderKey(entry.provider.providerKey)];- if (!providerFamily) return false;- const explicitSource = explicitModelSourceFamily(entry.model.modelId);- return !explicitSource || explicitSource === providerFamily;-}--function capabilitySignature(model: ModelsDevModel): string {- return JSON.stringify({- attachment: model.attachment ?? null,- temperature: model.temperature ?? null,- toolCall: model.toolCall ?? null,- structuredOutput: model.structuredOutput ?? null,- modalities: {- input: [...model.modalities.input].sort(),- output: [...model.modalities.output].sort(),- },- reasoning: model.reasoning,- reasoningOptions: model.reasoningOptions ?? null,- thinkingLevels: model.thinkingLevels,- });-}--function modelWithSharedCapabilities(- entries: readonly ModelsDevModel[],-): ModelsDevModel | undefined {- if (entries.length === 0) return undefined;- const signature = capabilitySignature(entries[0]);- if (entries.some((model) => capabilitySignature(model) !== signature)) return undefined;- return borrowedModel(entries);-}--/**- * Middle value of the numbers the publishers state. Even counts take the lower- * of the two middles, so a borrow never rounds a window up on its own.- */-function medianOf(values: readonly (number | undefined)[]): number | undefined {- const present = values.filter((value): value is number => value !== undefined);- if (present.length === 0) return undefined;- const sorted = [...present].sort((left, right) => left - right);- const middle = sorted.length >> 1;- return sorted.length % 2 === 1- ? sorted[middle]- : sorted[middle - 1];-}--/**- * Record to borrow for an id the row's own catalog provider does not publish.- *- * models.dev indexes a gateway's copy of a model under the vendor that owns- * the weights, so an endpoint serving `Vendor/Model` ids can have no record of- * its own while several other publishers state the identical id. Borrowing- * that record is what keeps such a model's context window, tool support and- * vision visible instead of dropping the row to the generic 128k text-only- * shape.- *- * Two rules keep the result honest about what the endpoint will accept:- *- * - Tool support follows the majority of the publishers that state it. One- * dissenting reseller must not decide the claim for a deployment it does not- * describe, and neither may one agreeing reseller: an id a relay lists can be- * stated by a hundred publishers, which is what left whole model lists on the- * generic seed before. An even split states no majority and claims nothing.- * - Every other capability is the *intersection*, so the borrow may only- * under-claim. Reasoning, image input and image/PDF attachment are reported- * only when every publisher states them, and a user who knows the endpoint- * does more can still turn them on in Advanced. Limits are the medians the- * publishers state, so neither one host's cap nor one host's round-up- * decides them.- */-/**- * Whether two ids name one model under different spellings.- *- * A publisher-prefixed copy (`anthropic/claude-sonnet-4-5` for- * `claude-sonnet-4-5`, `mify/mimo-v2.5-pro-0731` for `mimo-v2.5-pro`) and a- * dated or variant spelling of one id are the same model, so their records may- * be compared with each other. Two unrelated routes that happen to share a leaf- * (`provider-a/foo` vs `gateway/foo`) are not: that relation is a coincidence of- * naming, and nothing may treat it as identity.- *- * `catalogModelIdsMatch` stays the matcher of record; this only decides which of- * its matches a borrow without a provider identity may average.- */-function sameModelSpelling(catalogId: string, requested: string): boolean {- const left = catalogId.trim().toLowerCase();- const right = requested.trim().toLowerCase();- if (!left || !right) return false;- if (left === right) return true;- /*- Either side may carry a route prefix the other does not: a relay lists- `test/mimo-v2.5` where the catalog publishes `mimo-v2.5`, and a catalog that- publishes a routed copy answers for the bare id. Two *different* route paths- that merely share a leaf still never match.- */- if (left.endsWith(`/${right}`) || right.endsWith(`/${left}`)) return true;- const plain = (id: string) => stripReleaseSuffix(stripVariantSuffix(id));- const plainLeft = plain(left);- const plainRight = plain(right);- if (!plainLeft || !plainRight) return false;- return (- plainLeft === plainRight ||- plainLeft.endsWith(`/${plainRight}`) ||- plainRight.endsWith(`/${plainLeft}`)- );-}--/**- * Record to use when nothing identifies the row's provider.- *- * A relay or a gateway the catalog cannot place still serves models the catalog- * knows, and asking for one of them by id used to answer nothing at all. What- * every publisher of that model agrees on can be claimed instead: the same- * intersection and median `borrowedModel` computes for an anchored row.- *- * One thing is deliberately not claimed. Which *wire shape* a deployment accepts- * for reasoning is a property of that deployment — the same model behind an- * OpenAI-compatible gateway and behind Anthropic's own API takes different- * reasoning fields — so a record borrowed this way drops its `reasoningOptions`- * rather than speaking for an endpoint no publisher describes. `catalogModelConfigFor`- * still applies Anthropic's own shape to an Anthropic Messages row that is left- * without one.- */-function unanchoredConsensus(entries: readonly ModelsDevModel[]): ModelsDevModel | undefined {- const consensus = borrowedModel(entries);- return consensus ? { ...consensus, reasoningOptions: undefined } : undefined;-}--/**- * Which publisher's records answer for an id the row's own publisher lacks.- *- * Two preferences, in order. The app's supported publishers are read first:- * they are the vendors and gateways this app ships a provider for, so their- * records describe the model behind an id a relay lists, while a reseller's own- * flags describe its own deployment. Within that tier a record published under- * exactly this id outranks one reached through another spelling of it:- * `XiaomiMiMo/MiMo-V2.5` is the same model as `mimo-v2.5`, but a publisher that- * lists only its text half must not narrow what the model's own record states- * about vision. Only when none of them states the model does the pool widen to- * every publisher that does — siblings included, as this borrow has always read- * them — because a relay-only id would otherwise be shown as a generic 128k- * text-only row although the catalog publishes it.- */-function borrowPool(- entries: readonly IndexedModel[],- requested: string,-): readonly ModelsDevModel[] {- /*- A record under this id, or under the same id with a variant or release stamp- stripped: `mimo-v2.5` answers for `mimo-v2.5-thinking`.- */- const closestId = (value: string) =>- normalizedModelId(stripReleaseSuffix(stripVariantSuffix(value)));- const requestedClosest = closestId(requested);- const exact = (entry: IndexedModel) => {- const id = normalizedModelId(entry.model.modelId);- return id === requested || closestId(id) === requestedClosest;- };- const supported = (entry: IndexedModel) =>- SUPPORTED_PUBLISHER_KEYS.has(normalizedProviderKey(entry.provider.providerKey));- const tiers = [- entries.filter((entry) => supported(entry) && exact(entry)),- entries.filter(supported),- entries,- ];- const pool = tiers.find((tier) => tier.length > 0) ?? [];- return pool.map((entry) => entry.model);-}--/**- * Markers a deployment appends to a published id to name its own variant of it:- * a canary label, a context size, a preview channel. `test/mimo-v2.5-pro-test`- * and `gemini-2.5-pro-1m` are the published models with such a marker appended.- *- * Only a marker on this list is read that way. `-asr`, `-pro` or `-mini` name- * models of their own, so an unpublished id that carries one of those stays- * unknown instead of borrowing a sibling model's limits.- */-const DEPLOYMENT_MARKER_SUFFIXES: ReadonlySet<string> = new Set([- "test",- "staging",- "canary",- "dev",- "alpha",- "beta",- "rc",- "exp",- "experimental",- "preview",- "free",- "trial",- "thinking",- "think",- "agent",- "latest",- "1k",- "2k",- "4k",- "32k",- "64k",- "128k",- "200k",- "256k",- "512k",- "1m",- "2m",- "4m",-]);--/** The id without one trailing deployment marker, or the id unchanged. */-function dropDeploymentMarker(value: string): string {- const match = /^(.*)[-_:]([a-z0-9]+)$/i.exec(value);- if (!match) return value;- return DEPLOYMENT_MARKER_SUFFIXES.has(match[2].toLowerCase()) ? match[1] : value;-}--/**- * Published ids to read when nothing the catalog publishes matches the id the- * service serves: the id behind a route prefix, and that id without one- * deployment marker. Each is looked up as a whole published id, so nothing here- * follows a chain of aliases.- */-function fallbackLookupIds(requested: string): string[] {- const ids: string[] = [];- const push = (value: string) => {- if (value && value !== requested && !ids.includes(value)) ids.push(value);- };- const leaf = requested.slice(requested.lastIndexOf("/") + 1);- push(leaf);- push(dropDeploymentMarker(leaf));- push(dropDeploymentMarker(requested));- return ids;-}--/**- * The value most entries that state one agree on, or undefined when they split.- *- * A single dissenting publisher must not decide a claim, and a single agreeing- * one must not either: an id in a relay's list can be stated by a hundred- * resellers, and one reseller's flag is not evidence about the deployment this- * row talks to. An even split states no majority, so nothing is claimed.- */-function majorityOf(values: readonly (boolean | undefined)[]): boolean | undefined {- const stated = values.filter((value): value is boolean => value !== undefined);- if (stated.length === 0) return undefined;- const yes = stated.filter(Boolean).length;- if (yes * 2 > stated.length) return true;- if (yes * 2 < stated.length) return false;- return undefined;-}--function borrowedModel(entries: readonly ModelsDevModel[]): ModelsDevModel | undefined {- if (entries.length === 0) return undefined;- const toolCall = majorityOf(entries.map((model) => model.toolCall));- const every = (pick: (model: ModelsDevModel) => boolean | undefined): boolean | undefined =>- entries.every((model) => pick(model) === true) ? true- : entries.every((model) => pick(model) === false) ? false- : undefined;- const base = entries[0];- const keptModality = (modality: ModelModality): boolean =>- entries.every((model) => model.modalities.input.includes(modality));- const inputModalities = base.modalities.input.filter(keptModality);- const outputModalities = base.modalities.output.filter((modality) =>- entries.every((model) => model.modalities.output.includes(modality)),- );- const context = medianOf(entries.map((model) => model.limit.context));- const output = medianOf(entries.map((model) => model.limit.output));- const source = entries.find(- (model) =>- (context === undefined || model.limit.context === context) &&- (output === undefined || model.limit.output === output),- ) ?? base;- const reasoning = every((model) => model.reasoning) === true;- return {- ...source,- // Capabilities that must never be asserted on one publisher's word alone.- toolCall,- reasoning,- thinkingLevels: reasoning ? source.thinkingLevels : [],- structuredOutput: every((model) => model.structuredOutput),- attachment: every((model) => model.attachment),- modalities: {- input: inputModalities.length > 0 ? inputModalities : ["text"],- output: outputModalities.length > 0 ? outputModalities : ["text"],- },- limit: {- ...(context !== undefined ? { context } : {}),- ...(output !== undefined ? { output } : {}),- },- };-}--export class ModelsDevCatalog {- private providers = new Map<string, ModelsDevProvider>();- private lookupIndex: ModelsDevLookupIndex | undefined;- /** Host → publishers, derived from the current provider map. */- private hostIndex: Map<string, ModelsDevProvider[]> | undefined;- private readonly lookupMemo = new Map<string, ModelsDevModel | undefined>();- private loadPromise: Promise<boolean> | undefined;- private loaded = false;- private source: ModelsDevCatalogStatus["source"] = "empty";- private fetchedAt: string | undefined;- private lastError: string | undefined;- private readonly fetchImpl: typeof fetch;- private readonly timeoutMs: number;- private readonly now: () => number;- private readonly catalogPath: string;- private localLoadAttempted = false;- private localLoadPromise: Promise<boolean> | undefined;-- constructor(options: ModelsDevCatalogOptions) {- this.fetchImpl = options.fetchImpl ?? fetch;- this.timeoutMs = options.timeoutMs ?? MODELS_DEV_TIMEOUT_MS;- this.now = options.now ?? (() => Date.now());- this.catalogPath = options.catalogPath;+ modelConfigFor(input: CatalogTarget, unpublishedConfig?: ModelConfig): ModelConfig {+ const model = this.findModel(input);+ if (model) return { ...(this.effectiveConfigs.get(model) ?? modelConfigFromPi(model)), ...(input.baseUrl ? { baseUrl: input.baseUrl } : {}) };+ // Hand-typed custom IDs have no published metadata. Preserve historical+ // explicit limits without pretending that the generic seed is a catalog.+ const binding = input.providerId ? this.accountRows.get(input.providerId)?.models?.find((entry) => entry.id.trim().toLowerCase() === input.modelId.trim().toLowerCase()) : undefined;+ const limits = resolveBindingLimits(unpublishedConfig ?? genericModelConfig(input.modelId, input.baseUrl ?? ""), binding);+ return modelConfigWithBinding(limits.catalogConfig, limits.binding);}- /** Load the bundled release snapshot; this never performs network I/O. */async loadLocal(): Promise<boolean> {- if (this.localLoadPromise) return this.localLoadPromise;- if (this.localLoadAttempted) return this.loaded;- this.localLoadAttempted = true;- this.localLoadPromise = (async () => {- try {- const raw = JSON.parse(await readFile(this.catalogPath, "utf8")) as unknown;- const parsed = parseModelsDevCatalog(raw);- if (parsed.length === 0) throw new Error("models.dev snapshot contained no providers");- this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));- // Replacing the provider map invalidates the derived lookup index.- this.lookupIndex = undefined;- this.hostIndex = undefined;- this.lookupMemo.clear();- this.loaded = true;- this.source = "bundled";- this.lastError = undefined;- } catch (error) {- this.loaded = false;- this.lastError = error instanceof Error ? error.message : String(error);- }- return this.loaded;- })();- try {- return await this.localLoadPromise;- } finally {- this.localLoadPromise = undefined;- }+ if (this.loaded) return true;+ if (!this.loading) this.loading = this.models.refresh({ allowNetwork: false }).then((result) => {+ this.loaded = true;+ this.lastError = result.errors.size ? "Pi catalog cache initialization failed" : undefined;+ return this.models.getModelsOfType("chat").length > 0;+ }).finally(() => { this.loading = undefined; });+ return this.loading;}+ ensureLoaded(): Promise<boolean> { return this.loadLocal(); }- /** Ensure the release snapshot is available without contacting the network. */- async ensureLoaded(): Promise<boolean> {- return this.loadLocal();- }-- /** Refresh the in-memory snapshot for the current process; never writes user data. */async refresh(): Promise<boolean> {- if (this.loadPromise) return this.loadPromise;- this.loadPromise = (async () => {- const controller = new AbortController();- const timer = setTimeout(() => controller.abort(), this.timeoutMs);- try {- const response = await this.fetchImpl(MODELS_DEV_API_URL, {- headers: { Accept: "application/json" },- signal: controller.signal,- });- if (!response.ok) {- throw new Error(`models.dev catalog request failed (${response.status})`);- }- const parsed = parseModelsDevCatalog(await response.json());- if (parsed.length === 0) throw new Error("models.dev catalog contained no usable providers");- this.providers = new Map(parsed.map((provider) => [provider.providerKey, provider]));- // Replacing the provider map invalidates the derived lookup index.- this.lookupIndex = undefined;- this.hostIndex = undefined;- this.lookupMemo.clear();- this.loaded = true;- this.source = "remote";- this.fetchedAt = new Date(this.now()).toISOString();- this.lastError = undefined;- return true;- } catch (error) {- this.lastError = error instanceof Error ? error.message : String(error);- return false;- } finally {- clearTimeout(timer);- this.loadPromise = undefined;- }- })();- return this.loadPromise;+ await this.ensureLoaded();+ const collections = new Set<Models>([this.models, ...this.accounts.values()]);+ const results = await Promise.all([...collections].map((models) => models.refresh({ allowNetwork: true, force: true })));+ if (results.some((result) => result.aborted || result.errors.size > 0)) {+ // Error text may contain an endpoint or auth detail; do not project it to UI.+ this.lastError = "Pi model refresh failed; last-known models remain available";+ return false;+ }+ this.fetchedAt = new Date(this.now()).toISOString();+ this.lastError = undefined;+ return true;}getStatus(): ModelsDevCatalogStatus {return {loaded: this.loaded,- source: this.source,- catalogPath: this.catalogPath,- ...(this.fetchedAt ? { fetchedAt: this.fetchedAt } : {}),- providerCount: this.providers.size,- modelCount: [...this.providers.values()].reduce(- (count, provider) => count + provider.models.length,- 0,- ),- ...(this.lastError ? { lastError: this.lastError } : {}),+ source: !this.loaded ? "empty" : this.fetchedAt ? "remote" : "bundled",+ catalogPath: "@earendil-works/pi-ai",+ fetchedAt: this.fetchedAt,+ providerCount: this.models.getProviders().length,+ modelCount: this.models.getModelsOfType("chat").length,+ lastError: this.lastError,};}- private providerFor(input: { vendorKey?: string; baseUrl?: string }): ModelsDevProvider | undefined {- const candidates = new Set(providerKeyCandidates(input.vendorKey));- const apiProviders = [...this.providers.values()].filter((provider) =>- apiMatches(input.baseUrl, provider.api),- );- if (apiProviders.length > 0) {- // A shared API endpoint does not identify which publisher owns a custom- // model. Never pick the first provider simply because it was indexed first.- return apiProviders.find((provider) =>- candidates.has(normalizedProviderKey(provider.providerKey)),- ) ?? (apiProviders.length === 1 ? apiProviders[0] : undefined);- }- const knownKey = Object.entries(KNOWN_PROVIDER_BASE_URLS).find(([, urls]) =>- urls.some((url) => apiMatches(input.baseUrl, url)),- )?.[0];- if (knownKey) {- const knownCandidates = new Set(providerKeyCandidates(knownKey));- const knownProvider = [...this.providers.values()].find((provider) =>- knownCandidates.has(normalizedProviderKey(provider.providerKey)),- );- if (knownProvider) return knownProvider;- }- const byKey = [...this.providers.values()].find((provider) =>- candidates.has(normalizedProviderKey(provider.providerKey)),- );- return byKey ?? this.providerForUniqueHost(input.baseUrl);+ providerKeyForRow(input: { vendorKey?: string; baseUrl?: string }): string | undefined {+ const key = input.vendorKey?.trim().toLowerCase();+ const alias = key ? PI_VENDOR_ALIASES[key] ?? key : undefined;+ if (alias && alias !== "custom" && this.models.getProvider(alias)) return alias;+ const preset = matchNamedPreset(input);+ const presetKey = preset ? PI_VENDOR_ALIASES[preset.vendorKey] ?? preset.vendorKey : undefined;+ if (presetKey && this.models.getProvider(presetKey)) return presetKey;+ const candidates = this.models.getProviders().filter((provider) => apiMatches(provider.baseUrl, input.baseUrl));+ return candidates.length === 1 ? candidates[0].id : undefined;}- /**- * Publisher that uniquely owns this host, when nothing else identified the row.- *- * A custom endpoint on a published host is still that publisher's deployment:- * a user who types `https://open.bigmodel.cn/api/v1` for the Responses API is- * on Zhipu, not on an anonymous gateway. The catalog's own `api` host is the- * evidence, and it is only used when exactly one provider publishes from it,- * so a shared or unknown host still resolves to nothing — missing metadata- * stays ahead of wrong metadata.- *- * Built lazily from the current provider map and cleared with the lookup- * index, so it can never describe a previous catalog generation.- */- private providerForUniqueHost(baseUrl: string | undefined): ModelsDevProvider | undefined {- const host = hostOfUrl(baseUrl);- if (!host) return undefined;- if (!this.hostIndex) {- const index = new Map<string, ModelsDevProvider[]>();- for (const provider of this.providers.values()) {- const providerHost = hostOfUrl(provider.api);- if (!providerHost) continue;- const bucket = index.get(providerHost);- if (bucket) bucket.push(provider);- else index.set(providerHost, [provider]);- }- this.hostIndex = index;- }- const bucket = this.hostIndex.get(host);- return bucket?.length === 1 ? bucket[0] : undefined;+ publishedModelFor(input: CatalogTarget): Model<Api> | undefined {+ const model = this.findModel(input);+ return model ? this.publishedModels.get(model) ?? model : undefined;}- findModel(input: { vendorKey?: string; baseUrl?: string; modelId: string }): ModelsDevModel | undefined {- const requested = normalizedModelId(input.modelId);- if (!requested) return undefined;- // Resolve through the index of the current catalog generation. The candidate- // set is bounded by the catalog's model count, never by the number of- // distinct lookups a single read performs, so no eviction policy can force- if (!this.lookupIndex) this.lookupIndex = new ModelsDevLookupIndex(this.providers);- // Memoize the exact lookup so repeated reads of the same binding never re-touch- // the matched model. The memo is bounded and cleared wholesale on pressure;- // even if many distinct keys clear it mid-read, re-resolution goes through the- // small candidate index, never a full catalog scan.- const memoKey = `${input.vendorKey ?? ""}\u0000${input.baseUrl ?? ""}\u0000${requested}`;- if (this.lookupMemo.has(memoKey)) return this.lookupMemo.get(memoKey);- const preferredProvider = this.providerFor(input);- // Keep the same tie-breaking order as the scanned lookup: preferred-provider- // entries first, then the remaining providers in provider-map order.- const preferred: IndexedModel[] = [];- const rest: IndexedModel[] = [];- for (const entry of this.lookupIndex.candidates(requested)) {- (entry.provider === preferredProvider ? preferred : rest).push(entry);- }- const candidates: Array<{ model: ModelsDevModel; provider: ModelsDevProvider; score: number }> = [];- for (const { model, provider } of [...preferred, ...rest]) {- // A known endpoint must not inherit another provider's capabilities.- if (preferredProvider && provider !== preferredProvider) continue;- if (!catalogModelIdsMatch(model.modelId, requested)) continue;- const exact = model.modelId.toLowerCase() === requested;- let score = exact ? 20 : 10;- if (provider === preferredProvider) score += 100;- if (apiMatches(input.baseUrl, provider.api)) score += 80;- if (modelMatchesProvider(model, input.vendorKey)) score += 60;- candidates.push({ model, provider, score });- }- candidates.sort((left, right) =>- right.score - left.score || left.model.modelId.length - right.model.modelId.length,- );- // 0 → unmatched; 1 → enrich; ≥2 prefer unique official/source provider- // agreeing with model source; else shared identical capabilities; else unmatched.- const official = candidates.filter(isOfficialSourceProvider);- const result = candidates.length === 1- ? candidates[0].model- : official.length === 1- ? official[0].model- : modelWithSharedCapabilities(candidates.map(({ model }) => model));- /* The row's own catalog provider did not publish this id. Borrowing needs a- known provider identity to anchor on: the row resolved to a catalog- provider whose own records are authoritative, so anything missing from it- can be checked against the other publishers of the exact id instead of- dropping the model to the generic shape.-- This only fills a miss the lookup already had — a record the preferred- provider does publish stays authoritative. Without that anchor the scores- prove nothing about identity, and an unknown endpoint keeps the existing- behaviour: a unique unambiguous match, official disambiguation, shared- capabilities, or nothing. Deployment-marker / variant-suffix fallbacks- are intentionally not applied here (approved #1047 matching rules). */- const borrowed = result ??- (preferredProvider ? this.borrowedAcrossProviders(input) : undefined);- // Cache the result (a miss included) so a repeated miss is also O(1) and- // cannot grow the candidate index with query-dependent keys.- this.lookupMemo.set(memoKey, borrowed);- if (this.lookupMemo.size > LOOKUP_MEMO_LIMIT) this.lookupMemo.clear();- return borrowed;+ findModel(input: CatalogTarget): Model<Api> | undefined {+ return this.findModelOfType("chat", input);}- /**- * Exact-id fallback across catalog providers, used only when the row resolved- * to a catalog provider that published nothing for the id.- *- * A gateway's copy of a model is indexed under the vendor that owns the- * weights, so an endpoint serving `Vendor/Model` ids routinely has no record- * of its own while other publishers state the identical id. Their record is- * what keeps that model's window, tool support and vision visible.- *- * Three rules keep this from borrowing anything identity-sensitive:- *- * - A provider sharing the row's own endpoint is an alias for the row, not an- * independent source. Its failure to publish the id is an answer about this- * deployment, so nothing is borrowed past it.- * - The publishers this app ships a provider for answer before arbitrary- * resellers do, in the same order the unanchored borrow uses: an id a- * supported publisher states describes the model, while a reseller's copy- * describes its own deployment of it.- * - Only an identical id transfers, and only as a whole published id: a- * record the index reaches through an alias — a bare route leaf behind a- * prefix, a vendor-prefixed variant — describes a *different* id.- *- * `lookupId` reads the record of a published id the served name reduces to- * (`test/mimo-v2.5-pro-test` → `mimo-v2.5-pro`); it is only used when nothing- * published answered for the served id itself.- */- private borrowedAcrossProviders(- input: { vendorKey?: string; baseUrl?: string; modelId: string },- lookupId?: string,- ): ModelsDevModel | undefined {- // `findModel` already rejected an empty id; normalize here so the compare- // below is case-insensitive against the catalog's own normalization.- const requested = lookupId ?? normalizedModelId(input.modelId);- const matches: IndexedModel[] = [];- const seen = new Set<string>();- for (const candidate of this.lookupIndex?.candidates(requested) ?? []) {- const { model, provider } = candidate;- // The row's endpoint owns its own answers, including a negative one.- if (apiMatches(input.baseUrl, provider.api)) continue;- if (normalizedModelId(model.modelId) !== requested) continue;- const key = `${provider.providerKey}\u0000${model.modelId}`;- if (seen.has(key)) continue;- seen.add(key);- matches.push({ model, provider });+ findModelOfType<T extends ModelType>(type: T, input: CatalogTarget): ModelTypeMap[T] | undefined {+ if (input.providerId && this.removedAccounts.has(input.providerId)) return undefined;+ const models = (input.providerId && this.accounts.get(input.providerId)) || this.models;+ const providerId = this.providerKeyForRow(input) ?? input.vendorKey;+ if (!providerId || !models.getProvider(providerId)) {+ if (input.baseUrl && this.models.getProviders().filter(provider => apiMatches(provider.baseUrl, input.baseUrl)).length > 1) return undefined;+ return type === "chat" ? relayChatMetadata(this.models, input.modelId) as ModelTypeMap[T] | undefined : undefined;}- return borrowedModel(borrowPool(matches, requested));+ const exact = models.getModelOfType(type, providerId, input.modelId);+ if (exact) return exact;+ const id = input.modelId.trim().toLowerCase();+ return models.getModelsOfType(type, providerId).find((model) => model.id.toLowerCase() === id);}- /**- * Thinking wire metadata Anthropic publishes for exactly this id, or nothing.- * Aliases and other publishers' copies never answer: only Anthropic's own- * record states which thinking shape a Claude model accepts.- */- anthropicThinkingFor(- modelId: string,- ): Pick<ModelConfig, "reasoningOptions" | "thinkingLevelMap"> | undefined {- const requested = normalizedModelId(modelId);- const model = this.providers.get("anthropic")?.models.find(- (candidate) => normalizedModelId(candidate.modelId) === requested,- );- if (!model?.reasoning || !model.reasoningOptions?.length) return undefined;- const thinkingLevelMap = thinkingLevelMapFromModelsDev(- model.reasoningOptions,- model.thinkingLevels,- );- return {- reasoningOptions: model.reasoningOptions,- ...(thinkingLevelMap ? { thinkingLevelMap } : {}),- };+ settingsMetadataFor(input: CatalogTarget): ModelInfo | undefined {+ const vendor = this.providerKeyForRow(input);+ return settingsOperationMetadata(input.providerId ?? "", vendor, input.modelId)[0];}- modelsForProvider(input: {- vendorKey?: string;- baseUrl?: string;- providerId: string;- /**- * Include the models this provider publishes next to its chat models —- * embedding, speech, image and reranking endpoints. The settings picker- * asks for them because it renders the service's own catalog of what the- * credential can call; session and agent paths keep the default, which is- * the text models they can actually run.- */- includeNonChat?: boolean;- }): ModelInfo[] {- const preferredProvider = this.providerFor(input);- const providers = preferredProvider- ? [preferredProvider]- : [...this.providers.values()].filter((provider) =>- provider.models.some((model) => modelMatchesProvider(model, input.vendorKey)),- );- const seen = new Set<string>();- return providers.flatMap((provider) =>- provider.models- .filter((model) => {- const key = normalizedModelId(model.modelId);- if (seen.has(key)) return false;- if (!input.includeNonChat && !isTextAgentModel(model)) return false;- if (!preferredProvider && !modelMatchesProvider(model, input.vendorKey)) return false;- seen.add(key);- return true;- })- .map((model) => modelInfoFromModelsDev(model, input.providerId)),- );- }-- /** models.dev provider key for a configured row, when the catalog knows it. */- providerKeyForRow(input: { vendorKey?: string; baseUrl?: string }): string | undefined {- return this.providerFor(input)?.providerKey;+ modelsForProvider(input: { providerId: string; vendorKey?: string; baseUrl?: string; includeNonChat?: boolean }): ModelInfo[] {+ if (this.removedAccounts.has(input.providerId)) return [];+ const models = this.accounts.get(input.providerId) ?? this.models;+ const providerId = this.providerKeyForRow(input) ?? input.vendorKey;+ if (!providerId) return [];+ const chat = models.getModelsOfType("chat", providerId).map((model) => modelInfoFromModelsDev(model, input.providerId));+ if (!input.includeNonChat) return chat;+ const seen = new Set(chat.map(model => model.modelId.toLowerCase()));+ const extra = settingsOperationMetadata(input.providerId, providerId).filter(model => !seen.has(model.modelId.toLowerCase()));+ return [...chat, ...extra];}}diff --git a/apps/desktop/electron/main/oauth.ts b/apps/desktop/electron/main/oauth.tsindex e2b6bd6dd..6b7ba2945 100644--- a/apps/desktop/electron/main/oauth.ts+++ b/apps/desktop/electron/main/oauth.ts@@ -17,6 +17,7 @@*/import { randomUUID } from "node:crypto";+import { createInstallationIdentity } from "./installation-identity.ts";import { getSupportedThinkingLevels, InMemoryModelsStore } from "@earendil-works/pi-ai";import type {@@ -36,6 +37,7 @@ import { builtinModels } from "@earendil-works/pi-ai/providers/all";import {capabilitiesFromModelConfig,genericModelConfig,+ modelConfigFromPi,installProviderHeadersFetch,runWithProviderHeaders,type ModelConfig,@@ -94,6 +96,10 @@ export function apiStyleForWireApi(api: string): string {return API_STYLE_BY_WIRE_API[api] ?? "chat_completions";}+function wireApiForStyle(style: string): Api {+ return Object.entries(API_STYLE_BY_WIRE_API).find(([, value]) => value === style)?.[0] ?? "openai-completions";+}+export function protocolForApiStyle(apiStyle: string): string {return PROTOCOL_BY_API_STYLE[apiStyle] ?? "openai_compatible";}@@ -142,10 +148,16 @@ export type VendorOAuthDeps = {message: string,data?: Record<string, unknown>,) => void;+ /** Stable local installation identity, owned by Host secrets. */+ getInstallationId?: () => Promise<string>;+ /** Share account-owned Models with the catalog without duplicating credentials. */+ onAccountModels?: (providerId: string, models: MutableModels) => void;+ onAccountRemoved?: (providerId: string) => void;/** Test seam: build the pi-ai collection without touching the real flows. */createModels?: (credentials: CredentialStore) => MutableModels;/** Model configuration is supplied by the main-process models.dev catalog. */modelConfigFor?: (input: {+ providerId: string;vendorKey: string;option: OAuthModelOption;}) => Promise<ModelConfig | undefined>;@@ -173,6 +185,7 @@ type AccountModels = {providerId: string;vendorId: string;models: MutableModels;+ pinnedProvider?: Provider;};type LoginSession = {@@ -222,9 +235,11 @@ export class VendorOAuth {private readonly chains = new Map<string, Promise<unknown>>();private catalogPromise?: Promise<MutableModels>;private oauthFlowsRegistered = false;+ private readonly getInstallationId: () => Promise<string>;constructor(deps: VendorOAuthDeps) {this.deps = deps;+ this.getInstallationId = deps.getInstallationId ?? createInstallationIdentity(deps.call);installProviderHeadersFetch();}@@ -343,10 +358,11 @@ export class VendorOAuth {this.cancel(running.loginId);await running.finished?.catch(() => undefined);}+ await this.deps.call("providers.delete", { id: providerId });this.accountModels.delete(providerId);+ this.deps.onAccountRemoved?.(providerId);this.liveModelCache.delete(providerId);this.liveModelLoads.delete(providerId);- await this.deps.call("providers.delete", { id: providerId });}/**@@ -377,8 +393,6 @@ export class VendorOAuth {if (!account) throw new Error(`unknown vendor account provider: ${providerId}`);// Dynamic catalogs (radius) are empty until refreshed.await account.models.refresh({ providers: [account.vendorId] });- const live = await this.liveAccountModels(account);- if (live) return live;const available = await account.models.getAvailable(account.vendorId);return available.map((model) => this.optionFor(model));});@@ -416,19 +430,8 @@ export class VendorOAuth {): Promise<VendorModelBinding | undefined> {const account = await this.accountForProvider(providerId);if (!account) return undefined;- let model = account.models.getModel(account.vendorId, modelId);- if (!model) {- await account.models.refresh({ providers: [account.vendorId] });- model = account.models.getModel(account.vendorId, modelId);- }- const live = await this.liveAccountModels(account);- if (live) {- const option = live.find((item) => item.modelId === modelId);- // A successful account list replaces the pinned catalog. An id it did- // not return is not offered, even when pi-ai still ships that id.- if (!option) return undefined;- return this.bindingFromOption(account, option);- }+ await account.models.refresh({ providers: [account.vendorId] });+ const model = account.models.getModel(account.vendorId, modelId);if (!model) return undefined;return this.bindingFromOption(account, this.optionFor(model));}@@ -450,17 +453,19 @@ export class VendorOAuth {const pending = this.liveModelLoads.get(account.providerId);if (pending) return pending;const load = this.loadLiveAccountModels(account).finally(() => {- this.liveModelLoads.delete(account.providerId);+ if (this.liveModelLoads.get(account.providerId) === load) this.liveModelLoads.delete(account.providerId);});this.liveModelLoads.set(account.providerId, load);return load;}private rememberLiveModels(- providerId: string,+ account: AccountModels,models: OAuthModelOption[] | null,): OAuthModelOption[] | undefined {- this.liveModelCache.set(providerId, { at: Date.now(), models });+ if (this.accountModels.get(account.providerId) === account) {+ this.liveModelCache.set(account.providerId, { at: Date.now(), models });+ }return models ?? undefined;}@@ -489,8 +494,8 @@ export class VendorOAuth {try {const body = await readVendorModelList(request, this.deps.fetch ?? globalThis.fetch);const ids = parseVendorModelIds(account.vendorId, body, request.allowPolicyFallback);- if (!ids || ids.length === 0) return this.rememberLiveModels(account.providerId, null);- const pinned = await account.models.getAvailable(account.vendorId);+ if (!ids || ids.length === 0) return this.rememberLiveModels(account, null);+ const pinned = account.pinnedProvider?.getModels() ?? await account.models.getAvailable(account.vendorId);const known = new Map(pinned.map((model) => [model.id, model]));const wires = pinned.map((model) => ({id: model.id,@@ -508,8 +513,8 @@ export class VendorOAuth {baseUrl: wire.baseUrl,}];});- if (models.length === 0) return this.rememberLiveModels(account.providerId, null);- return this.rememberLiveModels(account.providerId, models);+ if (models.length === 0) return this.rememberLiveModels(account, null);+ return this.rememberLiveModels(account, models);} catch (error) {this.log("warn", "vendor account model list failed", {vendorId: account.vendorId,@@ -518,7 +523,7 @@ export class VendorOAuth {? { status: error.status, responseExcerpt: error.responseExcerpt }: {}),});- return this.rememberLiveModels(account.providerId, null);+ return this.rememberLiveModels(account, null);}}@@ -527,6 +532,7 @@ export class VendorOAuth {option: OAuthModelOption,): Promise<VendorModelBinding> {const published = await this.deps.modelConfigFor?.({+ providerId: account.providerId,vendorKey: account.vendorId,option,}).catch(() => undefined);@@ -552,7 +558,7 @@ export class VendorOAuth {): Promise<ModelConfig> {const config = published ?? genericModelConfig(option.modelId, option.baseUrl);if (config.source !== "generic") return config;- const pinned = await account.models.getAvailable(account.vendorId);+ const pinned = account.pinnedProvider?.getModels() ?? await account.models.getAvailable(account.vendorId);if (pinned.some((model) => model.id === option.modelId)) return config;const siblingId = pinnedSiblingId(account.vendorId,@@ -586,11 +592,14 @@ export class VendorOAuth {private async run(session: LoginSession, provider: Provider): Promise<void> {try {+ const installationId = await this.getInstallationId();+ session.controller.signal.throwIfAborted();await this.withRowHeaders(session.providerId, () =>session.account.models.login(session.vendorId,"oauth",this.interactionFor(session),+ { getDeviceId: () => installationId },),);const accountLabel = provider.auth.oauth?.name || provider.name;@@ -673,9 +682,12 @@ export class VendorOAuth {private async discardRow(session: LoginSession): Promise<void> {if (!session.createdRow) return;- this.accountModels.delete(session.providerId);try {await this.deps.call("providers.delete", { id: session.providerId });+ this.accountModels.delete(session.providerId);+ this.liveModelCache.delete(session.providerId);+ this.liveModelLoads.delete(session.providerId);+ this.deps.onAccountRemoved?.(session.providerId);} catch (error) {this.log("warn", "could not remove the half-created provider row", {vendorId: session.vendorId,@@ -816,6 +828,7 @@ export class VendorOAuth {}return builtinModels({credentials,+ authContext: { env: async () => undefined, fileExists: async () => false },modelsStore: new InMemoryModelsStore(),});}@@ -823,12 +836,45 @@ export class VendorOAuth {private createAccount(vendorId: string, providerId: string): AccountModels {const existing = this.accountModels.get(providerId);if (existing) return existing;- const account = {+ const account: AccountModels = {providerId,vendorId,models: this.createModels(this.credentialsFor(providerId, vendorId)),};+ const original = account.models.getProvider(vendorId);+ account.pinnedProvider = original;+ if (original && vendorId !== "radius") {+ let offered: Model<Api>[] | undefined;+ account.models.setProvider({+ ...original,+ getModels: () => offered ?? original.getModels(),+ getAllModels: () => [...(offered ?? original.getModels()), ...(original.getAllModels?.() ?? []).filter(model => model.type && model.type !== "chat")],+ // The successful live list is the account's entitlement authority.+ filterModels: (models, credential) => offered ? models : original.filterModels?.(models, credential) ?? models,+ refreshModels: async context => {+ await original.refreshModels?.(context);+ if (!context.allowNetwork) return;+ context.signal.throwIfAborted();+ if (context.force) this.liveModelCache.delete(providerId);+ const live = await this.withRowHeaders(providerId, () => this.liveAccountModels(account));+ if (!live) return;+ const projected = await Promise.all(live.map(async option => {+ const known = original.getModels().find(model => model.id === option.modelId);+ const config = known ? modelConfigFromPi(known) : await this.withPinnedSiblingFallback(account, option, undefined);+ return {+ ...config, id: option.modelId, provider: vendorId,+ api: wireApiForStyle(option.apiStyle), baseUrl: option.baseUrl,+ // A sibling supplies capabilities, never the price of a new ID.+ cost: known?.cost ?? { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN },+ } as Model<Api>;+ }));+ context.signal.throwIfAborted();+ await context.publish({ update: () => { offered = projected; } });+ },+ });+ }this.accountModels.set(providerId, account);+ this.deps.onAccountModels?.(providerId, account.models);return account;}@@ -843,8 +889,6 @@ export class VendorOAuth {private async accountForProvider(providerId: string,): Promise<AccountModels | undefined> {- const existing = this.accountModels.get(providerId);- if (existing) return existing;const row = (await this.rows()).find((candidate) =>candidate.id === providerId &&diff --git a/apps/desktop/electron/main/persistence-outbox.ts b/apps/desktop/electron/main/persistence-outbox.tsindex f471aba48..3aa8b0223 100644--- a/apps/desktop/electron/main/persistence-outbox.ts+++ b/apps/desktop/electron/main/persistence-outbox.ts@@ -5,7 +5,8 @@ import type { HostProcess } from "./host-process";type MessageAppend = {key: string;sessionId: string;- message: unknown;+ message?: unknown;+ usage?: unknown;turnId?: string;};@@ -89,9 +90,9 @@ export class PersistenceOutbox {const currentHost = getHost();if (!currentHost || !currentHost.isAvailable()) return;try {- await currentHost.call("session.appendMessage", {+ await currentHost.call(current.usage ? "session.recordUsage" : "session.appendMessage", {sessionId: current.sessionId,- message: current.message,+ ...(current.usage ? { usage: current.usage } : { message: current.message }),turnId: current.turnId,});} catch (error) {@@ -146,7 +147,7 @@ export class PersistenceOutbox {entry &&typeof entry.key === "string" &&typeof entry.sessionId === "string" &&- "message" in entry+ ("message" in entry || ("usage" in entry && typeof entry.turnId === "string")));});}diff --git a/apps/desktop/electron/main/pi-model-metadata.ts b/apps/desktop/electron/main/pi-model-metadata.tsnew file mode 100644index 000000000..90f9950fc--- /dev/null+++ b/apps/desktop/electron/main/pi-model-metadata.ts@@ -0,0 +1,52 @@+import type { Api, Model, Models } from "@earendil-works/pi-ai";+import type { ModelInfo, ModelModality } from "@pi-desktop/shared";+import operationMetadata from "./settings-operation-metadata.json" with { type: "json" };++// Desktop preset IDs predate Pi's namespaces. These aliases select a Pi provider;+// they never change the user's endpoint or on-wire model ID.+export const PI_VENDOR_ALIASES: Record<string, string> = {+ zhipuai: "zai", "zhipuai-coding-plan": "zai-coding-cn",+ "zai-coding-plan": "zai-coding-plan",+};++const publishers: Record<string, string> = {+ claude: "anthropic", gpt: "openai", o1: "openai", o3: "openai", o4: "openai",+ gemini: "google", grok: "xai",+};+const leaf = (id: string) => id.toLowerCase().split("/").at(-1);+const capabilities = (m: Model<Api>) => JSON.stringify([m.input, m.reasoning, m.contextWindow, m.maxTokens, m.thinkingLevelMap]);++/** Exact leaves only; ambiguous deployments remain unknown. No suffix stripping. */+export function relayChatMetadata(models: Models, id: string): Model<Api> | undefined {+ const requested = leaf(id.trim());+ const hits = models.getModelsOfType("chat").filter(model => leaf(model.id) === requested);+ if (!hits.length) return undefined;+ const publisher = publishers[requested?.split(/[-.]/)[0] ?? ""];+ const official = hits.filter(model => model.provider === publisher);+ if (official.length === 1) return official[0];+ return hits.every(model => capabilities(model) === capabilities(hits[0])) ? hits[0] : undefined;+}++/**+ * Display-only compatibility data for speech/embedding/image settings rows that+ * Pi 0.99.1 does not publish. It has no auth, prices, refresh, routing or dispatch.+ * Chat selection and typed Pi operation lookups never consult this data.+ */+export function settingsOperationMetadata(providerId: string, vendor?: string, id?: string): ModelInfo[] {+ const candidates = operationMetadata.filter(row =>+ (!vendor || row.vendor === vendor) && (!id || leaf(row.id) === leaf(id.trim())));+ const unique = new Map<string, typeof candidates>();+ for (const row of candidates) {+ const key = id ? id.trim().toLowerCase() : row.id;+ unique.set(key, [...(unique.get(key) ?? []), row]);+ }+ return [...unique.values()].flatMap(rows => {+ const row = rows[0];+ if (!rows.every(other => JSON.stringify([other.modalities, other.contextWindow, other.maxTokens]) === JSON.stringify([row.modalities, row.contextWindow, row.maxTokens]))) return [];+ const modalities = { input: row.modalities.input as ModelModality[], output: row.modalities.output as ModelModality[] };+ return [{ providerId, modelId: id ?? row.id, displayName: row.name, modalities,+ contextWindow: row.contextWindow, maxTokens: row.maxTokens,+ capabilities: [...new Set([...modalities.input, ...modalities.output])].filter((mode): mode is "text" | "audio" | "video" => mode === "text" || mode === "audio" || mode === "video"),+ source: "bundled" as const }];+ });+}diff --git a/apps/desktop/electron/main/remote/remote-event-bridge.ts b/apps/desktop/electron/main/remote/remote-event-bridge.tsindex fcac20a20..bb10fd09d 100644--- a/apps/desktop/electron/main/remote/remote-event-bridge.ts+++ b/apps/desktop/electron/main/remote/remote-event-bridge.ts@@ -110,6 +110,7 @@ function toToolPermissionRequest(reason: approval.summary,...(approval.agentName ? { agentName: approval.agentName } : {}),...(approval.parentToolCallId ? { parentToolCallId: approval.parentToolCallId } : {}),+ ...(approval.nestedParentToolCallId ? { nestedParentToolCallId: approval.nestedParentToolCallId } : {}),};}@@ -154,6 +155,7 @@ export function createRemoteEventBridge(options: RemoteEventBridgeOptions): Remots: Date.parse(envelope.occurredAt) || Date.now(),event,...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),};emit(IPC.event.agentMessage, local);diff --git a/apps/desktop/electron/main/runtime/event-persistence.ts b/apps/desktop/electron/main/runtime/event-persistence.tsindex d7ae32504..1be3e5d4b 100644--- a/apps/desktop/electron/main/runtime/event-persistence.ts+++ b/apps/desktop/electron/main/runtime/event-persistence.ts@@ -1,4 +1,5 @@-import { applyMessageUpdate, type AgentEventEnvelope, type UiMessage } from "@pi-desktop/shared";+import { createHash } from "node:crypto";+import { usageForEvent, ownsUsageTurn, applyMessageUpdate, tagMessageToolLineage, toolCallLineage, type AgentEventEnvelope, type UiMessage } from "@pi-desktop/shared";import type { FinishTurn } from "./plans";import type { RuntimeState } from "./context";import type { InflightCheckpointer } from "@pi-desktop/host-runtime";@@ -56,18 +57,27 @@ export function createEventPersistence({} {const inflightSnapshots = new Map<string, UiMessage>();function subagentTagged(message: UiMessage, envelope: AgentEventEnvelope): UiMessage {- if (!envelope.parentToolCallId) return message;- return {- ...message,- parentToolCallId: envelope.parentToolCallId,- ...(envelope.agentName ? { agentName: envelope.agentName } : {}),- };+ return tagMessageToolLineage(message, envelope);}function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined {const event = envelope.event;const turnId = activeTurns.get(envelope.sessionId);+ const usage = usageForEvent(envelope);+ if (usage) {+ if (ownsUsageTurn(envelope, turnId)) addActiveTurnUsage(envelope.sessionId, usage);+ const usageTurnId = envelope.turnId ?? turnId;+ if (usageTurnId && (usage.operationId || usage.operations?.length)) {+ void persistenceOutbox.enqueue({+ key: `usage:${envelope.sessionId}:${usageTurnId}:${createHash("sha256").update(JSON.stringify(usage)).digest("hex")}`,+ sessionId: envelope.sessionId, turnId: usageTurnId, usage,+ }, () => runtimeState.host).catch((error: unknown) => {+ logger.app("persistence", "warn", "usage enqueue failed", { sessionId: envelope.sessionId, data: String(error) });+ });+ }+ }+const executionId = (() => {const candidate = approvedExecutionIdsBySession.get(envelope.sessionId);if (!candidate) return undefined;@@ -119,10 +129,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefinedargs: event.args,createdAt: new Date(envelope.ts).toISOString(),turnId: envelope.turnId ?? turnId,- ...(envelope.parentToolCallId- ? { parentToolCallId: envelope.parentToolCallId }- : {}),- ...(envelope.agentName ? { agentName: envelope.agentName } : {}),+ ...toolCallLineage(envelope),});if ((event.toolName === "SubmitPlan" || event.toolName === "SubmitGoal") &&@@ -232,9 +239,6 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined})();return;}- if (event.type === "turn_end" && !envelope.parentToolCallId) {- addActiveTurnUsage(envelope.sessionId, event.subagentUsage);- }if (event.type === "message_end" && event.message.role === "user" && !envelope.parentToolCallId) {// Reserve the current reply before persisting input accepted during its stream.const preceding = event.precedingAssistant?.role === "assistant"@@ -253,9 +257,6 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined}}if (event.type === "message_end" && event.message.role === "assistant") {- if (!envelope.parentToolCallId && event.message.usage) {- addActiveTurnUsage(envelope.sessionId, event.message.usage);- }// Checkpoint the finished snapshot before the outbox append (D327).// Settling first dropped the last interval of text, and endTurn used to// delete the host file while the final row was still queued.@@ -343,10 +344,7 @@ function persistAgentEvent(envelope: AgentEventEnvelope): UiMessage | undefined: undefined,isError: event.isError,status: "complete",- ...(started?.parentToolCallId- ? { parentToolCallId: started.parentToolCallId }- : {}),- ...(started?.agentName ? { agentName: started.agentName } : {}),+ ...toolCallLineage(started ?? {}, envelope),};void persistenceOutbox.enqueue(diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.tsindex a94e52449..ce5e05680 100644--- a/apps/desktop/electron/main/runtime/host.ts+++ b/apps/desktop/electron/main/runtime/host.ts@@ -133,6 +133,9 @@ export function createHostRuntime({...(asking?.parentToolCallId? { parentToolCallId: asking.parentToolCallId }: {}),+ ...(asking?.nestedParentToolCallId+ ? { nestedParentToolCallId: asking.nestedParentToolCallId }+ : {}),},},};diff --git a/apps/desktop/electron/main/runtime/provider-catalog.ts b/apps/desktop/electron/main/runtime/provider-catalog.tsindex afb46d462..5dcdba2e8 100644--- a/apps/desktop/electron/main/runtime/provider-catalog.ts+++ b/apps/desktop/electron/main/runtime/provider-catalog.ts@@ -3,7 +3,6 @@ import {SESSION_THINKING_LEVELS,defaultCommandShellForPlatform,isCommandShellId,- resolveBindingLimits,validateNetworkProxy,validateSpeechSettings,type CommandShellId,@@ -12,7 +11,7 @@ import {} from "@pi-desktop/shared";import {capabilitiesFromModelConfig,- modelConfigWithBinding,+ type ModelConfig,visionFromModelConfig,type ThinkingCapabilities,} from "@pi-desktop/agent-runtime";@@ -78,6 +77,7 @@ export function createProviderCatalogRuntime({const modelsDevModelFor = (provider: RuntimeProvider, modelId: string) =>modelsDevCatalog.findModel({+ providerId: provider.id,vendorKey: provider.vendorKey,baseUrl: provider.baseUrl,modelId,@@ -89,22 +89,15 @@ export function createProviderCatalogRuntime({* the effective thinking capability for the endpoint.*/const effectiveSubagentModelConfig = (- provider: Pick<RuntimeProvider, "models">,+ provider: RuntimeProvider,modelId: string,- catalogModelConfig: Parameters<typeof modelConfigWithBinding>[0],+ catalogModelConfig?: ModelConfig,) => {- const resolved = resolveBindingLimits(- catalogModelConfig,- bindingForModel(provider, modelId),- );- const modelConfig = modelConfigWithBinding(- resolved.catalogConfig,- resolved.binding,- );- return {- modelConfig,- capabilities: capabilitiesFromModelConfig(modelConfig),- };+ modelsDevCatalog.configureAccount(provider);+ const modelConfig = modelsDevCatalog.modelConfigFor({+ providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,+ }, catalogModelConfig);+ return { modelConfig, capabilities: capabilitiesFromModelConfig(modelConfig) };};const enrichProvider = <T extends RuntimeProvider>(@@ -117,55 +110,20 @@ export function createProviderCatalogRuntime({provider.models?.[0]?.id ||provider.defaultModelId ||"";- const storedModel = bindingForModel(provider, modelId);- const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {- vendorKey: provider.vendorKey,- baseUrl: provider.baseUrl,- apiStyle: provider.apiStyle,- modelId,+ modelsDevCatalog.configureAccount(provider);+ const modelConfig = catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,});- const resolved = resolveBindingLimits(- catalogModelConfig,- storedModel,- );- const modelConfig = modelConfigWithBinding(- resolved.catalogConfig,- resolved.binding,- );const models = provider.models?.map((binding) => {- const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {- vendorKey: provider.vendorKey,- baseUrl: provider.baseUrl,- apiStyle: provider.apiStyle,- modelId: binding.id,+ const effective = catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId: binding.id,});- const bindingResolved = resolveBindingLimits(- catalogModelConfig,- binding,- );- const effective = modelConfigWithBinding(- bindingResolved.catalogConfig,- bindingResolved.binding,- );- return {- ...binding,- contextWindow: effective.contextWindow,- maxTokens: effective.maxTokens,- // An inherited window keeps its catalog provenance on the exposed row,- // so saving this form cannot freeze a models.dev value into a snapshot- // of its own.- ...(bindingResolved.binding.contextWindowSource- ? { contextWindowSource: bindingResolved.binding.contextWindowSource }- : {}),- ...(bindingResolved.binding.maxTokensSource- ? { maxTokensSource: bindingResolved.binding.maxTokensSource }- : {}),- };+ return { ...binding, contextWindow: effective.contextWindow, maxTokens: effective.maxTokens, maxTokensSource: binding.maxTokensSource ?? "user" as const };});return {...provider,...(models ? { models } : {}),- ...(catalogModelConfig.source !== "generic"+ ...(modelConfig.source !== "generic"? {contextWindow: modelConfig.contextWindow,maxOutputTokens: modelConfig.maxTokens,@@ -280,6 +238,7 @@ export function createProviderCatalogRuntime({{ includeDisabled },);await modelsDevCatalog.ensureLoaded();+ for (const provider of result.providers) modelsDevCatalog.configureAccount(provider);return result.providers;};@@ -324,6 +283,7 @@ export function createProviderCatalogRuntime({const pinnedProvider = session.providerId? providers.find((item) => item.id === session.providerId): undefined;+ if (session.providerId && (!pinnedProvider || pinnedProvider.enabled === false)) return null;const provider =pinnedProvider ||(defaults?.defaultProviderId@@ -360,19 +320,10 @@ export function createProviderCatalogRuntime({};}const { provider, modelId } = target;- const resolved = resolveBindingLimits(- catalogModelConfigFor(modelsDevCatalog, {- vendorKey: provider.vendorKey,- baseUrl: provider.baseUrl,- apiStyle: provider.apiStyle,- modelId,- }),- bindingForModel(provider, modelId),- );- const modelConfig = modelConfigWithBinding(- resolved.catalogConfig,- resolved.binding,- );+ modelsDevCatalog.configureAccount(provider);+ const modelConfig = catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,+ });return {...session,...capabilitiesFromModelConfig(modelConfig),diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 83497bebe..6a54abef0 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -6,7 +6,6 @@ import {imageGenerationBindings,isImageGenerationModel,normalizeMode,- resolveBindingLimits,trustedExtensionAgentKeyFromProviderId,type CommandShellCatalog,type McpServerRecord,@@ -69,7 +68,7 @@ export type SessionLaunchRuntimeDependencies = {modelId: string,) => ModelBinding | undefined;effectiveSubagentModelConfig: (- provider: Pick<RuntimeProvider, "models">,+ provider: RuntimeProvider,modelId: string,catalogModelConfig: Parameters<typeof modelConfigWithBinding>[0],) => {@@ -270,6 +269,7 @@ export function createSessionLaunchRuntime({"providers.list",{ includeDisabled: false },);+ for (const row of providers.providers) modelsDevCatalog.configureAccount(row);const requestedProviderId = overrides.providerId ?? session.providerId;const extensionAgentKey = requestedProviderId? trustedExtensionAgentKeyFromProviderId(requestedProviderId)@@ -282,7 +282,9 @@ export function createSessionLaunchRuntime({authKind: "none",extensionAgentKey,}- : providers.providers.find((item) => item.id === requestedProviderId) ||+ : requestedProviderId+ ? providers.providers.find((item) => item.id === requestedProviderId && item.enabled !== false)!+ :providers.providers.find((item) => item.id === settings.defaultProviderId) ||providers.providers.find((item) => item.hasSecret || item.hasOauth || item.authKind === "none",@@ -293,6 +295,7 @@ export function createSessionLaunchRuntime({errorCode: ErrorCodes.MODEL_NOT_CONFIGURED,});}+ modelsDevCatalog.configureAccount(provider);// Plugin-owned agents resolve credentials and transport inside the trusted// extension; the host never reads or injects a secret for them.const isExtensionAgent = Boolean(extensionAgentKey);@@ -350,16 +353,13 @@ export function createSessionLaunchRuntime({const baseUrl = vendorBinding?.baseUrl ?? provider.baseUrl;const catalogModelConfig = vendorBinding?.modelConfig ??catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id,vendorKey: provider.vendorKey,baseUrl,apiStyle,modelId,});- const resolvedLimits = resolveBindingLimits(catalogModelConfig, storedModel);- const modelConfig = modelConfigWithBinding(- resolvedLimits.catalogConfig,- resolvedLimits.binding,- );+ const modelConfig = catalogModelConfig;const thinkingCapabilities = capabilitiesFromModelConfig(modelConfig);const thinkingLevel = clampThinkingLevel(thinkingCapabilities,@@ -482,6 +482,7 @@ export function createSessionLaunchRuntime({vendorOAuth.bindingFor(pinned.id, pinnedModelId),resolveModel: async (pinned, pinnedModelId) => {const catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {+ providerId: pinned.id,vendorKey: pinned.vendorKey,baseUrl: pinned.baseUrl,apiStyle: pinned.apiStyle,@@ -543,13 +544,15 @@ export function createSessionLaunchRuntime({if (!vb) continue;catalogModelConfig =vb.modelConfig ?? catalogModelConfigFor(modelsDevCatalog, {- vendorKey: row.vendorKey,+ providerId: row.id,+ vendorKey: row.vendorKey,baseUrl: vb.baseUrl ?? row.baseUrl,apiStyle: vb.apiStyle ?? row.apiStyle,modelId: binding.id,});} else {catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {+ providerId: row.id,vendorKey: row.vendorKey,baseUrl: row.baseUrl,apiStyle: row.apiStyle,diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex 679362cbf..58098e73b 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -113,6 +113,7 @@ export function createSidecarRuntime({startedAt: number;turnId?: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;}>();@@ -197,6 +198,7 @@ export function createSidecarRuntime({startedAt: envelope.ts,turnId: envelope.turnId,parentToolCallId: envelope.parentToolCallId,+ nestedParentToolCallId: envelope.nestedParentToolCallId,agentName: envelope.agentName,});} else if (event.type === "tool_end") {@@ -219,6 +221,7 @@ export function createSidecarRuntime({turnId: envelope.turnId ?? started?.turnId,toolCallId: event.toolCallId,parentToolCallId: started?.parentToolCallId,+ nestedParentToolCallId: started?.nestedParentToolCallId,agentName: started?.agentName,...(resultCode ? { code: resultCode } : {}),data: {@@ -262,6 +265,7 @@ export function createSidecarRuntime({turnId: tool.turnId,toolCallId: tool.toolCallId,parentToolCallId: tool.parentToolCallId,+ nestedParentToolCallId: tool.nestedParentToolCallId,agentName: tool.agentName,data: {toolName: tool.toolName,@@ -454,12 +458,14 @@ export function createSidecarRuntime({}await modelsDevCatalog.ensureLoaded();+ modelsDevCatalog.configureAccount(provider);let catalogModelConfig: Parameters<typeof modelConfigWithBinding>[0];if (isVendorAccount) {const vendorBinding = await vendorOAuth.bindingFor(provider.id, modelId);if (!vendorBinding) throw new Error(`vendor "${provider.name}" does not offer "${modelId}"`);catalogModelConfig =vendorBinding.modelConfig ?? catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id,vendorKey: provider.vendorKey,baseUrl: vendorBinding.baseUrl ?? provider.baseUrl,apiStyle: vendorBinding.apiStyle ?? provider.apiStyle,@@ -467,6 +473,7 @@ export function createSidecarRuntime({});} else {catalogModelConfig = catalogModelConfigFor(modelsDevCatalog, {+ providerId: provider.id,vendorKey: provider.vendorKey,baseUrl: provider.baseUrl,apiStyle: provider.apiStyle,@@ -497,6 +504,13 @@ export function createSidecarRuntime({s.setLocalTool("GenerateImages", createImageGenerationTool({dataDir,getHost: () => runtimeState.host,+ resolveAuth: providerId => vendorOAuth.resolveAuth(providerId),+ resolveImageModel: async (provider, modelId) => {+ await modelsDevCatalog.ensureLoaded();+ return modelsDevCatalog.findModelOfType("image", {+ providerId: provider.id, vendorKey: provider.vendorKey, baseUrl: provider.baseUrl, modelId,+ });+ },// Fake-IP tolerance belongs to the network policy, not to the proxy switch.allowFakeIp: () => relaxedNetworkPolicyEnabled(),}));diff --git a/apps/desktop/electron/main/services/image-generation-service.ts b/apps/desktop/electron/main/services/image-generation-service.tsindex e3f2df96d..9dcbd2b46 100644--- a/apps/desktop/electron/main/services/image-generation-service.ts+++ b/apps/desktop/electron/main/services/image-generation-service.ts@@ -1,7 +1,9 @@import { randomUUID } from "node:crypto";import { mkdir, realpath, writeFile } from "node:fs/promises";import { isAbsolute, join, relative, resolve } from "node:path";-import { generateImageBatch } from "@pi-desktop/agent-runtime";+import { createImageBinding, generateImageBatch, type ImageOperationMetadata } from "@pi-desktop/agent-runtime";+import type { ImageApi, ImageModel } from "@earendil-works/pi-ai";+import type { VendorOAuth } from "../oauth";import {imageGenerationPrompts,parseImageGenerationBinding,@@ -26,6 +28,8 @@ export function createImageGenerationTool(options: {getHost: () => Pick<HostProcess, "call"> | null;fetchImpl?: typeof fetch;allowFakeIp?: () => boolean;+ resolveAuth?: VendorOAuth["resolveAuth"];+ resolveImageModel?: (provider: ProviderPublic, modelId: string) => Promise<ImageModel<ImageApi> | undefined>;}): LocalToolHandler {return async ({ sessionId, args, signal }) => {imageGenerationPrompts(args);@@ -51,16 +55,26 @@ export function createImageGenerationTool(options: {"The configured image model is unavailable. Update Settings > Models > Image generation model.",);}- if (provider.authKind === "oauth")- return failure(- "IMAGE_AUTH_UNSUPPORTED",- "Image generation requires an API-key or no-auth service.",- );- const { value } = await host.call<{ value?: string }>("providers.getSecret", {- id: provider.id,- });- if (provider.authKind !== "none" && !value)+ const { value } = provider.authKind === "oauth" || provider.authKind === "none"+ ? { value: undefined }+ : await host.call<{ value?: string }>("providers.getSecret", { id: provider.id });+ if (provider.authKind !== "none" && provider.authKind !== "oauth" && !value)return failure("IMAGE_AUTH_FAILED", "The image provider needs an API key.");+ const downloadOptions = { allowFakeIp: options.allowFakeIp?.() === true };+ let imageBinding;+ try {+ imageBinding = createImageBinding({+ nativeModel: await options.resolveImageModel?.(provider, binding.modelId),+ providerId: provider.id, vendorKey: provider.vendorKey, authKind: provider.authKind,+ baseUrl: provider.baseUrl, modelId: binding.modelId, apiKey: value, headers: provider.headers,+ ...(provider.authKind === "oauth" && options.resolveAuth+ ? { resolveAuth: () => options.resolveAuth!(provider.id) } : {}),+ }, downloadOptions);+ } catch (error) {+ if (error && typeof error === "object" && "errorCode" in error && error.errorCode === "IMAGE_AUTH_UNSUPPORTED")+ return failure("IMAGE_AUTH_UNSUPPORTED", "The selected account has no supported image operation.");+ throw error;+ }const { path } = await host.call<{ path: string }>("session.getScratchPath", { sessionId });const root = resolve(options.dataDir, "scratch");const within = (base: string, target: string) => {@@ -79,14 +93,11 @@ export function createImageGenerationTool(options: {id: sessionId,});if (!session) return failure("SESSION_NOT_FOUND", "The image session no longer exists.");+ const operations: ImageOperationMetadata[] = [];const results = await generateImageBatch({input: args,- endpoint: {- baseUrl: provider.baseUrl,- modelId: binding.modelId,- apiKey: value,- headers: provider.headers,- },+ binding: imageBinding,+ onOperation: operation => { operations.push(operation); },signal,fetchImpl: options.fetchImpl,downloadOptions: { allowFakeIp: options.allowFakeIp?.() === true },@@ -110,6 +121,7 @@ export function createImageGenerationTool(options: {providerId: binding.providerId,modelId: binding.modelId,results,+ operations: operations.sort((a, b) => a.index - b.index),},};};diff --git a/apps/desktop/electron/main/settings-operation-metadata.json b/apps/desktop/electron/main/settings-operation-metadata.jsonnew file mode 100644index 000000000..8d7b1ebbf--- /dev/null+++ b/apps/desktop/electron/main/settings-operation-metadata.json@@ -0,0 +1,3655 @@+[+ {+ "vendor": "poe",+ "id": "elevenlabs/elevenlabs-v2.5-turbo",+ "name": "ElevenLabs-v2.5-Turbo",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "elevenlabs/elevenlabs-v3",+ "name": "ElevenLabs-v3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "elevenlabs/elevenlabs-music",+ "name": "ElevenLabs-Music",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 2000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "lumalabs/ray2",+ "name": "Ray2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 5000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/imagen-3-fast",+ "name": "Imagen-3-Fast",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/imagen-4-ultra",+ "name": "Imagen-4-Ultra",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/imagen-4",+ "name": "Imagen-4",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/imagen-4-fast",+ "name": "Imagen-4-Fast",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/lyria",+ "name": "Lyria",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/veo-3-fast",+ "name": "Veo-3-Fast",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/veo-3.1",+ "name": "Veo-3.1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/nano-banana-pro",+ "name": "Nano-Banana-Pro",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 65536,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/imagen-3",+ "name": "Imagen-3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/veo-2",+ "name": "Veo-2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/veo-3.1-fast",+ "name": "Veo-3.1-Fast",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "google/veo-3",+ "name": "Veo-3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "ideogramai/ideogram-v2",+ "name": "Ideogram-v2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 150,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "ideogramai/ideogram-v2a-turbo",+ "name": "Ideogram-v2a-Turbo",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 150,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "ideogramai/ideogram-v2a",+ "name": "Ideogram-v2a",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 150,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "ideogramai/ideogram",+ "name": "Ideogram",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 150,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "runwayml/runway",+ "name": "Runway",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 256,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "runwayml/runway-gen-4-turbo",+ "name": "Runway-Gen-4-Turbo",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 256,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "stabilityai/stablediffusionxl",+ "name": "StableDiffusionXL",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 200,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-5.4",+ "name": "GPT-5.4",+ "modalities": {+ "input": [+ "text",+ "image",+ "pdf"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 1050000,+ "maxTokens": 128000+ },+ {+ "vendor": "poe",+ "id": "openai/dall-e-3",+ "name": "DALL-E-3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 800,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/sora-2",+ "name": "Sora-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-5.4-pro",+ "name": "GPT-5.4-Pro",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 1050000,+ "maxTokens": 128000+ },+ {+ "vendor": "poe",+ "id": "openai/sora-2-pro",+ "name": "Sora-2-Pro",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-image-2",+ "name": "GPT-Image-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-image-1",+ "name": "GPT-Image-1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-image-1-mini",+ "name": "GPT-Image-1-Mini",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "openai/gpt-image-1.5",+ "name": "gpt-image-1.5",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 0+ },+ {+ "vendor": "poe",+ "id": "topazlabs-co/topazlabs",+ "name": "TopazLabs",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 204,+ "maxTokens": 0+ },+ {+ "vendor": "groq",+ "id": "whisper-large-v3",+ "name": "Whisper",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "groq",+ "id": "whisper-large-v3-turbo",+ "name": "Whisper Large V3 Turbo",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "groq",+ "id": "canopylabs/orpheus-v1-english",+ "name": "Canopy Labs Orpheus V1 English",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 4000,+ "maxTokens": 50000+ },+ {+ "vendor": "groq",+ "id": "canopylabs/orpheus-arabic-saudi",+ "name": "Canopy Labs Orpheus Arabic Saudi",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 4000,+ "maxTokens": 50000+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "happyhorse-1.1-r2v",+ "name": "HappyHorse 1.1 Reference-to-Video",+ "modalities": {+ "input": [+ "image",+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "happyhorse-1.1-t2v",+ "name": "HappyHorse 1.1 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "qwen-image-2.0",+ "name": "Qwen Image 2.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "qwen-image-2.0-pro",+ "name": "Qwen Image 2.0 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "wan2.7-image",+ "name": "Wan2.7 Image",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "wan2.7-image-pro",+ "name": "Wan2.7 Image Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan",+ "id": "happyhorse-1.1-i2v",+ "name": "HappyHorse 1.1 Image-to-Video",+ "modalities": {+ "input": [+ "image",+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "nan",+ "id": "qwen-image-2.1",+ "name": "Qwen-Image-2.1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "nearai",+ "id": "black-forest-labs/FLUX.2-klein-4B",+ "name": "FLUX.2 Klein 4B",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 128000+ },+ {+ "vendor": "nearai",+ "id": "openai/whisper-large-v3",+ "name": "Whisper Large v3",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 448+ },+ {+ "vendor": "xiaomi-token-plan-cn",+ "id": "mimo-v2.5-tts-voicedesign",+ "name": "MiMo-V2.5-TTS-VoiceDesign",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-cn",+ "id": "mimo-v2.5-tts",+ "name": "MiMo-V2.5-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-cn",+ "id": "mimo-v2-tts",+ "name": "MiMo-V2-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-cn",+ "id": "mimo-v2.5-tts-voiceclone",+ "name": "MiMo-V2.5-TTS-VoiceClone",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "privatemode-ai",+ "id": "whisper-large-v3",+ "name": "Whisper large-v3",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 4096+ },+ {+ "vendor": "privatemode-ai",+ "id": "voxtral-mini-3b",+ "name": "Voxtral Mini 3B",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 32000,+ "maxTokens": 32000+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "happyhorse-1.1-r2v",+ "name": "HappyHorse 1.1 Reference-to-Video",+ "modalities": {+ "input": [+ "image",+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "happyhorse-1.1-t2v",+ "name": "HappyHorse 1.1 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "qwen-image-2.0",+ "name": "Qwen Image 2.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "qwen-image-2.0-pro",+ "name": "Qwen Image 2.0 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "wan2.7-image",+ "name": "Wan2.7 Image",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "wan2.7-image-pro",+ "name": "Wan2.7 Image Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-token-plan-cn",+ "id": "happyhorse-1.1-i2v",+ "name": "HappyHorse 1.1 Image-to-Video",+ "modalities": {+ "input": [+ "image",+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "azure",+ "id": "gpt-image-2",+ "name": "GPT-Image-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "azure",+ "id": "gpt-image-2.5-flare",+ "name": "GPT Image 2.5 Flare",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "azure",+ "id": "gpt-image-2.5-sunburst",+ "name": "GPT Image 2.5 Sunburst",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "azure",+ "id": "gpt-image-1",+ "name": "GPT-Image-1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba",+ "id": "qwen3-asr-flash",+ "name": "Qwen3-ASR Flash",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 53248,+ "maxTokens": 4096+ },+ {+ "vendor": "zenmux",+ "id": "z-ai/glm-image",+ "name": "GLM-Image",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 10240,+ "maxTokens": 0+ },+ {+ "vendor": "zenmux",+ "id": "x-ai/grok-voice-tts-1.0",+ "name": "Grok Voice TTS 1.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 15000,+ "maxTokens": 15000+ },+ {+ "vendor": "zenmux",+ "id": "x-ai/grok-imagine-image-2.0",+ "name": "Grok Imagine Image 2.0",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 66000,+ "maxTokens": 0+ },+ {+ "vendor": "zenmux",+ "id": "x-ai/grok-voice-stt-1.0",+ "name": "Grok Voice STT 1.0",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 15000,+ "maxTokens": 15000+ },+ {+ "vendor": "regolo-ai",+ "id": "qwen-image",+ "name": "Qwen-Image",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 4096+ },+ {+ "vendor": "regolo-ai",+ "id": "faster-whisper-large-v3",+ "name": "Faster Whisper Large v3",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 4096+ },+ {+ "vendor": "xiaomi-token-plan-ams",+ "id": "mimo-v2.5-tts-voiceclone",+ "name": "MiMo-V2.5-TTS-VoiceClone",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-ams",+ "id": "mimo-v2-tts",+ "name": "MiMo-V2-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-ams",+ "id": "mimo-v2.5-tts",+ "name": "MiMo-V2.5-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-ams",+ "id": "mimo-v2.5-tts-voicedesign",+ "name": "MiMo-V2.5-TTS-VoiceDesign",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "qiniu-ai",+ "id": "gemini-2.5-flash-image",+ "name": "Gemini 2.5 Flash Image",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 32768,+ "maxTokens": 8192+ },+ {+ "vendor": "qiniu-ai",+ "id": "kling-v2-6",+ "name": "Kling-V2 6",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 99999999,+ "maxTokens": 99999999+ },+ {+ "vendor": "google",+ "id": "gemini-omni-flash-preview",+ "name": "Gemini Omni Flash Preview",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 131072,+ "maxTokens": 65536+ },+ {+ "vendor": "google",+ "id": "veo-3.1-lite-generate-preview",+ "name": "Veo 3.1 lite",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 8192+ },+ {+ "vendor": "google",+ "id": "gemini-3.1-flash-tts-preview",+ "name": "Gemini 3.1 Flash TTS Preview",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 16384+ },+ {+ "vendor": "google",+ "id": "gemini-2.5-pro-preview-tts",+ "name": "Gemini 2.5 Pro Preview TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 16384+ },+ {+ "vendor": "google",+ "id": "gemini-2.5-flash-preview-tts",+ "name": "Gemini 2.5 Flash Preview TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 16384+ },+ {+ "vendor": "google",+ "id": "veo-3.1-fast-generate-preview",+ "name": "Veo 3.1 fast",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 8192+ },+ {+ "vendor": "google",+ "id": "veo-3.1-generate-preview",+ "name": "Veo 3.1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 8192+ },+ {+ "vendor": "google",+ "id": "gemini-3.5-live-translate-preview",+ "name": "Gemini 3.5 Live Translate Preview",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "audio",+ "text"+ ]+ },+ "contextWindow": 16384,+ "maxTokens": 32768+ },+ {+ "vendor": "xai",+ "id": "grok-imagine-image",+ "name": "Grok Imagine Image",+ "modalities": {+ "input": [+ "text",+ "image",+ "pdf"+ ],+ "output": [+ "image",+ "pdf"+ ]+ },+ "contextWindow": 16000,+ "maxTokens": 0+ },+ {+ "vendor": "xai",+ "id": "grok-imagine-video",+ "name": "Grok Imagine Video",+ "modalities": {+ "input": [+ "text",+ "image",+ "video",+ "pdf"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 1024,+ "maxTokens": 0+ },+ {+ "vendor": "xai",+ "id": "grok-imagine-video-1.5",+ "name": "Grok Imagine Video 1.5",+ "modalities": {+ "input": [+ "text",+ "image",+ "audio",+ "pdf"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 1024,+ "maxTokens": 0+ },+ {+ "vendor": "xai",+ "id": "grok-imagine-image-quality",+ "name": "Grok Imagine Image Quality",+ "modalities": {+ "input": [+ "text",+ "image",+ "pdf"+ ],+ "output": [+ "image",+ "pdf"+ ]+ },+ "contextWindow": 16000,+ "maxTokens": 0+ },+ {+ "vendor": "scaleway",+ "id": "whisper-large-v3",+ "name": "Whisper Large v3",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 8192+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-tts",+ "name": "Grok TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-stt",+ "name": "Grok STT",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-imagine-image",+ "name": "Grok Imagine Image",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-imagine-video",+ "name": "Grok Imagine",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-imagine-video-1.5",+ "name": "Grok Imagine Video 1.5",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "spacexai/grok-imagine-image-2.0",+ "name": "Grok Imagine Image 2.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "prodia/flux-fast-schnell",+ "name": "Flux Schnell",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v2",+ "name": "Recraft V2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4-pro",+ "name": "Recraft V4 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4.1-utility",+ "name": "Recraft V4.1 Utility",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4.1-pro",+ "name": "Recraft V4.1 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v3",+ "name": "Recraft V3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4.1",+ "name": "Recraft V4.1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4.1-flash",+ "name": "Recraft V4.1 Flash",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4.1-utility-pro",+ "name": "Recraft V4.1 Utility Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "recraft/recraft-v4",+ "name": "Recraft V4",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "quiverai/arrow-1.1",+ "name": "Arrow 1.1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 131072,+ "maxTokens": 131072+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-kontext-max",+ "name": "FLUX.1 Kontext Max",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-pro-1.1-ultra",+ "name": "FLUX1.1 [pro] Ultra",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-3-video",+ "name": "Flux 3",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-2-flex",+ "name": "FLUX.2 [flex]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-2-klein-4b",+ "name": "FLUX.2 [klein] 4B",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-pro-1.0-fill",+ "name": "FLUX.1 Fill [pro]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-2-klein-9b",+ "name": "FLUX.2 [klein] 9B",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-2-pro",+ "name": "FLUX.2 [pro]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 67300,+ "maxTokens": 67300+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-2-max",+ "name": "FLUX.2 [max]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 67300,+ "maxTokens": 67300+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-pro-1.1",+ "name": "FLUX1.1 [pro]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bfl/flux-kontext-pro",+ "name": "FLUX.1 Kontext Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 512,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "meta/muse-image-1.0",+ "name": "Muse Image 1.0",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.6-t2v",+ "name": "Wan v2.6 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.6-i2v-flash",+ "name": "Wan v2.6 Image-to-Video Flash",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.6-r2v-flash",+ "name": "Wan v2.6 Reference-to-Video Flash",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.6-i2v",+ "name": "Wan v2.6 Image-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.5-t2v-preview",+ "name": "Wan v2.5 Text-to-Video Preview",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v3.0-video",+ "name": "Wan v3.0 Video",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.7-r2v",+ "name": "Wan v2.7 Reference-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v3.0-video-prime",+ "name": "Wan v3.0 Video Prime",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.6-r2v",+ "name": "Wan v2.6 Reference-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "alibaba/wan-v2.7-t2v",+ "name": "Wan v2.7 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v2.6-t2v",+ "name": "Kling v2.6 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v2.6-i2v",+ "name": "Kling v2.6 Image-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v2.5-turbo-t2v",+ "name": "Kling v2.5 Turbo Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v3.0-i2v",+ "name": "Kling v3.0 Image-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v3.0-motion-control",+ "name": "Kling v3.0 Motion Control",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v3.0-t2v",+ "name": "Kling v3.0 Text-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v2.6-motion-control",+ "name": "Kling v2.6 Motion Control",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "klingai/kling-v2.5-turbo-i2v",+ "name": "Kling v2.5 Turbo Image-to-Video",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedream-5.0-lite",+ "name": "Seedream 5.0 Lite",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedream-4.5",+ "name": "Seedream 4.5",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedream-4.0",+ "name": "Seedream 4.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-v1.0-pro",+ "name": "Seedance v1.0 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-2.0",+ "name": "Seedance 2.0",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-2.0-fast",+ "name": "Seedance 2.0 Fast",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-v1.5-pro",+ "name": "Seedance v1.5 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-2.0-mini",+ "name": "Seedance 2.0 Mini",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-2.5",+ "name": "Seedance 2.5",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedance-v1.0-pro-fast",+ "name": "Seedance v1.0 Pro Fast",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "bytedance/seedream-5.0-pro",+ "name": "Seedream 5.0 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/gemini-3.5-transcribe-live",+ "name": "Gemini 3.5 Transcribe Live",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/gemini-3.8-flash-lite-tts",+ "name": "Gemini 3.8 Flash-Lite TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/veo-3.1-lite-generate-001",+ "name": "Veo 3.1 Lite Generate",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/veo-3.1-fast-generate-001",+ "name": "Veo 3.1 Fast Generate",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/veo-3.0-fast-generate-001",+ "name": "Veo 3.0 Fast Generate",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/veo-3.1-generate-001",+ "name": "Veo 3.1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/gemini-3.5-transcribe",+ "name": "Gemini 3.5 Transcribe",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/gemini-3.8-flash-tts",+ "name": "Gemini 3.8 Flash TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "google/veo-3.0-generate-001",+ "name": "Veo 3.0",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "minimax/minimax-h3",+ "name": "MiniMax H3",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "minimax/minimax-h3-max",+ "name": "MiniMax H3 Max",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "fish-audio/s2.1-pro",+ "name": "S2.1 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "fish-audio/s1",+ "name": "S1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "fish-audio/transcribe-1",+ "name": "Transcribe-1",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "fish-audio/s2-pro",+ "name": "S2 Pro",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-4o-transcribe",+ "name": "GPT-4o Transcribe",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-2",+ "name": "GPT Image 2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/whisper-1",+ "name": "Whisper",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-2.5-flare",+ "name": "GPT Image 2.5 Flare",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-2.5-sunburst",+ "name": "GPT Image 2.5 Sunburst",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-1",+ "name": "GPT Image 1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/tts-1",+ "name": "TTS-1",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-1-mini",+ "name": "GPT Image 1 Mini",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-4o-mini-transcribe",+ "name": "GPT-4o mini Transcribe",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-image-1.5",+ "name": "GPT Image 1.5",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/gpt-realtime-whisper",+ "name": "gpt-realtime-whisper",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "vercel",+ "id": "openai/tts-1-hd",+ "name": "TTS-1 HD",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "greenpt",+ "id": "green-s",+ "name": "Green S",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 8192+ },+ {+ "vendor": "greenpt",+ "id": "green-s-pro",+ "name": "Green S Pro",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 8192+ },+ {+ "vendor": "stepfun-ai",+ "id": "stepaudio-2.5-asr",+ "name": "StepAudio 2.5 ASR",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "stepfun-ai",+ "id": "stepaudio-2.5-tts",+ "name": "StepAudio 2.5 TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "stepfun-ai",+ "id": "step-tts-2",+ "name": "Step TTS 2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "bytedance/seedance-2",+ "name": "Seedance 2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 4096,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "google/veo3.1",+ "name": "Veo 3.1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 400000,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "google/imagen-4.0-ultra",+ "name": "Imagen 4 Ultra",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "google/veo3.1-lite",+ "name": "Veo 3.1 Lite",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 400000,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "google/veo3.1-fast",+ "name": "Veo 3.1 Fast",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 400000,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "google/imagen-4.0-fast",+ "name": "Imagen 4 Fast",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 480,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "wanx/wan-v2-6",+ "name": "Wan 2.6",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 400000,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "leonardo-ai/lucid-realism",+ "name": "Lucid Realism",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 4096,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "leonardo-ai/lucid-origin",+ "name": "Lucid Origin",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 4096,+ "maxTokens": 0+ },+ {+ "vendor": "fastrouter",+ "id": "openai/gpt-image-2",+ "name": "GPT Image 2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 0+ },+ {+ "vendor": "aihubmix",+ "id": "gpt-image-2",+ "name": "GPT-Image-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "aihubmix",+ "id": "gpt-image-2.5-flare",+ "name": "GPT Image 2.5 Flare",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "aihubmix",+ "id": "gpt-image-2.5-sunburst",+ "name": "GPT Image 2.5 Sunburst",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "nvidia",+ "id": "black-forest-labs/flux_1-schnell",+ "name": "FLUX.1-schnell",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 77,+ "maxTokens": 0+ },+ {+ "vendor": "nvidia",+ "id": "black-forest-labs/flux.1-dev",+ "name": "FLUX.1-dev",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 4096,+ "maxTokens": 0+ },+ {+ "vendor": "nvidia",+ "id": "black-forest-labs/flux_1-kontext-dev",+ "name": "FLUX.1-Kontext-dev",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 40960,+ "maxTokens": 40960+ },+ {+ "vendor": "nvidia",+ "id": "black-forest-labs/flux_2-klein-4b",+ "name": "FLUX.2 Klein 4B",+ "modalities": {+ "input": [+ "image",+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 40960,+ "maxTokens": 40960+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/sparsedrive",+ "name": "sparsedrive",+ "modalities": {+ "input": [+ "video"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 8192+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/bevformer",+ "name": "bevformer",+ "modalities": {+ "input": [+ "video"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 8192+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/cosmos-transfer1-7b",+ "name": "cosmos-transfer1-7b",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/cosmos-predict1-5b",+ "name": "cosmos-predict1-5b",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/synthetic-video-detector",+ "name": "synthetic-video-detector",+ "modalities": {+ "input": [+ "video"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/cosmos-transfer2_5-2b",+ "name": "cosmos-transfer2.5-2b",+ "modalities": {+ "input": [+ "text",+ "image",+ "video"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/active-speaker-detection",+ "name": "Active Speaker Detection",+ "modalities": {+ "input": [+ "video"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/streampetr",+ "name": "streampetr",+ "modalities": {+ "input": [+ "video"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 128000,+ "maxTokens": 8192+ },+ {+ "vendor": "nvidia",+ "id": "nvidia/magpie-tts-zeroshot",+ "name": "magpie-tts-zeroshot",+ "modalities": {+ "input": [+ "text",+ "audio"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "nvidia",+ "id": "qwen/qwen-image-edit",+ "name": "Qwen Image Edit",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "nvidia",+ "id": "qwen/qwen-image",+ "name": "Qwen Image",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "nvidia",+ "id": "openai/whisper-large-v3",+ "name": "Whisper Large v3",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 4096+ },+ {+ "vendor": "xiaomi-token-plan-sgp",+ "id": "mimo-v2.5-tts-voiceclone",+ "name": "MiMo-V2.5-TTS-VoiceClone",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-sgp",+ "id": "mimo-v2-tts",+ "name": "MiMo-V2-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-sgp",+ "id": "mimo-v2.5-tts",+ "name": "MiMo-V2.5-TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "xiaomi-token-plan-sgp",+ "id": "mimo-v2.5-tts-voicedesign",+ "name": "MiMo-V2.5-TTS-VoiceDesign",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 8192+ },+ {+ "vendor": "stepfun",+ "id": "step-tts-2",+ "name": "Step TTS 2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "stepfun",+ "id": "stepaudio-2.5-tts",+ "name": "StepAudio 2.5 TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "stepfun",+ "id": "stepaudio-2.5-asr",+ "name": "StepAudio 2.5 ASR",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "kenari",+ "id": "gpt-image-2",+ "name": "GPT-Image-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 272000,+ "maxTokens": 16384+ },+ {+ "vendor": "kenari",+ "id": "grok-imagine-image-2-0",+ "name": "Grok Imagine Image 2.0",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 8000,+ "maxTokens": 0+ },+ {+ "vendor": "kenari",+ "id": "whisper-large-v3-turbo",+ "name": "Whisper Large v3 Turbo",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 448+ },+ {+ "vendor": "kenari",+ "id": "gemini-3-1-flash-tts",+ "name": "Gemini 3.1 Flash TTS Preview",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 8192,+ "maxTokens": 16384+ },+ {+ "vendor": "mistral",+ "id": "voxtral-mini-tts-latest",+ "name": "Voxtral Mini TTS (latest)",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "mistral",+ "id": "voxtral-mini-latest",+ "name": "Voxtral Mini (latest)",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "google-vertex",+ "id": "gemini-2.5-flash-tts",+ "name": "Gemini 2.5 Flash TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 32768,+ "maxTokens": 16384+ },+ {+ "vendor": "google-vertex",+ "id": "gemini-2.5-pro-tts",+ "name": "Gemini 2.5 Pro TTS",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 32768,+ "maxTokens": 16384+ },+ {+ "vendor": "evroc",+ "id": "KBLab/kb-whisper-large",+ "name": "KB Whisper",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 448+ },+ {+ "vendor": "evroc",+ "id": "openai/whisper-large-v3",+ "name": "Whisper 3 Large",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 4096+ },+ {+ "vendor": "evroc",+ "id": "openai/whisper-large-v3-turbo",+ "name": "Whisper Large v3 Turbo",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 448,+ "maxTokens": 448+ },+ {+ "vendor": "openai",+ "id": "gpt-image-2",+ "name": "gpt-image-2",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "openai",+ "id": "gpt-image-1",+ "name": "gpt-image-1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "digitalocean",+ "id": "openai-gpt-image-1",+ "name": "GPT Image 1",+ "modalities": {+ "input": [+ "text",+ "image"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "digitalocean",+ "id": "stable-diffusion-3.5-large",+ "name": "Stable Diffusion 3.5 Large",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 256,+ "maxTokens": 1+ },+ {+ "vendor": "digitalocean",+ "id": "wan2-2-t2v-a14b",+ "name": "Wan2.2-T2V-A14B",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "video"+ ]+ },+ "contextWindow": 100,+ "maxTokens": 1+ },+ {+ "vendor": "digitalocean",+ "id": "qwen3-tts-voicedesign",+ "name": "Qwen3 TTS VoiceDesign",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 32768,+ "maxTokens": 1+ },+ {+ "vendor": "digitalocean",+ "id": "fal-ai/fast-sdxl",+ "name": "Fast SDXL",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "digitalocean",+ "id": "fal-ai/elevenlabs/tts/multilingual-v2",+ "name": "ElevenLabs Multilingual TTS v2",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "digitalocean",+ "id": "fal-ai/flux/schnell",+ "name": "FLUX.1 [schnell]",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "image"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "digitalocean",+ "id": "fal-ai/stable-audio-25/text-to-audio",+ "name": "Stable Audio 2.5 (Text-to-Audio)",+ "modalities": {+ "input": [+ "text"+ ],+ "output": [+ "audio"+ ]+ },+ "contextWindow": 0,+ "maxTokens": 0+ },+ {+ "vendor": "alibaba-cn",+ "id": "qwen3-asr-flash",+ "name": "Qwen3-ASR Flash",+ "modalities": {+ "input": [+ "audio"+ ],+ "output": [+ "text"+ ]+ },+ "contextWindow": 53248,+ "maxTokens": 4096+ }+]diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 0b2462dba..68291a911 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -36,7 +36,8 @@"electron-updater": "^6.8.9"},"devDependencies": {- "@earendil-works/pi-ai": "0.87.1",+ "@earendil-works/pi-ai": "0.99.1",+ "@earendil-works/pi-mcp": "0.99.1","@pi-desktop/agent-host": "workspace:*","@pi-desktop/agent-runtime": "workspace:*","@pi-desktop/host-runtime": "workspace:*",@@ -134,10 +135,6 @@{"from": "resources/plugins","to": "plugins"- },- {- "from": "resources/models.dev",- "to": "models.dev"}],"mac": {@@ -157,8 +154,8 @@"entitlements": "build/entitlements.mac.plist","entitlementsInherit": "build/entitlements.mac.plist","extendInfo": {- "NSLocalNetworkUsageDescription": "PI-Desktop needs local network access so agents can reach OpenAI-compatible providers, Ollama, and other AI endpoints running on your LAN. / PI-Desktop 需要本地网络访问权限,以便助手请求同一局域网中的 OpenAI 兼容服务、Ollama 等本地 AI 端点。",- "NSMicrophoneUsageDescription": "PI-Desktop plugins may use the microphone after you grant them audio access. / 在你授权后,PI-Desktop 插件可以使用麦克风。",+ "NSLocalNetworkUsageDescription": "PI-Desktop needs local network access so agents can reach OpenAI-compatible providers, Ollama, and other AI endpoints running on your LAN. / PI-Desktop \u9700\u8981\u672c\u5730\u7f51\u7edc\u8bbf\u95ee\u6743\u9650\uff0c\u4ee5\u4fbf\u52a9\u624b\u8bf7\u6c42\u540c\u4e00\u5c40\u57df\u7f51\u4e2d\u7684 OpenAI \u517c\u5bb9\u670d\u52a1\u3001Ollama \u7b49\u672c\u5730 AI \u7aef\u70b9\u3002",+ "NSMicrophoneUsageDescription": "PI-Desktop plugins may use the microphone after you grant them audio access. / \u5728\u4f60\u6388\u6743\u540e\uff0cPI-Desktop \u63d2\u4ef6\u53ef\u4ee5\u4f7f\u7528\u9ea6\u514b\u98ce\u3002","NSBonjourServices": ["_http._tcp","_https._tcp"diff --git a/apps/desktop/src/lib/assistant-turns.ts b/apps/desktop/src/lib/assistant-turns.tsindex 848566be3..ec80ddcda 100644--- a/apps/desktop/src/lib/assistant-turns.ts+++ b/apps/desktop/src/lib/assistant-turns.ts@@ -4,7 +4,7 @@ import type {MessageUsage,UiMessage,} from "@pi-desktop/shared";-import { hostedSearchRounds } from "@pi-desktop/shared";+import { addUsage, hostedSearchRounds } from "@pi-desktop/shared";import { isDelegationStartTool } from "./tool-display";export type AssistantActivityItem =@@ -548,22 +548,5 @@ export function assistantTurnUsage();if (usages.length === 0) return undefined;- const sum = (field: keyof MessageUsage) =>- usages.reduce((total, usage) => total + (usage[field] ?? 0), 0);- const optionalSum = (- field: "cacheReadTokens" | "cacheWriteTokens" | "reasoningTokens",- ) =>- usages.some((usage) => usage[field] !== undefined) ? sum(field) : undefined;- const cacheReadTokens = optionalSum("cacheReadTokens");- const cacheWriteTokens = optionalSum("cacheWriteTokens");- const reasoningTokens = optionalSum("reasoningTokens");-- return {- inputTokens: sum("inputTokens"),- outputTokens: sum("outputTokens"),- totalTokens: sum("totalTokens"),- ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}),- ...(cacheWriteTokens !== undefined ? { cacheWriteTokens } : {}),- ...(reasoningTokens !== undefined ? { reasoningTokens } : {}),- };+ return usages.reduce<MessageUsage | undefined>((total, usage) => addUsage(total, usage), undefined);}diff --git a/apps/desktop/src/stores/runtime/session-runtime.ts b/apps/desktop/src/stores/runtime/session-runtime.tsindex ab412b731..afa07661a 100644--- a/apps/desktop/src/stores/runtime/session-runtime.ts+++ b/apps/desktop/src/stores/runtime/session-runtime.ts@@ -101,6 +101,7 @@ export type SessionRuntime = {args: unknown;createdAt: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;},) => void;@@ -109,6 +110,7 @@ export type SessionRuntime = {args: unknown;createdAt: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;} | undefined;removeToolStart: (toolCallId: string) => void;@@ -289,6 +291,7 @@ export function createSessionRuntime({ get, set }: StoreAccess): SessionRuntime...(envelope.parentToolCallId? { parentToolCallId: envelope.parentToolCallId }: {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),});break;diff --git a/apps/desktop/src/stores/slices/events-slice.ts b/apps/desktop/src/stores/slices/events-slice.tsindex 446be4648..bcaecb7fe 100644--- a/apps/desktop/src/stores/slices/events-slice.ts+++ b/apps/desktop/src/stores/slices/events-slice.ts@@ -396,6 +396,7 @@ export function createEventsSlice({...(envelope.parentToolCallId? { parentToolCallId: envelope.parentToolCallId }: {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),});} else if (event.type === "tool_end") {@@ -544,6 +545,7 @@ export function createEventsSlice({...(envelope.parentToolCallId? { parentToolCallId: envelope.parentToolCallId }: {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),},],@@ -587,6 +589,7 @@ export function createEventsSlice({...(toolStart?.parentToolCallId? { parentToolCallId: toolStart.parentToolCallId }: {}),+ ...(toolStart?.nestedParentToolCallId ? { nestedParentToolCallId: toolStart.nestedParentToolCallId } : {}),...(toolStart?.agentName ? { agentName: toolStart.agentName } : {}),toolCompletedAt: completedAt,toolDurationMs: toolStartdiff --git a/apps/desktop/test/anthropic-oauth-retry.test.mjs b/apps/desktop/test/anthropic-oauth-retry.test.mjsindex 9dbaad2f7..b16c3eba0 100644--- a/apps/desktop/test/anthropic-oauth-retry.test.mjs+++ b/apps/desktop/test/anthropic-oauth-retry.test.mjs@@ -106,8 +106,10 @@ test("real Anthropic authorization exchange retries 429 and stores one successfuassert.equal(requests[0].body.grant_type, "authorization_code");assert.deepEqual(requests[1].body, requests[0].body, "PKCE/code body changed during retry");assert.ok(requests[1].time - requests[0].time >= 950);- assert.equal(host.writes.length, 1);- assert.equal(JSON.parse(host.writes[0].value).refresh, success.refresh_token);+ const accountWrites = host.writes.filter(write => write.secretRef === secretRefForProviderOauth(result.providerId));+ assert.equal(accountWrites.length, 1);+ assert.equal(JSON.parse(accountWrites[0].value).refresh, success.refresh_token);+ assert.equal(host.writes.filter(write => write.secretRef === "secret:installation:oauth-device-id").length, 1);});});@@ -136,7 +138,7 @@ test("429 exhaustion is three attempts with safe recovery text and no stored parassert.match(result.message, /rate limited.*start a new sign-in/i);safeError({ message: result.message });assert.equal(host.providers.size, 0);- assert.equal(host.secrets.size, 0);+ assert.deepEqual([...host.secrets.keys()], ["secret:installation:oauth-device-id"]);});});diff --git a/apps/desktop/test/custom-system-prompt-launch.test.mjs b/apps/desktop/test/custom-system-prompt-launch.test.mjsindex 593135e62..8bf3f5dbd 100644--- a/apps/desktop/test/custom-system-prompt-launch.test.mjs+++ b/apps/desktop/test/custom-system-prompt-launch.test.mjs@@ -44,7 +44,7 @@ function launchRuntime() {logger: { app() {} }, userMcp: { setRecords() {}, toolsForProject: async () => [] },plugins: { listLoaded: () => [], getSkills: () => [], getTools: () => [], getAgentExtensions: () => [] },sessionProjects: new Map(), dataDir: workspace, vendorOAuth: {},- modelsDevCatalog: { ensureLoaded: async () => {}, findModel: () => undefined },+ modelsDevCatalog: { configureAccount: () => {}, ensureLoaded: async () => {}, findModel: () => undefined },getWorkspacePath: () => workspace, pluginActiveInProject: () => true,bindingForModel: (row, id) => row.models.find((m) => m.id === id),effectiveSubagentModelConfig: () => ({}),diff --git a/apps/desktop/test/image-conversation-selection.test.mjs b/apps/desktop/test/image-conversation-selection.test.mjsindex 88aa2f5b7..a9b7f7147 100644--- a/apps/desktop/test/image-conversation-selection.test.mjs+++ b/apps/desktop/test/image-conversation-selection.test.mjs@@ -42,7 +42,7 @@ test("runtime rejects an image binding retained by an existing conversation", asif (method === "providers.getSecret") return {};throw new Error(`Unexpected host call: ${method}`);} } },- modelsDevCatalog: { ensureLoaded: async () => {} },+ modelsDevCatalog: { configureAccount: () => {}, ensureLoaded: async () => {} },});await assert.rejects(runtime.resolveAgentRuntimeLaunch("session", { providerId: "images", modelId: image.modelId }, { imageGeneration: image }),diff --git a/apps/desktop/test/installation-identity.test.mjs b/apps/desktop/test/installation-identity.test.mjsnew file mode 100644index 000000000..0fbc4aaa2--- /dev/null+++ b/apps/desktop/test/installation-identity.test.mjs@@ -0,0 +1,69 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createInstallationIdentity } from "../electron/main/installation-identity.ts";++const id = "12345678-1234-4234-8234-123456789abc";+const ref = "secret:installation:oauth-device-id";++function host(initial) {+ let value = initial;+ const calls = [];+ const call = async (method, params) => {+ calls.push({ method, params });+ await new Promise((resolve) => setImmediate(resolve));+ if (method === "secrets.getForRuntime") return { value };+ assert.equal(method, "secrets.set");+ value = params.value;+ };+ return { call, calls };+}++test("identity is lazy, single-flight, persisted before use, and stable after service restart", async () => {+ const storage = host(null);+ let generated = 0;+ const get = createInstallationIdentity(storage.call, () => { generated++; return id; });+ assert.equal(storage.calls.length, 0);+ const requests = Array.from({ length: 32 }, () => get());+ assert.ok(requests.every((pending) => pending === requests[0]));+ assert.deepEqual(await Promise.all(requests), Array(32).fill(id));+ assert.equal(generated, 1);+ assert.deepEqual(storage.calls, [+ { method: "secrets.getForRuntime", params: { secretRef: ref } },+ { method: "secrets.set", params: { secretRef: ref, value: id } },+ ]);+ assert.equal(await get(), id);+ assert.equal(storage.calls.length, 2);+ const restarted = createInstallationIdentity(storage.call, () => assert.fail("must reuse persisted identity"));+ assert.equal(await restarted(), id);+});++for (const failingMethod of ["secrets.getForRuntime", "secrets.set"]) {+ test(`identity ${failingMethod} failure is redacted, shared, and retryable`, async () => {+ const storage = host(null);+ let fail = true;+ const get = createInstallationIdentity(async (method, params) => {+ if (fail && method === failingMethod) throw new Error(`backend exposed ${id}`);+ return storage.call(method, params);+ }, () => id);+ const results = await Promise.allSettled([get(), get(), get()]);+ for (const result of results) {+ assert.equal(result.status, "rejected");+ assert.equal(result.reason.message, "Could not load or persist the OAuth installation identity");+ assert.equal(result.reason.cause, undefined);+ }+ fail = false;+ assert.equal(await get(), id);+ });+}++test("an invalid stored identity fails closed without overwriting it", async () => {+ const storage = host("invalid-private-value");+ await assert.rejects(createInstallationIdentity(storage.call)(), /Could not load or persist/);+ assert.equal(storage.calls.length, 1);+});++test("a generated non-UUID cannot be persisted", async () => {+ const storage = host(null);+ await assert.rejects(createInstallationIdentity(storage.call, () => "not-a-uuid")(), /Could not load or persist/);+ assert.equal(storage.calls.length, 1);+});diff --git a/apps/desktop/test/model-advanced-capabilities.test.mjs b/apps/desktop/test/model-advanced-capabilities.test.mjsindex dca4e022b..1deb8928f 100644--- a/apps/desktop/test/model-advanced-capabilities.test.mjs+++ b/apps/desktop/test/model-advanced-capabilities.test.mjs@@ -181,7 +181,7 @@ test("the published record is not shaped by the stored override", () => {// the binding to it would make an override its own justification.assert.match(mainSource,- /modalities: catalogModelConfig\.modalities \?\? \{ input: \["text"\], output: \["text"\] \}/,+ /modalities: operationMetadata\?\.modalities \?\? catalogModelConfig\.modalities \?\? \{ input: \["text"\], output: \["text"\] \}/,);const decorate = mainSource.slice(mainSource.indexOf("const decorate ="),@@ -223,9 +223,9 @@ test("a model the catalog does not describe still reports its binding overrides"),);for (const block of [providerBlock, sessionBlock]) {- assert.match(block, /modelConfigWithBinding\(/);+ assert.doesNotMatch(block, /modelConfigWithBinding\(/);assert.match(block, /catalogModelConfigFor\(modelsDevCatalog/);- assert.match(block, /bindingForModel\(provider, modelId\)/);+ assert.match(block, /providerId: provider.id/);}assert.doesNotMatch(providerCatalogSource,diff --git a/apps/desktop/test/model-binding-catalog-source.test.mjs b/apps/desktop/test/model-binding-catalog-source.test.mjsindex df609db91..aaaff8d70 100644--- a/apps/desktop/test/model-binding-catalog-source.test.mjs+++ b/apps/desktop/test/model-binding-catalog-source.test.mjs@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import { registerHooks } from "node:module";import test from "node:test";+import { fixtureProvider } from "./pi-catalog-fixtures.mjs";import { ModelsDevCatalog } from "../electron/main/models-dev-catalog.ts";const runtimeModule = new URL("../electron/main/runtime/provider-catalog.ts", import.meta.url);@@ -23,33 +24,11 @@ const { createProviderCatalogRuntime } = await import(runtimeModule.href)*/const CORRECTED_CONTEXT_WINDOW = 1_050_000;-const fixture = {- requesty: {- name: "Requesty",- api: "https://router.requesty.ai/v1",- models: {- "terra": {- id: "terra",- reasoning: true,- modalities: { input: ["text"], output: ["text"] },- limit: { context: CORRECTED_CONTEXT_WINDOW, output: 64_000 },- },- "unpublished": {- id: "unpublished",- reasoning: false,- modalities: { input: ["text"], output: ["text"] },- // No published limit: values.dev has nothing to correct here.- },- },- },-};-async function fixtureRuntime() {- const catalog = new ModelsDevCatalog({- catalogPath: "unused-model-catalog.json",- fetchImpl: async () => new Response(JSON.stringify(fixture), { status: 200 }),- });- assert.equal(await catalog.refresh(), true);+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("requesty", [+ { id: "terra", reasoning: true, contextWindow: CORRECTED_CONTEXT_WINDOW, maxTokens: 64_000 },+ ], { baseUrl: "https://router.requesty.ai/v1" })] });+ await catalog.ensureLoaded();return createProviderCatalogRuntime({getHost: () => null,modelsDevCatalog: catalog,@@ -71,7 +50,7 @@ function enrichedContextWindow(runtime, binding) {return provider.models[0].contextWindow;}-test("a catalog-sourced binding adopts a models.dev correction", async () => {+test("a catalog-sourced binding adopts a Pi catalog correction", async () => {const runtime = await fixtureRuntime();// The value the binding snapshotted when the model was added.const binding = {diff --git a/apps/desktop/test/model-cache.test.mjs b/apps/desktop/test/model-cache.test.mjsindex 9925129da..ec0ce7eca 100644--- a/apps/desktop/test/model-cache.test.mjs+++ b/apps/desktop/test/model-cache.test.mjs@@ -14,11 +14,11 @@ test("saved provider discovery persists models in the host catalog", () => {assert.match(mainSource, /req\.source === "cache"/);assert.match(mainSource, /"providers\.listModels"/);assert.match(mainSource, /"providers\.cacheModels"/);- assert.match(mainSource, /catalogPath: app\.isPackaged/);- assert.match(mainSource, /resources", "models\.dev", "api\.json"/);+ assert.match(mainSource, /new ModelsDevCatalog\(\)/);+ assert.doesNotMatch(mainSource, /catalogPath: app\.isPackaged/);assert.match(mainSource, /modelsDevCatalog\.loadLocal\(\)/);assert.match(mainSource, /modelsDevCatalog\.refresh\(\)/);- assert.match(mainSource, /const modelsDevModel = modelsDevCatalog\.findModel/);+ assert.match(mainSource, /const modelsDevModel = .*modelsDevCatalog\.publishedModelFor/);assert.match(mainSource, /modelConfigFromModelsDev/);assert.match(mainSource, /genericModelConfig/);assert.match(mainSource, /providersRefreshModelCatalog/);diff --git a/apps/desktop/test/model-discovery-precedence.test.mjs b/apps/desktop/test/model-discovery-precedence.test.mjsindex 9e0571978..22e147291 100644--- a/apps/desktop/test/model-discovery-precedence.test.mjs+++ b/apps/desktop/test/model-discovery-precedence.test.mjs@@ -72,10 +72,10 @@ test("only a live answer is written back to the model cache", () => {assert.match(handler, /const requestBaseUrl = baseUrl\.replace/);});-test("every returned model is enriched through models.dev regardless of origin", () => {+test("every returned model is enriched through the published Pi catalog regardless of origin", () => {// `decorate` is what attaches published limits, modalities and thinking// levels, so all three branches must route through it.- assert.match(handler, /const modelsDevModel = modelsDevCatalog\.findModel\(/);+ assert.match(handler, /const modelsDevModel = .*modelsDevCatalog\.publishedModelFor/);assert.match(handler, /outcome\.models\.map\(\(model\) => decorate\(model\)\)/);assert.match(handler, /catalogModels\.map\(\(model\) => decorate\(model\)\)/);});diff --git a/apps/desktop/test/models-dev-catalog.test.mjs b/apps/desktop/test/models-dev-catalog.test.mjsindex 247639fe7..ebaca4948 100644--- a/apps/desktop/test/models-dev-catalog.test.mjs+++ b/apps/desktop/test/models-dev-catalog.test.mjs@@ -1,1756 +1,194 @@import assert from "node:assert/strict";-import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";import test from "node:test";-import { fileURLToPath } from "node:url";-import {- apiStyleForAdapter,- bindingForCustomModelInfo,- catalogModelIdsMatch,- modelIdsMatch,-} from "@pi-desktop/shared";-import {- MODELS_DEV_API_URL,- ModelsDevCatalog,- catalogModelConfigFor,- modelConfigFromModelsDev,- modelInfoFromModelsDev,- parseModelsDevCatalog,- thinkingLevelsFromModelsDev,-} from "../electron/main/models-dev-catalog.ts";--const catalogFixture = {- anthropic: {- name: "Anthropic",- models: {- "claude-opus-4.6": {- id: "claude-opus-4.6",- name: "Claude 4.6 Opus",- description: "High-end Claude for difficult coding, planning, and slower expert reasoning",- family: "claude-opus",- attachment: true,- reasoning: true,- reasoning_options: [{- type: "effort",- values: ["low", "medium", "high", "xhigh", "max"],- }],- tool_call: true,- structured_output: true,- temperature: false,- knowledge: "2025-05-31",- release_date: "2026-02-05",- last_updated: "2026-03-13",- modalities: {- input: ["text", "image", "pdf"],- output: ["text"],- },- open_weights: false,- limit: {- context: 1_000_000,- input: 1_000_000,- output: 128_000,- },- cost: {- input: 5,- output: 25,- cache_read: 0.5,- cache_write: 6.25,- reasoning: 25,- input_audio: 7,- output_audio: 28,- tiers: [{- input: 10,- output: 37.5,- cache_read: 1,- tier: { type: "context", size: 200_000 },- }],- context_over_200k: {- input: 10,- output: 37.5,- cache_read: 1,- cache_write: 12.5,- },- },- interleaved: { field: "reasoning_content" },- status: "stable",- experimental: { modes: { fast: { enabled: true } } },- provider: { npm: "@ai-sdk/anthropic" },- },- "audio-only": {- id: "audio-only",- modalities: { input: ["audio"], output: ["text"] },- },- "metadata-sparse": { id: "metadata-sparse" },- },- },-};--function responseFor(body, status = 200) {- return new Response(JSON.stringify(body), {- status,- headers: { "content-type": "application/json" },- });+import { createModels, InMemoryModelsStore, getSupportedThinkingLevels } from "@earendil-works/pi-ai";+import { bindingForCustomModelInfo } from "@pi-desktop/shared";+import { ModelsDevCatalog, catalogModelConfigFor, modelInfoFromModelsDev } from "../electron/main/models-dev-catalog.ts";+import { fixtureProvider } from "./pi-catalog-fixtures.mjs";++function account(provider) {+ const models = createModels({ modelsStore: new InMemoryModelsStore(), authContext: { env: async () => undefined, fileExists: async () => false } });+ models.setProvider(provider);+ return models;}+const target = { providerId: "account", vendorKey: "example", modelId: "chat" };+const binding = (values = {}) => ({ id: "chat", contextWindow: 128_000, maxTokens: 8_192, thinkingLevels: ["low", "high"], ...values });-async function loadFixtureCatalog(t, fixture = catalogFixture) {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-cache-"));- t.after(() => rm(dir, { recursive: true, force: true }));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(fixture), "utf8");- const catalog = new ModelsDevCatalog({ catalogPath });- assert.equal(await catalog.ensureLoaded(), true);- return catalog;-}--function observeModelIdReads(model) {- const modelId = model.modelId;- let reads = 0;- Object.defineProperty(model, "modelId", {- configurable: true,- get() {- reads += 1;- return modelId;- },- });- return () => reads;-}--test("repeated model matches and misses resolve through the bounded catalog index", async (t) => {- const catalog = await loadFixtureCatalog(t);- const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };- const match = catalog.findModel(input);- assert.ok(match);- const reads = observeModelIdReads(match);- const perQuery = reads();-- assert.equal(catalog.findModel({ ...input }), match);- assert.equal(catalog.findModel({ ...input, modelId: " CLAUDE-OPUS-4.6 " }), match);- // A repeated exact match returns the same catalog object and touches only the- // constant-sized candidate bucket, not a full catalog scan.- assert.ok(reads() - perQuery <= 8, "a repeated match must reuse the catalog result");-- const missing = { ...input, modelId: "unpublished-model" };- assert.equal(catalog.findModel(missing), undefined);- const afterMiss = reads();- assert.equal(catalog.findModel({ ...missing }), undefined);- assert.equal(catalog.findModel({ ...missing, modelId: " UNPUBLISHED-MODEL " }), undefined);- // A miss resolves through an empty bucket without scanning or growing the index.- assert.equal(reads(), afterMiss, "a repeated miss must not search again");-});--test("cached matches remain scoped to the requested provider and endpoint", async (t) => {- const fixture = Object.fromEntries(["alpha", "beta"].map((key) => [key, {- name: key,- api: `https://${key}.example/v1`,- models: {- "shared-model": {- id: "shared-model",- name: `${key} model`,- modalities: { input: ["text"], output: ["text"] },- },- },- }]));- const catalog = await loadFixtureCatalog(t, fixture);- const queries = [- [{ vendorKey: "alpha", modelId: "shared-model" }, "alpha"],- [{ vendorKey: "beta", modelId: "shared-model" }, "beta"],- [{ vendorKey: "custom", baseUrl: "https://alpha.example/v1", modelId: "shared-model" }, "alpha"],- [{ vendorKey: "custom", baseUrl: "https://beta.example/v1", modelId: "shared-model" }, "beta"],- [{ vendorKey: "alpha", baseUrl: "https://beta.example/v1", modelId: "shared-model" }, "beta"],- ];- for (const [input, providerKey] of [...queries, ...queries.toReversed()]) {- assert.equal(catalog.findModel(input)?.providerKey, providerKey);- }-});--test("unknown endpoints do not inherit ambiguous cross-provider metadata", async (t) => {- for (const order of [["alpha", "beta"], ["beta", "alpha"]]) {- const fixture = Object.fromEntries(order.map((key) => [key, {- api: `https://${key}.example/v1`,- models: {- "shared-model": {- id: "shared-model",- reasoning: key === "alpha",- limit: { context: key === "alpha" ? 128_000 : 32_000, output: 8_192 },- },- },- }]));- const catalog = await loadFixtureCatalog(t, fixture);- for (const modelId of ["shared-model", "proxy/shared-model"]) {- const unknown = { vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId };- assert.equal(catalog.findModel(unknown), undefined, `ambiguous ${modelId} must miss`);- assert.equal(catalog.findModel(unknown), undefined, "ambiguous misses are cached");- }- const alpha = catalog.findModel({- vendorKey: "custom", baseUrl: "https://alpha.example/v1", modelId: "shared-model",- });- assert.equal(alpha?.providerKey, "alpha", "an exact endpoint scopes the lookup");- assert.equal(alpha?.reasoning, true);- assert.equal(alpha?.limit.context, 128_000);- const beta = catalog.findModel({ vendorKey: "beta", modelId: "shared-model" });- assert.equal(beta?.providerKey, "beta", "a known provider key scopes the lookup");- assert.equal(beta?.reasoning, false);- assert.equal(beta?.limit.context, 32_000);- }-});--test("an unknown endpoint can use a unique exact last-segment match", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: { models: { "shared-model": { id: "shared-model", reasoning: true } } },- });- assert.equal(catalog.findModel({- vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId: "proxy/shared-model",- })?.providerKey, "alpha");-});--test("a known endpoint cannot borrow another provider's catalog model", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: { api: "https://alpha.example/v1", models: { "alpha-only": { id: "alpha-only" } } },- beta: { api: "https://beta.example/v1", models: { "proxy/shared-model": { id: "proxy/shared-model", reasoning: true } } },- });- assert.equal(catalog.findModel({ baseUrl: "https://alpha.example/v1", modelId: "shared-model" }), undefined);- assert.equal(catalog.findModel({ baseUrl: "https://beta.example/v1", modelId: "shared-model" })?.providerKey, "beta");-});--test("a shared catalog API prefers the explicitly selected vendor", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: { api: "https://gateway.example/v1", models: { "alpha-only": { id: "alpha-only" } } },- beta: { api: "https://gateway.example/v1", models: { "beta-only": { id: "beta-only" } } },- });- const input = { vendorKey: "beta", baseUrl: "https://gateway.example/v1" };- assert.equal(catalog.findModel({ ...input, modelId: "beta-only" })?.providerKey, "beta");- assert.equal(catalog.findModel({ ...input, modelId: "alpha-only" }), undefined);-});--test("a shared catalog API with no vendor key cannot select the first publisher", async (t) => {- for (const order of [["alpha", "beta"], ["beta", "alpha"]]) {- const catalog = await loadFixtureCatalog(t, Object.fromEntries(order.map((key) => [key, {- api: "https://gateway.example/v1",- models: { "shared-model": { id: "shared-model", reasoning: key === "alpha",- limit: { context: key === "alpha" ? 128_000 : 32_000, output: 8_192 } } },- }])));- assert.equal(catalog.providerKeyForRow({ vendorKey: "custom", baseUrl: "https://gateway.example/v1" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "custom", baseUrl: "https://gateway.example/v1", modelId: "shared-model" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "beta", baseUrl: "https://gateway.example/v1", modelId: "shared-model" })?.providerKey, "beta");- }-});--test("a recognized endpoint takes priority over an unrelated vendor fallback", async (t) => {- const catalog = await loadFixtureCatalog(t, {- openai: { models: { "shared-model": { id: "shared-model" } } },- deepseek: { models: { "shared-model": { id: "shared-model" } } },- });- assert.equal(catalog.findModel({- vendorKey: "openai",- baseUrl: "https://api.deepseek.com",- modelId: "shared-model",- })?.providerKey, "deepseek");-});--test("model lookup memory is bounded by the catalog, not by query count", async (t) => {- const catalog = await loadFixtureCatalog(t);- const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };- const match = catalog.findModel(input);- assert.ok(match);- const reads = observeModelIdReads(match);-- // Thousands of distinct miss queries do not grow the per-generation index and- // do not evict an already-resolved key from it.- for (let index = 0; index < 3_000; index += 1) {- assert.equal(catalog.findModel({ ...input, modelId: `unknown-${index}` }), undefined);- }- const beforeRepeat = reads();- assert.equal(catalog.findModel(input), match);- // The resolved key stays resolvable to the same object without a catalog rescan.- assert.ok(reads() - beforeRepeat <= 8, "a resolved key stays usable after many distinct queries");-});--test("one read with more distinct keys than any cache budget does not rescan a resolved key", async (t) => {- const catalog = await loadFixtureCatalog(t);- const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };- const match = catalog.findModel(input);- assert.ok(match);- const reads = observeModelIdReads(match);- const baseline = reads();- const exactRepeats = 2_000;- // Interleave the originally resolved key among a burst of distinct keys far- // larger than the former 1,024-entry per-key eviction cache.- for (let index = 0; index < exactRepeats; index += 1) {- catalog.findModel({ ...input, modelId: `unknown-${index}` });- catalog.findModel(input);- }- const touches = reads() - baseline;- // Each exact re-query resolves through a bounded candidate bucket, so the work- // stays proportional to the repeated queries and independent of the distinct- // keys interleaved between them. The old 1,024-entry eviction cache would rescan- // the whole catalog (thousands of model reads) on every repeat once its budget- // was exceeded, growing with the distinct-key burst.- assert.ok(- touches <= exactRepeats * 8,- `exact re-queries touched the model ${touches} times, expected <= ${exactRepeats * 8}`,- );-});--test("model IDs match provider namespaces without matching model variants", () => {- assert.equal(modelIdsMatch("anthropic-claude-opus-5", "claude-opus-5"), true);- assert.equal(modelIdsMatch("anthropic/claude-opus-5", "claude-opus-5"), true);- assert.equal(modelIdsMatch("claude-opus-5@default", "claude-opus-5"), true);- assert.equal(modelIdsMatch("claude-opus-5-fast", "claude-opus-5"), false);- for (const suffix of ["agent", "latest", "thinking", "think"]) {- assert.equal(modelIdsMatch("foo", `foo-${suffix}`), false);- assert.equal(modelIdsMatch(`foo-${suffix}`, "foo"), false);- }- assert.equal(modelIdsMatch("gateway-a/foo", "gateway-b/foo"), false);- assert.equal(modelIdsMatch("foo@us-east", "foo@eu-west"), false);- assert.equal(modelIdsMatch("proxy/openai/gpt-4o", "openai/gpt-4o"), true);- assert.equal(modelIdsMatch("openai/gpt-4o", "proxy/gpt-4o"), false);-});-test("catalog metadata IDs match only exact case-insensitive last segments", () => {- for (const [catalogId, request] of [- ["claude-opus-4.6", "proxy/claude-opus-4.6"],- ["openai/gpt-4o", "hub/gpt-4o"],- ["google/gemini-2.5-flash", "openai/gemini-2.5-flash"],- ["proxy/nested/claude-opus-4.6", "other/CLAUDE-OPUS-4.6"],- ["gateway-a/foo", "gateway-b/foo"],- ]) {- assert.equal(catalogModelIdsMatch(catalogId, request), true, `${catalogId} / ${request}`);- assert.equal(catalogModelIdsMatch(request, catalogId), true, `${request} / ${catalogId}`);- }-- for (const [catalogId, request] of [- ["claude-opus-4.6", "proxy/claude-opus-4.6-thinking"],- ["claude-opus-4.6", "claude-opus-4.6:thinking"],- ["claude-opus-4.6", "proxy/claude-opus-4.6-agent"],- ["claude-opus-4.6", "proxy/claude-opus-4.6-latest"],- ["anthropic-claude-opus-4.6", "claude-opus-4.6"],- ["google/gemini-pro-latest", "ag/gemini-pro-agent"],- ["foo", "foo-think"],- ["foo", "foo-agent"],- ["foo", "foo-latest"],- ["foo@us-east", "foo"],- ]) {- assert.equal(catalogModelIdsMatch(catalogId, request), false, `${catalogId} / ${request}`);- assert.equal(catalogModelIdsMatch(request, catalogId), false, `${request} / ${catalogId}`);- }-});--test("catalog lookup uses exact last segments and rejects ambiguous matches", async (t) => {- const catalog = await loadFixtureCatalog(t, {- gateway: { models: {- "model": { id: "model" },- "nested/unique-model": { id: "nested/unique-model", reasoning: true },- "google/gemini-pro-latest": { id: "google/gemini-pro-latest", reasoning: true },- "route-a/shared-leaf": { id: "route-a/shared-leaf", reasoning: true },- "route-b/shared-leaf": { id: "route-b/shared-leaf", reasoning: false },- "regional@us-east": { id: "regional@us-east" },- } },- });-- assert.equal(- catalog.findModel({ vendorKey: "custom", modelId: "proxy/UNIQUE-MODEL" })?.modelId,- "nested/unique-model",- );- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "other/model" })?.modelId, "model");- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "gateway", modelId: "proxy/shared-leaf" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }), undefined);- assert.equal(catalog.findModel({ vendorKey: "custom", modelId: "regional" }), undefined);- assert.equal(- catalog.findModel({ vendorKey: "custom", modelId: "proxy/regional@us-east" })?.modelId,- "regional@us-east",- );-});--test("ambiguous leaf matches prefer one official provider", async (t) => {- for (const order of [["relay", "openai"], ["openai", "relay"]]) {- const definitions = {- relay: { models: { "route/shared-leaf": {- id: "route/shared-leaf", reasoning: false, tool_call: false,- limit: { context: 32_000 },- } } },- openai: { models: { "shared-leaf": {- id: "shared-leaf", reasoning: true, tool_call: true,- reasoning_options: [{ type: "effort", values: ["low", "medium", "high"] }],- limit: { context: 128_000 },- } } },- };- const catalog = await loadFixtureCatalog(t, Object.fromEntries(- order.map((key) => [key, definitions[key]]),- ));- const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });- assert.equal(match?.providerKey, "openai");- assert.equal(match?.reasoning, true);- assert.equal(match?.limit.context, 128_000);- }-});--test("official source keys ignore a cloud publisher carrying another vendor's model", async (t) => {- const catalog = await loadFixtureCatalog(t, {- xai: { models: { "grok-4.6": {- id: "grok-4.6", reasoning: true, tool_call: true,- reasoning_options: [{ type: "effort", values: ["low", "medium", "high", "xhigh"] }],- limit: { context: 500_000 },- } } },- "google-vertex": { models: { "xai/grok-4.6": {- id: "xai/grok-4.6", reasoning: true, tool_call: true,- limit: { context: 524_288 },- } } },- relay: { models: { "x-ai/grok-4.6": {- id: "x-ai/grok-4.6", reasoning: false, tool_call: false,- } } },- });- const match = catalog.findModel({ vendorKey: "custom", modelId: "ycj/grok-4.6" });- assert.equal(match?.providerKey, "xai");- assert.equal(match?.limit.context, 500_000);-});--test("ambiguous non-official leaf matches share unanimous capabilities", async (t) => {- const catalog = await loadFixtureCatalog(t, {- relayA: { models: { "route-a/shared-leaf": {- id: "route-a/shared-leaf", reasoning: true, tool_call: true,- reasoning_options: [{ type: "effort", values: ["low", "high"] }],- modalities: { input: ["text", "image"], output: ["text"] },- limit: { context: 64_000, output: 8_192 },- } } },- relayB: { models: { "route-b/shared-leaf": {- id: "route-b/shared-leaf", reasoning: true, tool_call: true,- reasoning_options: [{ type: "effort", values: ["low", "high"] }],- modalities: { input: ["image", "text"], output: ["text"] },- limit: { context: 128_000, output: 16_384 },- } } },- });- const match = catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" });- assert.ok(match);- assert.equal(match.reasoning, true);- assert.equal(match.toolCall, true);- assert.deepEqual(match.thinkingLevels, ["low", "high"]);- assert.deepEqual(match.modalities.input.toSorted(), ["image", "text"]);-});--test("ambiguous leaf matches with conflicting capabilities remain unmatched", async (t) => {- const catalog = await loadFixtureCatalog(t, {- relayA: { models: { "route-a/shared-leaf": {- id: "route-a/shared-leaf", reasoning: true, tool_call: true,- } } },- relayB: { models: { "route-b/shared-leaf": {- id: "route-b/shared-leaf", reasoning: false, tool_call: true,- } } },- });- assert.equal(- catalog.findModel({ vendorKey: "custom", modelId: "proxy/shared-leaf" }),- undefined,- );-});--test("gemini agent routes do not collapse to gemini latest catalog entries", async (t) => {- const catalog = await loadFixtureCatalog(t, {- google: { models: {- "gemini-pro-latest": { id: "gemini-pro-latest", reasoning: true },- } },- });- assert.equal(- catalog.findModel({ vendorKey: "custom", modelId: "ag/gemini-pro-agent" }),- undefined,- );-});--test("catalog lookup never collapses reasoning or release suffix variants", async (t) => {- const catalog = await loadFixtureCatalog(t);- const exact = catalog.findModel({ vendorKey: "custom", modelId: "proxy/claude-opus-4.6" });- assert.equal(exact?.modelId, "claude-opus-4.6");- assert.equal(exact.reasoning, true);-- for (const modelId of [- "proxy/claude-opus-4.6-thinking",- "proxy/claude-opus-4.6-agent",- "proxy/claude-opus-4.6-latest",- "claude-opus-4.6:thinking",- "anthropic-claude-opus-4.6",- ]) {- assert.equal(catalog.findModel({ vendorKey: "custom", modelId }), undefined, modelId);- }-});--/*- A gateway is indexed by models.dev under the vendor that owns the weights, so- an endpoint serving `Vendor/Model` ids often has no record of its own while- several other publishers state the identical id. Issue #938: those rows used- to fall back to the generic 128k text-only shape, hiding a correct context- window and tool support that the catalog does publish.-*/-test("an id the row's own catalog provider lacks borrows a unanimous exact-id record", async (t) => {- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: { "gateway/own-model": { id: "gateway/own-model" } } },- publisherA: { models: { "Vendor/Shared-Model-0731": {- id: "Vendor/Shared-Model-0731", tool_call: true, reasoning: true,- modalities: { input: ["text", "image"], output: ["text"] },- attachment: true, family: "shared",- limit: { context: 262_144, output: 65_536 },- } } },- publisherB: { models: { "Vendor/Shared-Model-0731": {- id: "Vendor/Shared-Model-0731", tool_call: true, reasoning: true,- modalities: { input: ["text", "image"], output: ["text"] },- attachment: true, family: "shared",- limit: { context: 1_048_576, output: 32_768 },- } } },- });- const match = catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Shared-Model-0731",- });- assert.ok(match, "a published exact id must not drop to the generic shape");- assert.equal(match.toolCall, true);- assert.equal(match.reasoning, true);- const info = modelInfoFromModelsDev(match, "provider-1");- assert.equal(info.capabilities.includes("tools"), true);- assert.equal(info.capabilities.includes("vision"), true);- // Limits are the medians the publishers state; an even count takes the lower- // middle, so a borrow never rounds a window up on its own.- assert.equal(match.limit.context, 262_144);- assert.equal(match.limit.output, 32_768);-});--test("a borrowed record under-claims instead of asserting one publisher's extras", async (t) => {- // Both publishers agree on tool support, so the id is borrowable. They differ- // on vision, reasoning and structured output, so none of those may be- // reported: the borrow may only claim what every publisher states.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: { "gateway/own-model": { id: "gateway/own-model" } } },- publisherA: { models: { "Vendor/Mixed": {- id: "Vendor/Mixed", tool_call: true, reasoning: true, structured_output: true,- modalities: { input: ["text", "image"], output: ["text"] }, attachment: true,- limit: { context: 262_144 },- } } },- publisherB: { models: { "Vendor/Mixed": {- id: "Vendor/Mixed", tool_call: true, reasoning: false, structured_output: false,- modalities: { input: ["text"], output: ["text"] }, attachment: false,- limit: { context: 262_144 },- } } },- });- const match = catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Mixed",- });- assert.ok(match, "unanimous tool support is enough to borrow");- assert.equal(match.toolCall, true);- assert.equal(match.reasoning, false);- // A capability the publishers do not state unanimously is left unasserted- // (`undefined` means "no published answer"), never claimed from one source.- assert.equal(match.structuredOutput, undefined);- assert.equal(match.attachment, undefined);- assert.deepEqual(match.modalities.input, ["text"]);- const info = modelInfoFromModelsDev(match, "provider-1");- assert.equal(info.capabilities.includes("vision"), false);- assert.equal(info.capabilities.includes("reasoning"), false);-});--test("an even split on tool support leaves conflicting leaves unmatched", async (t) => {- // Conflicting capability signatures (tool_call) mean shared-capabilities enrichment- // must miss — no majority/consensus borrow for an unanchored / empty-gateway row.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- publisherA: { models: { "Vendor/Split": { id: "Vendor/Split", tool_call: true, limit: { context: 262_144 } } } },- publisherB: { models: { "Vendor/Split": { id: "Vendor/Split", tool_call: false, limit: { context: 262_144 } } } },- });- assert.equal(catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Split",- }), undefined);-});--test("a borrowed record never replaces what the row's own catalog provider publishes", async (t) => {- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {- "Vendor/Shared-Model": { id: "Vendor/Shared-Model", tool_call: false, limit: { context: 200_000 } },- } },- publisherA: { models: {- "Vendor/Shared-Model": { id: "Vendor/Shared-Model", tool_call: true, limit: { context: 1_048_576 } },- } },- });- const match = catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Shared-Model",- });- assert.equal(match?.providerKey, "gateway");- assert.equal(match.limit.context, 200_000);- assert.equal(match.toolCall, false);-});--test("publishers that disagree about capabilities remain unmatched", async (t) => {- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- publisherA: { models: { "Vendor/Disputed": {- id: "Vendor/Disputed", tool_call: true, reasoning: true, limit: { context: 262_144 },- } } },- publisherB: { models: { "Vendor/Disputed": {- id: "Vendor/Disputed", tool_call: false, reasoning: false, limit: { context: 262_144 },- } } },- });- assert.equal(catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Disputed",- }), undefined);-});--test("a majority of publishers with conflicting capability signatures stays unmatched", async (t) => {- // #1047 does not majority-vote across publishers for an empty/unanchored row.- // Conflicting tool_call signatures ⇒ unmatched.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- publisherA: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 262_144 } } } },- publisherB: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 1_048_576 } } } },- publisherC: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: true, limit: { context: 1_048_576 } } } },- publisherD: { models: { "Vendor/Majority": { id: "Vendor/Majority", tool_call: false, limit: { context: 1_048_576 } } } },- });- assert.equal(catalog.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Majority",- }), undefined);-});--test("conflicting reseller and shipped records for a leaf stay unmatched without an official", async (t) => {- // deepseek is not an official/source family for #1047 disambiguation, and the- // capability signatures conflict, so an unanchored relay must miss.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- deepseek: { models: { "shared-model": {- id: "shared-model", tool_call: true, limit: { context: 1_000_000, output: 393_216 },- } } },- resellerA: { models: { "shared-model": {- id: "shared-model", tool_call: false, limit: { context: 128_000, output: 8_192 },- } } },- resellerB: { models: { "shared-model": {- id: "shared-model", tool_call: false, limit: { context: 131_072, output: 8_192 },- } } },- });- assert.equal(catalog.findModel({- vendorKey: "custom",- baseUrl: "https://relay.example/v1",- modelId: "shared-model",- }), undefined);-});--test("resellers still answer for an id no shipped publisher states", async (t) => {- // The preference above is not a filter: an id only resellers publish would- // otherwise be shown as a generic 128k text-only row.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- resellerA: { models: { "reseller-only-model": {- id: "reseller-only-model", tool_call: true, limit: { context: 262_144 },- } } },- resellerB: { models: { "reseller-only-model": {- id: "reseller-only-model", tool_call: true, limit: { context: 262_144 },- } } },- });- const match = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://relay.example/v1",- modelId: "reseller-only-model",- });- assert.ok(match, "a published id must not drop to the generic shape");- assert.equal(match.toolCall, true);- assert.equal(match.limit.context, 262_144);-});--test("a route prefix reaches a unique leaf while deployment markers stay unmatched", async (t) => {- // Exact last-segment match allows `test/mimo-v2.5` → `mimo-v2.5`.- // Markers like `-thinking` / `-test` are part of the leaf and do not strip.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- xiaomi: { models: {- "mimo-v2.5": {- id: "mimo-v2.5", tool_call: true,- modalities: { input: ["text", "image"], output: ["text"] },- limit: { context: 1_048_576, output: 131_072 },- },- "mimo-v2.5-pro": {- id: "mimo-v2.5-pro", tool_call: true, limit: { context: 1_048_576, output: 131_072 },- },- } },- });- const relay = (modelId) =>- catalog.findModel({ vendorKey: "custom", baseUrl: "https://relay.example/v1", modelId });-- for (const served of ["test/mimo-v2.5", "mimo-v2.5"]) {- assert.equal(relay(served)?.modelId, "mimo-v2.5", `${served} reads the published model`);- assert.equal(relay(served)?.limit.context, 1_048_576);- }- const info = modelInfoFromModelsDev(relay("test/mimo-v2.5"), "provider-1");- assert.ok(info.capabilities.includes("vision"));-- assert.equal(relay("mimo-v2.5-thinking"), undefined);- assert.equal(relay("test/mimo-v2.5-pro-test"), undefined);- assert.equal(relay("mimo-v2.5-asr"), undefined);-});--test("a shipped publisher answers first for a row anchored to a reseller", async (t) => {- // The row's own publisher is known and publishes nothing for this id, so the- // borrow runs — and it reads the publisher the app ships before the resellers- // that also carry the id.- const catalog = await loadFixtureCatalog(t, {- reseller: { api: "https://reseller.example/v1", models: { "reseller/own": { id: "reseller/own" } } },- xai: { models: { "Vendor/Model": {- id: "Vendor/Model", tool_call: true, limit: { context: 500_000, output: 500_000 },- } } },- otherA: { models: { "Vendor/Model": {- id: "Vendor/Model", tool_call: false, limit: { context: 128_000, output: 8_192 },- } } },- otherB: { models: { "Vendor/Model": {- id: "Vendor/Model", tool_call: false, limit: { context: 131_072, output: 8_192 },- } } },- });- const match = catalog.findModel({- vendorKey: "reseller",- baseUrl: "https://reseller.example/v1",- modelId: "Vendor/Model",- });- assert.equal(match?.providerKey, "xai", "the shipped publisher's record answers");- assert.equal(match.toolCall, true);- assert.equal(match.limit.context, 500_000);- assert.equal(match.limit.output, 500_000);-});--test("ambiguous same-leaf spellings with conflicting modalities stay unmatched", async (t) => {- // `mimo-v2.5` and `XiaomiMiMo/MiMo-V2.5` share a case-insensitive leaf but- // disagree on modalities, and neither publisher is an official/source family.- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- xiaomi: { models: { "mimo-v2.5": {- id: "mimo-v2.5", tool_call: true,- modalities: { input: ["text", "image", "audio"], output: ["text"] },- limit: { context: 1_048_576, output: 131_072 },- } } },- huggingface: { models: { "XiaomiMiMo/MiMo-V2.5": {- id: "XiaomiMiMo/MiMo-V2.5", tool_call: true,- modalities: { input: ["text"], output: ["text"] },- limit: { context: 1_048_576, output: 131_072 },- } } },- });- assert.equal(catalog.findModel({- vendorKey: "custom",- baseUrl: "https://relay.example/v1",- modelId: "mimo-v2.5",- }), undefined);-});--test("unique leaf enrichment coexists with exact-id borrowing and unknown misses", async (t) => {- const catalog = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- publisherA: { models: {- "Vendor/Known": { id: "Vendor/Known", limit: { context: 262_144 } },- "Vendor/Known-2507": { id: "Vendor/Known-2507", limit: { context: 131_072 } },- } },- });- const input = { vendorKey: "gateway", baseUrl: "https://gateway.example/v1" };- // Near-miss and unknown ids do not reuse a sibling's limits.- assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known-3000" }), undefined);- assert.equal(catalog.findModel({ ...input, modelId: "unknown-model-xyz" }), undefined);- // A different route with the same unique final segment is valid enrichment.- assert.equal(catalog.findModel({ ...input, modelId: "Other/Known" })?.modelId, "Vendor/Known");- // Exact ids still resolve, including a case-only difference.- assert.equal(catalog.findModel({ ...input, modelId: "vendor/known" })?.limit.context, 262_144);- assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known" })?.limit.context, 262_144);- assert.equal(catalog.findModel({ ...input, modelId: "Vendor/Known-2507" })?.limit.context, 131_072);- // The sibling exists under a different id, so nothing is borrowed through it.- assert.equal(- catalog.findModel({ ...input, modelId: "Vendor/Known-2507" })?.modelId,- "Vendor/Known-2507",- );-});--test("a provider sharing the row's endpoint owns its own negative answer", async (t) => {- // Two names for one endpoint: an id published only by the sibling is not- // borrowed, because that sibling was already consulted and does not list it.- const catalog = await loadFixtureCatalog(t, {- alpha: { api: "https://gateway.example/v1", models: { "alpha-only": { id: "alpha-only" } } },- beta: { api: "https://gateway.example/v1", models: { "beta-only": { id: "beta-only" } } },- });- const input = { vendorKey: "beta", baseUrl: "https://gateway.example/v1" };- assert.equal(catalog.findModel({ ...input, modelId: "alpha-only" }), undefined);- // A different endpoint is a genuinely independent source and still transfers.- const other = await loadFixtureCatalog(t, {- gateway: { api: "https://gateway.example/v1", models: {} },- publisherA: { models: { "Vendor/Elsewhere": { id: "Vendor/Elsewhere", limit: { context: 262_144 } } } },- });- assert.equal(- other.findModel({- vendorKey: "gateway",- baseUrl: "https://gateway.example/v1",- modelId: "Vendor/Elsewhere",- })?.limit.context,- 262_144,- );-});--test("models.dev records retain all published model parameters and modalities", () => {- const [provider] = parseModelsDevCatalog(catalogFixture);- assert.equal(provider.providerKey, "anthropic");- assert.equal(provider.models.length, 3, "raw parsing keeps non-text records too");-- const model = provider.models.find((item) => item.modelId === "claude-opus-4.6");- assert.equal(model.providerApi, undefined);- assert.equal(model.displayName, "Claude 4.6 Opus");- assert.equal(model.description, "High-end Claude for difficult coding, planning, and slower expert reasoning");- assert.equal(model.family, "claude-opus");- assert.equal(model.attachment, true);- assert.equal(model.reasoning, true);- assert.deepEqual(model.reasoningOptions, [{- type: "effort",- values: ["low", "medium", "high", "xhigh", "max"],- }]);- assert.deepEqual(model.modalities, {- input: ["text", "image", "pdf"],- output: ["text"],- });- assert.deepEqual(model.limit, {- context: 1_000_000,- input: 1_000_000,- output: 128_000,- });- assert.deepEqual(model.cost, {- input: 5,- output: 25,- cacheRead: 0.5,- cacheWrite: 6.25,- reasoning: 25,- inputAudio: 7,- outputAudio: 28,- tiers: [{- input: 10,- output: 37.5,- cacheRead: 1,- tier: { type: "context", size: 200_000 },- }],- contextOver200k: {- input: 10,- output: 37.5,- cacheRead: 1,- cacheWrite: 12.5,- },- });- assert.deepEqual(model.interleaved, { field: "reasoning_content" });- assert.equal(model.status, "stable");- assert.equal(model.temperature, false);- assert.deepEqual(model.experimental, { modes: { fast: { enabled: true } } });- assert.deepEqual(model.provider, { npm: "@ai-sdk/anthropic" });-- const info = modelInfoFromModelsDev(model, "provider-row");- assert.equal(info.providerId, "provider-row");- assert.equal(info.contextWindow, 1_000_000);- assert.equal(info.maxTokens, 128_000);- assert.ok(info.capabilities.includes("text"));- assert.ok(info.capabilities.includes("tools"));- assert.ok(info.capabilities.includes("vision"));- assert.ok(info.capabilities.includes("pdf"));- assert.ok(info.capabilities.includes("reasoning"));- assert.ok(info.capabilities.includes("json"));- assert.ok(info.capabilities.includes("attachments"));- assert.equal(info.capabilities.includes("temperature"), false);- assert.equal(info.catalogSource, "models.dev");- assert.deepEqual(info.thinkingLevelMap, {- low: "low",- medium: "medium",- high: "high",- xhigh: "xhigh",- max: "max",- // Effort ladder without a published none/off value (#603).- off: null,- });- assert.deepEqual(info.provider, { npm: "@ai-sdk/anthropic" });- assert.deepEqual(info.experimental, { modes: { fast: { enabled: true } } });- assert.ok(- modelInfoFromModelsDev({ ...model, temperature: true }, "provider-row").capabilities.includes(- "temperature",- ),- );- const allModalities = {- input: ["text", "image", "audio", "video", "pdf"],- output: ["text", "image", "audio", "video", "pdf"],- };- const multimodalInfo = modelInfoFromModelsDev(- { ...model, modalities: allModalities },- "provider-row",- );- assert.deepEqual(multimodalInfo.modalities, allModalities);- for (const capability of ["vision", "audio", "video", "pdf"]) {- assert.ok(multimodalInfo.capabilities.includes(capability), capability);- }-- const config = modelConfigFromModelsDev(model, "https://api.anthropic.com");- assert.equal(config.source, "models.dev");- assert.equal(config.name, "Claude 4.6 Opus");- assert.equal(config.contextWindow, 1_000_000);- assert.equal(config.maxTokens, 128_000);- assert.deepEqual(config.input, ["text", "image"]);- assert.deepEqual(config.modalities, info.modalities);- assert.deepEqual(config.supportedThinkingLevels, ["low", "medium", "high", "xhigh", "max"]);- assert.equal(config.thinkingProtocol, "adaptive");- assert.deepEqual(config.thinkingLevelMap, {- low: "low",- medium: "medium",- high: "high",- xhigh: "xhigh",- max: "max",- // Effort ladder without a published none/off value (#603).- off: null,- });- assert.equal(config.cost.reasoning, 25);- assert.deepEqual(config.provider, { npm: "@ai-sdk/anthropic" });- assert.deepEqual(config.catalogProvider, { npm: "@ai-sdk/anthropic" });- assert.deepEqual(config.experimental, { modes: { fast: { enabled: true } } });- assert.equal(config.cost.inputAudio, 7);- assert.equal(config.cost.outputAudio, 28);- assert.equal(config.cost.tiers?.[0]?.tier?.size, 200_000);- assert.equal(config.interleaved?.field, "reasoning_content");-- const sparse = provider.models.find((item) => item.modelId === "metadata-sparse");- assert.equal(sparse.reasoningPublished, false);- assert.equal(sparse.modalitiesPublished, false);-});--test("models.dev parsing keeps the per-model wire API with a responses-only fallback", () => {- const [provider, llmGateway] = parseModelsDevCatalog({- "opencode-go": {- name: "OpenCode Go",- api: "https://opencode.ai/zen/go/v1",- models: {- "muse-spark-1.3-contributor": { id: "muse-spark-1.3-contributor" },- "deepseek-v4-flash": { id: "deepseek-v4-flash" },- "custom-responses": { id: "custom-responses", api: "openai-responses" },- },- },- "llmgateway": {- name: "LLM Gateway",- models: {- "muse-spark-1.3-contributor": { id: "muse-spark-1.3-contributor" },- },- },- });- const byId = Object.fromEntries(provider.models.map((model) => [model.modelId, model]));- assert.equal(byId["muse-spark-1.3-contributor"].modelApi, "openai-responses");- assert.equal(byId["deepseek-v4-flash"].modelApi, undefined);- assert.equal(byId["custom-responses"].modelApi, "openai-responses");- const gatewayMuse = llmGateway.models.find((model) => model.modelId === "muse-spark-1.3-contributor");- assert.equal(gatewayMuse.modelApi, undefined);- const config = modelConfigFromModelsDev(- byId["muse-spark-1.3-contributor"],- "https://opencode.ai/zen/go/v1",- );- assert.equal(config.api, "openai-responses");-});--test("models.dev parsing retains every model in a provider", () => {- const models = Object.fromEntries(- Array.from({ length: 627 }, (_, index) => [- `model-${String(index).padStart(4, "0")}`,- { id: `model-${String(index).padStart(4, "0")}` },- ]),- );- const [provider] = parseModelsDevCatalog({- provider: { name: "Provider", models },- });- assert.equal(provider.models.length, 627);- assert.equal(provider.models.at(-1)?.modelId, "model-0626");-});--test("matches vendor-prefixed models when the catalog provider key is a gateway", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-provider-match-"));- const catalogPath = join(dir, "api.json");- await writeFile(- catalogPath,- JSON.stringify({- gateway: {- name: "Gateway",- api: "https://gateway.example/v1",- models: {- "deepseek/deepseek-v4": {- id: "deepseek/deepseek-v4",- name: "DeepSeek V4",- modalities: { input: ["text", "image", "pdf"], output: ["text"] },- limit: { context: 128_000, output: 16_000 },- },- },- },- }),- "utf8",- );- try {- const catalog = new ModelsDevCatalog({ catalogPath });- assert.equal(await catalog.ensureLoaded(), true);- const match = catalog.findModel({- vendorKey: "deepseek",- modelId: "deepseek-v4",- });- assert.equal(match?.modelId, "deepseek/deepseek-v4");- assert.deepEqual(match?.modalities.input, ["text", "image", "pdf"]);- assert.equal(- catalog.modelsForProvider({ vendorKey: "deepseek", providerId: "row" }).length,- 1,- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("maps the OpenAI Codex account to OpenAI models.dev metadata", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-openai-codex-"));- const catalogPath = join(dir, "api.json");- await writeFile(- catalogPath,- JSON.stringify({- openai: {- name: "OpenAI",- models: {- "gpt-5.6-sol": {- id: "gpt-5.6-sol",- name: "GPT-5.6 Sol",- reasoning: true,- reasoning_options: [{- type: "effort",- values: ["none", "low", "medium", "high", "xhigh", "max"],- }],- modalities: { input: ["text", "image", "pdf"], output: ["text"] },- limit: { context: 1_050_000, output: 128_000 },- },- },- },- }),- "utf8",- );- try {- const catalog = new ModelsDevCatalog({ catalogPath });- assert.equal(await catalog.ensureLoaded(), true);-- const input = {- vendorKey: "openai-codex",- baseUrl: "https://chatgpt.com/backend-api",- modelId: "gpt-5.6-sol",- };- const match = catalog.findModel(input);- assert.equal(match?.providerKey, "openai");- assert.equal(match?.reasoning, true);- assert.deepEqual(match?.thinkingLevels, [- "off",- "low",- "medium",- "high",- "xhigh",- "max",- ]);- assert.equal(match?.limit.context, 1_050_000);- assert.equal(match?.limit.output, 128_000);- assert.equal(catalog.providerKeyForRow(input), "openai");-- const fallback = catalog.modelsForProvider({- vendorKey: input.vendorKey,- baseUrl: input.baseUrl,- providerId: "oauth-row",- });- assert.equal(fallback.length, 1);- assert.equal(fallback[0].modelId, "gpt-5.6-sol");- assert.deepEqual(fallback[0].supportedThinkingLevels, [- "off",- "low",- "medium",- "high",- "xhigh",- "max",- ]);- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("matches Zhipu and Z.AI endpoints by catalog URL and vendor aliases", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-zhipu-"));- const catalogPath = join(dir, "api.json");- await writeFile(- catalogPath,- JSON.stringify({- zhipuai: {- name: "Zhipu AI",- api: "https://open.bigmodel.cn/api/paas/v4",- models: {- "glm-5": {- id: "glm-5",- name: "GLM-5",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 204_800, output: 131_072 },- },- },- },- "zhipuai-coding-plan": {- name: "Zhipu AI Coding Plan",- api: "https://open.bigmodel.cn/api/coding/paas/v4",- models: {- "glm-5.3": {- id: "glm-5.3",- name: "GLM-5.3",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 1_000_000, output: 131_072 },- },- },- },- zai: {- name: "Z.AI",- api: "https://api.z.ai/api/paas/v4",- models: {- "glm-5.1": {- id: "glm-5.1",- name: "GLM-5.1",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 200_000, output: 131_072 },- },- },- },- "zai-coding-plan": {- name: "Z.AI Coding Plan",- api: "https://api.z.ai/api/coding/paas/v4",- models: {- "glm-5.2": {- id: "glm-5.2",- name: "GLM-5.2",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 1_000_000, output: 131_072 },- },- },- },- }),- "utf8",- );- try {- const catalog = new ModelsDevCatalog({ catalogPath });- assert.equal(await catalog.ensureLoaded(), true);-- const chinaApi = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://open.bigmodel.cn/api/paas/v4",- modelId: "glm-5",- });- assert.equal(chinaApi?.providerKey, "zhipuai");-- const chinaCoding = catalog.findModel({- vendorKey: "zai-coding-cn",- modelId: "glm-5.3",- });- assert.equal(chinaCoding?.providerKey, "zhipuai-coding-plan");- assert.equal(chinaCoding?.modelId, "glm-5.3");-- const intlCoding = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://api.z.ai/api/coding/paas/v4",- modelId: "glm-5.2",- });- assert.equal(intlCoding?.providerKey, "zai-coding-plan");- assert.equal(- catalog.providerKeyForRow({- vendorKey: "bigmodel",- baseUrl: "https://open.bigmodel.cn/api/paas/v4",- }),- "zhipuai",- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("maps MiniMax OpenAI-compatible endpoints to multimodal catalog metadata", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-minimax-openai-"));- const catalogPath = join(dir, "api.json");- await writeFile(- catalogPath,- JSON.stringify({- "minimax-cn": {- name: "MiniMax (China)",- api: "https://api.minimaxi.com/anthropic/v1",- models: {- "MiniMax-M3": {- id: "MiniMax-M3",- name: "MiniMax-M3",- attachment: true,- reasoning: true,- modalities: { input: ["text", "image", "video"], output: ["text"] },- limit: { context: 1_048_576, output: 524_288 },- },- },- },- }),- "utf8",- );- try {- const catalog = new ModelsDevCatalog({ catalogPath });- assert.equal(await catalog.ensureLoaded(), true);- const input = {- vendorKey: "custom",- baseUrl: "https://api.minimaxi.com/v1",- providerId: "custom-row",- };- const match = catalog.findModel({ ...input, modelId: "MiniMax-M3" });- assert.equal(match?.providerKey, "minimax-cn");- assert.deepEqual(match?.modalities.input, ["text", "image", "video"]);- assert.equal(match?.attachment, true);- assert.equal(catalog.modelsForProvider(input)[0]?.modelId, "MiniMax-M3");- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("models.dev reasoning options map to canonical levels", () => {- assert.deepEqual(- thinkingLevelsFromModelsDev(true, [{- type: "effort",- values: ["max", "low", "none", "invalid"],- }]),- ["off", "low", "max"],- );- assert.deepEqual(thinkingLevelsFromModelsDev(true, [{ type: "toggle" }]), ["off", "medium"]);- assert.deepEqual(thinkingLevelsFromModelsDev(true, [{ type: "budget_tokens", min: 1024 }]), ["off", "medium"]);- assert.deepEqual(thinkingLevelsFromModelsDev(true, []), ["low", "medium", "high"]);- assert.deepEqual(thinkingLevelsFromModelsDev(false, [{ type: "effort", values: ["high"] }]), []);-});--test("toggle ladders still map off to none", () => {- const [provider] = parseModelsDevCatalog({- vendor: {- name: "Vendor",- models: {- "toggle-model": {- id: "toggle-model",- reasoning: true,- reasoning_options: [{ type: "toggle" }],- },- },- },- });- const info = modelInfoFromModelsDev(provider.models[0], "row");- assert.equal(info.thinkingLevelMap?.off, "none");-});--test("the application loads the bundled release snapshot without network access", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-release-"));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");- let calls = 0;- try {- const catalog = new ModelsDevCatalog({- catalogPath,- fetchImpl: async () => {- calls += 1;- throw new Error("startup must not fetch");- },- });- assert.equal(- catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" }),- undefined,- "a lookup before the bundled snapshot loads can miss",- );- assert.equal(await catalog.ensureLoaded(), true);- assert.equal(calls, 0);- assert.equal(catalog.getStatus().source, "bundled");- assert.equal(catalog.getStatus().catalogPath, catalogPath);- assert.equal(- catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,- "claude-opus",- );- assert.equal(- catalog.modelsForProvider({ vendorKey: "anthropic", providerId: "row" }).length,- 2,- "only text-capable models enter the agent picker",- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("the bundled snapshot maps the latest 0.87.1 model ids to usable metadata", async () => {- const catalog = new ModelsDevCatalog({- catalogPath: fileURLToPath(new URL("../resources/models.dev/api.json", import.meta.url)),- });+// Parser/URL/heuristic-ranking implementation tests retired with the independent+// models.dev parser. These exercise the replacement Pi public factory boundary.+test("offline startup uses Pi's shipped catalog and does not consult ambient auth", async () => {+ const catalog = new ModelsDevCatalog();assert.equal(await catalog.ensureLoaded(), true);-- const cases = [- {- vendorKey: "openai-codex",- baseUrl: "https://chatgpt.com/backend-api",- modelId: "gpt-6-sol",- contextWindow: 1_050_000,- maxTokens: 128_000,- thinkingLevels: ["off", "low", "medium", "high", "xhigh", "max"],- },- {- vendorKey: "openai-codex",- baseUrl: "https://chatgpt.com/backend-api",- modelId: "gpt-6-luna",- contextWindow: 1_050_000,- maxTokens: 128_000,- thinkingLevels: ["off", "low", "medium", "high", "xhigh", "max"],- },- {- vendorKey: "anthropic",- baseUrl: "https://api.anthropic.com",- modelId: "claude-opus-5-5",- contextWindow: 1_000_000,- maxTokens: 128_000,- thinkingLevels: ["low", "medium", "high", "xhigh", "max"],- },- {- vendorKey: "xai",- baseUrl: "https://api.x.ai/v1",- modelId: "grok-4.7",- contextWindow: 500_000,- maxTokens: 500_000,- thinkingLevels: ["low", "medium", "high", "xhigh"],- },- ];-- for (const expected of cases) {- const model = catalog.findModel(expected);- assert.ok(model, `${expected.vendorKey}/${expected.modelId} must be in the snapshot`);- assert.equal(model.reasoning, true);- assert.deepEqual(model.thinkingLevels, expected.thinkingLevels);- assert.deepEqual(model.modalities.input, ["text", "image", "pdf"]);- const config = modelConfigFromModelsDev(model, expected.baseUrl);- assert.equal(config.contextWindow, expected.contextWindow);- assert.equal(config.maxTokens, expected.maxTokens);- assert.deepEqual(config.input, ["text", "image"]);- }-- const copilotClaude = catalog.findModel({- vendorKey: "github-copilot",- baseUrl: "https://api.individual.githubcopilot.com",- modelId: "claude-opus-5.5",- });- assert.ok(copilotClaude, "GitHub Copilot must include Claude Opus 5.5");- assert.equal(copilotClaude.reasoning, true);- assert.equal(copilotClaude.limit.context, 1_000_000);-});--test("concurrent catalog reads share the bundled snapshot load", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-concurrent-load-"));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");- try {- const catalog = new ModelsDevCatalog({ catalogPath });- const first = catalog.ensureLoaded();- const second = catalog.ensureLoaded();- assert.equal(await first, true);- assert.equal(await second, true);- assert.equal(- catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,- "claude-opus",- );- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("Settings refresh always refetches models.dev and only updates memory", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-refresh-"));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");- const refreshedFixture = {- ...catalogFixture,- anthropic: {- ...catalogFixture.anthropic,- models: {- ...catalogFixture.anthropic.models,- "claude-opus-4.6": {- ...catalogFixture.anthropic.models["claude-opus-4.6"],- name: "Updated Claude",- },- "new-model": {- id: "new-model",- name: "New Model",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 64_000, output: 4_000 },- },- },- },- };- const calls = [];- try {- const catalog = new ModelsDevCatalog({- catalogPath,- fetchImpl: async (url, options) => {- calls.push({ url, options });- return responseFor(refreshedFixture);- },- });- assert.equal(await catalog.ensureLoaded(), true);- const existingInput = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };- const previousMatch = catalog.findModel(existingInput);- assert.ok(previousMatch);- assert.equal(catalog.findModel({ vendorKey: "anthropic", modelId: "new-model" }), undefined);- assert.equal(calls.length, 0);- assert.equal(await catalog.refresh(), true);- assert.equal(calls.length, 1);- assert.equal(calls[0].url, MODELS_DEV_API_URL);- assert.deepEqual(calls[0].options.headers, { Accept: "application/json" });- const refreshedMatch = catalog.findModel(existingInput);- assert.notEqual(refreshedMatch, previousMatch);- assert.equal(refreshedMatch?.displayName, "Updated Claude");- assert.equal(- catalog.findModel({ vendorKey: "anthropic", modelId: "new-model" })?.displayName,- "New Model",- );- assert.deepEqual(- JSON.parse(await readFile(catalogPath, "utf8")),- catalogFixture,- "settings refresh must not write the bundled release resource",- );- assert.equal(await catalog.refresh(), true, "a second settings refresh is also remote");- assert.equal(calls.length, 2);- assert.equal(catalog.getStatus().source, "remote");- } finally {- await rm(dir, { recursive: true, force: true });- }-});--test("a failed settings refresh preserves the bundled snapshot in memory", async () => {- const dir = await mkdtemp(join(tmpdir(), "pi-models-dev-failure-"));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(catalogFixture), "utf8");- try {- const catalog = new ModelsDevCatalog({- catalogPath,- fetchImpl: async () => {- throw new Error("offline");- },- });- assert.equal(await catalog.ensureLoaded(), true);- const input = { vendorKey: "anthropic", modelId: "claude-opus-4.6" };- const match = catalog.findModel(input);- assert.ok(match);- const reads = observeModelIdReads(match);- const missing = { ...input, modelId: "unpublished-model" };- assert.equal(catalog.findModel(missing), undefined);- const beforeRefresh = reads();- assert.equal(await catalog.refresh(), false);- assert.equal(catalog.findModel(input), match);- assert.equal(catalog.findModel(missing), undefined);- assert.equal(reads(), beforeRefresh, "a failed refresh preserves both cached matches and misses");- assert.equal(- catalog.findModel({ vendorKey: "anthropic", modelId: "claude-opus-4.6" })?.family,- "claude-opus",- );- assert.match(catalog.getStatus().lastError, /offline/);- } finally {- await rm(dir, { recursive: true, force: true });- }-});--/*- The published `npm` / `env` / `doc` fields survive parsing because the setup- form still derives the wire API from the adapter package and still points the- user at the provider's own docs. Migrated here when the catalog-search suite- was removed with the browsable-catalog UI.-*/-test("parsed providers keep the published npm, env and doc fields", () => {- const providers = parseModelsDevCatalog({- anthropic: {- id: "anthropic",- name: "Anthropic",- npm: "@ai-sdk/anthropic",- api: "https://api.anthropic.com",- doc: "https://docs.anthropic.com",- env: ["ANTHROPIC_API_KEY"],- models: {- "claude-opus-4.6": {- id: "claude-opus-4.6",- name: "Claude 4.6 Opus",- modalities: { input: ["text"], output: ["text"] },- limit: { context: 200000, output: 64000 },- },- },- },- "openrouter-lite": {- id: "openrouter-lite",- name: "OpenRouter Lite",- npm: "@ai-sdk/openai-compatible",- models: {- "some-model": {- id: "some-model",- name: "Some Model",- modalities: { input: ["text"], output: ["text"] },- },- },- },- });- const anthropic = providers.find((item) => item.providerKey === "anthropic");- assert.equal(anthropic.npm, "@ai-sdk/anthropic");- assert.equal(anthropic.doc, "https://docs.anthropic.com");- assert.deepEqual(anthropic.env, ["ANTHROPIC_API_KEY"]);- assert.equal(anthropic.api, "https://api.anthropic.com");- const gateway = providers.find((item) => item.providerKey === "openrouter-lite");- assert.deepEqual(gateway.env, [], "a provider without env vars parses to an empty list");- assert.equal(gateway.doc, undefined);-});--test("the wire API style is derived from the published adapter package", () => {- assert.equal(apiStyleForAdapter("@ai-sdk/anthropic"), "anthropic_messages");- assert.equal(apiStyleForAdapter("@ai-sdk/google-vertex/anthropic"), "anthropic_messages");- assert.equal(apiStyleForAdapter("@ai-sdk/google"), "google_generative_ai");- assert.equal(apiStyleForAdapter("@ai-sdk/openai"), "responses");- // The long tail of gateways is OpenAI-compatible chat completions.- assert.equal(apiStyleForAdapter("@ai-sdk/openai-compatible"), "chat_completions");- assert.equal(apiStyleForAdapter(undefined), "chat_completions");-});--// A custom Anthropic Messages gateway (unknown base URL, vendorKey "custom")-// serving a Claude id that several catalog providers publish with differing-// reasoning options. The lookup refuses to pick one publisher, but the thinking-// wire shape of an exact Anthropic id is Anthropic's own (#990).-const ambiguousClaudeFixture = {- anthropic: {- name: "Anthropic",- npm: "@ai-sdk/anthropic",- models: {- "claude-opus-5-5": {- id: "claude-opus-5-5",- name: "Claude Opus 5.5",- reasoning: true,- reasoning_options: [{ type: "effort", values: ["low", "medium", "high", "xhigh", "max"] }],- tool_call: true,- modalities: { input: ["text", "image"], output: ["text"] },- limit: { context: 1_000_000, output: 128_000 },- },- },- },- requesty: {- name: "Requesty",- npm: "@ai-sdk/openai-compatible",- api: "https://router.requesty.ai/v1",- models: {- "claude-opus-5-5": {- id: "claude-opus-5-5",- name: "Claude Opus 5.5",- reasoning: true,- reasoning_options: [- { type: "effort", values: ["none", "low", "medium", "high", "max"] },- { type: "budget_tokens" },- ],- tool_call: true,- modalities: { input: ["text"], output: ["text"] },- limit: { context: 200_000, output: 64_000 },- },- "glm-5": {- id: "glm-5",- name: "GLM 5",- reasoning: true,- reasoning_options: [{ type: "effort", values: ["low", "high"] }],- tool_call: true,- modalities: { input: ["text"], output: ["text"] },- limit: { context: 200_000, output: 32_000 },- },- },- },-};--const customGateway = {- vendorKey: "custom",- baseUrl: "https://gateway.example/v1",-};--test("a custom gateway enriches an ambiguous Claude leaf from the official provider", async (t) => {- const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);- const config = catalogModelConfigFor(catalog, {- ...customGateway,- apiStyle: "anthropic_messages",- modelId: "claude-opus-5-5",- });-- assert.equal(config.source, "models.dev");- assert.equal(config.contextWindow, 1_000_000);- assert.equal(config.maxTokens, 128_000);- assert.equal(config.reasoning, true);- assert.deepEqual(config.reasoningOptions, [- { type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },+ for (const vendorKey of ["openai", "openai-codex", "azure-openai-responses"]) {+ const model = catalog.findModel({ vendorKey, modelId: "gpt-6.1-sol" });+ assert.ok(model, vendorKey);+ assert.equal(model.type ?? "chat", "chat");+ assert.deepEqual(modelInfoFromModelsDev(model, "row").supportedThinkingLevels, getSupportedThinkingLevels(model));+ assert.ok(!getSupportedThinkingLevels(model).includes("off"));+ }+ assert.equal(catalog.getStatus().source, "bundled");+});++test("concurrent cache hydration shares one Pi refresh", async () => {+ let restores = 0;+ const base = fixtureProvider("example", [{ id: "chat" }]);+ const catalog = new ModelsDevCatalog({ providers: [{ ...base, refreshModels: async () => { restores++; } }] });+ await Promise.all(Array.from({ length: 40 }, () => catalog.ensureLoaded()));+ assert.equal(restores, 1);+});++test("explicit refresh updates Pi model objects and failed refresh preserves last success", async () => {+ let count = 0;+ let fail = false;+ const provider = fixtureProvider("example", [{ id: "chat", contextWindow: 10_000 }], {+ fetchModels: async () => {+ count++;+ if (fail) throw new Error("sensitive-endpoint-token");+ return [{ ...provider.getModels()[0], contextWindow: 20_000 }];+ },+ });+ const catalog = new ModelsDevCatalog({ providers: [provider], now: () => 1000 });+ await catalog.ensureLoaded();+ assert.equal(count, 0);+ assert.equal(await catalog.refresh(), true);+ assert.equal(catalog.findModel(target).contextWindow, 20_000);+ const previous = catalog.findModel(target);+ fail = true;+ assert.equal(await catalog.refresh(), false);+ assert.deepEqual(catalog.findModel(target), previous);+ assert.equal(count, 2);+ assert.equal(catalog.getStatus().fetchedAt, new Date(1000).toISOString());+ assert.ok(!catalog.getStatus().lastError.includes("sensitive"));+});++test("provider and endpoint identity never borrow unrelated capabilities", async () => {+ const catalog = new ModelsDevCatalog({ providers: [+ fixtureProvider("example", [{ id: "chat", contextWindow: 10_000 }]),+ fixtureProvider("other", [{ id: "chat", contextWindow: 20_000 }, { id: "other-only" }]),+ ] });+ await catalog.ensureLoaded();+ assert.equal(catalog.findModel(target).contextWindow, 10_000);+ assert.equal(catalog.findModel({ ...target, modelId: "other-only" }), undefined);+ assert.equal(catalog.findModel({ modelId: "chat", baseUrl: "https://unknown.example/v1" }), undefined);+ assert.equal(catalog.findModel({ modelId: "chat", baseUrl: "https://other.example/v1" }).contextWindow, 20_000);+ for (const modelId of ["proxy/chat", "chat-latest", "chat-20260930", "chat-thinking"]) {+ assert.equal(catalog.findModel({ ...target, modelId }), undefined);+ }+ assert.equal(catalog.findModel({ ...target, modelId: " CHAT " }).id, "chat");+});++test("ambiguous shared endpoint has no first-provider winner", async () => {+ const options = { baseUrl: "https://shared.example/v1" };+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("one", [{ id: "chat" }], options), fixtureProvider("two", [{ id: "chat" }], options)] });+ await catalog.ensureLoaded();+ assert.equal(catalog.findModel({ baseUrl: options.baseUrl, modelId: "chat" }), undefined);+ assert.equal(catalog.findModel({ vendorKey: "two", baseUrl: options.baseUrl, modelId: "chat" }).provider, "two");+});++test("same-vendor accounts have distinct effective objects and deleted accounts stay unavailable", async () => {+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat" }])] });+ for (const [id, contextWindow] of [["account", 10_000], ["other-account", 20_000]]) {+ catalog.setAccountModels(id, account(fixtureProvider("example", [{ id: "chat", contextWindow }])));+ }+ assert.equal(catalog.findModel(target).contextWindow, 10_000);+ assert.equal(catalog.findModel({ ...target, providerId: "other-account" }).contextWindow, 20_000);+ catalog.deleteAccount("account");+ catalog.configureAccount({ id: "account", vendorKey: "example" });+ assert.equal(catalog.findModel(target), undefined);+ assert.deepEqual(catalog.modelsForProvider({ providerId: "account", vendorKey: "example" }), []);+ assert.equal(catalog.findModel({ ...target, providerId: "other-account" }).contextWindow, 20_000);+});++test("an attached account missing a model never falls back to the vendor catalog", () => {+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat" }])] });+ catalog.setAccountModels("account", account(fixtureProvider("example", [])));+ assert.equal(catalog.findModel(target), undefined);+});++test("typed lookups retain chat/image/classifier with one ID and the legacy list stays chat-only", () => {+ const provider = fixtureProvider("example", [+ { id: "shared" },+ { id: "shared", type: "image", api: "openrouter-images", output: ["image"] },+ { id: "shared", type: "classifier", api: "fixture-classifier" },]);- assert.deepEqual(config.thinkingLevelMap, {- low: "low",- medium: "medium",- high: "high",- xhigh: "xhigh",- max: "max",- off: null,- });-});--test("official-provider enrichment is API-style independent while unknown ids stay generic", async (t) => {- const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);- const completions = catalogModelConfigFor(catalog, {- ...customGateway,- apiStyle: "chat_completions",- modelId: "claude-opus-5-5",- });- assert.equal(completions.source, "models.dev");- assert.equal(completions.contextWindow, 1_000_000);- assert.deepEqual(completions.reasoningOptions, [- { type: "effort", values: ["low", "medium", "high", "xhigh", "max"] },- ]);-- // An id absent from every publisher stays generic, even on Anthropic Messages.- const unlisted = catalogModelConfigFor(catalog, {- ...customGateway,- apiStyle: "anthropic_messages",- modelId: "unlisted-reasoning-model",- });- assert.equal(unlisted.source, "generic");- assert.equal(unlisted.reasoningOptions, undefined);- assert.equal(unlisted.thinkingLevelMap, undefined);-- // Aliases of a Claude id are not an exact Anthropic id.- const renamed = catalogModelConfigFor(catalog, {- ...customGateway,- apiStyle: "anthropic_messages",- modelId: "my-claude-opus-5-5-thinking",- });- assert.equal(renamed.reasoningOptions, undefined);+ const catalog = new ModelsDevCatalog({ providers: [provider] });+ const input = { ...target, modelId: "shared" };+ assert.equal(catalog.findModel(input).type ?? "chat", "chat");+ assert.equal(catalog.findModelOfType("image", input).type, "image");+ assert.equal(catalog.findModelOfType("classifier", input).type, "classifier");+ catalog.configureAccount({ id: "account", vendorKey: "example", models: [binding({ id: "shared", contextWindow: 64_000 })] });+ assert.equal(catalog.findModelOfType("image", input).type, "image");+ assert.equal(catalog.findModelOfType("classifier", input).type, "classifier");+ assert.deepEqual(catalog.modelsForProvider({ providerId: "account", vendorKey: "example", includeNonChat: true }).map((model) => model.modelId), ["shared"]);+});++test("projection and execution read the same effective Pi object and preserve native cost", () => {+ const native = fixtureProvider("example", [{ id: "chat", reasoning: true, input: ["text", "image"], contextWindow: 1_000_000, maxTokens: 64_000 }]);+ const models = account(native);+ const catalog = new ModelsDevCatalog({ providers: [native] });+ catalog.setAccountModels("account", models);+ const row = { id: "account", vendorKey: "example", models: [binding({ contextWindow: 32_000, maxTokens: 4_000, supportsImages: false })] };+ catalog.configureAccount(row);+ const effective = catalog.findModel(target);+ assert.equal(models.getModel("example", "chat"), effective);+ const info = modelInfoFromModelsDev(effective, "account");+ const config = catalogModelConfigFor(catalog, target);+ assert.equal(info.contextWindow, config.contextWindow);+ assert.equal(info.maxTokens, config.maxTokens);+ assert.deepEqual(info.modalities.input, config.input);+ assert.deepEqual(info.supportedThinkingLevels, getSupportedThinkingLevels(effective));+ assert.equal(effective.cost, native.getModels()[0].cost);+ assert.equal(native.getModels()[0].contextWindow, 1_000_000);+ assert.equal(catalog.findModel(target), effective, "stable reads share the effective object");+ row.models = [];+ catalog.configureAccount(row);+ assert.equal(catalog.findModel(target).contextWindow, 1_000_000);+});++test("catalog limit provenance follows refresh while legacy explicit limits stay pinned", async () => {+ let contextWindow = 100_000;+ const provider = fixtureProvider("example", [{ id: "chat", contextWindow }], {+ fetchModels: async () => [{ ...provider.getModels()[0], contextWindow }],+ });+ const catalog = new ModelsDevCatalog({ providers: [provider] });+ catalog.configureAccount({ id: "account", vendorKey: "example", models: [binding({ contextWindow: 90_000, contextWindowSource: "catalog" })] });+ catalog.configureAccount({ id: "legacy", vendorKey: "example", models: [binding({ contextWindow: 128_000 })] });+ contextWindow = 200_000;+ assert.equal(await catalog.refresh(), true);+ assert.equal(catalogModelConfigFor(catalog, target).contextWindow, 200_000);+ assert.equal(catalogModelConfigFor(catalog, { ...target, providerId: "legacy" }).contextWindow, 128_000);+});++test("custom unpublished bindings keep explicit limits without false published prices", () => {+ const catalog = new ModelsDevCatalog({ providers: [] });+ catalog.configureAccount({ id: "account", vendorKey: "custom", models: [binding({ contextWindow: 32_000, maxTokens: 2_000, supportsImages: true })] });+ const config = catalogModelConfigFor(catalog, { ...target, vendorKey: "custom" });+ assert.equal(config.source, "generic");+ assert.equal(config.contextWindow, 32_000);+ assert.equal(config.maxTokens, 2_000);+ assert.deepEqual(config.input, ["text", "image"]);});-test("a resolved catalog record still wins over the Anthropic thinking fallback", async (t) => {- const catalog = await loadFixtureCatalog(t, ambiguousClaudeFixture);- const config = catalogModelConfigFor(catalog, {- vendorKey: "requesty",- baseUrl: "https://router.requesty.ai/v1",- apiStyle: "anthropic_messages",- modelId: "claude-opus-5-5",- });- assert.equal(config.source, "models.dev");- assert.equal(config.contextWindow, 200_000);- assert.ok(config.reasoningOptions?.some((option) => option.type === "budget_tokens"));+test("custom IDs retain their wire spelling when a Pi row seeds a binding", () => {+ const provider = fixtureProvider("example", [{ id: "chat" }]);+ const info = modelInfoFromModelsDev(provider.getModels()[0], "account");+ const saved = bindingForCustomModelInfo("CHAT", info);+ assert.equal(saved.id, "CHAT");+ assert.equal(saved.contextWindowSource, "catalog");+ assert.equal(saved.maxTokensSource, "catalog");+ assert.equal(info.catalogSource, "pi");});-/*- Release stamps in the published catalog.-- A gateway serves `mify/mimo-v2.5-pro-0731` while models.dev indexes the model- under the id that owns the weights. The alias only ever borrows metadata: the- id the row is addressed with stays the discovery result.-*/-test("a dated snapshot leaf does not borrow an undated published model", async (t) => {- const catalog = await loadFixtureCatalog(t, {- mify: {- api: "https://api.mify.example/v1",- models: {- "mimo-v2.5-pro": {- id: "mimo-v2.5-pro",- name: "MiMo v2.5 Pro",- reasoning: true,- tool_call: true,- limit: { context: 262_144, output: 32_768 },- },- },- },- });- assert.equal(- catalog.findModel({ vendorKey: "mify", modelId: "mify/mimo-v2.5-pro-0731" }),- undefined,- );+test("unknown relays match the exact model leaf without rewriting the requested wire ID", () => {+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("anthropic", [{ id: "claude-fixture" }])] });+ const input = { vendorKey: "custom", modelId: "route/claude-fixture", baseUrl: "https://relay.example/v1" };+ assert.equal(catalog.findModel(input)?.id, "claude-fixture");+ assert.equal(catalog.findModel({ ...input, modelId: "route/claude-fixture-latest" }), undefined);});-test("exact published leaves resolve without release-stamp aliasing", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: { api: "https://alpha.example/v1", models: {- "foo-v2": { id: "foo-v2", limit: { context: 32_000 } },- "foo-v2-0731": { id: "foo-v2-0731", limit: { context: 128_000 } },- } },- beta: { api: "https://beta.example/v1", models: {- "foo-v2": { id: "foo-v2", limit: { context: 64_000 } },- } },- });- const exact = catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0731" });- assert.equal(exact?.modelId, "foo-v2-0731");- assert.equal(exact?.limit.context, 128_000);-- // Unpublished stamps do not strip down to a shorter sibling.- assert.equal(catalog.findModel({ vendorKey: "alpha", modelId: "foo-v2-0815" }), undefined);-- // Same leaf, identical capabilities (limits are not part of the signature) ⇒- // shared-capabilities enrichment with the lower median window.- const shared = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://relay.example/v1",- modelId: "foo-v2",- });- assert.equal(shared?.limit.context, 32_000);-- // A uniquely published dated leaf still enriches.- const published = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://relay.example/v1",- modelId: "foo-v2-0731",- });- assert.equal(published?.providerKey, "alpha");- assert.equal(published?.limit.context, 128_000);-});--/*- A custom endpoint is often the same publisher on another path.-- The reported failure: a custom row at `https://open.bigmodel.cn/api/v1` listed- its models but every one of them showed generic defaults, because provider- matching only accepted models.dev's own path for that host.-*/-test("a custom endpoint on a uniquely published host inherits that publisher", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: {- api: "https://alpha.example/api/paas/v4",- models: {- "glm-5.3": {- id: "glm-5.3",- reasoning: true,- tool_call: true,- limit: { context: 1_000_000, output: 131_072 },- },- },- },- });- const model = catalog.findModel({- vendorKey: "custom",- baseUrl: "https://alpha.example/api/v1",- modelId: "glm-5.3",- });- assert.equal(model?.providerKey, "alpha");- assert.equal(model?.limit.context, 1_000_000);- assert.equal(model?.toolCall, true);-- // The whole row's records are reachable, not just the one id.- assert.equal(- catalog.modelsForProvider({ vendorKey: "custom", baseUrl: "https://alpha.example/api/v1", providerId: "row" }).length,- 1,- );-});--test("a host two publishers share leaves conflicting leaves unmatched", async (t) => {- const catalog = await loadFixtureCatalog(t, {- alpha: {- api: "https://shared.example/api/paas/v4",- models: { "glm-5.3": { id: "glm-5.3", reasoning: true, limit: { context: 1_000_000 } } },- },- beta: {- api: "https://shared.example/api/coding/v4",- models: { "glm-5.3": { id: "glm-5.3", reasoning: false, limit: { context: 32_000 } } },- },- });- assert.equal(catalog.findModel({- vendorKey: "custom",- baseUrl: "https://shared.example/v1",- modelId: "glm-5.3",- }), undefined);- // Naming the publisher still resolves it to that publisher's own record.- const alpha = catalog.findModel({- vendorKey: "alpha",- baseUrl: "https://shared.example/v1",- modelId: "glm-5.3",- });- assert.equal(alpha?.providerKey, "alpha");- assert.equal(alpha?.limit.context, 1_000_000);+test("a stored extended level cannot invent native Pi support", () => {+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [{ id: "chat", reasoning: true, thinkingLevelMap: { off: null, low: "low", high: "high" } }])] });+ const row = { id: "account", vendorKey: "example", models: [binding({ thinkingLevels: ["low", "max"] })] };+ catalog.configureAccount(row);+ assert.deepEqual(getSupportedThinkingLevels(catalog.findModel(target)), ["low"]);+ assert.deepEqual(row.models[0].thinkingLevels, ["low", "max"]);});diff --git a/apps/desktop/test/oauth-standalone-bundle.test.mjs b/apps/desktop/test/oauth-standalone-bundle.test.mjsnew file mode 100644index 000000000..945f92ae5--- /dev/null+++ b/apps/desktop/test/oauth-standalone-bundle.test.mjs@@ -0,0 +1,148 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { promisify } from "node:util";+import test from "node:test";+import { createRequire } from "node:module";++const require = createRequire(new URL("../../../packages/agent-runtime/package.json", import.meta.url));+const { build } = require("esbuild");++const root = fileURLToPath(new URL("../../../", import.meta.url));++test("standalone Desktop bundle loads real ChatGPT and legacy Meta OAuth without repository modules", async () => {+ const directory = await mkdtemp(join(tmpdir(), "pi-oauth-bundle-"));+ try {+ const output = join(directory, "oauth.mjs");+ const result = await build({+ entryPoints: [resolve(root, "apps/desktop/electron/main/oauth.ts")],+ outfile: output,+ bundle: true,+ platform: "node",+ format: "esm",+ target: "node22",+ metafile: true,+ banner: { js: 'import { createRequire as bundleRequire } from "node:module"; const require = bundleRequire(import.meta.url);' },+ });+ const inputs = Object.keys(result.metafile.inputs);+ assert.ok(inputs.some((path) => path.endsWith("auth/oauth/openai-chatgpt.js")));+ assert.ok(inputs.some((path) => path.endsWith("auth/oauth/meta.js")));+ // All non-builtin dependencies must be inside this standalone artifact.+ const { isBuiltin } = await import("node:module");+ for (const artifact of Object.values(result.metafile.outputs)) {+ for (const dependency of artifact.imports) {+ // ws probes these optional accelerators under try/catch. Neither is+ // shipped into the isolated directory; its JavaScript path must work.+ const optionalNative = ["bufferutil", "utf-8-validate"].includes(dependency.path);+ assert.ok(!dependency.external || isBuiltin(dependency.path) || optionalNative, dependency.path);+ }+ }+ await writeFile(join(directory, "exercise.mjs"), exercise);+ const { stdout } = await promisify(execFile)(process.execPath, ["exercise.mjs"], {+ cwd: directory,+ env: { PATH: process.env.PATH, HOME: directory, NODE_PATH: "" },+ timeout: 30_000,+ });+ assert.equal(stdout.trim(), "standalone OAuth flows passed");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+});++// Only I/O is replaced. The production VendorOAuth, Models implementation,+// static registration, flow loading, PKCE, callback validation and token+// conversion all execute from the standalone build in a fresh process.+const exercise = String.raw`+import assert from "node:assert/strict";+import http from "node:http";+import { syncBuiltinESMExports } from "node:module";+http.Server.prototype.listen = function () { throw new Error("mock callback port unavailable"); };+syncBuiltinESMExports();+const { VendorOAuth, secretRefForProviderOauth } = await import("./oauth.mjs");+const secrets = new Map();+const providers = new Map([["legacy", { id: "legacy", vendorKey: "openai-codex", authKind: "oauth" }]]);+const legacy = JSON.stringify({ type: "oauth", access: "legacy-access", refresh: "legacy-refresh", expires: 4102444800000 });+secrets.set(secretRefForProviderOauth("legacy"), legacy);+const logs = [];+const hostIds = [];+let count = 0;+let exchanges = 0;+let oauth;+let complete;+let failed;+let authorization;+const json = (data) => new Response(JSON.stringify(data), { status: 200 });+globalThis.fetch = async (input, init = {}) => {+ const url = String(input);+ if (url === "https://auth.openai.com/api/accounts/oauth/token") {+ assert.equal(init.body.get("grant_type"), "authorization_code");+ assert.equal(init.body.get("client_id"), "test-issued-client");+ assert.equal(init.body.get("code"), "test-code");+ assert.ok(init.body.get("code_verifier"));+ exchanges++;+ return json({ access_token: "new-access-" + exchanges, refresh_token: "new-refresh-" + exchanges,+ id_token: "test-id-token", expires_in: 3600, scope: "chatgpt.tokens.use.direct" });+ }+ if (url === "https://auth.meta.com/oidc/device/authorization/") return json({+ device_code: "test-device", user_code: "TEST-CODE", verification_uri_complete: "https://auth.meta.com/device/verify", interval: 0.001, expires_in: 30 });+ if (url === "https://auth.meta.com/oidc/device/token/") return json({ access_token: "test-meta-identity" });+ if (url === "https://api.meta.ai/muse-code/key") return json({ api_key: "test-meta-key" });+ throw new Error("Unexpected mocked network operation");+};+const deps = {+ call: async (method, params = {}) => {+ if (method === "secrets.getForRuntime") return { value: secrets.get(params.secretRef) ?? null };+ if (method === "secrets.set") { secrets.set(params.secretRef, params.value); return {}; }+ if (method === "providers.list") return { providers: [...providers.values()].map((row) => ({ ...row, hasOauth: secrets.has(secretRefForProviderOauth(row.id)) })) };+ if (method === "providers.create") { const row = { ...params, id: "new-" + ++count }; providers.set(row.id, row); return { provider: row }; }+ if (method === "providers.update") { Object.assign(providers.get(params.id), params); return {}; }+ if (method === "providers.delete") { providers.delete(params.id); secrets.delete(secretRefForProviderOauth(params.id)); return {}; }+ throw new Error("Unexpected host operation");+ },+ log: (...args) => logs.push(args),+ openExternal: async (url) => {+ if (!url.startsWith("https://auth.openai.com/")) return;+ authorization = new URL(url);+ hostIds.push(authorization.searchParams.get("ext_agent_host_id"));+ },+ emit: (event) => {+ if (event.kind === "error") failed(new Error(event.message));+ if (event.kind === "done") complete(event.providerId);+ if (event.kind === "prompt") {+ const callback = new URL("http://127.0.0.1:1455/auth/callback");+ callback.searchParams.set("state", authorization.searchParams.get("state"));+ callback.searchParams.set("code", "test-code");+ callback.searchParams.set("client_id", "test-issued-client");+ oauth.respond({ loginId: event.loginId, promptId: event.request.promptId, value: callback.href });+ }+ },+};+oauth = new VendorOAuth(deps);+await oauth.listVendors();+assert.equal(secrets.size, 1, "listing must not generate identity");+async function login(vendor) {+ const result = new Promise((resolve, reject) => { complete = resolve; failed = reject; });+ await oauth.start(vendor);+ return result;+}+const first = await login("openai");+oauth = new VendorOAuth(deps);+const second = await login("openai");+assert.notEqual(first, second);+assert.equal(exchanges, 2);+assert.equal(hostIds[0], hostIds[1]);+assert.match(hostIds[0], /^urn:uuid:[0-9a-f-]{36}$/);+assert.deepEqual(await oauth.resolveAuth(first), { apiKey: "new-access-1" });+assert.deepEqual(await oauth.resolveAuth(second), { apiKey: "new-access-2" });+assert.equal(secrets.get(secretRefForProviderOauth("legacy")), legacy);+assert.equal(providers.get("legacy").vendorKey, "openai-codex");+await oauth.deleteAccount(first);+assert.deepEqual(await oauth.resolveAuth(second), { apiKey: "new-access-2" });+const meta = await login("meta");+assert.deepEqual(await oauth.resolveAuth(meta), { apiKey: "test-meta-key" });+assert.equal(JSON.stringify(logs).includes(hostIds[0].slice(9)), false);+console.log("standalone OAuth flows passed");+`;diff --git a/apps/desktop/test/packaging-footprint.test.mjs b/apps/desktop/test/packaging-footprint.test.mjsindex 23397c48e..a776dde60 100644--- a/apps/desktop/test/packaging-footprint.test.mjs+++ b/apps/desktop/test/packaging-footprint.test.mjs@@ -209,10 +209,6 @@ test("packaging keeps only shipped locales and excludes non-runtime artifacts",from: "resources/plugins",to: "plugins",},- {- from: "resources/models.dev",- to: "models.dev",- },]);assert.doesNotMatch(JSON.stringify(packageJson.build), /node-pty/);});diff --git a/apps/desktop/test/pi-catalog-fixtures.mjs b/apps/desktop/test/pi-catalog-fixtures.mjsnew file mode 100644index 000000000..ef4b11cdd--- /dev/null+++ b/apps/desktop/test/pi-catalog-fixtures.mjs@@ -0,0 +1,27 @@+import { createProvider } from "@earendil-works/pi-ai";++/** Real Pi providers with inert execution and explicit fixture-only auth. */+export function fixtureProvider(id, models, options = {}) {+ return createProvider({+ id,+ baseUrl: `https://${id}.example/v1`,+ auth: { apiKey: { name: "Fixture", resolve: async () => ({ auth: { apiKey: "fixture-only" } }) } },+ models: models.map((model) => ({+ id: model.id,+ name: model.id,+ provider: id,+ api: "openai-completions",+ reasoning: false,+ input: ["text"],+ contextWindow: 128_000,+ maxTokens: 8_192,+ cost: { input: 1, output: 2, cacheRead: 0.1, cacheWrite: 1 },+ ...model,+ })),+ api: {+ stream: () => { throw new Error("fixture must not execute"); },+ streamSimple: () => { throw new Error("fixture must not execute"); },+ },+ ...options,+ });+}diff --git a/apps/desktop/test/provider-catalog-runtime.test.mjs b/apps/desktop/test/provider-catalog-runtime.test.mjsindex e6208ad39..5e9426c3a 100644--- a/apps/desktop/test/provider-catalog-runtime.test.mjs+++ b/apps/desktop/test/provider-catalog-runtime.test.mjs@@ -2,6 +2,7 @@ import assert from "node:assert/strict";import { registerHooks } from "node:module";import test from "node:test";+import { fixtureProvider } from "./pi-catalog-fixtures.mjs";import { genericModelConfig } from "@pi-desktop/agent-runtime";import { ModelsDevCatalog } from "../electron/main/models-dev-catalog.ts";@@ -18,32 +19,12 @@ const resolution = registerHooks({const { createProviderCatalogRuntime } = await import(runtimeModule.href).finally(() => resolution.deregister());-const fixture = {- example: {- name: "Example",- api: "https://models.example/v1",- models: {- "catalog-model": {- id: "catalog-model",- reasoning: true,- modalities: { input: ["text", "image"], output: ["text"] },- limit: { context: 128_000, output: 8_192 },- },- "text-model": {- id: "text-model",- reasoning: false,- modalities: { input: ["text"], output: ["text"] },- },- },- },-};-async function fixtureRuntime() {- const catalog = new ModelsDevCatalog({- catalogPath: "unused-model-catalog.json",- fetchImpl: async () => new Response(JSON.stringify(fixture), { status: 200 }),- });- assert.equal(await catalog.refresh(), true);+ const catalog = new ModelsDevCatalog({ providers: [fixtureProvider("example", [+ { id: "catalog-model", reasoning: true, input: ["text", "image"] },+ { id: "text-model" },+ ])] });+ await catalog.ensureLoaded();const runtime = createProviderCatalogRuntime({getHost: () => null,modelsDevCatalog: catalog,@@ -92,7 +73,9 @@ for (const modelId of ["catalog-model", "unpublished-model"]) {const restored = runtime.enrichSession(session, [provider]);assert.equal(restored.supportsReasoning, true);assert.equal(restored.supportsVision, true);- assert.deepEqual(restored.supportedThinkingLevels, ["max"]);+ assert.deepEqual(restored.supportedThinkingLevels, modelId === "catalog-model"+ ? ["off", "minimal", "low", "medium", "high"] : ["max"]);+ assert.deepEqual(provider.models[0].thinkingLevels, ["max"], "saved preferences remain intact");assert.equal(catalog.findModel(input), published, "binding edits do not replace catalog metadata");assert.deepEqual(session, { id: "session-one", providerId: provider.id, modelId });});@@ -125,9 +108,9 @@ test("a bulk session refresh reuses catalog matches while preserving each sessioconst input = { vendorKey: provider.vendorKey, modelId: "catalog-model" };const match = catalog.findModel(input);assert.ok(match);- const modelId = match.modelId;+ const modelId = match.id;let modelReads = 0;- Object.defineProperty(match, "modelId", {+ Object.defineProperty(match, "name", {configurable: true,get() {modelReads += 1;@@ -147,10 +130,10 @@ test("a bulk session refresh reuses catalog matches while preserving each sessio...session,supportsReasoning: true,supportsVision: true,- supportedThinkingLevels: ["low", "medium", "high"],+ supportedThinkingLevels: ["off", "minimal", "low", "medium", "high"],})));}- assert.equal(modelReads, 0, "session list refreshes must not repeat catalog matching work");+ assert.ok(modelReads <= 4, "bulk session reads reuse the one effective projection");});test("full wire IDs isolate configured bindings while catalog aliases remain metadata-only", async () => {@@ -169,24 +152,24 @@ test("full wire IDs isolate configured bindings while catalog aliases remain met};const catalogConfig = genericModelConfig(modelId, provider.baseUrl);assert.equal(runtime.bindingForModel(provider, ` ${modelId} `), provider.models[1]);- assert.equal(runtime.modelsDevModelFor(provider, modelId)?.modelId, "catalog-model");+ assert.equal(runtime.modelsDevModelFor(provider, modelId), undefined, "wire prefixes do not borrow another model");const selected = runtime.effectiveSubagentModelConfig(provider, modelId, catalogConfig);assert.equal(selected.modelConfig.name, modelId, "request wire ID is not rewritten");assert.equal(selected.modelConfig.contextWindow, 32_000);assert.deepEqual(selected.capabilities.supportedThinkingLevels, ["high"]);const session = { providerId: provider.id, modelId };assert.deepEqual(runtime.enrichSession(session, [provider]).supportedThinkingLevels, ["high"]);- assert.equal(runtime.enrichProvider(provider, modelId).contextWindow, 32_000);+ assert.equal(runtime.enrichProvider(provider, modelId).models[1].contextWindow, 32_000);assert.equal(runtime.enrichProvider(provider, "catalog-model").contextWindow, 16_000);assert.equal(session.modelId, modelId);provider.models = [provider.models[0]];assert.equal(runtime.bindingForModel(provider, modelId), undefined);assert.equal(runtime.effectiveSubagentModelConfig(provider, modelId, catalogConfig).modelConfig.contextWindow, 128_000);- assert.deepEqual(runtime.enrichSession(session, [provider]).supportedThinkingLevels, ["low", "medium", "high"]);- assert.equal(runtime.enrichProvider(provider, modelId).contextWindow, 128_000);+ assert.deepEqual(runtime.enrichSession(session, [provider]).supportedThinkingLevels, ["off", "minimal", "low", "medium", "high", "xhigh", "max"]);+ assert.equal(runtime.effectiveSubagentModelConfig(provider, modelId).modelConfig.contextWindow, 128_000);const otherProvider = { ...provider, id: "other-provider", models: [binding(modelId, 48_000, ["off"])] };- assert.deepEqual(runtime.enrichSession(session, [otherProvider, provider]).supportedThinkingLevels, ["low", "medium", "high"]);+ assert.deepEqual(runtime.enrichSession(session, [otherProvider, provider]).supportedThinkingLevels, ["off", "minimal", "low", "medium", "high", "xhigh", "max"]);});test("unmatched models expose selectable thinking in providers, sessions and subagents", async () => {@@ -204,3 +187,15 @@ test("unmatched models expose selectable thinking in providers, sessions and subassert.deepEqual(runtime.effectiveSubagentModelConfig(provider, modelId, genericModelConfig(modelId)).capabilities.supportedThinkingLevels, expected);}});++test("a saved missing or disabled account never inherits another account's capabilities", async () => {+ const { runtime } = await fixtureRuntime();+ const provider = { id: "other", name: "Other", vendorKey: "example", enabled: true };+ const defaults = { defaultProviderId: provider.id, defaultModelId: "catalog-model" };+ for (const providers of [[provider], [provider, { ...provider, id: "saved", enabled: false }]]) {+ const result = runtime.enrichSession({ providerId: "saved", modelId: "catalog-model" }, providers, defaults);+ assert.equal(result.supportsReasoning, false);+ assert.equal(result.supportsVision, false);+ }+ assert.equal(runtime.enrichSession({}, [provider], defaults).supportsVision, true);+});diff --git a/apps/desktop/test/provider-endpoint-metadata.test.mjs b/apps/desktop/test/provider-endpoint-metadata.test.mjsindex 78a5c2e03..bb17e5bf4 100644--- a/apps/desktop/test/provider-endpoint-metadata.test.mjs+++ b/apps/desktop/test/provider-endpoint-metadata.test.mjs@@ -109,7 +109,7 @@ test("a custom row on a published host gets that publisher's model metadata", asconst [model] = result.models;assert.equal(model.modelId, "glm-5.3", "the wire id is the one the service served");- assert.equal(model.catalogSource, "models.dev", "the host identified the publisher");+ assert.equal(model.catalogSource, "pi", "the host identified the publisher");assert.equal(model.contextWindow, 1_000_000);assert.equal(model.maxTokens, 131_072);for (const capability of ["tools", "reasoning"]) {@@ -129,7 +129,7 @@ test("a relay's list reads the shipped publisher's record for a known id", asyncconst byId = new Map(result.models.map((model) => [model.modelId, model]));const known = byId.get("claude-sonnet-4-5");- assert.equal(known.catalogSource, "models.dev", "several publishers state this id");+ assert.equal(known.catalogSource, "pi", "several publishers state this id");// Anthropic's published window, not a median dragged down by resellers that// state a smaller deployment of the same id.assert.equal(known.contextWindow, 1_000_000);@@ -190,13 +190,14 @@ test("a relay enriches unique/official leaves and leaves ambiguous or marker lea// Unique leaf still enriches.const tts = byId.get("mimo-v2.5-tts");- assert.equal(tts.catalogSource, "models.dev");+ assert.equal(tts.source, "bundled");+ assert.equal(tts.catalogSource, undefined);assert.ok(tts.capabilities.includes("audio"));assert.equal(tts.contextWindow, 8_192);// Official Anthropic disambiguation still enriches Claude leaves.const claude = byId.get("claude-sonnet-4-5");- assert.equal(claude.catalogSource, "models.dev");+ assert.equal(claude.catalogSource, "pi");assert.equal(claude.contextWindow, 1_000_000);// Marker leaf is not stripped to gemini-2.5-pro.@@ -214,7 +215,7 @@ test("a relay enriches a uniquely published dated leaf without reseller majorityconst [model] = result.models;// Accept either enrichment from an exact leaf hit, or generic when ambiguous.- if (model.catalogSource === "models.dev") {+ if (model.catalogSource === "pi") {assert.ok(model.contextWindow > 0);} else {assert.equal(model.catalogSource, undefined);diff --git a/apps/desktop/test/provider-lookup-model-handler.test.mjs b/apps/desktop/test/provider-lookup-model-handler.test.mjsindex 0e14ed11a..577924e31 100644--- a/apps/desktop/test/provider-lookup-model-handler.test.mjs+++ b/apps/desktop/test/provider-lookup-model-handler.test.mjs@@ -1,3 +1,4 @@+import { fixtureProvider } from "./pi-catalog-fixtures.mjs";/*** Contract test for the custom-model library lookup.*@@ -37,29 +38,11 @@ function load(relative, imports) {return module.exports;}-const fixture = {- anthropic: {- name: "Anthropic",- api: "https://api.anthropic.com",- models: {- "claude-opus-4.6": {- id: "claude-opus-4.6",- name: "Claude Opus 4.6",- reasoning: true,- reasoning_options: [{ type: "effort", values: ["low", "medium", "high"] }],- modalities: { input: ["text", "image"], output: ["text"] },- limit: { context: 1_000_000, output: 128_000 },- },- },- },-};--async function fixtureCatalog(t) {- const dir = await mkdtemp(join(tmpdir(), "pi-lookup-model-"));- t.after(() => rm(dir, { recursive: true, force: true }));- const catalogPath = join(dir, "api.json");- await writeFile(catalogPath, JSON.stringify(fixture), "utf8");- const catalog = new modelsDev.ModelsDevCatalog({ catalogPath });+async function fixtureCatalog() {+ const catalog = new modelsDev.ModelsDevCatalog({ providers: [fixtureProvider("anthropic", [{+ id: "claude-opus-4.6", reasoning: true, input: ["text", "image"], contextWindow: 1_000_000, maxTokens: 128_000,+ thinkingLevelMap: { off: null, minimal: null, low: "low", medium: "medium", high: "high", xhigh: null, max: null },+ }])] });assert.equal(await catalog.ensureLoaded(), true);return catalog;}@@ -149,6 +132,7 @@ test("a published id returns the snapshot record for the typed id", async (t) =>assert.deepEqual(h.catalogCalls[0], "ensureLoaded");assert.equal(h.catalogCalls[1][0], "findModel");assert.deepEqual(h.catalogCalls[1][1], {+ providerId: "provider-1",vendorKey: "anthropic",baseUrl: undefined,modelId: "Claude-Opus-4.6",diff --git a/apps/desktop/test/remote-event-bridge.test.mjs b/apps/desktop/test/remote-event-bridge.test.mjsindex 9780472d5..7146ba17c 100644--- a/apps/desktop/test/remote-event-bridge.test.mjs+++ b/apps/desktop/test/remote-event-bridge.test.mjs@@ -113,6 +113,22 @@ test("item.started forwards the AgentEvent verbatim under the remote session id"assert.equal(events[0].payload.ts, Date.parse("2026-09-18T10:00:00.000Z"));});+test("nested tool events keep Task ownership separate across the remote bridge", () => {+ for (const parentToolCallId of [undefined, "task-1"]) {+ const { bridge, events } = collect();+ const agentEvent = { type: "tool_start", toolCallId: "read-1", toolName: "Read", args: {} };+ bridge.handle(makeEnvelope({+ turnId: "turn-1",+ nestedParentToolCallId: "code-1",+ ...(parentToolCallId ? { parentToolCallId, agentName: "reader" } : {}),+ payload: { itemType: "tool", itemId: "read-1", event: agentEvent },+ }));+ assert.equal(events[0].payload.nestedParentToolCallId, "code-1");+ assert.equal(events[0].payload.parentToolCallId, parentToolCallId);+ assert.deepEqual(events[0].payload.event, agentEvent);+ }+});+test("session.changed forwards a PlanningStateEvent as a local planning_state AgentEvent", () => {const { bridge, events } = collect();bridge.handle(diff --git a/apps/desktop/test/subagent-model-launch.test.mjs b/apps/desktop/test/subagent-model-launch.test.mjsindex 108f08420..bc247bcec 100644--- a/apps/desktop/test/subagent-model-launch.test.mjs+++ b/apps/desktop/test/subagent-model-launch.test.mjs@@ -40,7 +40,7 @@ test("launch resolves definition-only pins without granting Task.model selectionlogger: { app() {} }, userMcp: { setRecords() {}, toolsForProject: async () => [] },plugins: { listLoaded: () => [], getSkills: () => [], getTools: () => [], getAgentExtensions: () => [] },sessionProjects: new Map(), dataDir: root, vendorOAuth: {},- modelsDevCatalog: { ensureLoaded: async () => {}, findModel: () => undefined },+ modelsDevCatalog: { configureAccount: () => {}, ensureLoaded: async () => {}, findModel: () => undefined },getWorkspacePath: () => root, pluginActiveInProject: () => true,bindingForModel: (row, id) => row.models.find((m) => m.id === id),effectiveSubagentModelConfig: (row, id, catalog) => {diff --git a/apps/desktop/test/subagent-settlement-persistence.test.mjs b/apps/desktop/test/subagent-settlement-persistence.test.mjsindex d9a558a6c..245f1da43 100644--- a/apps/desktop/test/subagent-settlement-persistence.test.mjs+++ b/apps/desktop/test/subagent-settlement-persistence.test.mjs@@ -63,6 +63,56 @@ test("a settled Task snapshot survives outbox recovery with its original turn an});+for (const delegate of [false, true]) {+ test(`nested ${delegate ? "delegate" : "root"} tool lineage survives outbox recovery`, async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-nested-tool-outbox-"));+ const silent = () => undefined;+ try {+ const persistenceOutbox = new PersistenceOutbox(dir, silent);+ const queued = [];+ const enqueue = persistenceOutbox.enqueue.bind(persistenceOutbox);+ persistenceOutbox.enqueue = (...args) => {+ const pending = enqueue(...args);+ queued.push(pending);+ return pending;+ };+ const { persistAgentEvent } = createEventPersistence({+ runtimeState: { host: null },+ activeTurns: new Map([["session", "turn-1"]]),+ activeToolCalls: new Map(),+ activeToolCallKey: (sessionId, toolCallId) => `${sessionId}:${toolCallId}`,+ approvedExecutionIdsBySession: new Map(),+ approvedExecutionTurns: new Map(),+ pendingExecutionFinishes: new Map(),+ planSubmissionTurnIds: new Set(),+ persistenceOutbox,+ logger: { app: silent },+ });+ const lineage = {+ nestedParentToolCallId: "code-1",+ ...(delegate ? { parentToolCallId: "task-1", agentName: "reader" } : {}),+ };+ persistAgentEvent({ sessionId: "session", turnId: "turn-1", ts: 1_000, ...lineage,+ event: { type: "tool_start", toolCallId: "read-1", toolName: "Read", args: { path: "a.ts" } } });+ persistAgentEvent({ sessionId: "session", turnId: "turn-1", ts: 1_100, ...lineage,+ event: { type: "tool_end", toolCallId: "read-1", result: "contents" } });+ await Promise.all(queued);+ const recovered = new PersistenceOutbox(dir, silent);+ const writes = [];+ await recovered.flush(() => ({ isAvailable: () => true, call: async (_method, params) => {+ writes.push(params);+ return {};+ } }));+ assert.equal(writes.length, 1);+ assert.equal(writes[0].turnId, "turn-1");+ assert.equal(writes[0].message.nestedParentToolCallId, "code-1");+ assert.equal(writes[0].message.parentToolCallId, delegate ? "task-1" : undefined);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+ });+}+test("settlement replacing an in-flight Task append is written after the initial snapshot", async () => {const dir = await mkdtemp(join(tmpdir(), "pi-subagent-outbox-race-"));const outbox = new PersistenceOutbox(dir, () => undefined);@@ -94,3 +144,32 @@ test("settlement replacing an in-flight Task append is written after the initialawait rm(dir, { recursive: true, force: true });}});++test("independent usage aggregates survive an unavailable Host and outbox restart", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-usage-outbox-"));+ try {+ const outbox = new PersistenceOutbox(dir, () => undefined);+ const queued = [];+ const enqueue = outbox.enqueue.bind(outbox);+ outbox.enqueue = (...args) => { const promise = enqueue(...args); queued.push(promise); return promise; };+ const { persistAgentEvent } = createEventPersistence({+ runtimeState: { host: null }, activeTurns: new Map([["session", "turn"]]),+ activeToolCalls: new Map(), activeToolCallKey: (s, t) => `${s}:${t}`,+ approvedExecutionIdsBySession: new Map(), approvedExecutionTurns: new Map(),+ pendingExecutionFinishes: new Map(), planSubmissionTurnIds: new Set(),+ persistenceOutbox: outbox, logger: { app: () => undefined }, addActiveTurnUsage: () => undefined,+ });+ for (const id of ["image-a", "image-b", "image-a"]) {+ const operation = { operationId: id, inputTokens: 10, outputTokens: 2, totalTokens: 12 };+ persistAgentEvent({ sessionId: "session", turnId: "turn", ts: 1, event: {+ type: "usage", usage: { ...operation, operationId: undefined, aggregation: "aggregate", operations: [operation] },+ } });+ }+ await Promise.all(queued);+ const recovered = new PersistenceOutbox(dir, () => undefined);+ const written = [];+ await recovered.flush(() => ({ isAvailable: () => true, call: async (method, params) => { if (method === "session.recordUsage") written.push(params); return {}; } }));+ assert.deepEqual(written.flatMap(row => row.usage.operations.map(op => op.operationId)).sort(), ["image-a", "image-b"]);+ assert.ok(written.every(row => row.turnId === "turn"));+ } finally { await rm(dir, { recursive: true, force: true }); }+});diff --git a/apps/desktop/test/subagent-transcript-turns.test.mjs b/apps/desktop/test/subagent-transcript-turns.test.mjsindex 66cbdfb0f..3e77ad7e3 100644--- a/apps/desktop/test/subagent-transcript-turns.test.mjs+++ b/apps/desktop/test/subagent-transcript-turns.test.mjs@@ -136,6 +136,27 @@ test("parallel delegates never mix into each other's turns", () => {);});+test("nested tools stay with their owning delegate, not their tool parent", () => {+ const messages = [+ taskCall("task-1", "Inspect files", { toolResult: { delegationId: "delegate-1" } }),+ message("root-read", "root result", {+ role: "tool", toolName: "Read", nestedParentToolCallId: "root-code",+ }),+ message("code-1", "running", {+ role: "tool", toolName: "codemode", parentToolCallId: "task-1", agentName: "reader",+ }),+ message("nested-read", "delegate result", {+ role: "tool", toolName: "Read", parentToolCallId: "task-1",+ nestedParentToolCallId: "code-1", agentName: "reader",+ }),+ ];+ const transcript = buildSubagentTranscript(messages, "delegate-1");+ assert.equal(transcript.agentName, "reader");+ assert.deepEqual(transcript.turns[0].rows.map((row) => row.message.id), ["code-1", "nested-read"]);+ assert.equal(transcript.turns[0].rows[1].message.nestedParentToolCallId, "code-1");+ assert.equal(buildSubagentTranscript(messages, "root-code"), null);+});+test("an unknown delegation id yields no transcript", () => {const messages = [taskCall("call-1", "Task", {toolResult: { delegationId: "del-1" },diff --git a/apps/desktop/test/subagent-wiring.test.mjs b/apps/desktop/test/subagent-wiring.test.mjsindex 6e7085042..68b7b3cc0 100644--- a/apps/desktop/test/subagent-wiring.test.mjs+++ b/apps/desktop/test/subagent-wiring.test.mjs@@ -50,7 +50,7 @@ test("subagent models use the exact stored binding for thinking capability", ()assert.match(providerCatalogSource, /const effectiveSubagentModelConfig = \(/);assert.match(providerCatalogSource,- /const effectiveSubagentModelConfig = \([\s\S]*?bindingForModel\(provider, modelId\)[\s\S]*?modelConfigWithBinding\(/,+ /const effectiveSubagentModelConfig = \([\s\S]*?modelsDevCatalog\.configureAccount\(provider\)[\s\S]*?modelsDevCatalog\.modelConfigFor\(/,);// The helper is used for definition pins, the pre-resolved delegation// catalog, and the on-demand Task.model path.@@ -91,8 +91,8 @@ test("persisted subagent rows keep their attribution", () => {/function subagentTagged\(message: UiMessage, envelope: AgentEventEnvelope\)/,);assert.match(eventPersistenceSource, /message: subagentTagged\(event\.message, envelope\),/);- assert.match(eventPersistenceSource, /started\?\.parentToolCallId/);- assert.match(eventPersistenceSource, /started\?\.agentName/);+ assert.match(eventPersistenceSource, /tagMessageToolLineage\(message, envelope\)/);+ assert.match(eventPersistenceSource, /toolCallLineage\(started \?\? \{\}, envelope\)/);// host-core round-trips both through the message `meta` object.assert.match(hostSessionsSource, /pub parent_tool_call_id: Option<String>/);assert.match(hostSessionsSource, /meta_obj\.insert\("parentToolCallId"\.into\(\)/);diff --git a/apps/desktop/test/todo-recovery.test.mjs b/apps/desktop/test/todo-recovery.test.mjsindex a3e170d6c..fdbb33f1c 100644--- a/apps/desktop/test/todo-recovery.test.mjs+++ b/apps/desktop/test/todo-recovery.test.mjs@@ -92,13 +92,14 @@ const snapshot = (sessionId, revision, content = "Recovered work") => ({test("TodoDock recovers a failed first read when the host returns without a session switch", async (t) => {const diagnostics = t.mock.method(console, "error", () => undefined);+ const recoveryErrors = () => diagnostics.mock.calls.filter(call => call.arguments[0] === "Session checklist recovery failed");const h = await harness();try {assert.equal(h.render("session-a"), "");await h.settle();assert.deepEqual(h.reads, ["session-a"]);- assert.equal(diagnostics.mock.callCount(), 1);- assert.match(diagnostics.mock.calls[0].arguments[1].message, /host unavailable/);+ assert.equal(recoveryErrors().length, 1);+ assert.match(recoveryErrors()[0].arguments[1].message, /host unavailable/);h.setRead(async (id) => snapshot(id, 1));h.emit(IPC.event.hostStatus, { ok: true, component: "host" });await h.settle();@@ -179,6 +180,7 @@ test("TodoDock never reads the local host for remote or native sessions", asynctest("TodoDock rejects a mismatched snapshot and ignores pending work after unmount", async (t) => {const diagnostics = t.mock.method(console, "error", () => undefined);+ const recoveryErrors = () => diagnostics.mock.calls.filter(call => call.arguments[0] === "Session checklist recovery failed");const h = await harness();const pending = [];h.setRead(() => new Promise((resolve, reject) => pending.push({ resolve, reject })));@@ -187,12 +189,12 @@ test("TodoDock rejects a mismatched snapshot and ignores pending work after unmopending[0].resolve(snapshot("different-session", 1));await h.settle();assert.equal(h.store.getState().sessionTodos["different-session"], undefined);- assert.equal(diagnostics.mock.callCount(), 1);+ assert.equal(recoveryErrors().length, 1);h.emit(IPC.event.hostStatus, { ok: true, component: "host", restarted: true });h.unmount();pending[1].reject(new Error("Disposed read"));await h.settle();- assert.equal(diagnostics.mock.callCount(), 1);+ assert.equal(recoveryErrors().length, 1);assert.equal(h.listenerCount(IPC.event.hostStatus), 0);} finally { await h.close(); }});diff --git a/apps/desktop/test/vendor-oauth-login.test.mjs b/apps/desktop/test/vendor-oauth-login.test.mjsindex 6dd17f899..8016ae3be 100644--- a/apps/desktop/test/vendor-oauth-login.test.mjs+++ b/apps/desktop/test/vendor-oauth-login.test.mjs@@ -79,7 +79,7 @@ function fakeHost() {* test exercises the credential path rather than mocking it away.*/function fakeModels(credentials, { login, models: configuredModels, provider: providerOverride } = {}) {- const provider = providerOverride ?? {+ let provider = providerOverride ?? {id: "anthropic",name: "Anthropic",baseUrl: "https://api.anthropic.com",@@ -124,13 +124,18 @@ function fakeModels(credentials, { login, models: configuredModels, provider: prmaxTokens: 8_192,},];+ provider = { ...provider, getModels: () => models };return {+ setProvider: next => { provider = next; },getProviders: () => [provider],getProvider: (id) => (id === provider.id ? provider : undefined),- refresh: async () => ({ aborted: false, errors: new Map() }),- getAvailable: async () => models,+ refresh: async (options = {}) => {+ await provider.refreshModels?.({ allowNetwork: options.allowNetwork !== false, signal: options.signal ?? new AbortController().signal, force: options.force, publish: async ({ update }) => { update?.(); return true; } });+ return { aborted: false, errors: new Map() };+ },+ getAvailable: async () => provider.getModels(),getModel: (providerId, modelId) => providerId === provider.id- ? models.find((model) => model.id === modelId)+ ? provider.getModels().find((model) => model.id === modelId): undefined,login:login ??@@ -170,7 +175,7 @@ function harness(options = {}) {let counter = 0;const stores = [];const oauth = new VendorOAuth({- call: host.call,+ call: (method, params) => options.call ? options.call(method, params, host.call) : host.call(method, params),emit: (event) => events.push(event),openExternal: async (url) => {opened.push(url);@@ -181,6 +186,8 @@ function harness(options = {}) {return fakeModels(store, options);},modelConfigFor: options.modelConfigFor,+ onAccountModels: options.onAccountModels,+ onAccountRemoved: options.onAccountRemoved,log: options.log,newId: () => `id-${++counter}`,fetch:@@ -338,7 +345,7 @@ test("cancelling takes the half-created row back out", async () => {await waitFor(events, "cancelled");assert.equal(host.providers.size, 0);- assert.equal(host.secrets.size, 0);+ assert.deepEqual([...host.secrets.keys()], ["secret:installation:oauth-device-id"]);// The pending prompt is closed out so the dialog cannot hang on it.assert.ok(events.some((event) => event.kind === "promptCancelled"));});@@ -526,7 +533,7 @@ test("Meta OAuth removes the provider row when API-key minting reports an expireconst error = await waitFor(events, "error", 1200);assert.match(error.message, /Meta session expired/);assert.equal(host.providers.size, 0);- assert.equal(host.secrets.size, 0);+ assert.deepEqual([...host.secrets.keys()], ["secret:installation:oauth-device-id"]);} finally {globalThis.fetch = previousFetch;}@@ -549,6 +556,7 @@ test("the real pi-ai catalog offers every vendor account we ship", async () => {"github-copilot","kimi-coding","meta",+ "openai","openai-codex","openrouter","radius",@@ -577,7 +585,7 @@ test("the ChatGPT OAuth catalog includes GPT-6 Astra", async () => {assert.equal(model.api, "openai-codex-responses");});-test("the pi-ai 0.87.1 OAuth catalogs include the stable model wires", async () => {+test("the pi-ai 0.99.1 OAuth catalogs include the stable model wires", async () => {const { OPENAI_CODEX_MODELS } = await import("@earendil-works/pi-ai/providers/openai-codex.models");@@ -647,7 +655,7 @@ test("credential writes for one account run one at a time", async () => {// pi-ai's locked refresh depends on to avoid double-refreshing a token.assert.equal(overlapped, false);assert.deepEqual(seen, ["access-for-abc", "rotated-1"]);- assert.equal(host.secrets.size, 1);+ assert.deepEqual([...host.secrets.keys()].sort(), ["secret:installation:oauth-device-id", secretRefForProviderOauth("row-1")].sort());});test("conversation-model filter drops xAI image and video ids", () => {@@ -793,6 +801,8 @@ async function liveCopilotBinding(sibling, options = {}) {},models: [sibling],modelConfigFor: options.modelConfigFor,+ onAccountModels: options.onAccountModels,+ onAccountRemoved: options.onAccountRemoved,fetch: async () => new Response(JSON.stringify({data: [{ id: modelId, model_picker_enabled: true, policy: { state: "enabled" } }],}), { status: 200, headers: { "content-type": "application/json" } }),@@ -1058,3 +1068,67 @@ test("a failed ChatGPT model list logs the status and a token-free response exceassert.equal(logged.includes(code), false);assert.equal(logged.includes(code.split(".")[1]), false);});++test("failed Host deletion keeps the account catalog and credentials usable", async () => {+ const host = fakeHost();+ const row = { id: "saved", vendorKey: "anthropic", authKind: "oauth" };+ host.providers.set(row.id, row);+ host.secrets.set(secretRefForProviderOauth(row.id), JSON.stringify({+ type: "oauth", access: "fixture-access", refresh: "fixture-refresh", expires: 4102444800000,+ }));+ const removed = [];+ const oauth = new VendorOAuth({+ call: async (method, params) => {+ if (method === "providers.delete") throw new Error("fixture Host deletion failed");+ return host.call(method, params);+ },+ emit: () => {}, openExternal: async () => {},+ createModels: store => fakeModels(store),+ onAccountRemoved: id => removed.push(id),+ });+ assert.deepEqual(await oauth.resolveAuth(row.id), { apiKey: "fixture-access" });+ await assert.rejects(oauth.deleteAccount(row.id), /Host deletion failed/);+ assert.deepEqual(removed, []);+ assert.deepEqual(await oauth.resolveAuth(row.id), { apiKey: "fixture-access" });+});++test("an unsigned OAuth account cannot borrow an ambient API key", async (t) => {+ const previous = process.env.ANTHROPIC_API_KEY;+ process.env.ANTHROPIC_API_KEY = "fixture-ambient-not-this-account";+ t.after(() => { if (previous === undefined) delete process.env.ANTHROPIC_API_KEY; else process.env.ANTHROPIC_API_KEY = previous; });+ const host = fakeHost();+ host.providers.set("unsigned", { id: "unsigned", vendorKey: "anthropic", authKind: "oauth", enabled: true });+ const oauth = new VendorOAuth({ call: host.call, emit: () => undefined, openExternal: async () => undefined,+ fetch: async () => { throw new Error("No network expected"); } });+ await assert.rejects(oauth.resolveAuth("unsigned"), /not signed in/);+});++test("forced account refresh bypasses the live model TTL", async () => {+ let models = ["gpt-6-luna"];+ let attached;+ const h = harness({ onAccountModels: (_id, collection) => { attached = collection; }, provider: codexProvider(), models: [codexModel("gpt-6-luna"), codexModel("gpt-6.1-sol")],+ fetch: async () => Response.json({ models: models.map(slug => ({ slug, visibility: "list" })) }) });+ const { loginId } = await h.oauth.start("openai-codex");+ const prompt = await waitFor(h.events, "prompt");+ h.oauth.respond({ loginId, promptId: prompt.request.promptId, value: codexLoginCode() });+ const done = await waitFor(h.events, "done");+ models = ["gpt-6.1-sol"];+ await attached.refresh({ allowNetwork: true, force: true });+ assert.deepEqual((await h.oauth.listModels(done.providerId)).map(model => model.modelId), ["gpt-6.1-sol"]);+});++test("failed cleanup after a rejected login preserves the surviving account instance", async () => {+ const attached = []; const removed = [];+ const h = harness({ login: async () => { throw new Error("fixture login rejected"); },+ call: (method, params, call) => { if (method === "providers.delete") throw new Error("fixture delete rejected"); return call(method, params); },+ onAccountModels: (id, models) => attached.push({ id, models }),+ onAccountRemoved: id => removed.push(id),+ });+ await h.oauth.start("anthropic");+ await waitFor(h.events, "error");+ assert.equal(h.host.providers.size, 1);+ assert.deepEqual(removed, []);+ const rowId = [...h.host.providers.keys()][0];+ await h.oauth.listModels(rowId);+ assert.equal(attached.filter(account => account.id === rowId).length, 1);+});diff --git a/crates/host-core/src/plugin_sessions.rs b/crates/host-core/src/plugin_sessions.rsindex da9eb4022..3dee8f6a3 100644--- a/crates/host-core/src/plugin_sessions.rs+++ b/crates/host-core/src/plugin_sessions.rs@@ -257,6 +257,7 @@ fn parse_message(tool_duration_ms: None,is_error: None,parent_tool_call_id: None,+ nested_parent_tool_call_id: None,agent_name: None,hosted_search: None,session_message: None,diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 2417ce829..84d30a9b8 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -2937,6 +2937,23 @@ async fn handle_request(.map_err(session_collaboration_rpc_err)?;Ok(json!({ "turnId": turn_id }))}+ "session.recordUsage" => {+ let session_id = params+ .get("sessionId")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;+ let turn_id = params+ .get("turnId")+ .and_then(Value::as_str)+ .ok_or_else(|| rpc_err(1002, "turnId required", "INVALID_PARAMS"))?;+ let usage = params+ .get("usage")+ .ok_or_else(|| rpc_err(1002, "usage required", "INVALID_PARAMS"))?;+ let st = state.lock().await;+ let recorded = sessions::record_usage(&st.db, session_id, turn_id, usage)+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;+ Ok(json!({ "ok": recorded }))+ }"session.endTurn" => {let turn_id = params.get("turnId")diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 309288708..778b3c344 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -12,6 +12,8 @@ use std::sync::{Mutex, OnceLock};use crate::transcripts::{self, CompactionRecord, MessageRecord, RevisionRecord};mod fork_files;+mod usage;+pub use usage::record_usage;pub const MODES: [&str; 3] = ["plan", "goal", "agent"];@@ -127,6 +129,10 @@ pub struct MessageUsage {#[serde(skip_serializing_if = "Option::is_none")]pub reasoning_tokens: Option<i64>,pub total_tokens: i64,+ /// Additive accounting provenance and atomic operation ledger. Preserve these+ /// JSON fields verbatim, including fields introduced by a newer producer.+ #[serde(default, flatten)]+ pub accounting: serde_json::Map<String, Value>,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]@@ -215,6 +221,8 @@ pub struct UiMessage {/// runtime excludes them from the parent's model context.#[serde(skip_serializing_if = "Option::is_none")]pub parent_tool_call_id: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub nested_parent_tool_call_id: Option<String>,/// Subagent definition name that produced the row.#[serde(skip_serializing_if = "Option::is_none")]pub agent_name: Option<String>,@@ -326,17 +334,7 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringmeta_obj.insert("providerId".into(), json!(provider_id));}if let Some(usage) = &message.usage {- meta_obj.insert(- "usage".into(),- json!({- "inputTokens": usage.input_tokens,- "outputTokens": usage.output_tokens,- "cacheReadTokens": usage.cache_read_tokens,- "cacheWriteTokens": usage.cache_write_tokens,- "reasoningTokens": usage.reasoning_tokens,- "totalTokens": usage.total_tokens,- }),- );+ meta_obj.insert("usage".into(), json!(usage));}if let Some(duration) = message.response_duration_ms {meta_obj.insert("responseDurationMs".into(), json!(duration));@@ -359,6 +357,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<Stringif let Some(parent) = &message.parent_tool_call_id {meta_obj.insert("parentToolCallId".into(), json!(parent));}+ if let Some(parent) = &message.nested_parent_tool_call_id {+ meta_obj.insert("nestedParentToolCallId".into(), json!(parent));+ }if let Some(agent) = &message.agent_name {meta_obj.insert("agentName".into(), json!(agent));}@@ -493,6 +494,22 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {cache_write_tokens: value.get("cacheWriteTokens").and_then(|v| v.as_i64()),reasoning_tokens: value.get("reasoningTokens").and_then(|v| v.as_i64()),total_tokens,+ accounting: value+ .as_object()?+ .iter()+ .filter(|(key, _)| {+ !matches!(+ key.as_str(),+ "inputTokens"+ | "outputTokens"+ | "cacheReadTokens"+ | "cacheWriteTokens"+ | "reasoningTokens"+ | "totalTokens"+ )+ })+ .map(|(key, value)| (key.clone(), value.clone()))+ .collect(),})});let error = meta.get("error").cloned();@@ -508,6 +525,10 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {.get("parentToolCallId").and_then(|v| v.as_str()).map(|s| s.to_string());+ let nested_parent_tool_call_id = meta+ .get("nestedParentToolCallId")+ .and_then(Value::as_str)+ .map(str::to_string);let agent_name = meta.get("agentName").and_then(|v| v.as_str())@@ -603,6 +624,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {tool_duration_ms: block.get("durationMs").and_then(|v| v.as_i64()),is_error,parent_tool_call_id,+ nested_parent_tool_call_id,agent_name,hosted_search: hosted_search.clone(),}@@ -646,6 +668,7 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {tool_duration_ms: None,is_error,parent_tool_call_id,+ nested_parent_tool_call_id,agent_name,hosted_search,}@@ -3458,6 +3481,21 @@ pub fn end_turn_settling("completed" | "aborted" | "error" => status,_ => "completed",};+ let existing_usage: Option<String> = db+ .conn()+ .query_row(+ "SELECT usage_json FROM turns WHERE id = ?1",+ params![turn_id],+ |row| row.get(0),+ )+ .optional()?+ .flatten();+ let existing_usage = existing_usage+ .as_deref()+ .map(serde_json::from_str::<Value>)+ .transpose()?;+ let merged_usage = usage.map(|next| usage::merge_usage(existing_usage.as_ref(), next));+ let usage = merged_usage.as_ref().or(existing_usage.as_ref());let input_tokens = usage.and_then(|u| u.get("inputTokens")).and_then(|v| v.as_i64());@@ -3487,6 +3525,19 @@ pub fn end_turn_settling(usage.map(|u| u.to_string()),turn_id,])?;+ // A replay after startup recovery may complete accounting for a terminal+ // turn, but must never change its settled status or emit another notification.+ if n == 0 && usage.is_some_and(|value| value.get("operations").is_some()) {+ tx.execute(+ "UPDATE turns SET input_tokens = ?1, output_tokens = ?2, usage_json = ?3 WHERE id = ?4",+ params![+ input_tokens,+ output_tokens,+ usage.map(Value::to_string),+ turn_id+ ],+ )?;+ }let notification = if n > 0 && create_notification {notifications::insert_for_terminal_turn(&tx, turn_id, status, error_code)?} else {@@ -3889,6 +3940,7 @@ mod tests {tool_duration_ms: None,is_error: None,parent_tool_call_id: None,+ nested_parent_tool_call_id: None,agent_name: None,hosted_search: None,session_message: None,@@ -4536,6 +4588,7 @@ mod tests {tool_duration_ms: Some(1_000),is_error: None,parent_tool_call_id: None,+ nested_parent_tool_call_id: None,agent_name: None,hosted_search: None,session_message: None,@@ -4934,6 +4987,79 @@ mod tests {assert_eq!(full.messages[1].content.len(), 80_000);}+ #[test]+ fn nested_lineage_roundtrips_independently_of_legacy_task_parent() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ for (id, task, nested) in [+ ("legacy", Some("task-1"), None),+ ("nested-root", None, Some("code-root")),+ ("nested-delegate", Some("task-1"), Some("code-child")),+ ] {+ let mut message = user_msg(id, "result", "2026-09-30T00:00:00Z");+ message.role = "assistant".into();+ message.parent_tool_call_id = task.map(str::to_owned);+ message.nested_parent_tool_call_id = nested.map(str::to_owned);+ append_message(&db, &session.id, &message, None).unwrap();+ }+ let detail = get_session(&db, &session.id).unwrap().unwrap();+ assert_eq!(+ detail.messages[0].parent_tool_call_id.as_deref(),+ Some("task-1")+ );+ assert_eq!(detail.messages[0].nested_parent_tool_call_id, None);+ assert_eq!(detail.messages[1].parent_tool_call_id, None);+ assert_eq!(+ detail.messages[1].nested_parent_tool_call_id.as_deref(),+ Some("code-root")+ );+ assert_eq!(+ detail.messages[2].parent_tool_call_id.as_deref(),+ Some("task-1")+ );+ assert_eq!(+ detail.messages[2].nested_parent_tool_call_id.as_deref(),+ Some("code-child")+ );+ }++ #[test]+ fn usage_accounting_roundtrips_without_rewriting_legacy_tokens() {+ let db = test_db();+ let session = create_session(&db, None, None, None, None, None).unwrap();+ let fixtures = [+ json!({"inputTokens": 12, "outputTokens": 3, "totalTokens": 15}),+ json!({+ "inputTokens": 12, "outputTokens": 3, "totalTokens": 15,+ "operationId": "request-1", "usageOrigin": "pi",+ "providerId": "physical-account", "modelId": "physical-model",+ "costStatus": "reported", "aggregation": "operation",+ "cost": {"input": 0.12, "output": 0.03, "cacheRead": 0, "cacheWrite": 0, "total": 0.15}+ }),+ json!({+ "inputTokens": 12, "outputTokens": 3, "totalTokens": 15,+ "costStatus": "unknown", "aggregation": "aggregate",+ "operations": [+ {"operationId": "child-1", "usageOrigin": "pi", "inputTokens": 10, "outputTokens": 2, "totalTokens": 12, "costStatus": "unknown"},+ {"operationId": "classifier-1", "usageOrigin": "pi", "inputTokens": 2, "outputTokens": 1, "totalTokens": 3, "costStatus": "estimated", "cost": {"input": 0.2, "output": 0.1, "cacheRead": 0, "cacheWrite": 0, "total": 0.3}}+ ]+ }),+ ];+ for (index, usage) in fixtures.iter().enumerate() {+ let mut message = user_msg(&format!("usage-{index}"), "answer", "2026-09-30T00:00:00Z");+ message.role = "assistant".into();+ message.usage = Some(serde_json::from_value(usage.clone()).unwrap());+ append_message(&db, &session.id, &message, None).unwrap();+ // Replayed message_end replaces a row; it must not duplicate usage.+ append_message(&db, &session.id, &message, None).unwrap();+ }+ let detail = get_session(&db, &session.id).unwrap().unwrap();+ assert_eq!(detail.messages.len(), fixtures.len());+ for (message, expected) in detail.messages.iter().zip(fixtures) {+ assert_eq!(json!(message.usage), expected);+ }+ }+#[test]fn assistant_thinking_roundtrips_as_canonical_blocks() {let db = test_db();@@ -4959,6 +5085,7 @@ mod tests {cache_write_tokens: None,reasoning_tokens: Some(5),total_tokens: 48,+ accounting: serde_json::Map::new(),}),response_duration_ms: Some(2_000),response_output_tokens: Some(34),@@ -4975,6 +5102,7 @@ mod tests {tool_duration_ms: None,is_error: None,parent_tool_call_id: None,+ nested_parent_tool_call_id: None,agent_name: None,hosted_search: None,session_message: None,@@ -5054,6 +5182,7 @@ mod tests {tool_duration_ms: None,is_error: None,parent_tool_call_id: None,+ nested_parent_tool_call_id: None,agent_name: None,hosted_search: Some(json!({"status": "completed",diff --git a/crates/host-core/src/sessions/usage.rs b/crates/host-core/src/sessions/usage.rsnew file mode 100644index 000000000..42a4327f7--- /dev/null+++ b/crates/host-core/src/sessions/usage.rs@@ -0,0 +1,287 @@+//! Durable physical-request accounting in the existing turn JSON column.+//! No transcript row, second database, or schema migration is needed.++use anyhow::{anyhow, Result};+use rusqlite::{params, OptionalExtension};+use serde_json::{json, Map, Value};++use crate::db::Database;++const TOKENS: [&str; 6] = [+ "inputTokens",+ "outputTokens",+ "cacheReadTokens",+ "cacheWriteTokens",+ "reasoningTokens",+ "totalTokens",+];+const COSTS: [&str; 5] = ["input", "output", "cacheRead", "cacheWrite", "total"];++fn operations(usage: &Value) -> Vec<Value> {+ if let Some(records) = usage+ .get("operations")+ .and_then(Value::as_array)+ .filter(|v| !v.is_empty())+ {+ return records.clone();+ }+ if usage.get("operationId").and_then(Value::as_str).is_some() {+ let mut record = usage.clone();+ if let Some(object) = record.as_object_mut() {+ object.remove("operations");+ object.remove("aggregation");+ }+ return vec![record];+ }+ vec![]+}++fn count(value: &Value, key: &str) -> i64 {+ value.get(key).and_then(Value::as_i64).unwrap_or(0).max(0)+}++fn known_cost(record: &Value) -> bool {+ record.get("costStatus").and_then(Value::as_str) != Some("unknown")+ && COSTS.iter().all(|key| {+ record+ .get("cost")+ .and_then(|c| c.get(key))+ .and_then(Value::as_f64)+ .is_some_and(|n| n.is_finite() && n >= 0.0)+ })+}+fn sum_counts(records: &[Value], key: &str) -> i64 {+ records.iter().fold(0_i64, |total, record| {+ total.saturating_add(count(record, key))+ })+}+fn validate(usage: &Value) -> Result<()> {+ let records = operations(usage);+ if records.is_empty() {+ return Err(anyhow!("usage requires a physical operation identity"));+ }+ for record in records {+ if record+ .get("operationId")+ .and_then(Value::as_str)+ .is_none_or(str::is_empty)+ {+ return Err(anyhow!("usage operationId required"));+ }+ for key in TOKENS {+ if record.get(key).is_none()+ && !["inputTokens", "outputTokens", "totalTokens"].contains(&key)+ {+ continue;+ }+ if record+ .get(key)+ .and_then(Value::as_i64)+ .is_none_or(|v| v < 0)+ {+ return Err(anyhow!("invalid usage token count"));+ }+ }+ }+ Ok(())+}++/// End-turn is a snapshot, not another charge. Union its ledger with requests+/// already persisted before the process stopped. Legacy token-only snapshots+/// retain their historical replacement semantics.+pub(super) fn merge_usage(existing: Option<&Value>, incoming: &Value) -> Value {+ let Some(existing) = existing else {+ return incoming.clone();+ };+ let left = operations(existing);+ let right = operations(incoming);+ if left.is_empty() && right.is_empty() {+ return incoming.clone();+ }+ let mut records: Vec<Value> = Vec::new();+ for record in left.iter().chain(&right) {+ let Some(id) = record.get("operationId").and_then(Value::as_str) else {+ continue;+ };+ if let Some(index) = records+ .iter()+ .position(|v| v.get("operationId").and_then(Value::as_str) == Some(id))+ {+ let previous = &records[index];+ let incoming_count = count(record, "totalTokens");+ let previous_count = count(previous, "totalTokens");+ if incoming_count > previous_count+ || (incoming_count == previous_count+ && (!known_cost(previous)+ || (known_cost(record)+ && record.get("costStatus").and_then(Value::as_str)+ == Some("reported"))))+ {+ records[index] = record.clone();+ }+ } else {+ records.push(record.clone());+ }+ }+ let mut merged = Map::new();+ let mut has_legacy = false;+ for key in TOKENS {+ let left_count: i64 = sum_counts(&left, key);+ let right_count: i64 = sum_counts(&right, key);+ let residual = count(existing, key)+ .saturating_sub(left_count)+ .max(count(incoming, key).saturating_sub(right_count))+ .max(0);+ has_legacy |= residual > 0;+ let total = sum_counts(&records, key).saturating_add(residual);+ if total > 0+ || ["inputTokens", "outputTokens", "totalTokens"].contains(&key)+ || existing.get(key).is_some()+ || incoming.get(key).is_some()+ {+ merged.insert(key.into(), json!(total));+ }+ }+ let known = !has_legacy+ && records.iter().all(known_cost)+ && COSTS.iter().all(|key| {+ records+ .iter()+ .filter_map(|v| v.get("cost")?.get(key)?.as_f64())+ .sum::<f64>()+ .is_finite()+ });+ if known {+ let mut cost = Map::new();+ for key in COSTS {+ let total: f64 = records+ .iter()+ .filter_map(|v| v.get("cost")?.get(key)?.as_f64())+ .sum();+ cost.insert(key.into(), json!(total));+ }+ merged.insert("cost".into(), Value::Object(cost));+ let reported = records+ .iter()+ .all(|v| v.get("costStatus").and_then(Value::as_str) == Some("reported"));+ merged.insert(+ "costStatus".into(),+ json!(if reported { "reported" } else { "estimated" }),+ );+ } else {+ merged.insert("costStatus".into(), json!("unknown"));+ }+ merged.insert("aggregation".into(), json!("aggregate"));+ merged.insert("operations".into(), Value::Array(records));+ Value::Object(merged)+}++/// The immutable session/turn pair is checked even when a durable outbox is+/// replayed after shutdown. Late writes may complete the old turn's bill, never+/// the newer turn's. Deleted sessions/turns are not recreated.+pub fn record_usage(db: &Database, session_id: &str, turn_id: &str, usage: &Value) -> Result<bool> {+ validate(usage)?;+ let existing: Option<Option<String>> = db+ .conn()+ .query_row(+ "SELECT usage_json FROM turns WHERE id = ?1 AND session_id = ?2",+ params![turn_id, session_id],+ |row| row.get(0),+ )+ .optional()?;+ let Some(existing) = existing else {+ return Ok(false);+ };+ let parsed = existing+ .as_deref()+ .map(serde_json::from_str::<Value>)+ .transpose()?;+ let merged = merge_usage(parsed.as_ref(), usage);+ db.conn().execute(+ "UPDATE turns SET usage_json = ?1, input_tokens = ?2, output_tokens = ?3 WHERE id = ?4 AND session_id = ?5",+ params![merged.to_string(), count(&merged, "inputTokens"), count(&merged, "outputTokens"), turn_id, session_id],+ )?;+ Ok(true)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn operation(id: &str, known: bool) -> Value {+ let mut value = json!({"operationId": id, "usageOrigin": "pi", "inputTokens": 12, "outputTokens": 3, "totalTokens": 15, "costStatus": "unknown"});+ if known {+ value["costStatus"] = json!("reported");+ value["cost"] = json!({"input": 0.12, "output": 0.03, "cacheRead": 0, "cacheWrite": 0, "total": 0.15});+ }+ value+ }++ #[test]+ fn usage_ledger_deduplicates_child_parent_and_replayed_snapshots() {+ let child = operation("child", true);+ let other = operation("classifier", false);+ let total = merge_usage(Some(&child), &other);+ assert_eq!(total["totalTokens"], 30);+ assert_eq!(total["costStatus"], "unknown");+ assert!(total.get("cost").is_none());+ assert_eq!(total["operations"][0]["cost"]["total"], 0.15);+ assert_eq!(merge_usage(Some(&total), &child), total);+ assert_eq!(merge_usage(Some(&total), &total), total);+ }++ #[test]+ fn equal_token_replay_preserves_known_cost() {+ let known = operation("request", true);+ let unknown = operation("request", false);+ for (left, right) in [(&known, &unknown), (&unknown, &known)] {+ let total = merge_usage(Some(left), right);+ assert_eq!(total["costStatus"], "reported");+ assert_eq!(total["cost"]["total"], 0.15);+ }+ }++ #[test]+ fn oversized_counts_cannot_overflow_the_ledger() {+ let left = json!({"operationId": "left", "inputTokens": i64::MAX, "outputTokens": 0, "totalTokens": i64::MAX});+ let right =+ json!({"operationId": "right", "inputTokens": 1, "outputTokens": 0, "totalTokens": 1});+ let total = merge_usage(Some(&left), &right);+ assert_eq!(total["totalTokens"], i64::MAX);+ assert_eq!(total["inputTokens"], i64::MAX);+ }++ #[test]+ fn usage_ledger_survives_restart_and_rejects_wrong_turn_owner() {+ let dir = std::env::temp_dir().join(format!("pi-usage-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("test.sqlite");+ let db = Database::open(&path).unwrap();+ let session = super::super::create_session(&db, None, None, None, None, None).unwrap();+ let turn = super::super::begin_turn(&db, &session.id, None, None).unwrap();+ let child = operation("child", true);+ assert!(!record_usage(&db, "other-session", &turn, &child).unwrap());+ assert!(record_usage(&db, &session.id, &turn, &child).unwrap());+ drop(db);+ let db = Database::open(&path).unwrap();+ assert!(record_usage(&db, &session.id, &turn, &child).unwrap());+ let parent = merge_usage(Some(&child), &operation("parent", true));+ super::super::end_turn(&db, &turn, "completed", None, Some(&parent), false).unwrap();+ super::super::end_turn(&db, &turn, "completed", None, Some(&parent), false).unwrap();+ assert!(record_usage(&db, &session.id, &turn, &child).unwrap());+ let stored: String = db+ .conn()+ .query_row(+ "SELECT usage_json FROM turns WHERE id = ?1",+ params![turn],+ |row| row.get(0),+ )+ .unwrap();+ let stored: Value = serde_json::from_str(&stored).unwrap();+ assert_eq!(stored["totalTokens"], 30);+ assert_eq!(stored["cost"]["total"], 0.3);+ assert_eq!(stored["operations"].as_array().unwrap().len(), 2);+ drop(db);+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/docs/adr/0134-models-dev-sole-model-metadata-source.md b/docs/adr/0134-models-dev-sole-model-metadata-source.mdindex b4cf22fcc..7d6bcfee2 100644--- a/docs/adr/0134-models-dev-sole-model-metadata-source.md+++ b/docs/adr/0134-models-dev-sole-model-metadata-source.md@@ -1,6 +1,6 @@# ADR 0134: Use models.dev as the sole model metadata source with a local snapshot-- Status: Accepted+- Status: Superseded by [Pi 0.99.1 authority](pi-ai-core-0991-authority.md)- Date: 2026-08-29- Deciders: PI-Desktop core- Amends: ADR 0027, ADR 0133, D136, D266diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 881c2b2cd..56c49b2f4 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -20,6 +20,7 @@ Each ADR includes:| ID | Title | Status ||---|---|---|+| pi-ai-core-0991-authority | [Pi 0.99.1 account model authority](pi-ai-core-0991-authority.md) | Accepted for current migration candidate || plan-tool-declarations-and-execution-denials | [Keep known tool declarations while denying contract-mode execution](plan-tool-declarations-and-execution-denials.md) | Accepted for implementation || trusted-extension-operation-ownership | [Trusted extension operation ownership](trusted-extension-operation-ownership.md) | Implemented candidate || scheduled-desktop-automations | [Desktop automation scheduling](scheduled-desktop-automations.md) | Accepted for implementation |diff --git a/docs/adr/pi-ai-core-0991-authority.md b/docs/adr/pi-ai-core-0991-authority.mdnew file mode 100644index 000000000..220c80921--- /dev/null+++ b/docs/adr/pi-ai-core-0991-authority.md@@ -0,0 +1,49 @@+# ADR: Pi 0.99.1 account model authority++- Status: Accepted for the current migration candidate+- Date: 2026-09-30+- Supersedes: ADR 0134 model metadata source++## Context++The authorized migration targets pi-ai and pi-agent-core. Pi 0.99.1 exposes typed+Models operations, provider refresh/filter hooks and native thinking metadata.+Keeping a second executable catalog alongside them creates inconsistent limits,+account entitlement and pricing. Desktop accounts and persistence remain owned+by Host; Desktop plugins retain their SDK and lifecycle.++## Decision++Use Pi Providers/Models as the published model authority. Maintain one Models+collection per account, with Host credential storage and explicit Desktop binding+projection. Disable ambient auth for catalog startup. Put OAuth live discovery+inside the same provider refresh/filter boundary. Keep raw published metadata+separate from effective user overrides. Route images through generateImages with+a registered compatible adapter where a native provider operation is absent.++Preserve non-chat settings visibility with a display-only metadata supplement;+it must not provide authentication, dispatch, pricing or entitlement. Unknown+relay matches remain conservative and cannot rewrite physical wire IDs. Remove+the independent release catalog fetch and packaging resource.++Attribute usage to physical operation identities through runtime, events and+Host persistence. Aggregate replayed records once and retain unknown costs as+unknown. Immediate nested-tool parent and owning Task are separate fields.++Keep pi-coding-agent as the existing compaction/file compatibility dependency.+Do not adopt its AgentSession, Codemode, tool composition or virtual routing as+part of this migration. Their reusable designs and adoption conditions are+recorded in [the design review](../project/pi-coding-agent-design-review.md).++## Alternatives++Retaining models.dev as executable authority would require duplicating Pi's+operation metadata and refresh semantics. Adopting ModelRuntime/AgentSession+would introduce another account/session owner and impede later removal.++## Consequences++The account adapter reuses Desktop's existing boundaries and preserves saved data,+with a small explicit display-only compatibility gap. Catalog changes now track+reviewed Pi pins. No schema migration is needed for the usage ledger: it uses the+existing turns usage JSON with optional compatible provenance fields.diff --git a/docs/project/pi-0991-adoption.md b/docs/project/pi-0991-adoption.mdnew file mode 100644index 000000000..77bd13fdc--- /dev/null+++ b/docs/project/pi-0991-adoption.md@@ -0,0 +1,91 @@+# Pi 0.99.1 adoption++Status: scoped migration implemented and local candidate validated; release+qualification is separate. Comprehensive review findings and repairs are in+[the migration review](pi-0991-review.md). These are local candidate results;+installed release qualification is separate.++## Scope and implementation++Migrate pi-ai and pi-agent-core to 0.99.1. pi-coding-agent stays pinned compatibly+for existing compaction/file utilities; no new AgentSession dependency is added.+MCP implementation, Desktop plugin SDK, installation, grants and lifecycle remain+owned by Desktop. Tool composition, Codemode and virtual routing were evaluated+in [the design review](pi-coding-agent-design-review.md), not enabled.++- Published and effective model metadata use account-scoped Pi Models. Host owns+ credentials and explicit binding overrides. Startup is cache-only with ambient+ auth disabled. Same-vendor accounts, deletion and disabled accounts remain+ isolated. Settings reads published metadata separately from user overrides.+- OAuth live entitlement discovery publishes through the Pi provider refresh+ boundary. Existing headers and live-only same-tier transport/thinking behavior+ survive, with unknown prices retained. Installation identity is persisted before+ login, concurrent-safe, restart-stable and separate from account credentials.+- Native thinking helpers normalize actual dispatch, including unsupported/native+ null effort mappings and omitted reasoning, without rewriting saved settings.+- Images enter Pi generateImages through native OpenRouter or a compatible+ OpenAI-images adapter. Generations/edits, bounded downloads, cancellation,+ stable batch artifacts, response text/IDs and physical usage remain supported.+- Physical request usage IDs propagate through runtime, Host, remote events and+ renderer. Retry/delegate/image replay bills once; unknown cost differs from a+ known free operation. Immediate nested parent differs from owning Task.+- Release scripts no longer fetch/package an independent models.dev catalog.+ Display-only non-chat compatibility metadata preserves settings visibility;+ it supplies no credentials, runtime dispatch, pricing or entitlement.++## Candidate and environment++- Worktree: `PI-Desktop-worktrees/pi-0991-resume`.+- Branch: `refactor/pi-0991-resume`.+- Base main: `e77404ea3c4834a6213759868a66cde8da759056`.+- Original Claude session: `d4616efd-1246-40aa-b2e2-3a3767555595`;+ original migration and interrupted worktrees are preserved.+- Reused host Node/pnpm dependencies and Cargo target. Lockfile-only resolution+ records the new Pi pins/patches. Offline fixtures replace external provider I/O.++## Validation evidence++After withdrawing out-of-scope coding-agent/MCP integrations and completing the+account isolation, compaction and durable usage review:++| Check | Result |+| --- | --- |+| Full agent-runtime suite | 1,150 passed / 81 files |+| Full Desktop suite | 3,271 passed / 0 failed |+| Full shared suite | 1,156 passed / 94 files |+| agent-host | 53 passed / 4 files |+| host-runtime | 93 passed / 14 files |+| host-core | 704 passed |+| JS workspace build | Passed |+| Desktop typecheck | Passed |+| Lint (Biome and style tokens) | Passed |+| cargo fmt --check | Passed |+| cargo clippy, all targets, locked | Passed with existing dead-code/unused-variable warnings |+| Production sidecar hosted-search E2E | All 7 scenarios passed |+| Pi patch clean-application verification | All 3 patches passed; installed patched files match |+| Documentation and release preflight | 540 pages, locale pairing and release checks passed |+| Changed-file secret pattern scan | No high-confidence credential candidates |++Production sidecar SHA-256:+`6192678b203bd04dbcb75e24ca229a808eef8bfdd01af4e19e3894945c3eb38e`.+The scenarios cover next-prompt search, read, changed instructions, delegation,+persisted restore and invalid search container/phase. Standalone OAuth tests in+the Desktop suite load and execute actual ChatGPT/Meta login modules outside the+repository with external I/O mocked. Image tests enter the real Pi operation API.+Usage tests cover replay, late turns, nesting, compaction attempts, offline outbox+recovery, known-free/unknown cost, malformed external counts and Host integer+overflow. The retained coding-agent patch also has a public offline SDK compaction+regression. Build/typecheck, fmt and clippy passed; existing bundle-size and+unused-variable/dead-code warnings remain.++The first scoped Desktop run had three retired catalog/layout source assertions.+They were updated to Pi published metadata and the actual resources contract;+the complete rerun passed. No product behavior test was removed.++## Release limits++Installed Electron, real accounts/paid providers, cross-platform artifacts and+cross-version rollback were not tested. No UI verification command was run because+it was not requested. These checks are release qualification, not evidence supplied+by local offline regression. Remaining release work is in+[pi-0991-gaps.md](pi-0991-gaps.md).diff --git a/docs/project/pi-0991-gaps.md b/docs/project/pi-0991-gaps.mdnew file mode 100644index 000000000..c5a6edeb8--- /dev/null+++ b/docs/project/pi-0991-gaps.md@@ -0,0 +1,17 @@+# Pi 0.99.1 release qualification and follow-ups++The pi-ai/pi-agent-core migration passes the local candidate gates documented in+[adoption](pi-0991-adoption.md). The following are not claimed complete:++| Surface | Remaining work |+| --- | --- |+| Installed artifacts | Exercise installed Electron loading, native Host and packaged OAuth/image modules across supported platform/architecture lanes. Local standalone bundles and sidecar E2E passed. |+| Real account integration | Real OAuth and paid requests were not authorized or used; offline flows prove contracts, not current vendor service availability. |+| Cross-version rollback | Qualify the prior released version against retained data. Optional provenance fields and the existing usage JSON require no new schema, but that alone is not an executed rollback test. |+| Dependency removal | pi-coding-agent remains the pre-existing compaction/file utility compatibility dependency. Removing it is a separate refactor. |+| Design follow-ups | Tool inventory separation, an independent Codemode sandbox adapter, and physical/virtual routing contracts are evaluated in the design review. They are outside this migration and are not enabled. |++No MCP migration, coding-agent session integration, classifier/router feature,+plugin conversion or new Codemode feature is promised by this scoped candidate.+The display-only operation metadata supplement remains explicit compatibility+data until Pi publishes equivalent non-chat settings metadata.diff --git a/docs/project/pi-0991-review.md b/docs/project/pi-0991-review.mdnew file mode 100644index 000000000..0ce542354--- /dev/null+++ b/docs/project/pi-0991-review.md@@ -0,0 +1,37 @@+# Pi 0.99.1 migration review++The scoped candidate has been reviewed and repaired in `refactor/pi-0991-resume`.+These local checks do not qualify an installed release or a real paid provider request.+Migration scope remains pi-ai and pi-agent-core; pi-coding-agent is retained solely+for the existing compatibility utilities. Tool composition, Codemode and virtual+routing recommendations remain in [the design review](pi-coding-agent-design-review.md).++## Repaired findings++| Impact | Finding and repair | Regression evidence |+| --- | --- | --- |+| Account isolation | An unsigned OAuth row could use an ambient API key. Account Models now explicitly disable environment/file credential lookup. | Actual built-in Anthropic auth resolution rejects the unsigned row even with an environment key. |+| Runtime failure | Three coding-agent compatibility patch additions referenced an undefined `requestModel`. They now use the locally resolved `model`. | An offline public SDK session performs manual compaction with an extension-supplied summary. The original patch raised `ReferenceError`. |+| Lost accounting | Offline aggregate usage reports shared one outbox key. Keys now fingerprint the full snapshot; physical IDs still deduplicate replay. | Offline image aggregates survive durable outbox restart and replay independently. |+| Lost accounting | Session compaction omitted usage, while delegate summaries invented an identity after aggregation. Observe each actual `completeSimple` dispatch, before retries/chunking are collapsed, and remove the extra delegate summary charge. | Summary attempt tests include failed/successful replies, distinct IDs, account/model provenance, preserved headers and replay identity. Runtime/delegate suites pass. |+| Lost accounting | One-shot completions returned only the final retry's usage. Observe each attempt inside the existing retry factory and return their union. | Existing one-shot transport/cancellation tests pass; returned usage carries the physical operation and account/model. |+| Incorrect price | Equal-token replay could replace a known cost with an unknown one. TS and Rust prefer a complete known cost, with reported prices preferred on equal counts. | Both replay orders preserve the reported amount in shared and durable Host ledger tests. |+| Incorrect price | Missing or nonfinite Pi native rates could become a known free operation. Validate native rates before marking estimated cost; malformed or overflowing totals remain unknown. | Native unknown-rate and malformed-price tests preserve the unknown/free distinction. |+| Invalid accounting | External tool usage accepted nonfinite, negative or fractional counts. Validate required and optional counts. Rust validates optional counts and saturates integer ledger totals. | Invalid tool-count cases are ignored; the Host maximum-count case no longer panics. |+| Unsupported capability | Saved overrides re-enabled thinking levels that Pi omitted or explicitly disabled. Known Pi models intersect overrides with native support; saved preferences remain intact. | Native-null/absent effort fixtures and account capability/cache tests pass. |+| Stale model list | Forced refresh still used the live-model TTL. Force now invalidates that cache. Old account loads cannot repopulate another account instance's cache or clear its single-flight entry. | Forced entitlement refresh takes effect immediately; account lifecycle and refresh tests pass. |+| Account lifecycle | Failed cleanup of a newly created OAuth row invalidated a row that Host had failed to delete. Invalidate only after successful Host deletion. | Failed cleanup retains the surviving account instance; failed ordinary deletion retains credentials and catalog. |+| Relay metadata | Route-prefixed model IDs failed exact leaf matching. Compare leaves for metadata lookup while retaining the requested wire ID. | Prefix fixtures match exactly, without borrowing metadata for similarly named models. |+| Release gate drift | Preflight still required the retired bundled models.dev snapshot. Validate display-only operation metadata instead, including rejection of runtime/auth/price fields. | Release documentation preflight passes. |++## Validation and limits++Final counts, build checks and the production sidecar fingerprint are recorded in+[adoption](pi-0991-adoption.md). All three patches were reversed in temporary+package copies, applied cleanly again, and compared byte-for-byte with the installed+files used by tests. The changed tracked diff and untracked deliverables contain+no candidates matching the reviewed high-confidence credential patterns.++Installed Electron, real OAuth/paid APIs, cross-platform packaging and rollback+against the previous release remain unqualified. See [release gaps](pi-0991-gaps.md).+No new coding-agent session integration or Codemode feature was enabled.diff --git a/docs/project/pi-coding-agent-design-review.md b/docs/project/pi-coding-agent-design-review.mdnew file mode 100644index 000000000..928e987b0--- /dev/null+++ b/docs/project/pi-coding-agent-design-review.md@@ -0,0 +1,84 @@+# pi-coding-agent 0.99.1 design review++Scope: reference evaluation alongside the pi-ai/pi-agent-core migration. This+review does not enable Codemode, virtual models, or replace Desktop's tool+runtime. The installed 0.99.1 JavaScript and declarations are the evidence;+no third-party account or paid request was used.++## Tool composition++`core/agent-session.js` separates registered, callable, and declared tools.+`_getCallableTools` and `_applyToolLoadout` honor exposure and `prepareLoadout`.+The tool-search extension ranks names, descriptions, namespaces, and schema+properties with BM25 and activates deferred tools. Transcript loadouts restore+activation across resume and branches.++Adopt the separation of declaration from execution when consolidating Desktop's+existing deferred tool search. A visible declaration must never grant execution+permission. Search, direct invocation, delegates, and nested invocation should+resolve against the same session inventory and pass Host authorization. Preserve+Desktop's existing ToolSearch names and persisted activation history.++Do not import private AgentSession methods or add exports by patching Pi. The+installed package does not expose an independent ToolComposition API; the+composition is coupled to session state, extension hooks, and Pi session storage.+Replacing Desktop's own session manager to obtain it would expand this migration+and complicate removing pi-coding-agent later.++## Codemode++`extensions/codemode/execute.js` uses pi-codemode's QuickJS sandbox, a worker,+a 256 MiB VM heap cap, output limits, and a four-call model concurrency limiter.+It strips model headers before exposing metadata to scripts. `execute.lazy.js`+defers sandbox loading. Script tool calls go through `ctx.executeTool` rather+than obtaining host functions or credentials directly.++`core/nested-tool-calls.js` records the immediate parent, routes each call through+`runToolCall`, and serializes tools that require exclusive execution. Arguments+are bounded to 8 KiB per call and 32 KiB total, with at most 256 recorded calls;+usage is collected even when a record is omitted. Errors describe completed side+effects instead of implying rollback.++These are useful design constraints for a future Desktop Codemode implementation.+Keep Task ownership distinct from the immediate nested parent, preserve operation+identities when aggregating usage, propagate cancellation to every host call, and+bound both output and execution. The current migration already preserves separate+lineage fields and physical usage identities without requiring AgentSession.+Pi's additive usage totals alone are insufficient for Desktop's replayable ledger.++Prefer a future narrow sandbox adapter to adopting the coding-agent extension+runtime. Adoption requires an ADR for the execution boundary, tests proving Host+permission enforcement and cancellation, and a standalone production bundle test+covering worker/WASM assets from outside node_modules. QuickJS isolation does not+itself grant permission to tools. No Codemode execution is enabled by this review.++## Virtual routing++`core/model-runtime.js`, `core/virtual-models.d.ts`, and `docs/virtual-models.md`+separate virtual selection from physical dispatch. Routing gets a request reason+(user, continuation, retry, direct), previous/failed physical responses, an abort+signal, and JSON-serializable branch state. It rejects unavailable or virtual+routing targets and clamps effort to the physical model. The session persists+router state and checks context against the dispatched model.++Borrow these contracts if Desktop introduces automatic routing: retain the user's+selected route, attribute requests and price to physical account/model IDs, pin+continuations and retries unless policy explicitly switches, use dispatched+context limits, and restore route state on resume/fork. A classifier request is+an additional physical operation with its own latency and usage.++Do not add routing now. `ModelRuntime.create` builds its own provider/config/auth+composition; its public creation options do not accept Desktop's existing+account-scoped Models collection. Direct adoption would introduce a second+account authority. A future router should take allowed physical bindings from+the existing pi-ai account collections and return a resolved physical binding;+it must not silently broaden the account or provider allowlist.++## Recommendation++Complete the pi-ai/pi-agent-core migration first. Keep coding-agent as the+existing compatibility dependency for compaction/file utilities, with no new+session-runtime dependency. Record the above patterns for follow-up work; first+consolidate tool inventory, then evaluate the sandbox independently, and add+routing only with a product policy and persistence contract. None of these+follow-ups is a migration acceptance requirement.diff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.mdindex b407796ec..5f161d253 100644--- a/docs/spec/00-baseline.md+++ b/docs/spec/00-baseline.md@@ -2,7 +2,7 @@- Baseline Version: `0.4.19`- Date: `2026-09-29`-- Status: `Frozen for implementation details (indefinite local permission approvals + Plan checkpoint artifact + approval/execution startup fence + protocol v11 + schema v16 + host-owned plugin session import/read/update/delete P0/P1 + selectable shell catalog + icon-free composer prompt row + turn-boundary context checkpoint compaction + session-scoped work panel + edge-specific work-panel/chat resize ownership + models.dev model catalog with a bundled release snapshot + provider/runtime safety + M5 hardening + settings IA + project archive + sidebar organization + app update delivery + three-platform release + Extensions page density and theme-readable actions + custom global UI font + ChatGPT-style logical project groups)`+- Status: `Frozen for implementation details (indefinite local permission approvals + Plan checkpoint artifact + approval/execution startup fence + protocol v11 + schema v16 + host-owned plugin session import/read/update/delete P0/P1 + selectable shell catalog + icon-free composer prompt row + turn-boundary context checkpoint compaction + session-scoped work panel + edge-specific work-panel/chat resize ownership + account-scoped Pi model catalog + provider/runtime safety + M5 hardening + settings IA + project archive + sidebar organization + app update delivery + three-platform release + Extensions page density and theme-readable actions + custom global UI font + ChatGPT-style logical project groups)`- Language policy: **English-first**- Backend policy: **Rust host core + pi agent sidecar**@@ -28,10 +28,9 @@> Settings as the fifth **Project archive** destination through D133 / ADR 0026.> `0.4.9` made the pinned pi-ai catalog authoritative for known-model metadata> and removed desktop-owned model parameter overrides through D136 / ADR 0027.-> ADR 0133 / D266 first introduced models.dev as a remote primary; ADR 0134-> supersedes that fallback design and makes models.dev the sole metadata source-> with a checked-in release snapshot. pi-ai remains the transport, OAuth, and-> account-availability layer.+> ADR 0133 / D266 and ADR 0134 describe the historical models.dev source.+> [Pi 0.99.1 authority](../adr/pi-ai-core-0991-authority.md) supersedes that+> source with account-scoped Pi Models, preserving explicit Desktop bindings.> `0.4.10` replaces destructive work-panel clearing on conversation switches> with runtime session-scoped contexts through D142 / ADR 0028.> `0.4.11` adopts turn-boundary model-context checkpoint compaction through@@ -155,7 +154,7 @@32. Observability MVP: **local logs only**33. Error model: **shared AppError code registry**34. Provider coverage: **universal via pi-ai native + OpenAI-compatible + custom**-35. Model policy: **no closed allowlist; models.dev release catalog, generic unknown IDs, and free-form model IDs**+35. Model policy: **no closed allowlist; account-scoped Pi catalog, generic unknown IDs, and free-form model IDs**36. Provider storage: **Rust SQLite configs + OS secret store references**37. Secrets backend: **safeStorage primary + encrypted file fallback**38. Workspace ignore: **denylist + defaults + `.pi-desktopignore`**diff --git a/docs/spec/02-architecture/02-tech-stack.md b/docs/spec/02-architecture/02-tech-stack.mdindex 86dab96e3..005ff6ff8 100644--- a/docs/spec/02-architecture/02-tech-stack.md+++ b/docs/spec/02-architecture/02-tech-stack.md@@ -12,18 +12,14 @@| Host backend | **Rust** | stable Rust toolchain | tools/plugins/permissions/persistence adapters || Rust async | tokio | stable | host services || Host RPC | stdio JSON-RPC (NDJSON) | frozen (D001) | Electron main ↔ Rust host |-| Agent engine | `@earendil-works/pi-agent-core` | 0.87.1 | agent loop |-| Model API | `@earendil-works/pi-ai` | 0.87.1 | provider adapters, OAuth, and stream handling |-| Model catalog | `https://models.dev/api.json` | bundled release snapshot + process-local refresh | sole provider/model metadata source |--> pi-ai is not consulted for model names, capabilities, limits, modalities,-> thinking levels, or prices. It remains the request transport dependency.-> ChatGPT Plus/Pro and GitHub Copilot OAuth availability still comes from the-> pinned pi-ai catalog; 0.87.1 includes `gpt-6-sol`, `gpt-6-luna`, and-> `grok-4.7` alongside the existing `gpt-6-astra` catalog entry.-> The 0.87.1 pi-ai catalog also registers Claude Opus 5.5 and Meta/Muse-> subscription OAuth; Desktop enumerates them dynamically rather than-> maintaining a separate vendor list.+| Agent engine | `@earendil-works/pi-agent-core` | 0.99.1 | agent loop |+| Model API | `@earendil-works/pi-ai` | 0.99.1 | provider adapters, OAuth, and stream handling |+| Model catalog | pi-ai Providers/Models | pinned 0.99.1 + explicit provider refresh | account-scoped metadata and typed operations |++> pi-ai owns published metadata, native thinking support, transports and auth.+> Host persists Desktop account rows, credentials, and explicit binding overrides.+> pi-coding-agent remains an existing compatibility dependency for compaction and+> file utilities; this migration does not adopt AgentSession, Codemode or routing.| Node runtime | Node.js | `>= 22.19` | pi requirement || DB | SQLite | Rust host-core via `rusqlite` | sessions/settings |diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex b9ae1141c..0262e800a 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -107,7 +107,7 @@ No host RPC or storage schema change is required.1. load the durable session and reject a missing session2. resolve that session's mode/provider/model and project binding (app/currentworkspace defaults are legacy fallback only)-3. resolve the complete models.dev metadata record for the exact provider/API+3. resolve the complete Pi catalog metadata record for the exact provider/APIURL and model and clamp the durable session thinking level to its nearestsupported value; an ID absent from the snapshot uses the explicit genericfallback@@ -706,7 +706,7 @@ criterion-by-criterion report of what was met and the evidence observed.not a catalog/binding capability: the runtime keeps agent bookkeeping at`off` and uses the low-level provider stream so no thinking override issynthesized (ADR 0194 / ADR 0295).-- The bundled models.dev release snapshot is authoritative for published+- The bundled Pi catalog release snapshot is authoritative for publishedreasoning support, thinking-level mapping, limits, input/output modalities,pricing, and other model metadata. pi-ai remains responsible for requestserialization and adapter compatibility.@@ -714,7 +714,7 @@ criterion-by-criterion report of what was met and the evidence observed.limits, or other model metadata. The explicit attachment capability fieldsare the exception: `supportsImages` and `supportsDocuments` are effectivebinding overrides for the endpoint.-- Unsupported requested levels use the selected models.dev model's+- Unsupported requested levels use the selected Pi catalog model'snearest-supported-level rule: scan upward first, then downward. Anon-reasoning provider always resolves to `off`.- Vision support starts from the same published model record. An absent or@@ -909,7 +909,7 @@ No new event type or storage schema is required.process with the definition's system prompt, its (possibly pinned)provider/model, its declared tools, and the same host connection. A pinned orexplicitly selected delegation model uses the exact provider/model binding-saved in Settings for its effective thinking capability; models.dev supplies+saved in Settings for its effective thinking capability; Pi catalog suppliesthe baseline only. It runs underthe same bounded provider retry policy as the parent. A delegate has no turnlimit: it ends when it finishes, when the parent calls `TaskStop`, when the user@@ -1030,7 +1030,7 @@ multi-turn conversation under its latest `Task` card, with no separate"resumed" marker.**Model pins.** `model: <provider>/<model>` in the frontmatter is resolved once-per launch in Electron main, where credentials and the models.dev snapshot live, against+per launch in Electron main, where credentials and the Pi catalog snapshot live, againstprovider id, vendor key or display name, and capped at`MAX_SUBAGENT_PROVIDERS` (8) distinct providers. An unresolvable pin is omittedfrom the binding map on purpose; the runtime turns the missing entry into a tool@@ -1202,10 +1202,10 @@ MVP UI always includes at least:Runtime responsibilities:- resolve `(providerId, modelId)`-- resolve and serialize the complete models.dev record, or label an absent ID+- resolve and serialize the complete Pi catalog record, or label an absent IDwith the unknown generic fallback- resolve model reasoning capability and effective thinking level from the- models.dev record+ Pi catalog record- fetch secrets via host (never cache raw secrets in logs)- translate vendor failures into provider AppError codes- stream tokens/events to orchestrator@@ -1567,7 +1567,7 @@ with the original v3 `SessionManager`, Pi `ModelRuntime`, `SettingsManager`, andleaf, compaction, model/thinking changes, and context-bearing custom messages;it is never reconstructed from renderer `UiMessage` rows.-The 0.87.1 SDK also applies append-only `context_edit` entries to this model+The 0.99.1 SDK also applies append-only `context_edit` entries to this modelprojection. An edit can omit or replace an earlier message for later providerrequests without rewriting its raw JSONL entry or the visible native history.Native Pi extensions use the SDK's boundary hooks; all entries they append,@@ -1636,3 +1636,18 @@ cause survives adapter message flattening, remains on the final error row,and never triggers a provider transport rebuild. Protocol errors such as`EPROTO` keep their existing retry behavior. See[certificate trust ADR](../../adr/provider-system-certificates.md).++## Pi 0.99.1 execution boundary++Published model metadata and account entitlement come from one account-scoped+Pi Models collection. Effective binding projection is shared by launch, delegates+and compaction. Dispatch thinking normalization uses the resolved physical Pi+model; native null/unsupported mappings remain unavailable without mutating+saved preferences. Agent bookkeeping and omitted request reasoning are distinct.++Every physical stream attempt has an operation identity before dispatch. Usage+survives stream/result projection and events through Host/remote/renderer paths;+retries and images retain physical account/model attribution. Nested immediate+parent and owning Task remain distinct. The migration does not add coding-agent+AgentSession, Codemode or virtual routing. See the coding-agent design review for+future adoption conditions.diff --git a/docs/spec/03-runtime/04-data-storage.md b/docs/spec/03-runtime/04-data-storage.mdindex 6cb98bfae..c105ba959 100644--- a/docs/spec/03-runtime/04-data-storage.md+++ b/docs/spec/03-runtime/04-data-storage.md@@ -1646,3 +1646,15 @@ Hourly rows retain their fields but require explicit calendar confirmationwhen converted. Known intent survives cadence changes and database reopen.This additive JSON key needs no table or schema-version migration. Olderversions ignore the key and cannot enforce the new conversion guard.++## Physical operation usage ledger++Optional operation ID, origin, physical account/model and cost status augment+existing message/turn usage. `session.recordUsage` merges identities into the+existing turn `usage_json`; no schema migration or historical rewrite is needed.+Identified records are idempotent across event replay, outbox retries, tool results+and parent/subagent rollups. Legacy token-only rows remain readable and additive.+An unknown price is distinct from a known zero price; partial known costs remain+on the individual operations. Late usage targets its captured turn and does not+revive it or debit the currently active turn. Immediate nested parent and owning+Task remain separate optional transcript/event fields.diff --git a/docs/spec/03-runtime/11-provider-model-system.md b/docs/spec/03-runtime/11-provider-model-system.mdindex 0ec75e4cc..da4b3c674 100644--- a/docs/spec/03-runtime/11-provider-model-system.md+++ b/docs/spec/03-runtime/11-provider-model-system.md@@ -6,7 +6,7 @@ PI-Desktop must support **all major market model vendors and models** that usersStrategy:-> **Universal provider coverage via models.dev model metadata + pi-ai transport adapters + OpenAI-compatible escape hatch.**+> **Universal provider coverage via Pi catalog model metadata + pi-ai transport adapters + OpenAI-compatible escape hatch.**We do **not** re-implement every vendor SDK ourselves.We standardize on pi’s multi-provider layer and add product-level configuration, catalog, and UX.@@ -40,7 +40,7 @@ Settings / UI├─ openai-compatible provider└─ custom provider definitions→ ModelCatalogService- ├─ models.dev snapshot (sole model metadata source)+ ├─ Pi catalog snapshot (sole model metadata source)├─ runtime/provider discovery (IDs only for custom/dynamic models)└─ Rust-owned provider cache```@@ -101,8 +101,8 @@ OpenAI-style Copilot wire APIs keep signing the token as the request key; allwires retain per-request auth resolution and the account-specific `baseUrl`.Zhipu / GLM and Z.AI are named OpenAI-compatible endpoint presets among a-short models.dev-backed Service list of first-party vendors (including-Xiaomi). The add-provider Service picker persists the matching models.dev+short Pi catalog-backed Service list of first-party vendors (including+Xiaomi). The add-provider Service picker persists the matching Pi catalog`vendorKey` and uses the published endpoint withoutshowing Name, Base URL, or API format on the named-service path. Chat turnsstill use the selected pi-ai adapter (`chat_completions`, `responses`,@@ -121,9 +121,9 @@ ADR 0256 / #296). Official `deepseek.com` rows keep empty-string fill (#223).The overlay does not change `thinkingFormat`.Anthropic Messages requests set `forceAdaptiveThinking: true` when the-models.dev record publishes a reasoning `effort` option and no+Pi catalog record publishes a reasoning `effort` option and no`budget_tokens` option (for example Opus 4.7+, Opus 5.x, Fable). Those models-reject `thinking.type=enabled` with HTTP 400, and models.dev carries no pi-ai+reject `thinking.type=enabled` with HTTP 400, and Pi catalog carries no pi-aicompat record, so without the flag pi-ai would fall back to budget thinking.Models that still publish `budget_tokens`, including those that also publish`effort`, keep budget thinking by default. The catalog uses this same rule@@ -135,7 +135,7 @@ catalog `compat` record is preserved.An Anthropic Messages row the catalog cannot identify (for example a customgateway URL serving an id several publishers list) still falls back to thegeneric model shape, but takes `reasoning_options` and the derived-`thinkingLevelMap` from Anthropic's own models.dev record when that record+`thinkingLevelMap` from Anthropic's own Pi catalog record when that recordhas exactly the same model id. Which thinking shape a Claude id accepts is aproperty of the model, not of the deployment, so only those two fieldstransfer; limits and modalities stay generic, and aliases, renamed ids, other@@ -144,9 +144,9 @@ wire APIs, and non-Claude ids served over the Anthropic protocol are unchanged## 5. Built-in vendor matrix (ship intent)-> Model metadata follows the bundled/in-memory models.dev catalog. Provider adapters remain+> Model metadata follows the bundled/in-memory Pi catalog catalog. Provider adapters remain> available through pi-ai, and the OpenAI-compatible path stays open for models-> that models.dev does not list.+> that Pi catalog does not list.### Tier A — always exposed in UI- OpenAI@@ -190,110 +190,37 @@ Any vendor not listed but reachable by:PI-Desktop must not permanently restrict users to a short fixed model list.### 6.2 Catalog responsibilities-1. **models.dev** (`https://models.dev/api.json`) is the sole model metadata- source. Electron main reads the checked-in release resource at- `apps/desktop/resources/models.dev/api.json` in development and the- packaged `resources/models.dev/api.json` path in released builds. It never- sends provider credentials to the catalog.-2. The checked-in snapshot is refreshed by `scripts/release.mjs` before a- release tag is created. At runtime, Settings → Model configuration may- explicitly refetch `https://models.dev/api.json`; a successful response- replaces only the in-memory catalog for the current process. A failed fetch- keeps the last valid in-memory catalog and never writes user data.-3. **Runtime/provider discovery** and the Rust-owned cache supply model IDs for- custom, local, or authenticated account-specific endpoints. Provider matching- accepts the configured vendor key, normalized API URL, models.dev provider- identity, and vendor-prefixed IDs such as `deepseek/deepseek-v4`; a provider- model ID without the catalog prefix is matched to the exact unprefixed- suffix only when the provider identity is unambiguous. Native adapter keys- may use a catalog alias — for example, pi-ai's `openai-codex` ChatGPT- subscription adapter resolves model metadata through the `openai` record —- while the adapter keeps its own transport identity. They cannot invent or- replace model metadata. A configured free-form ID remains selectable with- the generic text-only, non-reasoning baseline when it is absent from- models.dev. Settings still permits an explicit thinking-level override for- an endpoint the catalog does not know yet.-4. The models.dev record maps `id`, `name`, `description`, `family`,- `attachment`, `reasoning`, `reasoning_options`, `tool_call`,- `structured_output`, `temperature`, `knowledge`, `release_date`,- `last_updated`, `modalities.input/output`, `open_weights`,- `limit.context/input/output`, `cost`, `interleaved`, `status`,- `experimental`, and `provider` into the shared model surfaces.-5. pi-ai remains the request/OAuth implementation layer; published model- configuration comes from models.dev, not pi-ai's bundled catalog. The- bounded exception is the live-only OAuth same-tier fallback in §8a, which- borrows an existing adapter contract and interprets its effort mapping with- pi-ai's capability helper until published metadata becomes available.-6. Input and output modality arrays retain `text`, `image`, `audio`, `video`,- and `pdf`. The text agent picker exposes models that can handle text while- preserving all raw records in the file for future surfaces. Image input is- sent as a transient image content block only when the model accepts image- input. PDF capability is surfaced and retained in model metadata; because- pi-ai 0.87.1 has no native PDF content block, PDF attachments remain bounded- file references rather than being incorrectly encoded as images.-7. User-edited `ModelBinding` values remain explicit provider configuration:- they control selected request limits, enabled thinking levels, the default- thinking level applied to a new home draft and newly persisted session- (clamped onto the enabled set; a known catalog match uses the- strongest-enabled level when the default is unset, while an unmatched- model starts at `off`), and the attachment capability overrides.- `models.dev` supplies published metadata and seeds the initial- thinking selection for a newly added known model; it is not a runtime gate- on a level the user explicitly enables for the endpoint. For compatibility,- a binding that still contains the legacy generic `128,000` context seed- follows a newly published `limit.context`; a non-default Advanced value- remains explicit. This keeps the sidecar and context inspector on the same- effective window after a catalog refresh.-8. Settings renders the seven canonical thinking levels for every binding.- Published levels begin selected for a known reasoning model. A non-reasoning- or unknown model shows the same choices unselected, with a short manual- override note. `defaultThinkingLevel` is chosen from `omit` plus the levels- the binding enables, so a stored default is either `omit` or part of that- explicit set.-9. `supportsImages` and `supportsDocuments` are three-state overrides. Absent- or `null` follows the published models.dev modality, so a catalog correction- still reaches a saved binding; `true` or `false` is the user's explicit- answer and survives catalog changes. Unlike thinking levels these overrides- are not narrowed to the published capability, because a proxied or- self-hosted endpoint routinely accepts input its catalog entry omits.- Enabling image input turns on the transient image content block; enabling PDF- input records the capability but does not change the encoding, since pi-ai- 0.87.1 has no PDF content block and PDFs stay bounded file references.-10. The settings checkboxes show the effective answer against the published- baseline. An untouched or `null` value follows the catalog; once the user- changes a checkbox, its selected boolean is explicit and remains pinned,- even if it equals the currently published value. Catalog refreshes therefore- cannot undo a deliberate choice.-10a. `nativeWebSearch` is a two-state opt-in (absent means off; there is no- catalog baseline because models.dev publishes no hosted-tool capability).- When enabled and the model resolves to `anthropic-messages`,- `openai-responses`, `azure-openai-responses`, or- `openai-codex-responses` (stored apiStyle `anthropic_messages`, `responses`,- or `openai_codex_responses`, or a published official search route from- Chat Completions), the adapter attaches the provider's hosted- search tool (`web_search_20250305` / `web_search`), extracts activity into- `UiMessage.hostedSearch` (`rounds` for display, `replay` for convertMessages),- and restores raw blocks on later turns including after restart (ADR 0297).- OpenAI OAuth uses the separate Codex Responses adapter and its ChatGPT- subscription endpoint, not the public `/v1/responses` transport; it sends- the hosted tool in the Codex request body's top-level `tools` list. The- settings checkbox remains opt-in and the runtime checks support against the- final resolved wire API, so stale flags cannot leak to unsupported adapters.- Gateways that reject the tool surface the provider error; the remedy is- unchecking. Search runs on the provider: there is no local fetch or permission- prompt. Compaction keeps its existing prefix/tail retention strategy. The- summary request includes search replay data from the compacted prefix; the- generated text summary is not a lossless copy of raw provider search blocks.-11. `ModelInfo` is the published record the settings surface compares against,- so a stored binding must not shape its capabilities or reasoning fields.- Effective limits, reasoning and thinking levels are resolved through the- exact binding; the effective transport modality arrays additionally apply- the explicit attachment overrides.-12. A model the user has configured keeps its published record even when live- discovery no longer lists it, so its capabilities remain visible and- editable. Only ids already present in the provider's `models` are re-added,- never the catalog at large, and only the rows discovery actually returned- are written to the model cache.++1. pi-ai 0.99.1 Providers/Models own published metadata, transport, thinking+ support and native operation types. Electron's historically named+ `ModelsDevCatalog` is an account-aware adapter over this public API.+2. Startup is cache-only and disables ambient environment/file credentials.+ Each configured account has its own Models collection and Host credential+ store. Same-vendor rows cannot borrow one another's credentials.+3. OAuth live entitlement IDs are published through the account provider's+ refresh/filter boundary. A successful list governs available chat models;+ discovery failure preserves the pinned catalog. Live-only IDs may inherit+ same-tier adapter/thinking metadata, with unknown prices retained as unknown.+4. Settings exposes published metadata separately from explicit binding+ overrides. Effective chat limits, inputs, thinking and request shape are+ projected once at the account boundary and reused for ordinary sessions,+ delegates, compaction and image lookup. Pi's unsupported/null effort mappings+ cannot be re-enabled by stale persisted settings. No saved data is rewritten.+5. Chat, image and classifier models are selected by operation type even when+ they share a model ID. A small display-only operation metadata supplement+ preserves settings visibility for image/audio/video/embedding records that+ Pi does not publish. It supplies no runtime auth, dispatch, price or entitlement.+6. Free-form IDs remain configurable. Conservative generic metadata applies+ when no published model matches; explicit user overrides remain supported.+ Unknown relay metadata uses exact final-segment matching and an unambiguous+ official publisher. Known endpoint aliases cannot borrow past an ambiguous+ same-endpoint miss. No deployment/date/thinking suffix is removed.+7. Settings catalog refresh calls Pi's public refresh API. Release scripts no+ longer fetch or package the independent Pi catalog JSON catalog. Pi version+ pins provide the reproducible catalog baseline.+8. PDF capability remains metadata; attachments use bounded file references+ until the runtime supports a native PDF content block. Image capability is+ resolved against the effective selected binding before transport.### 6.3 Model families to coverCatalog and custom model entry must support common capability classes:@@ -418,7 +345,7 @@ type ThinkingLevel =The compatibility fields above are retained as a persisted-schema compatibilitysurface for older clients. PI-Desktop no longer reads them as runtime modeloverrides. `ModelInfo` reasoning support and supported thinking levels describe-the resolved models.dev record; effective provider/session capability comes from+the resolved Pi catalog record; effective provider/session capability comes fromthe exact `ModelBinding`. Unknown free-form ids start with the generic shape andno inferred reasoning capability; an empty binding level array is the genericseed, while a non-empty explicit binding may opt into or disable levels.@@ -521,7 +448,7 @@ excerpt of the response body with the request's credentials and anytoken-shaped value removed, so an upstream contract change is diagnosablefrom the provider log.-Image, video, speech and embedding ids are dropped. A model models.dev does+Image, video, speech and embedding ids are dropped. A model Pi catalog doesnot know yet inherits limits, reasoning, adapter compatibility, and the wireeffort mapping from a pinned sibling of the same tier; xAI uses an explicitnewest-first sibling (`grok-4.7`, then `grok-4.6`, then `grok-4.5`, then@@ -536,8 +463,8 @@ effort map remains non-reasoning. Truly unclassified generic models and explicituser overrides retain their existing effective-thinking policy.The same effective mapping determines both the supported levels and wireeffort, so a sparse map cannot silently promote `high` to `xhigh` or lose the-adaptive protocol. Published models.dev records bypass this fallback entirely.-models.dev still cannot add an id the account list did not return. A vendor+adaptive protocol. Published Pi catalog records bypass this fallback entirely.+Pi catalog still cannot add an id the account list did not return. A vendormay span wire APIs — Copilot serves Anthropic, Chat Completions and Responsesmodels — so the row's `apiStyle` follows the selected model.Deleting a row calls the normal host `providers.delete` path, which removes its@@ -546,7 +473,7 @@ same vendor key.### Anthropic token endpoint rate limits-The pinned pi-ai 0.87.1 patch gives Anthropic authorization-code exchange and+The pinned pi-ai 0.99.1 patch gives Anthropic authorization-code exchange andrefresh a shared, bounded token-request policy: retry only an explicit HTTP429, at most three total requests. Wait at least 1 s then 2 s, or longer when`Retry-After` gives delta seconds or an HTTP date. A server delay beyond the@@ -593,7 +520,7 @@ type ModelDescriptor = {modelId: stringdisplayName: stringsource: "bundled" | "discovered" | "user"- catalogSource?: "models.dev"+ catalogSource?: "pi"capabilities: Array<"text" | "tools" | "vision" | "reasoning" | "json">contextWindow?: numbermaxOutputTokens?: number@@ -653,38 +580,20 @@ type ModelDescriptor = {When starting a turn with `(providerId, modelId)`:-1. load provider config from host-2. if missing/disabled → fail (`MODEL_NOT_CONFIGURED`; reserved detail: `PROVIDER_DISABLED`)-3. resolve the credential: for a keyed row read the secret via `secretRef`- (never log it; missing → `PROVIDER_SECRET_MISSING`); for an `oauth` row skip- this entirely and launch with an empty key, because auth is resolved per- request (§8a)-4. resolve the models.dev record by matched provider key/API URL and exact model- id-5. copy its complete model configuration — name, description, family,- attachment/reasoning/tool/structured-output/temperature flags, knowledge and- release dates, input/output modalities, weights, status, interleaving,- limits, cost data, and thinking options — into the runtime model snapshot;- when absent, use the generic text-only, non-reasoning shape-6. derive vision transport from models.dev `modalities.input`; provider- discovery/cache claims cannot promote an unresolved model, while an explicit- attachment binding override can-7. clamp the session thinking level against the exact binding's enabled levels- and build the runtime provider adapter by replacing only provider/model- identity, selected API adapter, auth, and an explicitly configured endpoint- URL. For `anthropic_messages`, the runtime removes a trailing `/v1` from- that URL before passing it to pi-ai because the Anthropic SDK appends `/v1`- itself; configured roots with or without `/v1` therefore both reach the- same `/v1/messages` route. Subagent providers resolved from a definition pin,- the delegation model catalog, or `Task.model` use this same binding-aware- model configuration before their thinking level is clamped; models.dev is- only the baseline and cannot erase explicit binding levels.-8. execute stream with abort handle and separate answer/thinking events-9. translate vendor errors into shared `AppError` codes (§15)--If the model is absent from models.dev, still allow it when the user explicitly-enters a model id and the provider accepts unknown ids. Cached/provider-capability fields do not promote that fallback into a known runtime model.+1. Load the Host provider row; fail for a missing or disabled explicit account.+2. Resolve credentials only for that account. OAuth refresh remains per request.+3. Resolve the typed chat model from the account Pi collection, with conservative+ generic fallback for explicitly configured unknown compatible IDs.+4. Apply the central effective binding projection and clamp thinking with Pi's+ public capability helper. Preserve native costs and unknown-price provenance.+5. Build the transport with the actual vendor/model identity and the configured+ endpoint. Anthropic roots normalize a trailing `/v1` because its adapter+ appends `/v1/messages`. Delegates use the same account/binding resolution.+6. Stream with cancellation and separate answer/thinking events. Attribute usage+ to each physical request operation, including retries, and translate errors+ to shared AppError codes. Replay aggregation deduplicates operation IDs.++An unavailable saved account never silently falls back to the default account.## 12. Compatibility tiers@@ -699,18 +608,13 @@ UI may show tier hints, but must not hard-block unknown models by default.## 13. Refresh & update policy-1. Electron main reads the bundled release resource before serving model- metadata: `apps/desktop/resources/models.dev/api.json` in development and- `resources/models.dev/api.json` in packaged builds.-2. `scripts/release.mjs` fetches `https://models.dev/api.json`, validates it,- and atomically replaces the checked-in resource before creating a release- tag.-3. Settings → Model configuration can force a remote refresh at any time; a- successful response updates only the current process's in-memory catalog.-4. Provider endpoint discovery supplies IDs only for models absent from the- bundled/in-memory models.dev snapshot; unknown IDs use generic metadata.-5. Refresh failure must not wipe the bundled file, Rust-owned provider cache, or- configured bindings.+1. Use the pinned Pi catalog at startup without network or ambient credentials.+2. Settings may explicitly refresh Pi provider catalogs in memory.+3. Provider endpoint discovery preserves configured IDs and Host caches; OAuth+ live discovery publishes account entitlements through the same Models owner.+4. Failed refresh retains available metadata and configured bindings.+5. Release catalog changes arrive through reviewed Pi pins and patches; the+ release script does not fetch a second model catalog.## 14. Local / offline model support@@ -786,7 +690,7 @@ response, it stops consuming the stream instead of awaiting the server'sTCP FIN. Upstream pi-ai keeps iterating until the server closes theconnection, which hangs the turn behind reverse proxies that hold the idleconnection open. Until the fix ships upstream, `patches/` carries a pnpm-patch on `@earendil-works/[email protected]` that breaks the event loop on the+patch on `@earendil-works/[email protected]` that breaks the event loop on theterminal event (the OpenAI SDK aborts the underlying request when theconsumer stops iterating). Drop the patch once a pi-ai release includes thefix.diff --git a/docs/spec/03-runtime/13-model-catalog-and-selection.md b/docs/spec/03-runtime/13-model-catalog-and-selection.mdindex 0bcf95d5b..5497dcab2 100644--- a/docs/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/spec/03-runtime/13-model-catalog-and-selection.md@@ -15,7 +15,7 @@ Therefore:Model configuration is **discovery-first**: the AI service is the authority onwhich models it serves, so the service's own endpoint is asked first and-models.dev is used only to enrich what came back. The bundled catalog is never+Pi catalog is used only to enrich what came back. The bundled catalog is neverpresented as a browsable list of every published model — a deployment does notnecessarily host everything its vendor publishes, and a key is not necessarilyentitled to it.@@ -232,37 +232,22 @@ If user selects model tagged without tools while in Agent mode:## 6. Refresh behavior-The bundled `apps/desktop/resources/models.dev/api.json` snapshot is the-startup baseline. It is refreshed by `scripts/release.mjs` before a release tag-is created; application startup does not fetch or write a catalog. Settings-invokes the Electron-only `providers.refreshModelCatalog` channel to refetch-`https://models.dev/api.json`; a successful response replaces only the-current process's in-memory models.dev catalog and never writes user data.--Repeated metadata lookups use a bounded process-local cache keyed by the-configured vendor key, base URL, and case-insensitive, trimmed model ID. Both-matches and misses are cached; provider/API preference and candidate ranking-still apply. Replacing the catalog after a successful bundled load or Settings-refresh invalidates the cache. A failed refresh preserves the previous catalog-and its results. Session capability-enrichment resolves a matching catalog record once per session and then applies-the current provider/model binding and session defaults, so user overrides are-never retained as stale cached capabilities. Refreshing a large session list-must not repeat a full catalog scan for every occurrence of the same lookup.--Provider model loading remains stale-while-revalidate:--1. `source: "cache"` hydrates a saved provider's normalized discovery rows from- Rust-owned SQLite without provider network access.-2. The renderer can show those rows immediately in the Composer and provider- dialog.-3. `source: "refresh"` uses the bundled/in-memory models.dev catalog first and- probes a provider endpoint only to discover IDs that models.dev does not- expose.-4. Successful provider discovery may update the Rust-owned normalized cache;- it cannot replace a matching models.dev record or its metadata.-5. Configured `ModelBinding` IDs are retained when discovery is partial or- unavailable, and an ID absent from models.dev receives generic metadata.+The pinned pi-ai 0.99.1 catalog is the startup baseline. Startup reads no remote+catalog and uses no ambient credentials. `providers.refreshModelCatalog` invokes+Pi's public refresh API; settings metadata lookups themselves are local.++For keyed endpoints, live discovery supplies IDs and the central Pi catalog+adapter enriches their metadata. For OAuth, the account provider refresh hook+publishes live entitlement IDs into its existing Models collection. Successful+account lists are authoritative; a failed list preserves the pinned baseline.+Same-tier fallback for live-only IDs preserves transport and thinking behavior+but cannot invent known prices.++`source: "cache"` reads Host caches and configured bindings without network.+`source: "refresh"` probes the selected endpoint/account and decorates returned+IDs. Saved bindings remain visible when discovery is partial or unavailable.+Account removal invalidates catalog access; failed Host deletion preserves the+still-existing account. Refresh does not rewrite configured models or history.## 7. Offline behavior@@ -273,10 +258,9 @@ If refresh fails / offline:- allow custom model id- still allow providers with known model ids- when a saved provider cache is empty or partial, append every configured- model binding before applying models.dev metadata decoration, so multi-model+ model binding before applying Pi catalog metadata decoration, so multi-modelsettings remain editable and per-model capability state stays aligned-- if the bundled release snapshot is absent or invalid during an offline- release, keep the configured IDs visible with generic text-only metadata+- if no matching pinned Pi metadata is available offline, keep the configured IDs visible with generic text-only metadata## 8. Catalog item schema@@ -303,7 +287,7 @@ type ModelCatalogItem = {"off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max">/** Which known catalog supplied metadata for this row. */- catalogSource?: "models.dev"+ catalogSource?: "pi"}```@@ -313,13 +297,13 @@ When UI/search requests models for picker:1. recent models for enabled providers2. user-defined models-3. models.dev records for the matching provider/API URL+3. Pi catalog records for the matching provider/API URL4. provider discovery/cache for custom or account-specific models5. always include "custom model id" entry actionDeduplicate by `(providerId, modelId)` with priority:-`user > models.dev > provider-discovered > recent-only`. The `catalogSource`-field records a models.dev match; a provider cache stores only normalized+`user > Pi catalog > provider-discovered > recent-only`. The `catalogSource`+field records a Pi catalog match; a provider cache stores only normalizedselection fields and is re-decorated from the local raw catalog on the nextread.@@ -330,11 +314,11 @@ model window and output cap. Bindings record their provenance independently:`contextWindowSource` belongs to `contextWindow`, and `maxTokensSource` belongsto `maxTokens`.-- `catalog` — that limit is a models.dev snapshot, so a later correction to its+- `catalog` — that limit is a Pi catalog snapshot, so a later correction to itspublished field replaces it. A refreshed context such as `gpt-5.6-luna`(`1,050,000` tokens) stops appearing as a 128k model, and a row added whilenothing published its id stops reporting the generic 8.2k output once the- record resolves. Only a resolved models.dev record counts as published: when+ record resolves. Only a resolved Pi catalog record counts as published: whenlookup falls back to the generic shape (for example a gateway serving an idseveral publishers list), its 128k / 8.2k values are not a correction and thestored catalog snapshot stays in force.@@ -428,31 +412,17 @@ Warnings are non-blocking unless execution is impossible.### 11.1 Reasoning capability resolution-1. Resolve models.dev metadata under the matching provider/API URL using the- metadata-only ID lookup described in §11.3. This lookup does not change- configured model binding identity.-2. The models.dev record is authoritative for published `reasoning` and- `reasoning_options`; cached/provider capability claims cannot replace it.-3. The provider's exact `ModelBinding.thinkingLevels` is authoritative for the- user's effective selection. It may explicitly enable a canonical level that- the catalog does not publish.-4. A free-form ID absent from models.dev starts as an unknown generic model in- the host capability snapshot. Composer still exposes the seven canonical- thinking levels for an unmatched model so the user can opt in manually;- an empty binding level array is the generic seed and does not override that- ladder; a non-empty binding override remains authoritative. Without a- stored binding default its draft/session level is `off`.-5. The Composer renders the effective binding levels in canonical order. If no- binding exists, a catalog match supplies the published model levels; an- unmatched model exposes the canonical ladder instead.-6. If a stored/requested level is unavailable, choose the nearest enabled- binding level by scanning upward first and then downward. A binding with no- non-`off` level resolves to `off`.-7. Changing to a provider/model with no enabled reasoning level persists `off`;- no unconfigured level leaks into the next request.-8. For explicitly enabled `xhigh`/`max`, an absent or null catalog mapping is- materialized as an identity adapter mapping; a non-null catalog mapping is- preserved.+1. Resolve published Pi thinking metadata for the exact physical model.+2. Project explicit binding levels at the account boundary. Known unsupported+ levels and native null mappings remain unavailable; saved settings are not+ rewritten. Clamp the dispatched request using Pi's public helper.+3. Unknown free-form IDs retain the generic Desktop ladder for manual opt-in,+ with `off` as the unset default. Explicit binding defaults remain scoped to+ new drafts/sessions rather than overwriting existing session preferences.+4. `omit` remains a distinct request choice: no thinking field is sent. Agent+ bookkeeping may store `off` while the request omits reasoning.+5. The Composer renders effective enabled levels in canonical order. Dispatch+ normalization cannot silently enable a native unsupported level.### 11.2 Vision capability resolution@@ -476,76 +446,30 @@ window, output limit, capability badges and thinking defaults come from`bindingFromModelInfo` over the enriched record, so the common path needs nomanual token entry. The enrichment lookup is:-1. A matching models.dev provider is preferred by `vendorKey`, then by- normalized provider API URL, including explicit native-adapter aliases- such as `openai-codex` → `openai`; its exact model record supplies the fields.-2. A provider endpoint may add custom/account-specific IDs, but cannot replace- models.dev metadata. A free-form miss receives the fixed generic defaults- from `bindingForCustomModel`.-3. The lookup does not send API keys to models.dev. Runtime model resolution- uses the same models.dev record and the selected pi-ai transport adapter.--Catalog enrichment uses `catalogModelIdsMatch`, not the shared-`modelIdsMatch` used to resolve an exact configured binding. Binding identity-retains its existing case-insensitive wire-ID, region, route-suffix and known-vendor-prefix rules. Metadata lookup itself uses only the lower-cased final-`/` segment: `route/model` can reach a catalog row for `model`, but the route-prefix is not treated as model identity. The candidate index uses the same-last-segment key, so two routes sharing a leaf become competing candidates-rather than an automatic match.--Resolution is deliberately conservative. Zero candidates stays unmatched; one-candidate enriches the row. When there are multiple candidates, a unique-official/source provider is preferred only when its provider family agrees with-an explicit source prefix (`anthropic`, `openai`, `google*`, `xai`/`x-ai`). If-there is no unique official hit, enrichment is allowed only when every-candidate has the same published capabilities and thinking metadata; otherwise-the row stays unmatched. The matcher no longer strips `thinking`, `think`,-`agent`, `latest`, release-date or deployment-marker suffixes, and it does not-collapse vendor-dash aliases. A known provider may still borrow an exact ID-from another catalog publisher when its own record is absent; an unknown-provider does not use unanchored consensus or deployment-marker fallback.+1. Resolve account/vendor identity and normalized endpoint against Pi providers.+2. Read the published typed chat model separately from effective user overrides.+3. When Pi has no chat record, display-only operation metadata may describe a+ non-chat settings entry. It cannot promote that entry into a chat model or+ grant operation entitlement.+4. Use generic metadata on a miss; no metadata lookup sends account credentials.+5. Apply the conservative relay rules in §11.3.1 without rewriting wire IDs.These rules attach published metadata only: they never rewrite the configuredwire model ID or infer reasoning from a suffix. An unmatched free-form ID keepsthe host's generic capability snapshot, while Composer exposes the canonicalthinking ladder for explicit manual opt-in.-#### 11.3.1 Cross-provider exact-id fallback--models.dev indexes a gateway's copy of a model under the vendor that owns the-weights, so an endpoint serving `Vendor/Model` ids can have no record of its own-while another publisher states the identical id. When the row resolves to a-known catalog provider whose own record is missing, `findModel` may consult the-other publishers of the **exact** id instead of leaving the model on the generic-128k text-only shape (issue #938).--The borrow is bounded:--- It runs only for a row with a known catalog provider identity, and only after- that provider's own lookup missed. A provider record, or a supported alias of- it, stays authoritative.-- A provider sharing the row's own endpoint is an alias for the row, so its- silence is an answer about this deployment and nothing is borrowed past it.-- Only a case-insensitive identical id transfers. A record the index reaches- through a last-segment candidate or other non-exact spelling is not borrowed- by this fallback.-- The publishers this app ships a provider for answer before arbitrary resellers- do, but only for the exact requested ID. A copy reached through a different- spelling cannot narrow or expand what the model's own record states about- vision.-- Tool support follows the majority of the publishers that state it, because a- wrong `true` puts tool declarations on the wire that the endpoint may reject,- while one dissenting reseller must not void a record a hundred of them agree- on; an even split claims nothing. Reasoning, image/PDF input and attachment are- the intersection, so a borrow may only under-claim; a user who knows the- endpoint does more still enables it in Advanced. Limits are the medians the- publishers state, never one host's cap.-- An id no publisher states stays an unknown generic model; there is no- deployment-marker or unanchored-consensus fallback.--This changes metadata only. The configured wire id, provider identity, and the-binding precedence in §11.3 are unchanged.+#### 11.3.1 Relay metadata matching++The Pi adapter preserves the configured wire ID. Unknown endpoints may attach+metadata from an exact, case-insensitive final `/` segment. A unique official+publisher compatible with the ID family wins; conflicting capability/thinking+candidates remain unknown. No thinking/date/deployment suffix is stripped.++Known provider lookup and aliases stay authoritative. An ambiguous known+same-endpoint miss does not borrow from arbitrary publishers. There is no+majority-vote capability or median-limit algorithm. Unmatched IDs use conservative+generic metadata and explicit binding overrides.## 12. Refresh strategy@@ -555,7 +479,7 @@ binding precedence in §11.3 are unchanged.- refresh failures keep previous cache and surface non-fatal errorElectron decorates cached and freshly returned model rows from the local-models.dev snapshot. Runtime model resolution passes the same full models.dev+Pi catalog snapshot. Runtime model resolution passes the same full Pi catalogconfiguration to the selected pi-ai transport adapter. Provider discoveryremains an ID-only fallback for custom/account-specific models absent from thesnapshot.@@ -611,11 +535,11 @@ same model to the check mark, the toggle and the duplicate guard.- [ ] the settings picker always exposes the canonical thinking ladder;published levels seed known models and explicit binding levels clamp thesame way in Composer, Electron main, and the pi sidecar-- [ ] models.dev metadata wins for a matching provider/model; an ID absent from+- [ ] Pi catalog metadata wins for a matching provider/model; an ID absent fromit uses the generic shape while pi-ai supplies only transport/OAuth- [ ] provider settings and cached discovery cannot replace known catalogcapabilities; explicit binding edits remain persisted configuration-- [ ] a models.dev limit correction reaches an already saved `catalog` binding+- [ ] a Pi catalog limit correction reaches an already saved `catalog` bindingwithout deleting and re-adding the model, while a number the user entered inAdvanced (`user`) survives every correction, a hand-entered `128,000`included@@ -625,7 +549,7 @@ same model to the check mark, the toggle and the duplicate guard.- [ ] the provenance marker survives a provider save/read round trip and anunmarked record keeps working- [ ] unknown free-form models remain runnable without invented capabilities-- [ ] a models.dev record and an unknown generic record resolve through the same+- [ ] a Pi catalog record and an unknown generic record resolve through the sameselected transport without sending provider credentials to the remote catalog- [ ] compact limit text never reads above the published value, keeps theneighbouring 1M-line windows apart (`1M` / `1.05M` / `1.1M`), and neverdiff --git a/docs/spec/03-runtime/14-secrets-storage.md b/docs/spec/03-runtime/14-secrets-storage.mdindex af13bc99a..12b8f19ec 100644--- a/docs/spec/03-runtime/14-secrets-storage.md+++ b/docs/spec/03-runtime/14-secrets-storage.md@@ -139,6 +139,14 @@ assumption holds across concurrent turns. Each OAuth provider row gets its owncollection and store scope; two rows with the same vendor key never share acredential or refresh lock.+Pi login receives an installation context whose `getDeviceId` returns one stable+UUID v4. Electron main creates it lazily, shares concurrent initialization, and+persists it through Host secrets under `secret:installation:oauth-device-id`+before exposing it to the flow. It is independent of provider accounts and+survives cancellation, account deletion, and service restart. Initialization+failures remain retryable and use a redacted error. The identity never enters+provider rows, portable configuration, renderer events, or ordinary diagnostics.+Request auth flows one way only:1. The launch payload for an `authKind: "oauth"` row carries `apiKey: ""`.diff --git a/docs/spec/03-runtime/21-image-generation.md b/docs/spec/03-runtime/21-image-generation.mdindex 4aea0cf17..33051d644 100644--- a/docs/spec/03-runtime/21-image-generation.md+++ b/docs/spec/03-runtime/21-image-generation.md@@ -122,3 +122,18 @@ model/image HTTP fixtures: adjacent default settings, composer submission, batchpreviews, editing a generated file, collapsed results, and setup navigation.Live verification is opt-in via `scripts/test-image-generation-live.mjs`, limitedto one generation plus one edit and never a default test command.++## Pi 0.99.1 operation boundary++Image generation and edits execute through account-scoped Pi `Models.generateImages`.+Use native OpenRouter images or a registered compatible OpenAI-images adapter,+with JSON generations and multipart edits preserved. Each prompt is one physical+operation; no automatic retry may duplicate a billable image request. Batch+workers preserve output order, propagate cancellation/timeouts, and bound download+sizes and URL safety. Returned text, response ID and operation usage survive the+artifact projection. Multiple images from one response count as one operation.++The existing settings UI still excludes OAuth candidates. The internal adapter+may accept OAuth only with an actual supported native image model and account+auth resolver; it cannot fabricate entitlement or fall back to another account.+Unknown pricing remains unknown. Images never route through the chat selector.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 6d1478647..09f730cbf 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3111,6 +3111,20 @@ identify the platform validation still needed.- **Acceptance**: G (MCP bridge) + E (tools & permissions) + Security- **Status**: Unit-covered (`plugin-mcp.test.mjs` stdio + HTTP stubs); agent-facing scenario Draft+#### E2E-MCP-pi-client-owner-policy: Pi protocol under existing Desktop owners++- **Preconditions**: Pi 0.99.1 with the pinned host-policy patch; offline stdio and+ HTTP fixtures, no paid provider or user credentials.+- **Steps**: Run `plugin-mcp.test.mjs`, `user-mcp.test.mjs`,+ `mcp-stdio-launch.test.mjs`, `mcp-call-registry.test.mjs`, `mcp-oauth.test.mjs`,+ and `mcp-oauth-discovery.test.mjs` under `apps/desktop/test` using `node --test`.+- **Expected**: Concurrent discovery starts one process; host launch/env/egress+ policies remain enforced; Pi delivers progress and structured content; progress+ cannot extend the total call deadline; cancellation reaches the stdio peer and+ leaves other calls usable. OAuth uses Pi DCR/PKCE/refresh with host TLS/redirect,+ scope, callback-state, and encrypted-storage boundaries. No legacy client runs.+- **Status**: Offline integration-covered; packaged Electron journey NOT RUN.+#### E2E-MCP-CANCEL: Stop interrupts only the calling session's MCP request- **Preconditions**: Two Agent sessions share one user or plugin MCP server;@@ -4655,7 +4669,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.runnable with the generic text-only, non-reasoning shape; pi-ai supplies onlythe selected wire adapter, OAuth flow, and account model availability. AChatGPT Plus/Pro or GitHub Copilot account lists `gpt-6-sol`, `gpt-6-luna`,- and `grok-4.7` from the pinned pi-ai 0.87.1 catalog; models.dev then+ and `grok-4.7` from the pinned pi-ai 0.99.1 catalog; the account Pi adapter thensupplies their published metadata.- **Specs linked**: `02-architecture/02-tech-stack.md`,`03-runtime/11-provider-model-system.md`,@@ -15208,11 +15222,11 @@ plugin-form fixtures in an isolated temporary directory at runtime.#### E2E-MODEL-catalog-window-correction-reaches-saved-bindings-- **Goal**: a models.dev limit correction — the context window or the output cap —+- **Goal**: a Pi catalog limit correction — the context window or the output cap —reaches an already saved binding without deleting and re-adding the model, whilea number the user entered in Settings is never overwritten.- **Steps**:- 1. Configure a provider, select a model models.dev publishes a `limit.context`+ 1. Configure a provider, select a model Pi publishes a context windowfor, and save. Open the row's Advanced body and read the context-window fieldand its hint.2. Serve a corrected catalog record for that model (a different published@@ -15227,7 +15241,7 @@ plugin-form fixtures in an isolated temporary directory at runtime.5. Repeat step 4 with a row whose stored output cap is the generic `8192`, andone whose cap the user typed, and read the cap in the settings row and in therequest a new session launches with.-- **Expected**: Step 1 shows the published number with the "follows models.dev"+- **Expected**: Step 1 shows the published number with the "follows the catalog"hint. Step 2 shows the corrected number everywhere the effective window is used(settings row, context inspector, session launch) with no delete and re-add.Step 3 keeps the entered number in the settings row, in the inspector, and in@@ -15969,3 +15983,35 @@ renderer's durable transcript reads. No real model or provider is contacted.- **Acceptance:** Cache-path, migration, and cleanup unit tests pass; Windows task-candidate validation confirms the updater feed transport, installer handoff, and filesystem behavior without a live release feed.- **Milestone:** M6+- **Status:** Unit and source-contract covered (`update-cache.test.mjs`, `auto-update.test.mjs`); Windows installer/E2E validation remains required.++## E2E-OAUTH-pi-installation-identity-and-standalone-load++- **Preconditions**: Pi 0.99.1; temporary Host secrets and account fixtures;+ network/browser/callback I/O mocked; no user account or paid service.+- **Steps**: Run `installation-identity.test.mjs`, `vendor-oauth-login.test.mjs`+ and `oauth-standalone-bundle.test.mjs` under `apps/desktop/test`.+- **Expected**: One lazy, persisted UUID per installation; failed persistence+ never reaches login and is retryable. Multiple same-vendor accounts retain+ separate credentials. The standalone bundle executes the actual ChatGPT and+ Meta OAuth flows from outside the repository with empty `NODE_PATH`, including+ PKCE, callback validation and token conversion. Legacy Codex credentials remain+ unchanged; account deletion leaves the installation identity and other accounts.+- **Acceptance**: Offline identity/account/module-loading contracts pass.+- **Status**: Offline integration covered. Installed Electron artifact loading,+ Anthropic/Codex/Copilot flow execution and final migration packaging NOT RUN.++## E2E-PI-0991-account-operations-and-usage++- Scope: pi-ai and pi-agent-core; coding-agent design review is reference-only.+- Offline provider/catalog flows preserve same-vendor account isolation, live+ entitlement, unavailable-account errors, relay matching and explicit overrides.+- Native Pi image operation contract tests cover generations/edits, cancellation,+ downloads, multiple artifacts, text/response IDs and physical usage provenance.+- Shared/Main/Host tests replay parent, delegate and image records, including late+ old-turn usage, and assert one ledger entry per physical operation.+- Production sidecar hosted-search E2E covers seven scenarios with offline+ providers, delegation and persisted restore. Standalone OAuth tests execute+ actual login modules outside the repository with mocked external I/O.+- Installed Electron, real account/paid API and cross-version rollback are+ separate release qualification. No MCP, Codemode or virtual-router migration+ is included. See `docs/project/pi-0991-adoption.md` for candidate evidence.diff --git a/docs/zh-CN/spec/02-architecture/02-tech-stack.md b/docs/zh-CN/spec/02-architecture/02-tech-stack.mdindex 8c9d1f044..481e67014 100644--- a/docs/zh-CN/spec/02-architecture/02-tech-stack.md+++ b/docs/zh-CN/spec/02-architecture/02-tech-stack.md@@ -15,15 +15,14 @@| 主机后端 | **Rust** | 稳定的 Rust 工具链 | tools/plugins/permissions/persistence 适配器 || Rust 异步 | 东京 | 稳定 | 主机服务 || 主机 RPC | stdio JSON-RPC (NDJSON) | 冷冻(D001) | Electron 主 ↔ Rust 主机 |-| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.87.1 | 代理循环 |-| 模型 API | `@earendil-works/pi-ai` | 0.87.1 | 提供商 |-| 模型目录 | `https://models.dev/api.json` | 随发版内置的快照 + 进程内刷新 | 唯一的提供商/模型元数据来源 |--> 当前引脚为 **0.87.1**。ChatGPT / Copilot OAuth 目录包含-> `gpt-6-sol`、`gpt-6-luna`、`grok-4.7` 及已有的 `gpt-6-astra`;Claude-> Opus 5.5 目录元数据也已可用。0.87.1 的 pi-ai 目录还注册了-> Meta/Muse 订阅 OAuth;桌面端动态枚举这些条目,不维护独立的供应商列表。->(`claude-opus-5`,1M 上下文,适应性思维)。+| Agent 引擎 | `@earendil-works/pi-agent-core` | 0.99.1 | 代理循环 |+| 模型 API | `@earendil-works/pi-ai` | 0.99.1 | 提供商 |+| Model catalog | pi-ai Providers/Models | pinned 0.99.1 + explicit provider refresh | account-scoped metadata and typed operations |++> pi-ai owns published metadata, native thinking support, transports and auth.+> Host retains Desktop account rows, credentials and explicit binding overrides.+> No AgentSession, Codemode or virtual routing is adopted by this migration.+| Node 运行时 | Node.js | `>= 22.19` | 圆周率要求 || 数据库 | SQLite | Rust host-core 通过 `rusqlite` | sessions/settings || 包装 | 电子制造商 | 稳定 | macOS arm64、Intel x64、Windows x64 和 Linux x64 释放通道 |diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 19e78cc1a..e98492af2 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -87,7 +87,7 @@ pi 消费排队输入时保留渲染器提供的消息 id;即使补充输入1. 加载持久会话,会话缺失则拒绝2. 解析该会话的 mode/provider/model 与项目绑定(app/当前工作区默认值仅作为旧版回退)-3. 针对该确切的 provider/API URL 与 model 解析完整的 models.dev 元数据记录,+3. 针对该确切的 provider/API URL 与 model 解析完整的 Pi catalog 元数据记录,并把持久会话的思考级别钳制到它最接近的受支持值;快照中不存在的 id 使用显式的通用回退4. 验证 model/secret 可用性@@ -540,16 +540,16 @@ Goal 批准所承诺的内容与 Plan 批准所承诺的内容完全相同:`mo和 `max`。会话(及子智能体)选择器还接受 `omit`,它不是目录/绑定能力:运行时把智能体记账保持为 `off`,走低层 provider 流,不合成思考覆盖(ADR 0194 / ADR 0295)。-- 随包的 models.dev 发布快照对于已发布的推理支持具有权威性,+- 随包的 Pi catalog 发布快照对于已发布的推理支持具有权威性,思维层面的映射、限制、输入模式、定价、标题和适配器每个已解决的已知模型的兼容性。- 提供商配置不能覆盖已知模型语义。未知自由格式的 id 仍然可以通过通用的纯文本、非推理的方式运行模型,因此仅公开 `off`。-- 不支持的请求级别采用所选 models.dev 模型的最近受支持级别规则:先向上扫描+- 不支持的请求级别采用所选 Pi catalog 模型的最近受支持级别规则:先向上扫描先向上,然后向下。非推理提供商总是决心`off`。-- 视觉支持由同一条 models.dev 记录解析:只有 `input.includes("image")` 才启用+- 视觉支持由同一条 Pi catalog 记录解析:只有 `input.includes("image")` 才启用图片传输。未知/自定义模型 id 保持为保守的 text/path 模型,即使发现到的元数据声称支持 `vision`。- 有效级别会传给 pi `Agent`;特定于提供商的请求@@ -749,7 +749,7 @@ transcript 把一条链渲染成它最新 `Task` 卡片下的一段连续多轮“已恢复”标记。**模型引脚。** Frontmatter 中的 `model: <provider>/<model>` 在每次启动时于-Electron main 里解析一次——凭据与 models.dev 快照都在那里——匹配提供商 id、+Electron main 里解析一次——凭据与 Pi catalog 快照都在那里——匹配提供商 id、厂商键或显示名称,且最多 `MAX_SUBAGENT_PROVIDERS`(8)个不同的提供商。无法解析的引脚会被有意地排除在绑定映射之外;运行时把这个缺失的条目转成一个点名该引脚的工具错误,绝不回退到会话模型。定义中的 `thinkingLevel` 会按第 5c 节@@ -1162,3 +1162,18 @@ System/Direct/Custom 代理路由保持不变。终态。结构化原因会穿过 adapter 的错误扁平化,保留在最终错误行中,也不会触发provider transport 重建。`EPROTO` 等协议错误继续使用原有重试行为。详见[证书信任 ADR](../../../adr/provider-system-certificates.md)。++## Pi 0.99.1 execution boundary++Published model metadata and account entitlement come from one account-scoped+Pi Models collection. Effective binding projection is shared by launch, delegates+and compaction. Dispatch thinking normalization uses the resolved physical Pi+model; native null/unsupported mappings remain unavailable without mutating+saved preferences. Agent bookkeeping and omitted request reasoning are distinct.++Every physical stream attempt has an operation identity before dispatch. Usage+survives stream/result projection and events through Host/remote/renderer paths;+retries and images retain physical account/model attribution. Nested immediate+parent and owning Task remain distinct. The migration does not add coding-agent+AgentSession, Codemode or virtual routing. See the coding-agent design review for+future adoption conditions.diff --git a/docs/zh-CN/spec/03-runtime/04-data-storage.md b/docs/zh-CN/spec/03-runtime/04-data-storage.mdindex 01323ff6a..ed16f95c3 100644--- a/docs/zh-CN/spec/03-runtime/04-data-storage.md+++ b/docs/zh-CN/spec/03-runtime/04-data-storage.md@@ -1364,3 +1364,15 @@ schedule 就推断为日历配置;旧版 Hourly 行保留字段,但转换时已知意图在周期切换和数据库重开后仍然保留。该新增 JSON 字段不需要表或 schema版本迁移;旧版本会忽略它,也无法执行新的转换保护。++## Physical operation usage ledger++Optional operation ID, origin, physical account/model and cost status augment+existing message/turn usage. `session.recordUsage` merges identities into the+existing turn `usage_json`; no schema migration or historical rewrite is needed.+Identified records are idempotent across event replay, outbox retries, tool results+and parent/subagent rollups. Legacy token-only rows remain readable and additive.+An unknown price is distinct from a known zero price; partial known costs remain+on the individual operations. Late usage targets its captured turn and does not+revive it or debit the currently active turn. Immediate nested parent and owning+Task remain separate optional transcript/event fields.diff --git a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md b/docs/zh-CN/spec/03-runtime/11-provider-model-system.mdindex dbe07a1dd..5336bb26c 100644--- a/docs/zh-CN/spec/03-runtime/11-provider-model-system.md+++ b/docs/zh-CN/spec/03-runtime/11-provider-model-system.md@@ -97,9 +97,9 @@ Copilot 的 Anthropic Messages(Claude)请求将每次请求解析的 OAuthOpenAI 风格的 Copilot 线路 API 仍将令牌作为请求密钥签名;所有线路均保留逐请求认证解析与账户专属的 `baseUrl`。-智谱 / GLM 与 Z.AI 是命名的 OpenAI 兼容端点预设,收录在一份由 models.dev+智谱 / GLM 与 Z.AI 是命名的 OpenAI 兼容端点预设,收录在一份由 Pi catalog支撑的、简短的第一方厂商服务列表中(含小米)。添加提供商时的「服务」选择器-会持久化匹配的 models.dev `vendorKey`,并使用已发布的端点,在命名服务这条+会持久化匹配的 Pi catalog `vendorKey`,并使用已发布的端点,在命名服务这条路径上不显示名称、Base URL 或 API 格式。对话回合仍然使用选定的 pi-ai 适配器(`chat_completions`、`responses`、`anthropic_messages`、`google_generative_ai` 或 `opencode_go`)。智谱 / Z.AI 的 Completions 请求@@ -113,15 +113,15 @@ OpenAI 风格的 Copilot 线路 API 仍将令牌作为请求密钥签名;所见 ADR 0256 / #296)。官方 `deepseek.com` 行仍使用空串回填(#223)。该覆盖不改`thinkingFormat`。-当 models.dev 记录发布了推理 `effort` 选项且没有 `budget_tokens` 选项时+当 Pi catalog 记录发布了推理 `effort` 选项且没有 `budget_tokens` 选项时(例如 Opus 4.7+、Opus 5.x、Fable),Anthropic Messages 请求会设置`forceAdaptiveThinking: true`。这些模型会以 HTTP 400 拒绝-`thinking.type=enabled`,而 models.dev 不携带 pi-ai 的 compat 记录,缺少该标志时+`thinking.type=enabled`,而 Pi catalog 不携带 pi-ai 的 compat 记录,缺少该标志时pi-ai 会回落到 budget 思考。仍发布 `budget_tokens` 的模型保持 budget 思考,显式的目录 `compat` 记录会被保留。目录无法识别的 Anthropic Messages 行(例如某个自定义网关 URL 提供多家发布方都列出的-模型 ID)仍回退到通用模型形状,但当 Anthropic 自己的 models.dev 记录中存在完全相同的+模型 ID)仍回退到通用模型形状,但当 Anthropic 自己的 Pi catalog 记录中存在完全相同的模型 ID 时,会采用该记录的 `reasoning_options` 及派生的 `thinkingLevelMap`。Claude模型接受哪种思考形状是模型本身的属性,而非部署的属性,因此只迁移这两个字段;上下文与模态限制保持通用值,别名、改名后的 ID、其他 wire API,以及通过 Anthropic 协议提供的@@ -172,81 +172,38 @@ pi-ai 会回落到 budget 思考。仍发布 `budget_tokens` 的模型保持 bud### 6.1 无硬性模型许可名单上限PI-Desktop 不得把用户永久限制在一份简短的固定模型列表上。-### 6.2 目录职责-1. **models.dev**(`https://models.dev/api.json`)是唯一的模型元数据来源。- Electron main 在开发时读取签入仓库的发布资源- `apps/desktop/resources/models.dev/api.json`,在发布构建中读取打包后的- `resources/models.dev/api.json` 路径。它绝不会把提供商凭据发给目录。-2. 签入的快照由 `scripts/release.mjs` 在创建发布标签之前刷新。运行时,- 设置 → 模型配置可以显式地重新抓取 `https://models.dev/api.json`;成功的- 响应只替换当前进程的内存内目录。抓取失败则保留上一份有效的内存内目录,- 并且绝不写入用户数据。-3. **运行时/提供商发现**与 Rust 拥有的缓存,为自定义、本地或需要认证的账户- 专属端点提供模型 id。提供商匹配接受已配置的厂商键、归一化的 API URL、- models.dev 的提供商身份,以及带厂商前缀的 id(例如- `deepseek/deepseek-v4`);不带目录前缀的提供商模型 id,只有在提供商身份- 明确无歧义时,才会匹配到那个去掉前缀的精确后缀。原生适配器键可以使用目录- 别名——例如 pi-ai 的 `openai-codex` ChatGPT 订阅适配器通过 `openai` 记录- 解析模型元数据——而适配器本身保留自己的传输身份。它们不能凭空发明或替换- 模型元数据。已配置的自由格式 id 在 models.dev 中不存在时,仍可选中,- 并使用通用的纯文本、非推理基线。对于目录尚不认识的端点,设置里依然允许- 显式覆盖思考级别。-4. models.dev 记录把 `id`、`name`、`description`、`family`、`attachment`、- `reasoning`、`reasoning_options`、`tool_call`、`structured_output`、- `temperature`、`knowledge`、`release_date`、`last_updated`、- `modalities.input/output`、`open_weights`、`limit.context/input/output`、- `cost`、`interleaved`、`status`、`experimental` 和 `provider` 映射到共享的- 模型界面上。-5. pi-ai 仅仅是请求/OAuth 的实现层。它自带的模型目录与模型能力函数,不会被- 用来读取名称、上限、定价、模态、推理或其他模型配置。-6. 输入与输出模态数组保留 `text`、`image`、`audio`、`video` 和 `pdf`。文本- agent 选择器暴露能处理文本的模型,同时在文件中保留全部原始记录以备将来的- 界面使用。只有当模型接受图片输入时,图片才会作为临时图片内容块发送。PDF- 能力会在模型元数据中呈现并保留;由于 pi-ai 0.87.1 没有原生的 PDF 内容块,- PDF 附件仍然是有界的文件引用,而不会被错误地编码成图片。-7. 用户编辑过的 `ModelBinding` 值仍属于显式的提供商配置:它们控制选定的请求- 上限、启用的思考级别、应用到新的主页草稿与新持久化会话的默认思考级别- (会被钳制到已启用集合上;已匹配目录的模型在默认值未设置时取已启用中最强的- 那个,未匹配模型则从 `off` 开始),以及附件能力覆盖。`models.dev` 提供已发布的- 元数据,并为新添加的已知模型- 播下初始的思考级别选择;它不是对用户为该端点显式启用的级别的运行时闸门。- 出于兼容考虑,仍然带着旧的通用 `128,000` 上下文种子的 binding 会跟随新- 发布的 `limit.context`;非默认的 Advanced 值仍保持显式。这样目录刷新之后,- sidecar 与上下文检查器仍处在同一个有效窗口上。-8. 设置为每个 binding 渲染七个规范思考级别。对已知的推理模型,已发布的级别- 一开始就是选中的。非推理或未知模型显示同样的选项但不选中,并附一行简短的- 手动覆盖说明。`defaultThinkingLevel` 从 `omit` 加上该 binding 已启用的级别- 中选取,因此存下来的默认值要么是 `omit`,要么属于那个显式集合。-9. `supportsImages` 与 `supportsDocuments` 是三态覆盖。缺省或 `null` 表示跟随- 已发布的 models.dev 模态,因此目录的更正仍然能作用到已保存的 binding;- `true` 或 `false` 是用户的显式回答,并在目录变动后继续有效。与思考级别- 不同,这两个覆盖不会被收窄到已发布的能力,因为经过代理或自托管的端点- 经常接受其目录条目未列出的输入。启用图片输入会打开临时图片内容块;启用- PDF 输入只记录该能力,不改变编码方式——pi-ai 0.87.1 没有 PDF 内容块,- PDF 仍是有界的文件引用。-10. 设置里的复选框展示相对于已发布基线的有效答案。未修改或为 `null` 时跟随目录;- 用户一旦更改复选框,所选布尔值就会显式固定,即使它与当前目录值相同。目录刷新- 不会撤销用户主动做出的选择。-10a. `nativeWebSearch` 是两态主动开启(缺省即关闭;models.dev 不发布托管工具能力,- 因此没有目录默认值)。启用后,当模型解析到 `anthropic-messages`、- `openai-responses`、`azure-openai-responses` 或 `openai-codex-responses`- (存储的 apiStyle 为 `anthropic_messages`、`responses` 或- `openai_codex_responses`,或从 Chat Completions 解析到已确认的官方搜索路径)时,适配器附加提供商托管搜索工具- (`web_search_20250305` / `web_search`),将活动写入- `UiMessage.hostedSearch`,并在后续回合(含重启后)回放原始数据(ADR 0297)。- OpenAI OAuth 使用独立的 Codex Responses 适配器和 ChatGPT 订阅端点,不是公开的- `/v1/responses`;搜索工具写入 Codex 请求体顶层 `tools`。设置仍需用户逐模型- 勾选;运行时还会按最终解析的 wire API 校验,旧配置不会把工具带给不支持的适配器。- 不支持工具的网关会显示提供商错误,用户可取消勾选。搜索由提供商执行,没有- 本地抓取或权限询问。压缩仍按既有前缀/尾部策略保留;摘要请求含被压缩前缀的- 搜索回放,但生成的文本摘要不是原始搜索块的无损副本。-11. `ModelInfo` 是设置界面用来对照的已发布记录,因此已存储的 binding 不得- 塑造它的能力或推理字段。有效上限、推理与思考级别都通过那个确切的 binding- 解析;有效的传输模态数组还会额外套用显式的附件覆盖。-12. 用户已配置过的模型,即使实时发现不再列出它,也保留它已发布的记录,使其- 能力仍然可见、可编辑。只有已经存在于该提供商 `models` 中的 id 才会被- 重新加入,绝不会加入整个目录;而且只有发现实际返回的那些行才会被写入- 模型缓存。+### 6.2 Catalog responsibilities++1. pi-ai 0.99.1 Providers/Models own published metadata, transport, thinking+ support and native operation types. Electron's historically named+ `ModelsDevCatalog` is an account-aware adapter over this public API.+2. Startup is cache-only and disables ambient environment/file credentials.+ Each configured account has its own Models collection and Host credential+ store. Same-vendor rows cannot borrow one another's credentials.+3. OAuth live entitlement IDs are published through the account provider's+ refresh/filter boundary. A successful list governs available chat models;+ discovery failure preserves the pinned catalog. Live-only IDs may inherit+ same-tier adapter/thinking metadata, with unknown prices retained as unknown.+4. Settings exposes published metadata separately from explicit binding+ overrides. Effective chat limits, inputs, thinking and request shape are+ projected once at the account boundary and reused for ordinary sessions,+ delegates, compaction and image lookup. Pi's unsupported/null effort mappings+ cannot be re-enabled by stale persisted settings. No saved data is rewritten.+5. Chat, image and classifier models are selected by operation type even when+ they share a model ID. A small display-only operation metadata supplement+ preserves settings visibility for image/audio/video/embedding records that+ Pi does not publish. It supplies no runtime auth, dispatch, price or entitlement.+6. Free-form IDs remain configurable. Conservative generic metadata applies+ when no published model matches; explicit user overrides remain supported.+ Unknown relay metadata uses exact final-segment matching and an unambiguous+ official publisher. Known endpoint aliases cannot borrow past an ambiguous+ same-endpoint miss. No deployment/date/thinking suffix is removed.+7. Settings catalog refresh calls Pi's public refresh API. Release scripts no+ longer fetch or package the independent Pi catalog JSON catalog. Pi version+ pins provide the reproducible catalog baseline.+8. PDF capability remains metadata; attachments use bounded file references+ until the runtime supports a native PDF content block. Image capability is+ resolved against the effective selected binding before transport.### 6.3 涵盖的模型系列目录和自定义模型条目必须支持通用功能类:@@ -343,7 +300,7 @@ type ThinkingLevel =上面这些兼容性字段,是为老客户端保留的持久化模式兼容面。PI-Desktop 不再把它们当作运行时的模型覆盖来读取。`ModelInfo` 的推理支持与受支持的思考级别-描述的是解析出的 models.dev 记录;有效的 provider/会话能力则来自那个确切的+描述的是解析出的 Pi catalog 记录;有效的 provider/会话能力则来自那个确切的`ModelBinding`。未知的自由格式 id 以通用形态起步,不带任何推断出的推理能力;空的绑定等级数组是通用种子,非空的显式 binding 才会主动启用或禁用相应级别。@@ -417,14 +374,14 @@ Codex CLI 版本(`CODEX_MODELS_CLIENT_VERSION`),账户模型缺失时调(Kimi 走 Anthropic 风格的 `/v1`)。Radius 继续用网关目录刷新,不再另打一遍。账户请求失败时,日志记录 HTTP 状态码和一小段单行的响应内容摘要,其中去掉了请求自身的凭据和任何形似令牌的值,便于从提供商日志诊断上游契约变化。-图像、视频、语音和嵌入模型会被丢掉。models.dev 不认识的 id 只从同档位的 pin+图像、视频、语音和嵌入模型会被丢掉。Pi catalog 不认识的 id 只从同档位的 pin兄弟继承限额,xAI 按 `grok-4.7`、`grok-4.6`、`grok-4.5`、`grok-4.3` 的固定新到旧顺序,-不按 pin 顺序。models.dev 不能把账户列表里没有的 id 加进去。一个厂商可以+不按 pin 顺序。Pi catalog 不能把账户列表里没有的 id 加进去。一个厂商可以跨越多种线路 API,因此行的 `apiStyle` 跟随所选模型。### Anthropic token 端点限流-固定版本 pi-ai 0.87.1 的仓库补丁为 Anthropic 授权码交换与刷新提供同一套+固定版本 pi-ai 0.99.1 的仓库补丁为 Anthropic 授权码交换与刷新提供同一套有限策略:只重试明确的 HTTP 429,最多总共三次请求。先等待至少 1 秒、再等待至少 2 秒;若 `Retry-After` 给出更长的秒数或 HTTP 日期,则遵守该时间。服务器要求的等待超出剩余预算时结束本次尝试,不缩短等待后提前重试。@@ -515,30 +472,24 @@ type ModelDescriptor = {- 提供商未经授权- 目录刷新失败(仍然允许手动模型 ID)-## 11. 运行时解析算法--当使用 `(providerId, modelId)` 开始回合时:--1.从主机加载提供程序配置-2. 如果 missing/disabled → 失败(`MODEL_NOT_CONFIGURED`;保留详细信息:`PROVIDER_DISABLED`)-3. 解析凭据:密钥行通过 `secretRef` 读取机密(从不记录机密;丢失 →- `PROVIDER_SECRET_MISSING`);`oauth` 行完全跳过这一步并以空密钥启动,- 因为认证按请求解析(第 8a 节)-4. 通过精确的 vendor/id 或兼容的解析完整的 pi-ai 模型记录- 带有分隔符限制后缀的网关别名-5.解决后,复制pi的名字,推理标志,思维层次图,输入- 模式、定价、上下文窗口、输出限制、标题和兼容性- 逐字记录;当未解决时,接受原始模型 ID 和通用模型- 纯文本、非推理后备-6. 将会话思维水平与 PI 支持的水平相结合并构建- 通过仅替换 provider/model 标识来选择运行时提供程序适配器- API 适配器、身份验证和显式配置的端点 URL-7. 使用中止句柄和单独的 answer/thinking 事件执行流-8. 将供应商错误转换为共享 `AppError` 代码 (§15)--如果模型不在 pi 的目录中,当用户明确指定时仍然允许它-输入模型 ID,提供商接受未知 ID。 Cached/discovered-能力字段不会促进回退到已知的运行时模型。+## 11. Runtime resolution algorithm++When starting a turn with `(providerId, modelId)`:++1. Load the Host provider row; fail for a missing or disabled explicit account.+2. Resolve credentials only for that account. OAuth refresh remains per request.+3. Resolve the typed chat model from the account Pi collection, with conservative+ generic fallback for explicitly configured unknown compatible IDs.+4. Apply the central effective binding projection and clamp thinking with Pi's+ public capability helper. Preserve native costs and unknown-price provenance.+5. Build the transport with the actual vendor/model identity and the configured+ endpoint. Anthropic roots normalize a trailing `/v1` because its adapter+ appends `/v1/messages`. Delegates use the same account/binding resolution.+6. Stream with cancellation and separate answer/thinking events. Attribute usage+ to each physical request operation, including retries, and translate errors+ to shared AppError codes. Replay aggregation deduplicates operation IDs.++An unavailable saved account never silently falls back to the default account.## 12. 兼容性层@@ -551,18 +502,15 @@ type ModelDescriptor = {UI 可能会显示层级提示,但默认情况下不得硬阻止未知模型。-## 13. 刷新和更新策略+## 13. Refresh & update policy-1. Electron main 在提供模型元数据之前先读取随包的发布资源:开发时是- `apps/desktop/resources/models.dev/api.json`,打包构建中是- `resources/models.dev/api.json`。-2. `scripts/release.mjs` 抓取 `https://models.dev/api.json`,校验它,并在创建- 发布标签之前原子地替换签入仓库的那份资源。-3. 设置 → 模型配置可以随时强制一次远程刷新;成功的响应只更新当前进程的- 内存内目录。-4. 提供商端点发现只为随包/内存内 models.dev 快照中没有的模型提供 id;未知的- id 使用通用元数据。-5. 刷新失败不得擦除随包文件、Rust 拥有的提供商缓存,或已配置的 binding。+1. Use the pinned Pi catalog at startup without network or ambient credentials.+2. Settings may explicitly refresh Pi provider catalogs in memory.+3. Provider endpoint discovery preserves configured IDs and Host caches; OAuth+ live discovery publishes account entitlements through the same Models owner.+4. Failed refresh retains available metadata and configured bindings.+5. Release catalog changes arrive through reviewed Pi pins and patches; the+ release script does not fetch a second model catalog.## 14. 本地/离线模型支持@@ -632,7 +580,7 @@ OpenAI Responses 适配器必须把 `response.completed`(以及而不是继续等待服务端的 TCP FIN。上游 pi-ai 会一直迭代直到服务端关闭连接,在保持空闲连接不关的反向代理后面会导致整个回合挂起。在该修复随上游发布之前,`patches/` 通过 pnpm patch 修改-`@earendil-works/[email protected]`,在终态事件处跳出事件循环(消费方停止+`@earendil-works/[email protected]`,在终态事件处跳出事件循环(消费方停止迭代时 OpenAI SDK 会中止底层请求)。待 pi-ai 发布包含该修复的版本后移除补丁。diff --git a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.mdindex 38392600a..1387c71f8 100644--- a/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md+++ b/docs/zh-CN/spec/03-runtime/13-model-catalog-and-selection.md@@ -134,33 +134,24 @@ type RecentModelRef = {- 显示非阻塞警告- 不要硬阻止(供应商标签可能不完整)-## 6. 刷新行为--随应用打包的 `apps/desktop/resources/models.dev/api.json` 快照是启动基线。-`scripts/release.mjs` 在创建发布标签前更新该快照;应用启动不会请求或写入目录。-设置页通过 Electron 专用的 `providers.refreshModelCatalog` 通道重新获取-`https://models.dev/api.json`;成功响应只替换当前进程内存中的 models.dev-目录,不会写入用户数据。--重复的元数据查询使用容量有界的进程内缓存,键由配置的厂商键、基础 URL 和-去除首尾空白且不区分大小写的模型 ID 组成。匹配和未匹配结果都会缓存,原有的-提供商偏好、别名匹配和候选排序保持不变。成功加载打包快照或在设置中刷新并-替换目录后,缓存失效;刷新失败则保留之前的目录及查询结果。补全会话能力时,-每个会话只解析一次匹配的目录记录,再应用当前提供商/模型绑定和会话默认值,-因此用户覆盖值不会作为过期能力留在缓存中。刷新大型会话列表时,同样的查询-不能在每次出现时都重新扫描完整目录。--提供商模型加载仍采用 stale-while-revalidate:--1. `source: "cache"` 从 Rust 拥有的 SQLite 读取已保存提供商的规范化发现记录,- 不访问提供商网络。-2. 渲染器可以立即在 Composer 和提供商对话框中显示这些记录。-3. `source: "refresh"` 优先使用打包或内存中的 models.dev 目录,只有需要发现- models.dev 未提供的模型 ID 时才探测提供商端点。-4. 成功的提供商发现可以更新 Rust 拥有的规范化缓存,但不能替换匹配的- models.dev 记录或其元数据。-5. 发现结果不完整或不可用时,保留已配置的 `ModelBinding` ID;models.dev- 中不存在的 ID 使用通用元数据。+## 6. Refresh behavior++The pinned pi-ai 0.99.1 catalog is the startup baseline. Startup reads no remote+catalog and uses no ambient credentials. `providers.refreshModelCatalog` invokes+Pi's public refresh API; settings metadata lookups themselves are local.++For keyed endpoints, live discovery supplies IDs and the central Pi catalog+adapter enriches their metadata. For OAuth, the account provider refresh hook+publishes live entitlement IDs into its existing Models collection. Successful+account lists are authoritative; a failed list preserves the pinned baseline.+Same-tier fallback for live-only IDs preserves transport and thinking behavior+but cannot invent known prices.++`source: "cache"` reads Host caches and configured bindings without network.+`source: "refresh"` probes the selected endpoint/account and decorates returned+IDs. Saved bindings remain visible when discovery is partial or unavailable.+Account removal invalidates catalog access; failed Host deletion preserves the+still-existing account. Refresh does not rewrite configured models or history.## 7. 线下行为@@ -216,10 +207,10 @@ type ModelCatalogItem = {运行时、上下文检查器与设置界面解析同一个有效窗口与输出上限。两个限额的来源分别保存:`contextWindowSource` 只适用于 `contextWindow`,`maxTokensSource` 只适用于 `maxTokens`。-- `catalog` —— 对应限额是 models.dev 快照,之后该目录字段的修正可以替换它。刷新后的+- `catalog` —— 对应限额是 Pi catalog 快照,之后该目录字段的修正可以替换它。刷新后的长上下文模型(例如 `gpt-5.6-luna`,1,050,000 tokens)不再显示为 128k 模型;在目录尚未收录该 ID 时加入的行,记录解析后也不再显示通用的 8.2k 输出上限。只有成功解析- 的 models.dev 记录才算已发布;查询未命中、回退到通用形态时不算目录修正。+ 的 Pi catalog 记录才算已发布;查询未命中、回退到通用形态时不算目录修正。- `user` —— 该限额来自单个模型「高级」里的输入或预设档位,目录永不替换它,包括与通用种子相同的 128,000 或 8,192。设置上下文窗口不会改变最大输出 token 的来源。@@ -277,68 +268,34 @@ type ModelCatalogItem = {除非不可能执行,否则警告是非阻塞的。-### 11. 1 推理能力解析--1. 解析 pi 目录元数据以获得确切的 `(vendorKey, modelId)` 或- 分隔符限制的兼容网关别名。-2、完整的pi模型记录,权威; cached/discovered 模型- 功能和遗留提供程序覆盖不能取代其推理- 旗帜或思维层面的地图。-3. pi 中不存在的自由格式 id 在 host 能力快照中仍是未知通用模型。Composer 对- 未匹配模型提供七个规范思考等级供用户手动启用;没有存储的绑定默认值时,草稿- 和新会话从 `off` 开始。空的绑定等级数组只是未知模型的通用种子,不会覆盖这条- 阶梯;非空的显式 binding 覆盖仍然优先。-4. Composer 按规范顺序渲染有效的绑定等级;目录命中时使用已发布的模型等级,- 未命中时使用完整规范阶梯。-5. 如果 stored/requested 级别不可用,请选择最近支持的级别-通过先向上然后向下扫描来调整水平。非推理模型- 始终解析为 `off`。-6. 更改为非推理提供商仍然存在 `off`;没有不支持的级别- 泄漏到下一个请求中。--### 11.2 目录元数据的模型 ID 匹配--目录补全使用 `catalogModelIdsMatch`,不使用解析已配置绑定身份的共享-`modelIdsMatch`。绑定身份保留原有的不区分大小写 wire ID、区域、路径后缀与已知-厂商前缀规则。元数据查询本身只取 ID 最后一个 `/` 段并按小写精确比较:-`route/model` 可以命中 `model` 的目录记录,但路由前缀不等于模型身份。索引使用-同一个末段键,因此共享叶子的不同路由会成为候选竞争,而不会自动认定为同一模型。--解析采用保守规则:零个候选保持未匹配,一个候选用于补全;多个候选时,仅当唯一-官方/来源提供商的提供商族与显式来源前缀(`anthropic`、`openai`、`google*`、-`xai`/`x-ai`)一致时优先采用。没有唯一官方命中时,只有所有候选的能力和思考元数据-完全一致才允许补全,否则保持未匹配。匹配器不再剥离 `thinking`、`think`、`agent`、-`latest`、发布日期或部署标记后缀,也不再折叠厂商短横线别名。已知提供商自己的记录-缺失时仍可从其他目录发布方借用完全相同的 ID;未知提供商不再使用无锚点共识或部署-标记兜底。--这些规则只附加已发布元数据,不改写配置中的 wire ID,也不从后缀推断推理能力。未匹配-的自由格式 ID 在 host 侧保留通用能力快照,而 Composer 提供完整规范思考阶梯供用户-手动启用。--#### 11.3.1 跨发布方的同名 ID 兜底--models.dev 把网关上的模型副本记在拥有权重的厂商名下,因此返回 `Vendor/Model` 这类 ID 的端点-自身可能没有记录,而其他发布方声明了完全相同的 ID。当行解析到明确的目录提供商、而它自己没有这条-记录时,`findModel` 可以读取声明该 **完全相同** ID 的其他发布方,而不是把模型留在通用的-128k 纯文本形态(issue #938)。--借用是有边界的:--- 只在行已有明确目录发布方身份、且它自己的查询未命中时运行。该提供商自己的记录及其受支持的别名- 始终优先。-- 与行的端点同址的提供商是行的别名,不是独立来源:它对这条 ID 的沉默就是对该部署的回答,- 不会越过它去借用。-- 只转移大小写不敏感的完全相同 ID。通过末段候选或其他非精确拼写命中的记录不参与该兜底。-- app 自带 provider 的发布方先于任意中转商回答,但只针对完全相同的请求 ID。通过另一种拼写命中的- 副本不能收窄或扩张模型自身声明的视觉能力。-- 工具能力按声明它的发布方多数决:错误的 `true` 会把工具声明放到线上、可能被端点拒绝,- 但一个持不同意见的中转商也不应让上百家一致同意的记录作废;票数持平则不声明。其余能力取交集,- 因此借用只可能低估 —— 知道端点支持更多的用户仍可在「高级」里打开。窗口取各发布方声明值的中位数,- 而不是某一家的上限。-- 没有任何发布方声明该 ID 时,它保持为未知的通用模型,不再走部署标记或无锚点共识兜底。--这只改变元数据:配置的线上 ID、提供商身份,以及 §11.3 的绑定优先级都不变。+### 11.1 Reasoning capability resolution++1. Resolve published Pi thinking metadata for the exact physical model.+2. Project explicit binding levels at the account boundary. Known unsupported+ levels and native null mappings remain unavailable; saved settings are not+ rewritten. Clamp the dispatched request using Pi's public helper.+3. Unknown free-form IDs retain the generic Desktop ladder for manual opt-in,+ with `off` as the unset default. Explicit binding defaults remain scoped to+ new drafts/sessions rather than overwriting existing session preferences.+4. `omit` remains a distinct request choice: no thinking field is sent. Agent+ bookkeeping may store `off` while the request omits reasoning.+5. The Composer renders effective enabled levels in canonical order. Dispatch+ normalization cannot silently enable a native unsupported level.++### 11.2 Vision capability resolution++1. Resolve the published image-input baseline from the matching model record.+2. Apply the exact configured binding's `supportsImages` value to that+ baseline. An absent or `null` value follows the published capability;+ `true` enables image input for a configured endpoint even when its published+ record is text-only, and `false` disables a published image capability.+3. The Composer model-row vision badge and the main attachment transport gate+ use this same effective result. An unknown or custom model without an+ explicit binding override remains on the conservative path-fallback route;+ discovery or cache metadata alone cannot promote it to image transport.+4. The main process prepares pasted images as content-addressed refs. A+ vision-capable model receives images within the 10 MB app-side inline+ bound as transient image blocks; other cases receive a safe `@path`.## 12. 刷新策略@@ -347,14 +304,14 @@ models.dev 把网关上的模型副本记在拥有权重的厂商名下,因此- MVP 中没有激进的背景轮询- 刷新失败保留以前的缓存并显示非致命错误-Electron 使用本地 `models.dev` 记录装饰缓存和新发现的模型行。其+Electron 使用本地 `Pi catalog` 记录装饰缓存和新发现的模型行。其`contextWindow` 与 agent sidecar 共享同一套 effective 解析;提供商发现只为目录缺失的模型提供 ID,未知模型仍使用通用后备。上下文窗口解析必须与 agent runtime 使用同一个 effective window。每个 binding 记录自己的 `contextWindow` 从哪来(`contextWindowSource`):-- `catalog`——该值是 models.dev 快照,之后目录修正 `limit.context` 时会跟着更新,+- `catalog`——该值是 Pi catalog 快照,之后目录修正 `limit.context` 时会跟着更新,所以 `gpt-5.6-luna`(`1,050,000`)这类记录不会再显示为 128k,被修正上限的模型也不用删掉重建;- `user`——该值来自 Advanced 里的手改(含预设档位),任何目录修正都不会覆盖它,diff --git a/docs/zh-CN/spec/03-runtime/21-image-generation.md b/docs/zh-CN/spec/03-runtime/21-image-generation.mdindex 52f63c879..e7190bf66 100644--- a/docs/zh-CN/spec/03-runtime/21-image-generation.md+++ b/docs/zh-CN/spec/03-runtime/21-image-generation.md@@ -57,3 +57,18 @@验证:`node scripts/e2e-image-generation.mjs` 覆盖宿主、stdio、HTTP 和存储;`node scripts/e2e-image-generation-ui.mjs` 使用 API 边界夹具覆盖真实 React/Chromium 交互。单元及服务测试覆盖限制、取消、部分失败、认证、超时、不安全路径和受限下载。`node scripts/e2e-image-chat.mjs` 在隔离桌面中使用本地模型/图片 HTTP 夹具,覆盖相邻默认设置、Composer 提交、批量结果、引用生成文件编辑、收起详情和配置跳转。真实接口验证通过 `scripts/test-image-generation-live.mjs` 显式启用,仅限一次生成和一次编辑,不属于默认测试命令。++## Pi 0.99.1 operation boundary++Image generation and edits execute through account-scoped Pi `Models.generateImages`.+Use native OpenRouter images or a registered compatible OpenAI-images adapter,+with JSON generations and multipart edits preserved. Each prompt is one physical+operation; no automatic retry may duplicate a billable image request. Batch+workers preserve output order, propagate cancellation/timeouts, and bound download+sizes and URL safety. Returned text, response ID and operation usage survive the+artifact projection. Multiple images from one response count as one operation.++The existing settings UI still excludes OAuth candidates. The internal adapter+may accept OAuth only with an actual supported native image model and account+auth resolver; it cannot fabricate entitlement or fall back to another account.+Unknown pricing remains unknown. Images never route through the chat selector.diff --git a/packages/agent-host/src/agent-host.ts b/packages/agent-host/src/agent-host.tsindex aebd304ab..9eeec7c8c 100644--- a/packages/agent-host/src/agent-host.ts+++ b/packages/agent-host/src/agent-host.ts@@ -239,6 +239,7 @@ export class AgentHost {const meta2 = {turnId,parentToolCallId: envelope.parentToolCallId,+ nestedParentToolCallId: envelope.nestedParentToolCallId,agentName: envelope.agentName,};@@ -359,6 +360,7 @@ export class AgentHost {this.emit(state, "turn.activity", { event }, meta2);return;}+ case "usage":case "turn_start":case "turn_end":this.emit(state, "turn.activity", { event }, meta2);@@ -909,7 +911,7 @@ export class AgentHost {error?: NonNullable<TurnRecord["error"]>;kind: Parameters<EventHub["publish"]>[0]["kind"];payload: Record<string, unknown>;- meta: { turnId?: string; parentToolCallId?: string; agentName?: string };+ meta: { turnId?: string; parentToolCallId?: string; nestedParentToolCallId?: string; agentName?: string };},): void {if (turn) {@@ -1192,7 +1194,7 @@ export class AgentHost {state: SessionState,kind: Parameters<EventHub["publish"]>[0]["kind"],payload: unknown,- meta: { turnId?: string; parentToolCallId?: string; agentName?: string },+ meta: { turnId?: string; parentToolCallId?: string; nestedParentToolCallId?: string; agentName?: string },): void {const durable = racpDurable(kind);if (durable) state.revision += 1;@@ -1203,6 +1205,7 @@ export class AgentHost {revision: state.revision,kind,...(meta.parentToolCallId ? { parentToolCallId: meta.parentToolCallId } : {}),+ ...(meta.nestedParentToolCallId ? { nestedParentToolCallId: meta.nestedParentToolCallId } : {}),...(meta.agentName ? { agentName: meta.agentName } : {}),payload: this.boundPayload(payload),});@@ -1279,6 +1282,7 @@ export class AgentHost {status,createdAt: new Date(envelope.ts).toISOString(),...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),content,};@@ -1297,6 +1301,7 @@ export class AgentHost {expiresAt: new Date(this.clock.now() + this.approvalLifetime(state)).toISOString(),...(envelope.agentName ? { agentName: envelope.agentName } : {}),...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),questions: request.questions.map((question, index) => ({id: `${request.requestId}:${index}`,question: question.question,diff --git a/packages/agent-host/src/approvals.ts b/packages/agent-host/src/approvals.tsindex 61ab7479e..034c2ab28 100644--- a/packages/agent-host/src/approvals.ts+++ b/packages/agent-host/src/approvals.ts@@ -78,6 +78,7 @@ export class ApprovalBroker {risk: request.risk,...(request.agentName ? { agentName: request.agentName } : {}),...(request.parentToolCallId ? { parentToolCallId: request.parentToolCallId } : {}),+ ...(request.nestedParentToolCallId ? { nestedParentToolCallId: request.nestedParentToolCallId } : {}),allowedDecisions: context.allowSession? [...RACP_TOOL_APPROVAL_DECISIONS]: RACP_TOOL_APPROVAL_DECISIONS.filter((decision) => decision !== "allow-session"),diff --git a/packages/agent-host/src/event-log.ts b/packages/agent-host/src/event-log.tsindex fa1917124..b07079544 100644--- a/packages/agent-host/src/event-log.ts+++ b/packages/agent-host/src/event-log.ts@@ -12,6 +12,7 @@ export type EventDraft = {revision: number;kind: RacpEventKind;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;payload: unknown;occurredAt?: string;diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.jsonindex 42bf98a12..be74adbf9 100644--- a/packages/agent-runtime/package.json+++ b/packages/agent-runtime/package.json@@ -27,9 +27,9 @@"clean": "node -e \"fs.rmSync('dist',{recursive:true,force:true});fs.rmSync('dist-bundle',{recursive:true,force:true})\""},"dependencies": {- "@earendil-works/pi-agent-core": "0.87.1",- "@earendil-works/pi-ai": "0.87.1",- "@earendil-works/pi-coding-agent": "0.87.1",+ "@earendil-works/pi-agent-core": "0.99.1",+ "@earendil-works/pi-ai": "0.99.1",+ "@earendil-works/pi-coding-agent": "0.99.1","@pi-desktop/shared": "workspace:*","jiti": "2.7.0","typebox": "1.3.27",diff --git a/packages/agent-runtime/src/agent-messages.ts b/packages/agent-runtime/src/agent-messages.tsindex 9b2e947d4..ba284c459 100644--- a/packages/agent-runtime/src/agent-messages.ts+++ b/packages/agent-runtime/src/agent-messages.ts@@ -7,7 +7,7 @@import type { AgentMessage, JsonValue } from "@earendil-works/pi-agent-core";import type { Usage } from "@earendil-works/pi-ai";-import type { MessageUsage } from "@pi-desktop/shared";+import type { MessageUsage, UsageProvenance } from "@pi-desktop/shared";export function nowIso(): string {return new Date().toISOString();@@ -47,26 +47,29 @@ export function toJsonObject(value: unknown): Record<string, JsonValue> {: {};}+/** Pi requires numeric costs, including when replaying history with no price. */+export type AccountedPiUsage = Usage & { desktopUsage?: MessageUsage };+export function usageFromPi(usage: Usage | undefined | null,+ provenance: UsageProvenance = {},): MessageUsage | undefined {if (!usage) return undefined;- const inputTokens = Math.max(0, Math.round(usage.input || 0));- const outputTokens = Math.max(0, Math.round(usage.output || 0));- const cacheReadTokens = Math.max(0, Math.round(usage.cacheRead || 0));- const cacheWriteTokens = Math.max(0, Math.round(usage.cacheWrite || 0));- const reasoningTokens =- typeof usage.reasoning === "number"- ? Math.max(0, Math.round(usage.reasoning))- : undefined;- const totalTokens = Math.max(- 0,- Math.round(- usage.totalTokens ||- inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens,- ),- );- if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0) return undefined;+ const retained = (usage as AccountedPiUsage).desktopUsage;+ if (retained) return { ...retained, ...provenance };+ const tokens = (value: number | undefined) => Number.isFinite(value) ? Math.max(0, Math.round(value ?? 0)) : 0;+ const inputTokens = tokens(usage.input);+ const outputTokens = tokens(usage.output);+ const cacheReadTokens = tokens(usage.cacheRead);+ const cacheWriteTokens = tokens(usage.cacheWrite);+ const reasoningTokens = typeof usage.reasoning === "number" ? tokens(usage.reasoning) : undefined;+ const totalTokens = tokens(usage.totalTokens) || inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens;+ const validCost = usage.cost && (["input", "output", "cacheRead", "cacheWrite", "total"] as const).every((key) => Number.isFinite(usage.cost[key]) && usage.cost[key] >= 0);+ // Pi adapters normally calculate cost from model rates. Unmarked all-zero+ // costs are also their missing-price placeholder, not evidence of free use.+ const costStatus = provenance.costStatus ?? (validCost && usage.cost.total > 0 ? "estimated" : "unknown");+ const cost = validCost && costStatus !== "unknown" ? { ...usage.cost } : undefined;+ if (totalTokens <= 0 && inputTokens <= 0 && outputTokens <= 0 && !cost?.total) return undefined;return {inputTokens,outputTokens,@@ -74,10 +77,15 @@ export function usageFromPi(...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),...(reasoningTokens !== undefined ? { reasoningTokens } : {}),totalTokens,+ usageOrigin: "pi",+ ...provenance,+ costStatus: cost ? costStatus : "unknown",+ ...(cost ? { cost } : {}),+ ...(provenance.operationId ? { aggregation: "operation" } : {}),};}-export function usageToPi(usage: MessageUsage | undefined): Usage {+export function usageToPi(usage: MessageUsage | undefined): AccountedPiUsage {const input = usage?.inputTokens ?? 0;const output = usage?.outputTokens ?? 0;const cacheRead = usage?.cacheReadTokens ?? 0;@@ -87,12 +95,14 @@ export function usageToPi(usage: MessageUsage | undefined): Usage {output,cacheRead,cacheWrite,- ...(usage?.reasoningTokens !== undefined- ? { reasoning: usage.reasoningTokens }- : {}),- totalTokens:- usage?.totalTokens ?? input + output + cacheRead + cacheWrite,- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ ...(usage?.reasoningTokens !== undefined ? { reasoning: usage.reasoningTokens } : {}),+ totalTokens: usage?.totalTokens ?? input + output + cacheRead + cacheWrite,+ cost: usage?.cost && usage.costStatus !== "unknown"+ ? { ...usage.cost }+ : { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ // Explicitly tag the numeric placeholder so it can never become a known+ // zero-dollar charge when reconstructed history crosses this boundary again.+ ...(usage ? { desktopUsage: { ...usage } } : {}),};}diff --git a/packages/agent-runtime/src/compaction-request.test.ts b/packages/agent-runtime/src/compaction-request.test.tsindex 457f8f9d7..19858579c 100644--- a/packages/agent-runtime/src/compaction-request.test.ts+++ b/packages/agent-runtime/src/compaction-request.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import type { Api, Model, Models, ModelsSimpleStreamOptions } from "@earendil-works/pi-ai";+import type { AssistantMessage, Api, Model, Models, ModelsSimpleStreamOptions } from "@earendil-works/pi-ai";import {OPENCODE_CLIENT_HEADER,OPENCODE_CLIENT_VALUE,@@ -259,3 +259,20 @@ describe("compaction summary conversation key", () => {expect(sentMutation.prompt_cache_key).toBe("session-1");});});++ it("accounts each summary attempt with its account and preserves replay identity", async () => {+ const reports: import("@pi-desktop/shared").MessageUsage[] = [];+ const response = (failed: boolean): AssistantMessage => ({ role: "assistant", content: [], api: model.api,+ provider: model.provider, model: model.id, timestamp: 1, stopReason: failed ? "error" : "stop",+ usage: { input: 12, output: 3, cacheRead: 0, cacheWrite: 0, totalTokens: 15,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } } });+ const completeSimple = vi.fn().mockResolvedValueOnce(response(true)).mockResolvedValueOnce(response(false));+ const wrapped = withCompactionRequestHeaders({ completeSimple } as unknown as Models, provider, "summary-session", usage => reports.push(usage));+ const failed = await wrapped.completeSimple(model, context);+ await wrapped.completeSimple(model, context);+ expect(reports).toHaveLength(2);+ expect(new Set(reports.map(usage => usage.operationId)).size).toBe(2);+ expect(reports[0]).toMatchObject({ providerId: provider.id, modelId: model.id, totalTokens: 15, costStatus: "unknown" });+ expect((failed.usage as unknown as { desktopUsage?: { operationId?: string } }).desktopUsage?.operationId).toBe(reports[0]?.operationId);+ expect(completeSimple.mock.calls[0]?.[2]).toMatchObject({ sessionId: "summary-session", headers: { [OPENCODE_SESSION_HEADER]: "summary-session" } });+});diff --git a/packages/agent-runtime/src/compaction-request.ts b/packages/agent-runtime/src/compaction-request.tsindex 293344c07..d12052ac2 100644--- a/packages/agent-runtime/src/compaction-request.ts+++ b/packages/agent-runtime/src/compaction-request.ts@@ -11,6 +11,8 @@* the collection is the seam that reaches its one request.*/+import { accountModelResult, nativeCostStatus, requestUsageIdentity, type UsageObserver } from "./request-usage.js";+import { requestThinkingLevel } from "./thinking-level.js";import type {Api,Context,@@ -46,7 +48,7 @@ export function compactionRequestOptions(input: {const { provider, sessionId, model, context, options } = input;return withProviderHeaders(withOpenCodeSessionHeaders(- { ...options, sessionId },+ { ...options, sessionId, reasoning: requestThinkingLevel(model, options?.reasoning ?? "off") },{ ...openCodeEndpointFromProvider(provider, model), sessionId },),mergeProviderHeaders(@@ -104,8 +106,10 @@ export function withCompactionRequestHeaders(models: Models,provider: RuntimeProviderConfig,sessionId: string,+ onUsage?: UsageObserver,): Models {- const completeSimple: Models["completeSimple"] = (model, context, options) => {+ const completeSimple: Models["completeSimple"] = async (model, context, options) => {+ const identity = { ...requestUsageIdentity(model, provider.id), costStatus: nativeCostStatus(provider.modelConfig?.nativeCost) };const requestOptions = compactionRequestOptions({ provider, sessionId, model, context, options });const previousOnPayload = requestOptions.onPayload;if (SUMMARY_CONVERSATION_APIS.has(model.api)) {@@ -122,7 +126,8 @@ export function withCompactionRequestHeaders(return keyed === base ? replacement : keyed;};}- return models.completeSimple(model, context, requestOptions);+ const result = await models.completeSimple(model, context, requestOptions);+ return onUsage ? accountModelResult(result, identity, onUsage) : result;};return new Proxy(models, {get: (target, property, receiver) =>diff --git a/packages/agent-runtime/src/image-generation/binding.ts b/packages/agent-runtime/src/image-generation/binding.tsnew file mode 100644index 000000000..a52e9a2b7--- /dev/null+++ b/packages/agent-runtime/src/image-generation/binding.ts@@ -0,0 +1,51 @@+import type { ImageApi, ImageModel, Models } from "@earendil-works/pi-ai";+import * as openrouterImages from "@earendil-works/pi-ai/api/openrouter-images";+import { createAccountModels, type RuntimeProviderConfig } from "../provider-binding.js";+import { OPENAI_IMAGES_API, openAIImagesAdapter } from "./openai-images.js";+import { imageError, type ImageDownloadOptions } from "./download.js";++export type ImageEndpoint = {+ baseUrl: string;+ modelId: string;+ apiKey?: string;+ headers?: Record<string, string>;+ providerId?: string;+ vendorKey?: string;+ authKind?: string;+ resolveAuth?: RuntimeProviderConfig["resolveAuth"];+ /** Effective typed model from the host's shared Pi account registry. */+ nativeModel?: ImageModel<ImageApi>;+};+export type ImageBinding = { models: Models; model: ImageModel<ImageApi>; accountId?: string };++/** An explicitly marked legacy image binding is an operation override, not chat capability inference. */+export function createImageBinding(endpoint: ImageEndpoint, downloads: ImageDownloadOptions = {}): ImageBinding {+ const providerId = endpoint.vendorKey?.trim() || endpoint.providerId || "pi-desktop-images";+ const known = endpoint.nativeModel;+ if (known && (known.type !== "image" || known.id !== endpoint.modelId || known.api !== "openrouter-images" && known.api !== OPENAI_IMAGES_API))+ throw imageError("IMAGE_MODEL_UNAVAILABLE");+ const native = known?.api === "openrouter-images" || providerId === "openrouter";+ // OAuth must have an actual native image operation, not an invented entitlement.+ if (endpoint.authKind === "oauth" && (known?.api !== "openrouter-images" || !endpoint.resolveAuth))+ throw imageError("IMAGE_AUTH_UNSUPPORTED");+ const model: ImageModel<ImageApi> = {+ ...(known ?? {+ type: "image", name: endpoint.modelId, input: ["text", "image"], output: ["image", "text"],+ // NaN denotes unavailable prices; never expose a fabricated zero cost.+ cost: { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN },+ }),+ id: endpoint.modelId, provider: providerId,+ api: native ? "openrouter-images" : OPENAI_IMAGES_API,+ baseUrl: endpoint.baseUrl, headers: endpoint.headers,+ };+ const models = createAccountModels({+ id: endpoint.providerId ?? providerId, vendorKey: endpoint.vendorKey,+ name: providerId, modelId: model.id, baseUrl: model.baseUrl,+ apiKey: endpoint.apiKey ?? "", authKind: endpoint.authKind ?? (endpoint.apiKey ? "api_key" : "none"),+ resolveAuth: endpoint.resolveAuth, supportsReasoning: false, supportedThinkingLevels: [],+ }, {+ models: [model],+ images: { [model.api]: native ? openrouterImages : openAIImagesAdapter(downloads) },+ });+ return { models, model, accountId: endpoint.providerId };+}diff --git a/packages/agent-runtime/src/image-generation/image-generation.test.ts b/packages/agent-runtime/src/image-generation/image-generation.test.tsindex 70963684b..46350d2bb 100644--- a/packages/agent-runtime/src/image-generation/image-generation.test.ts+++ b/packages/agent-runtime/src/image-generation/image-generation.test.ts@@ -1,5 +1,7 @@import { describe, expect, it, vi } from "vitest";-import { generateImageBatch, generateOneImage, imageGenerationUrl } from "./index.js";+import { generateImageBatch } from "./index.js";+import { imageGenerationUrl } from "./openai-images.js";+import { generateTestImage } from "./test-fixture.js";import {publicImageAddress,generatedImageType,@@ -49,7 +51,7 @@ describe("image generation", () => {});it("uses the configured model, key and headers without chat protocol fields", async () => {const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(response());- const image = await generateOneImage(+ const image = await generateTestImage({ ...endpoint, headers: { "X-Test": "custom" } },"draw",new AbortController().signal,@@ -112,6 +114,7 @@ describe("image generation", () => {save,fetchImpl,});+ await vi.waitFor(() => expect(fetchImpl).toHaveBeenCalledTimes(2));controller.abort();expect((await batch).every((item) => item.status === "cancelled")).toBe(true);expect(fetchImpl).toHaveBeenCalledTimes(2);diff --git a/packages/agent-runtime/src/image-generation/index.ts b/packages/agent-runtime/src/image-generation/index.tsindex b1161fbf9..e6db3904c 100644--- a/packages/agent-runtime/src/image-generation/index.ts+++ b/packages/agent-runtime/src/image-generation/index.ts@@ -1,181 +1,130 @@-import {- IMAGE_GENERATION_TIMEOUT_MS,- imageGenerationItems,- type GeneratedImageResult,-} from "@pi-desktop/shared";-import {- boundedBytes,- downloadGeneratedImage,- generatedImageType,- imageError,- MAX_IMAGE_BYTES,- type ImageDownloadOptions,-} from "./download.js";+import { usageFromPi } from "../agent-messages.js";+import { nativeCostStatus, requestUsageIdentity } from "../request-usage.js";+import { IMAGE_GENERATION_TIMEOUT_MS, imageGenerationItems, type GeneratedImageResult, type MessageUsage } from "@pi-desktop/shared";+import { boundedBytes, generatedImageType, imageError, MAX_IMAGE_BYTES, type ImageDownloadOptions } from "./download.js";+import { decodeImageBase64, safeImageError } from "./openai-images.js";+import { createImageBinding, type ImageBinding, type ImageEndpoint } from "./binding.js";export { generatedImageType, MAX_IMAGE_BYTES } from "./download.js";--export type ImageEndpoint = {- baseUrl: string;- modelId: string;- apiKey?: string;- headers?: Record<string, string>;-};--export function imageGenerationUrl(baseUrl: string, edit = false): string {- const url = new URL(baseUrl);- if (- !["http:", "https:"].includes(url.protocol) ||- url.username ||- url.password ||- url.search ||- url.hash- )- throw imageError("IMAGE_INVALID_ENDPOINT");- const path = url.pathname.replace(/\/+$/, "");- url.pathname = `${path || "/v1"}/images/${edit ? "edits" : "generations"}`;- return url.href;-}+export { createImageBinding, type ImageBinding, type ImageEndpoint } from "./binding.js";export type ImageEditInput = { bytes: Uint8Array; mimeType: string; extension: string };+export type ImageOperationMetadata = {+ index: number;+ text: string[];+ responseId?: string;+ usage?: MessageUsage;+};-export async function generateOneImage(- endpoint: ImageEndpoint,- prompt: string,- signal: AbortSignal,- fetchImpl: typeof fetch = fetch,- images: ImageEditInput[] = [],- downloadOptions: ImageDownloadOptions = {},-) {- const headers = new Headers(endpoint.headers);- headers.set("Content-Type", "application/json");- if (endpoint.apiKey) headers.set("Authorization", `Bearer ${endpoint.apiKey}`);- const responseFormat = /^dall-e-[23]$/i.test(endpoint.modelId) ? "b64_json" : undefined;- let body: BodyInit = JSON.stringify({- model: endpoint.modelId, prompt, n: 1,- ...(responseFormat ? { response_format: responseFormat } : {}),- });- if (images.length) {- const form = new FormData();- form.set("model", endpoint.modelId);- form.set("prompt", prompt);- form.set("n", "1");- if (responseFormat) form.set("response_format", responseFormat);- images.forEach((image, index) =>- form.append(- images.length === 1 ? "image" : "image[]",- new Blob([new Uint8Array(image.bytes)], { type: image.mimeType }),- `input-${index}.${image.extension}`,- ),- );- headers.delete("Content-Type");- body = form;- }- const response = await fetchImpl(imageGenerationUrl(endpoint.baseUrl, images.length > 0), {- method: "POST",- headers,- redirect: "error",- signal,- body,+/** Stop waiting for a credential resolver that cannot accept AbortSignal. Late dispatch is fenced by fetch. */+function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {+ return new Promise((resolve, reject) => {+ const abort = () => reject(imageError("IMAGE_CANCELLED"));+ promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));+ if (signal.aborted) abort();+ else signal.addEventListener("abort", abort, { once: true });});- if (!response.ok) {- await response.body?.cancel();- throw imageError(- response.status === 401 || response.status === 403- ? "IMAGE_AUTH_FAILED"- : `IMAGE_HTTP_${response.status}`,- );- }- const raw = await boundedBytes(response, Math.ceil((MAX_IMAGE_BYTES * 4) / 3) + 65536);- let payload: unknown;- try {- payload = JSON.parse(Buffer.from(raw).toString("utf8"));- } catch {- throw imageError("IMAGE_INVALID_RESPONSE");- }- const data = (payload as { data?: unknown })?.data;- if (!Array.isArray(data) || data.length !== 1 || !data[0] || typeof data[0] !== "object")- throw imageError("IMAGE_INVALID_RESPONSE");- const item = data[0] as Record<string, unknown>;- let bytes: Uint8Array;- if (- typeof item.b64_json === "string" &&- item.b64_json.length &&- /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(item.b64_json)- ) {- bytes = Buffer.from(item.b64_json, "base64");- } else if (typeof item.url === "string") {- bytes = await downloadGeneratedImage(item.url, signal, {- ...downloadOptions,- fetchImpl: downloadOptions.fetchImpl ?? fetchImpl,- });- } else throw imageError("IMAGE_INVALID_RESPONSE");- return { bytes, ...generatedImageType(bytes) };}-/** Two workers, stable result ordering, no automatic retry of billable requests. */+/** Two workers, stable result ordering, and exactly one Pi call per requested operation. */export async function generateImageBatch(options: {input: unknown;- endpoint: ImageEndpoint;+ endpoint?: ImageEndpoint;+ binding?: ImageBinding;signal: AbortSignal;- save: (image: Awaited<ReturnType<typeof generateOneImage>>, index: number) => Promise<string>;+ save: (image: ImageEditInput, index: number) => Promise<string>;fetchImpl?: typeof fetch;downloadOptions?: ImageDownloadOptions;loadImages?: (paths: string[]) => Promise<ImageEditInput[]>;+ onOperation?: (metadata: ImageOperationMetadata) => void;}): Promise<GeneratedImageResult[]> {const prompts = imageGenerationItems(options.input);- const results: GeneratedImageResult[] = new Array(prompts.length);+ const binding = options.binding ?? (options.endpoint && createImageBinding(options.endpoint, options.downloadOptions));+ if (!binding) throw imageError("IMAGE_MODEL_UNAVAILABLE");+ const results: GeneratedImageResult[][] = Array.from({ length: prompts.length }, () => []);let next = 0;let authFailed = false;const worker = async () => {while (next < prompts.length) {const index = next++;+ const output = results[index];if (options.signal.aborted || authFailed) {- results[index] = {- index,- status: "cancelled",- errorCode: authFailed ? "IMAGE_AUTH_FAILED" : "IMAGE_CANCELLED",- };+ output.push({ index, status: "cancelled", errorCode: authFailed ? "IMAGE_AUTH_FAILED" : "IMAGE_CANCELLED" });continue;}const controller = new AbortController();const signal = AbortSignal.any([options.signal, controller.signal]);const timer = setTimeout(() => controller.abort(), IMAGE_GENERATION_TIMEOUT_MS);+ let transportError: string | undefined;try {const item = prompts[index];if (item.images && !options.loadImages) throw imageError("IMAGE_EDIT_UNAVAILABLE");const images = item.images ? await options.loadImages!(item.images) : [];signal.throwIfAborted();- const image = await generateOneImage(- options.endpoint,- item.prompt,- signal,- options.fetchImpl,- images,- options.downloadOptions,- );- const path = await options.save(image, index);- results[index] = { index, status: "succeeded", path, mimeType: image.mimeType };+ const identity = requestUsageIdentity(binding.model, binding.accountId);+ const result = await untilAborted(binding.models.generateImages(binding.model, {+ input: [{ type: "text", text: item.prompt }, ...images.map(image => ({+ type: "image" as const, data: Buffer.from(image.bytes).toString("base64"), mimeType: image.mimeType,+ }))],+ }, {+ signal, maxRetries: 0, timeoutMs: IMAGE_GENERATION_TIMEOUT_MS,+ // Host request policy, not a competing implementation of the native wire protocol.+ fetch: async (url, init) => {+ try {+ signal.throwIfAborted();+ const response = await (options.fetchImpl ?? fetch)(url, { ...init, signal, redirect: "error" });+ if (!response.ok) {+ transportError = response.status === 401 || response.status === 403 ? "IMAGE_AUTH_FAILED" : `IMAGE_HTTP_${response.status}`;+ await response.body?.cancel();+ throw imageError(transportError);+ }+ const bytes = await boundedBytes(response, Math.ceil(MAX_IMAGE_BYTES * 4 / 3) * 10 + 65536);+ return new Response(new Uint8Array(bytes), { status: response.status, statusText: response.statusText, headers: response.headers });+ } catch (error) {+ transportError ??= safeImageError(error);+ throw error;+ }+ },+ transformHeaders: headers => {+ const merged = new Headers();+ for (const entries of [headers, binding.model.headers ?? {}])+ for (const [name, value] of Object.entries(entries)) {+ if (value === null) merged.delete(name);+ else if (value !== undefined) merged.set(name, value);+ }+ return Object.fromEntries(merged);+ },+ }), signal);+ const usage = usageFromPi(result.usage, { ...identity, costStatus: nativeCostStatus(binding.model.cost) });+ options.onOperation?.({ index, text: result.output.filter(part => part.type === "text").map(part => part.text),+ ...(result.responseId ? { responseId: result.responseId } : {}),+ ...(usage ? { usage } : {}),+ });+ signal.throwIfAborted();+ for (const part of result.output) {+ if (part.type !== "image") continue;+ signal.throwIfAborted();+ try {+ const bytes = decodeImageBase64(part.data);+ const image = { bytes, ...generatedImageType(bytes) };+ const path = await options.save(image, index);+ output.push({ index, status: "succeeded", path, mimeType: image.mimeType });+ } catch (error) {+ output.push({ index, status: "failed", errorCode: safeImageError(error) });+ }+ }+ if (result.stopReason !== "stop")+ throw imageError(result.stopReason === "aborted" ? "IMAGE_CANCELLED" : transportError ??+ (/^IMAGE_[A-Z0-9_]+$/.test(result.errorMessage ?? "") ? result.errorMessage! : "IMAGE_REQUEST_FAILED"));+ if (!output.length) throw imageError("IMAGE_INVALID_RESPONSE");} catch (error) {- const code = options.signal.aborted- ? "IMAGE_CANCELLED"- : controller.signal.aborted- ? "IMAGE_TIMEOUT"- : error &&- typeof error === "object" &&- "errorCode" in error &&- typeof error.errorCode === "string"- ? error.errorCode- : "IMAGE_REQUEST_FAILED";+ const code = options.signal.aborted ? "IMAGE_CANCELLED" : controller.signal.aborted ? "IMAGE_TIMEOUT" : safeImageError(error);if (code === "IMAGE_AUTH_FAILED") authFailed = true;- results[index] = {- index,- status: options.signal.aborted ? "cancelled" : "failed",- errorCode: code,- };+ output.push({ index, status: code === "IMAGE_CANCELLED" ? "cancelled" : "failed", errorCode: code });} finally {clearTimeout(timer);}}};await Promise.all([worker(), worker()]);- return results;+ return results.flat().map((result, index) => ({ ...result, index }));}diff --git a/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts b/packages/agent-runtime/src/image-generation/openai-images-contract.test.tsindex 477f59f03..4822acb87 100644--- a/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts+++ b/packages/agent-runtime/src/image-generation/openai-images-contract.test.ts@@ -1,7 +1,8 @@import { createServer } from "node:http";import type { AddressInfo } from "node:net";import { afterEach, expect, it } from "vitest";-import { generateImageBatch, generateOneImage, type ImageEditInput } from "./index.js";+import { generateImageBatch, type ImageEditInput } from "./index.js";+import { generateTestImage } from "./test-fixture.js";const png = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9mQAAAAASUVORK5CYII=", "base64");const input: ImageEditInput = { bytes: png, mimeType: "image/png", extension: "png" };@@ -28,7 +29,7 @@ async function fixture() {servers.push(server);await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));const baseUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`;- return { requests, failures, call: (modelId: string, images: ImageEditInput[] = []) => generateOneImage({ baseUrl, modelId }, "A cup", new AbortController().signal, fetch, images) };+ return { requests, failures, call: (modelId: string, images: ImageEditInput[] = []) => generateTestImage({ baseUrl, modelId }, "A cup", new AbortController().signal, fetch, images) };}it("requests b64_json for DALL-E without sending response_format to GPT Image", async () => {@@ -81,11 +82,11 @@ it("rejects more than four reference images before reading files or sending HTTPit("does not leak provider error bodies and bounds JSON before decoding", async () => {for (const status of [401, 403, 429, 500]) {- await expect(generateOneImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,+ await expect(generateTestImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,async () => new Response("private upstream token", { status }),)).rejects.toMatchObject({ errorCode: [401, 403].includes(status) ? "IMAGE_AUTH_FAILED" : `IMAGE_HTTP_${status}` });}- await expect(generateOneImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,+ await expect(generateTestImage({ baseUrl: "https://example.invalid", modelId: "gpt-image-2.5" }, "cup", new AbortController().signal,async () => new Response("", { headers: { "content-length": "999999999" } }),)).rejects.toMatchObject({ errorCode: "IMAGE_TOO_LARGE" });});diff --git a/packages/agent-runtime/src/image-generation/openai-images.ts b/packages/agent-runtime/src/image-generation/openai-images.tsnew file mode 100644index 000000000..d4edb9a14--- /dev/null+++ b/packages/agent-runtime/src/image-generation/openai-images.ts@@ -0,0 +1,116 @@+import type { AssistantImages, ProviderImages } from "@earendil-works/pi-ai";+import {+ boundedBytes, downloadGeneratedImage, generatedImageType, imageError, MAX_IMAGE_BYTES,+ type ImageDownloadOptions,+} from "./download.js";++/** Private wire API, not a provider identity or a second model catalog. */+export const OPENAI_IMAGES_API = "pi-desktop-openai-images";++export function imageGenerationUrl(baseUrl: string, edit = false): string {+ const url = new URL(baseUrl);+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash)+ throw imageError("IMAGE_INVALID_ENDPOINT");+ const path = url.pathname.replace(/\/+$/, "");+ url.pathname = `${path || "/v1"}/images/${edit ? "edits" : "generations"}`;+ return url.href;+}++export function safeImageError(error: unknown): string {+ return error && typeof error === "object" && "errorCode" in error &&+ typeof error.errorCode === "string" && /^IMAGE_[A-Z0-9_]+$/.test(error.errorCode)+ ? error.errorCode : "IMAGE_REQUEST_FAILED";+}++/** Only the generations/edits protocol missing from Pi; auth and dispatch belong to Models. */+export function openAIImagesAdapter(downloadOptions: ImageDownloadOptions = {}): ProviderImages {+ return {+ async generateImages(model, context, options) {+ const result: AssistantImages = {+ api: model.api, provider: model.provider, model: model.id,+ output: [], stopReason: "stop", timestamp: Date.now(),+ };+ try {+ const signal = options?.signal ?? new AbortController().signal;+ signal.throwIfAborted();+ const headers = new Headers(model.headers);+ if (options?.apiKey) headers.set("Authorization", `Bearer ${options.apiKey}`);+ for (const [name, value] of Object.entries(options?.headers ?? {})) {+ if (value === null) headers.delete(name);+ else headers.set(name, value);+ }+ const prompt = context.input.filter(item => item.type === "text").map(item => item.text).join("\n");+ const images = context.input.filter(item => item.type === "image");+ const responseFormat = /^dall-e-[23]$/i.test(model.id) ? "b64_json" : undefined;+ let body: BodyInit;+ if (images.length) {+ const form = new FormData();+ form.set("model", model.id);+ form.set("prompt", prompt);+ form.set("n", "1");+ if (responseFormat) form.set("response_format", responseFormat);+ images.forEach((image, index) => {+ const bytes = decodeImageBase64(image.data);+ const type = generatedImageType(bytes);+ form.append(images.length === 1 ? "image" : "image[]",+ new Blob([new Uint8Array(bytes)], { type: type.mimeType }), `input-${index}.${type.extension}`);+ });+ headers.delete("Content-Type");+ body = form;+ } else {+ headers.set("Content-Type", "application/json");+ body = JSON.stringify({ model: model.id, prompt, n: 1,+ ...(responseFormat ? { response_format: responseFormat } : {}) });+ }+ const response = await (options?.fetch ?? fetch)(imageGenerationUrl(model.baseUrl, images.length > 0), {+ method: "POST", headers, redirect: "error", signal, body,+ });+ await options?.onResponse?.({ status: response.status, headers: Object.fromEntries(response.headers) }, model);+ if (!response.ok) {+ await response.body?.cancel();+ throw imageError(response.status === 401 || response.status === 403 ? "IMAGE_AUTH_FAILED" : `IMAGE_HTTP_${response.status}`);+ }+ // A response may contain several images. Bound the entire JSON as well as every image.+ const raw = await boundedBytes(response, Math.ceil(MAX_IMAGE_BYTES * 4 / 3) * 10 + 65536);+ let payload: unknown;+ try { payload = JSON.parse(Buffer.from(raw).toString("utf8")); }+ catch { throw imageError("IMAGE_INVALID_RESPONSE"); }+ const reported = (payload as { usage?: Record<string, unknown> })?.usage;+ if (reported) {+ const count = (key: string): number => typeof reported[key] === "number" && Number.isFinite(reported[key]) ? Math.max(0, Math.round(reported[key])) : 0;+ const input = count("input_tokens") || count("prompt_tokens");+ const output = count("output_tokens") || count("completion_tokens");+ if (input || output || count("total_tokens")) result.usage = {+ input, output, cacheRead: 0, cacheWrite: 0, totalTokens: count("total_tokens") || input + output,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },+ };+ }+ const data = (payload as { data?: unknown } | null)?.data;+ if (!Array.isArray(data) || !data.length || data.length > 10) throw imageError("IMAGE_INVALID_RESPONSE");+ for (const item of data) {+ if (!item || typeof item !== "object") throw imageError("IMAGE_INVALID_RESPONSE");+ if (typeof item.revised_prompt === "string") result.output.push({ type: "text", text: item.revised_prompt });+ let bytes: Uint8Array;+ if (typeof item.b64_json === "string") bytes = decodeImageBase64(item.b64_json);+ else if (typeof item.url === "string") bytes = await downloadGeneratedImage(item.url, signal, {+ ...downloadOptions, fetchImpl: downloadOptions.fetchImpl ?? options?.fetch,+ });+ else throw imageError("IMAGE_INVALID_RESPONSE");+ const type = generatedImageType(bytes);+ result.output.push({ type: "image", data: Buffer.from(bytes).toString("base64"), mimeType: type.mimeType });+ }+ } catch (error) {+ result.stopReason = options?.signal?.aborted ? "aborted" : "error";+ result.errorMessage = safeImageError(error);+ }+ return result;+ },+ };+}++export function decodeImageBase64(data: string): Uint8Array {+ if (data.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4) throw imageError("IMAGE_TOO_LARGE");+ if (!data.length || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data))+ throw imageError("IMAGE_INVALID_RESPONSE");+ return Buffer.from(data, "base64");+}diff --git a/packages/agent-runtime/src/image-generation/pi-images.test.ts b/packages/agent-runtime/src/image-generation/pi-images.test.tsnew file mode 100644index 000000000..208dbdb79--- /dev/null+++ b/packages/agent-runtime/src/image-generation/pi-images.test.ts@@ -0,0 +1,104 @@+import { expect, it, vi } from "vitest";+import { createModels, createProvider, type AssistantImages, type ImageModel } from "@earendil-works/pi-ai";+import { openrouterProvider } from "@earendil-works/pi-ai/providers/openrouter";+import { createImageBinding, generateImageBatch, type ImageOperationMetadata } from "./index.js";++const png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8=";+const input = { items: [{ prompt: "draw" }] };+const signal = () => new AbortController().signal;+const save = vi.fn(async (_image: unknown, index: number) => `/scratch/${index}.png`);+const endpoint = { baseUrl: "https://images.example/v1", modelId: "custom-image", apiKey: "fixture" };+const nativeResponse = () => Response.json({ id: "response-1", choices: [{ message: {+ content: "Two views", images: [{ image_url: { url: `data:image/png;base64,${png}` } }, { image_url: { url: `data:image/png;base64,${png}` } }],+} }], usage: { prompt_tokens: 10, completion_tokens: 20 } });++it("dispatches native OpenRouter through Pi once, preserving every image, text and usage", async () => {+ const known = openrouterProvider().getAllModels!().find((model): model is ImageModel<string> => model.type === "image");+ expect(known).toBeDefined();+ const binding = createImageBinding({ ...endpoint, vendorKey: "openrouter", modelId: known!.id });+ const generate = vi.spyOn(binding.models, "generateImages");+ const transport = vi.fn<typeof fetch>().mockResolvedValue(nativeResponse());+ const operations: ImageOperationMetadata[] = [];+ const result = await generateImageBatch({ binding, input, signal: signal(), save, fetchImpl: transport, onOperation: op => operations.push(op) });+ expect(generate).toHaveBeenCalledTimes(1);+ expect(generate.mock.calls[0][2]).toMatchObject({ maxRetries: 0 });+ expect(transport).toHaveBeenCalledTimes(1);+ expect(String(transport.mock.calls[0][0])).toContain("/chat/completions");+ expect(JSON.parse(String(transport.mock.calls[0][1]?.body))).toMatchObject({ model: known!.id, stream: false });+ expect(result.map(item => item.status)).toEqual(["succeeded", "succeeded"]);+ expect(operations).toHaveLength(1);+ expect(operations[0]).toMatchObject({ text: ["Two views"], responseId: "response-1", usage: { inputTokens: 10, outputTokens: 20 } });+});++it("never retries native billable failures or falls back to the OpenAI adapter", async () => {+ for (const status of [401, 429, 500]) {+ const transport = vi.fn<typeof fetch>().mockImplementation(async () => new Response("secret", { status }));+ const results = await generateImageBatch({ endpoint: { ...endpoint, vendorKey: "openrouter" }, input, signal: signal(), save, fetchImpl: transport });+ expect(transport).toHaveBeenCalledTimes(1);+ expect(results[0].errorCode).toBe(status === 401 ? "IMAGE_AUTH_FAILED" : `IMAGE_HTTP_${status}`);+ expect(JSON.stringify(results)).not.toContain("secret");+ }+});++it("keeps same-vendor accounts isolated through actual Models auth resolution", async () => {+ const auths: string[] = [];+ await Promise.all(["account-a", "account-b"].map(key => generateImageBatch({+ endpoint: { ...endpoint, providerId: key, vendorKey: "custom", apiKey: key }, input, signal: signal(), save,+ fetchImpl: async (_url, init) => { auths.push(new Headers(init?.headers).get("authorization")!); return Response.json({ data: [{ b64_json: png }] }); },+ })));+ expect(auths.sort()).toEqual(["Bearer account-a", "Bearer account-b"]);+});++it("requires real native image capability for OAuth and resolves supported auth via the shared seam", async () => {+ const resolveAuth = vi.fn(async () => ({ apiKey: "oauth-fixture" }));+ expect(() => createImageBinding({ ...endpoint, authKind: "oauth", resolveAuth })).toThrow("IMAGE_AUTH_UNSUPPORTED");+ const known = openrouterProvider().getAllModels!().find(model => model.type === "image")!;+ const binding = createImageBinding({ ...endpoint, vendorKey: "openrouter", modelId: known.id, nativeModel: known, authKind: "oauth", resolveAuth });+ const transport = vi.fn<typeof fetch>().mockResolvedValue(nativeResponse());+ await generateImageBatch({ binding, input, signal: signal(), save, fetchImpl: transport });+ expect(resolveAuth).toHaveBeenCalledTimes(1);+ expect(new Headers(transport.mock.calls[0][1]?.headers).get("authorization")).toBe("Bearer oauth-fixture");+});++it("retains multiple OpenAI outputs in stable operation order without extra requests", async () => {+ const transport = vi.fn<typeof fetch>().mockImplementation(async () => Response.json({ data: [{ b64_json: png }, { b64_json: png }] }));+ const results = await generateImageBatch({ endpoint, input: { items: [{ prompt: "a", count: 2 }] }, signal: signal(), save, fetchImpl: transport });+ expect(results.map(result => result.index)).toEqual([0, 1, 2, 3]);+ expect(transport).toHaveBeenCalledTimes(2);+});++it("honors returned error/aborted and rejects text-only successful responses without paid retries", async () => {+ const model: ImageModel<string> = { type: "image", id: "m", name: "m", api: "fixture", provider: "fixture", baseUrl: endpoint.baseUrl,+ input: ["text"], output: ["image"], cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 } };+ for (const stopReason of ["error", "aborted", "stop"] as const) {+ const generate = vi.fn(async (): Promise<AssistantImages> => ({ api: "fixture", provider: "fixture", model: "m", output: [{ type: "text", text: "no image" }], stopReason, timestamp: 0, errorMessage: "private token" }));+ const models = createModels();+ models.setProvider(createProvider({ id: "fixture", models: [model], auth: { apiKey: { name: "none", resolve: async () => ({ auth: {} }) } }, images: { fixture: { generateImages: generate } } }));+ const results = await generateImageBatch({ binding: { models, model }, input, signal: signal(), save });+ expect(generate).toHaveBeenCalledTimes(1);+ expect(results[0]).toMatchObject({ status: stopReason === "aborted" ? "cancelled" : "failed", errorCode: stopReason === "stop" ? "IMAGE_INVALID_RESPONSE" : stopReason === "aborted" ? "IMAGE_CANCELLED" : "IMAGE_REQUEST_FAILED" });+ }+});++it("cancels while resolving auth without sending a request", async () => {+ let finish!: () => void;+ const controller = new AbortController();+ const resolveAuth = vi.fn(async () => { await new Promise<void>(resolve => { finish = resolve; }); return { apiKey: "fixture" }; });+ const transport = vi.fn<typeof fetch>();+ const run = generateImageBatch({ endpoint: { ...endpoint, resolveAuth }, input, signal: controller.signal, save, fetchImpl: transport });+ await vi.waitFor(() => expect(resolveAuth).toHaveBeenCalledTimes(1));+ controller.abort(); finish();+ expect((await run)[0].status).toBe("cancelled");+ expect(transport).not.toHaveBeenCalled();+});++it("bounds native data URLs and does not claim zero pricing for custom image models", async () => {+ const operations: ImageOperationMetadata[] = [];+ await generateImageBatch({ endpoint: { ...endpoint, vendorKey: "openrouter" }, input, signal: signal(), save,+ fetchImpl: async () => nativeResponse(), onOperation: operation => operations.push(operation) });+ expect(operations[0].usage).toBeDefined();+ expect(operations[0].usage?.cost).toBeUndefined();+ const results = await generateImageBatch({ endpoint: { ...endpoint, vendorKey: "openrouter" }, input, signal: signal(), save,+ fetchImpl: async () => new Response("", { headers: { "content-length": "999999999" } }) });+ expect(results[0].errorCode).toBe("IMAGE_TOO_LARGE");+});diff --git a/packages/agent-runtime/src/image-generation/test-fixture.ts b/packages/agent-runtime/src/image-generation/test-fixture.tsnew file mode 100644index 000000000..c664004b4--- /dev/null+++ b/packages/agent-runtime/src/image-generation/test-fixture.ts@@ -0,0 +1,15 @@+import { generateImageBatch, type ImageEditInput, type ImageEndpoint } from "./index.js";+import type { ImageDownloadOptions } from "./download.js";++/** Test convenience only: exercises the actual Models-backed production batch entry. */+export async function generateTestImage(endpoint: ImageEndpoint, prompt: string, signal: AbortSignal,+ fetchImpl: typeof fetch = fetch, images: ImageEditInput[] = [], downloadOptions: ImageDownloadOptions = {}) {+ let image: ImageEditInput | undefined;+ const results = await generateImageBatch({+ endpoint, input: { items: [{ prompt, ...(images.length ? { images: images.map((_, index) => `${index}.png`) } : {}) }] },+ signal, fetchImpl, downloadOptions, loadImages: async () => images,+ save: async output => { image = output; return "/scratch/test.png"; },+ });+ if (!image) throw Object.assign(new Error(results[0].errorCode), { errorCode: results[0].errorCode });+ return image;+}diff --git a/packages/agent-runtime/src/model-capabilities.test.ts b/packages/agent-runtime/src/model-capabilities.test.tsindex 20121686c..b72b1ef62 100644--- a/packages/agent-runtime/src/model-capabilities.test.ts+++ b/packages/agent-runtime/src/model-capabilities.test.ts@@ -278,3 +278,13 @@ describe("unmatched model effective thinking policy", () => {expect(capabilitiesFromModelConfig(modelConfigWithBinding(trusted, { ...binding, thinkingLevels: [] })).supportsReasoning).toBe(false);});});++it("keeps native Pi null and absent extended mappings unavailable", () => {+ const configured = modelConfigWithBinding({ ...knownModel(), source: "pi",+ supportedThinkingLevels: ["low", "high"], thinkingLevelMap: { off: null, xhigh: null } }, {+ contextWindow: 64_000, maxTokens: 4_000, thinkingLevels: ["low", "xhigh", "max"],+ });+ expect(configured.supportedThinkingLevels).toEqual(["low"]);+ expect(configured.thinkingLevelMap?.xhigh).toBeNull();+ expect(configured.thinkingLevelMap?.max).toBeUndefined();+});diff --git a/packages/agent-runtime/src/model-capabilities.ts b/packages/agent-runtime/src/model-capabilities.tsindex 21f682c82..dda3a9bce 100644--- a/packages/agent-runtime/src/model-capabilities.ts+++ b/packages/agent-runtime/src/model-capabilities.ts@@ -1,3 +1,4 @@+import { getSupportedThinkingLevels, type Api, type Model } from "@earendil-works/pi-ai";import {effectiveContextWindow,THINKING_LEVELS,@@ -10,11 +11,29 @@ import type { ModelConfig, ThinkingCapabilitySet } from "./thinking-level.js";export {agentThinkingLevel,clampThinkingLevel,+ effectiveThinkingLevel,omitThinkingModel,type ModelConfig,type ThinkingCapabilitySet,} from "./thinking-level.js";+/** Read-only, credential-free projection of a resolved Pi chat model. */+export function modelConfigFromPi(model: Model<Api>): ModelConfig {+ const { id: _id, provider: _provider, cost, compat, ...metadata } = model;+ return {+ ...metadata,+ ...(compat ? { compat: { ...compat } } : {}),+ source: "pi",+ nativeCost: cost,+ // Desktop's historical tier schema differs; do not invent a translation.+ cost: { input: cost.input, output: cost.output, cacheRead: cost.cacheRead, cacheWrite: cost.cacheWrite },+ modalities: { input: [...model.input], output: ["text"] },+ limit: { context: model.contextWindow, output: model.maxTokens },+ catalogContextWindow: model.contextWindow,+ supportedThinkingLevels: getSupportedThinkingLevels(model),+ };+}+export type ModelCapabilities = ThinkingCapabilitySet;/** Compatibility name used by Electron main and existing runtime callers. */export type ThinkingCapabilities = ModelCapabilities;@@ -105,9 +124,13 @@ export function modelConfigWithBinding(};}if (!binding) return model;- const enabledThinkingLevels = model.source === "generic" && binding.thinkingLevels.length === 0+ const requestedLevels = model.source === "generic" && binding.thinkingLevels.length === 0? [...THINKING_LEVELS]: THINKING_LEVELS.filter((level) => binding.thinkingLevels.includes(level));+ // Known native models cannot gain unsupported effort mappings from saved settings.+ const enabledThinkingLevels = model.source === "pi"+ ? requestedLevels.filter(level => model.supportedThinkingLevels?.includes(level))+ : requestedLevels;const thinkingLevelMap = { ...(model.thinkingLevelMap ?? {}) };const compat = binding.thinkingProtocol? {@@ -120,7 +143,7 @@ export function modelConfigWithBinding(// extended level without a catalog translation must pass through as-is.for (const level of ["xhigh", "max"] as const) {if (- enabledThinkingLevels.includes(level) &&+ model.source !== "pi" && enabledThinkingLevels.includes(level) &&thinkingLevelMap[level] == null) {thinkingLevelMap[level] = level;@@ -149,7 +172,9 @@ export function modelConfigWithBinding(context: contextWindow,},maxTokens: binding.maxTokens,- reasoning: enabledThinkingLevels.some((level) => level !== "off"),+ reasoning: model.source === "pi"+ ? model.reasoning || enabledThinkingLevels.some((level) => level !== "off")+ : enabledThinkingLevels.some((level) => level !== "off"),supportedThinkingLevels: enabledThinkingLevels,...(binding.thinkingProtocol? { thinkingProtocol: binding.thinkingProtocol }diff --git a/packages/agent-runtime/src/one-shot-complete.ts b/packages/agent-runtime/src/one-shot-complete.tsindex 8c2a228a2..a87fc2116 100644--- a/packages/agent-runtime/src/one-shot-complete.ts+++ b/packages/agent-runtime/src/one-shot-complete.ts@@ -11,7 +11,9 @@ import type {Model,SimpleStreamOptions,} from "@earendil-works/pi-ai";-import type { MessageUsage, ThinkingLevel } from "@pi-desktop/shared";+import { addUsage, type MessageUsage, type ThinkingLevel } from "@pi-desktop/shared";+import { accountModelStream } from "./request-usage.js";+import { requestThinkingLevel } from "./thinking-level.js";import { classifyAgentError } from "./agent-errors.js";import { clampOutputToContext } from "./output-cap.js";import { assistantContent, usageFromPi } from "./agent-messages.js";@@ -89,6 +91,7 @@ export async function completeOneShot(options.stream ??((requestModel, requestContext, streamOptions) =>models.streamSimple(requestModel, requestContext, streamOptions));+ let usage: MessageUsage | undefined;let providerStatus: number | undefined;let providerHeaders: Record<string, string> | undefined;let providerFailure: ProviderFetchFailure | undefined;@@ -107,7 +110,7 @@ export async function completeOneShot(),...(options.signal ? { signal: options.signal } : {}),maxRetries: 0,- ...(thinkingLevel !== "off" ? { reasoning: thinkingLevel } : {}),+ reasoning: requestThinkingLevel(model, thinkingLevel),fetch: providerRequestFetch(model.api,captureProviderResponse(undefined, (response, _requestBytes, failure) => {@@ -132,7 +135,10 @@ export async function completeOneShot(model,context,requestOptions,- (retryOptions) => streamSimple(model, context, retryOptions),+ (retryOptions) => accountModelStream(model, () => streamSimple(model, context, retryOptions), {+ providerId: provider.id, nativeCost: provider.modelConfig?.nativeCost,+ onUsage: attemptUsage => { usage = addUsage(usage, attemptUsage); },+ }),{claim: (error, phase) => {if (phase !== "request" || !error.retriable) return undefined;@@ -180,5 +186,5 @@ export async function completeOneShot(options.emptyErrorMessage ?? "The model returned no text.",);}- return { text, usage: usageFromPi(result.usage) };+ return { text, usage: usage ?? usageFromPi(result.usage) };}diff --git a/packages/agent-runtime/src/opencode-session-headers.test.ts b/packages/agent-runtime/src/opencode-session-headers.test.tsindex 9b930e182..8430d80b0 100644--- a/packages/agent-runtime/src/opencode-session-headers.test.ts+++ b/packages/agent-runtime/src/opencode-session-headers.test.ts@@ -241,6 +241,7 @@ describe("completeOneShot OpenCode headers", () => {},);expect(result.text).toBe("ok");+ expect(result.usage).toMatchObject({ operationId: expect.any(String), providerId: provider.id, modelId: provider.modelId });expect(captured?.sessionId).toBe("session-9");expect(captured?.headers).toMatchObject({[OPENCODE_SESSION_HEADER]: "session-9",diff --git a/packages/agent-runtime/src/pi-ai-provider-sync.test.ts b/packages/agent-runtime/src/pi-ai-provider-sync.test.tsindex 72962a604..fca62a0ef 100644--- a/packages/agent-runtime/src/pi-ai-provider-sync.test.ts+++ b/packages/agent-runtime/src/pi-ai-provider-sync.test.ts@@ -17,6 +17,8 @@ const UNSUPPORTED: Record<string, string> = {"google-vertex": "requires a project and location instead of a fixed base URL","openai-codex":"offered as a vendor account (ChatGPT subscription) service in this app",+ typesafe:+ "classifier-only operation; not a chat preset or ordinary plugin API",radius:"pi_messages is an account-only style here and the gateway publishes no model list",};@@ -33,6 +35,15 @@ describe("pi-ai built-in provider sync", () => {}});+ it("keeps TypeSafe's classifier operation out of chat presets", () => {+ const provider = providers.find((entry) => entry.id === "typesafe");+ expect(provider).toBeDefined();+ expect(provider!.getModels()).toEqual([]);+ const models = provider!.getAllModels?.() ?? [];+ expect(models.length).toBeGreaterThan(0);+ expect(models.every((model) => model.type === "classifier")).toBe(true);+ });+it("covers every other built-in provider with a named preset", () => {const unmatched = providers.filter((provider) => !(provider.id in UNSUPPORTED))diff --git a/packages/agent-runtime/src/pi-coding-agent-compaction.test.ts b/packages/agent-runtime/src/pi-coding-agent-compaction.test.tsnew file mode 100644index 000000000..6823a7de9--- /dev/null+++ b/packages/agent-runtime/src/pi-coding-agent-compaction.test.ts@@ -0,0 +1,34 @@+import { mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { expect, it } from "vitest";+import { createAgentSession, DefaultResourceLoader, ModelRuntime, SessionManager, SettingsManager } from "@earendil-works/pi-coding-agent";+import { getBuiltinModel } from "@earendil-works/pi-ai/providers/all";++it("the retained coding-agent compatibility patch supports offline manual compaction", async () => {+ const dir = await mkdtemp(join(tmpdir(), "pi-compact-patch-"));+ let session: Awaited<ReturnType<typeof createAgentSession>>["session"] | undefined;+ try {+ const settingsManager = SettingsManager.inMemory({ compaction: { enabled: true, reserveTokens: 512, keepRecentTokens: 512 } });+ const resourceLoader = new DefaultResourceLoader({ cwd: dir, agentDir: dir, settingsManager,+ noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true,+ extensionFactories: [pi => { pi.on("session_before_compact", async event => ({ compaction: {+ summary: "offline extension summary", firstKeptEntryId: event.preparation.firstKeptEntryId,+ tokensBefore: event.preparation.tokensBefore,+ } })); }],+ });+ await resourceLoader.reload();+ const modelRuntime = await ModelRuntime.create({ modelsPath: null, refreshOnCreate: false,+ credentials: { read: async () => undefined, list: async () => [], modify: async (_id, fn) => fn(undefined), delete: async () => undefined } });+ const model = getBuiltinModel("openai", "gpt-6.1-sol");+ const manager = SessionManager.inMemory(dir);+ for (let i = 0; i < 6; i++) manager.appendMessage({ role: "user", content: `message-${i} ${"fixture ".repeat(1500)}`, timestamp: i + 1 });+ ({ session } = await createAgentSession({ cwd: dir, agentDir: dir, modelRuntime, model, settingsManager,+ resourceLoader, sessionManager: manager, noTools: "all" }));+ await session.bindExtensions({});+ const compacted = await session.compact();+ expect(compacted.summary).toBe("offline extension summary");+ expect(compacted.estimatedTokensAfter).toBeGreaterThan(0);+ expect(manager.getBranch().some(entry => entry.type === "compaction")).toBe(true);+ } finally { session?.dispose(); await rm(dir, { recursive: true, force: true }); }+});diff --git a/packages/agent-runtime/src/provider-binding.test.ts b/packages/agent-runtime/src/provider-binding.test.tsindex cb4c5ff6f..ed92aba4c 100644--- a/packages/agent-runtime/src/provider-binding.test.ts+++ b/packages/agent-runtime/src/provider-binding.test.ts@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from "vitest";import { DEEPSEEK_REASONING_REPLAY_PLACEHOLDER } from "@pi-desktop/shared";import type { ModelAuth } from "@earendil-works/pi-ai";import { convertMessages } from "@earendil-works/pi-ai/api/openai-completions";-import { genericModelConfig, modelConfigWithBinding } from "./model-capabilities.js";+import { genericModelConfig, modelConfigFromPi, modelConfigWithBinding } from "./model-capabilities.js";+import { builtinProviders } from "@earendil-works/pi-ai/providers/all";import type { ModelConfig } from "./thinking-level.js";import {adapterAcceptsCustomFetch,@@ -26,6 +27,53 @@ const keyedProvider: RuntimeProviderConfig = {supportedThinkingLevels: ["off"],};+describe("account-local Pi registries", () => {+ it("preserves native pricing tiers through a serialized model projection", () => {+ const native = builtinProviders().flatMap((provider) => provider.getModels())+ .find((model) => model.cost.tiers?.length);+ expect(native).toBeDefined();+ if (!native) throw new Error("Missing tiered Pi catalog model");+ const modelConfig: ModelConfig = JSON.parse(JSON.stringify(modelConfigFromPi(native)));+ const restored = buildProviderModel({+ ...keyedProvider,+ modelId: native.id,+ vendorKey: native.provider,+ modelConfig,+ });+ expect(restored.cost).toEqual(native.cost);+ expect(restored.cost.tiers).toHaveLength(native.cost.tiers!.length);+ });++ it("keeps same-vendor credentials isolated during concurrent resolution", async () => {+ const first: RuntimeProviderConfig = {+ ...keyedProvider,+ id: "account-one",+ vendorKey: "openai",+ resolveAuth: async () => ({ apiKey: "first-fixture-key" }),+ };+ const second: RuntimeProviderConfig = {+ ...first,+ id: "account-two",+ resolveAuth: async () => ({ apiKey: "second-fixture-key" }),+ };+ const firstModel = buildProviderModel(first);+ const secondModel = buildProviderModel(second);+ const firstModels = createProviderModels(first, firstModel);+ const secondModels = createProviderModels(second, secondModel);+ expect(firstModels).not.toBe(secondModels);+ expect(firstModel.provider).toBe("openai");+ expect(secondModel.provider).toBe("openai");+ const [firstAuth, secondAuth] = await Promise.all([+ firstModels.getAuth(firstModel),+ secondModels.getAuth(secondModel),+ ]);+ expect(firstAuth?.auth.apiKey).toBe("first-fixture-key");+ expect(secondAuth?.auth.apiKey).toBe("second-fixture-key");+ expect(first.id).toBe("account-one");+ expect(second.id).toBe("account-two");+ });+});+describe("apiBindingForStyle", () => {it("binds OpenCode Go to its fixed OpenAI-compatible endpoint", () => {const opencode = apiBindingForStyle("opencode_go");@@ -467,7 +515,7 @@ describe("buildProviderModel OpenAI-compatible role compatibility", () => {},}) as any;- expect(model.provider).toBe("row-uuid");+ expect(model.provider).toBe("siliconflow-cn");expect(model.compat).toMatchObject({requiresReasoningContentOnAssistantMessages: true,requiresNonEmptyReasoningReplay: true,@@ -884,7 +932,7 @@ describe("GitHub Copilot transport identity", () => {it("retains pi-ai static headers for a row-scoped OAuth model", () => {const model = buildProviderModel(provider);- expect(model.provider).toBe(provider.id);+ expect(model.provider).toBe(provider.vendorKey);expect(model.headers).toMatchObject({"Editor-Version": "vscode/1.107.0","Editor-Plugin-Version": "copilot-chat/0.35.0",@@ -1020,7 +1068,7 @@ describe("GitHub Copilot transport identity", () => {expect(request?.headers.get("X-Initiator")).toBe("user");expect(request?.headers.get("Openai-Intent")).toBe("conversation-edits");expect(request?.url).toBe("https://api.business.githubcopilot.com/v1/messages?beta=true");- expect(model.provider).toBe(claudeProvider.id);+ expect(model.provider).toBe(claudeProvider.vendorKey);});it("re-resolves the rotating Bearer token for each row-scoped Claude request", async () => {diff --git a/packages/agent-runtime/src/provider-binding.ts b/packages/agent-runtime/src/provider-binding.tsindex 159269315..2d494403b 100644--- a/packages/agent-runtime/src/provider-binding.ts+++ b/packages/agent-runtime/src/provider-binding.ts@@ -56,7 +56,7 @@ export type RuntimeProviderConfig = {apiStyle?: string;supportsReasoning: boolean;supportedThinkingLevels: ThinkingLevel[];- /** Complete model metadata resolved from models.dev by Electron main. */+ /** Effective Pi model metadata resolved by Electron main. */modelConfig?: ModelConfig;/*** Optional outbound HTTP headers. Empty/absent keeps adapter defaults.@@ -212,7 +212,7 @@ function nativeCopilotHeaders(modelId: string): Record<string, string> | undefin: undefined;if (model?.headers) return model.headers;- // A model returned by models.dev or a user's Copilot entitlement may not be+ // A model returned by Pi or a user's Copilot entitlement may not be// present in pi-ai's pinned built-in catalog. Its transport still requires// the same client identity headers as every other Copilot model.return Object.values(GITHUB_COPILOT_MODELS).find((entry) => entry.headers)?.headers;@@ -268,8 +268,8 @@ function copilotRequestAuth(* Claude models that publish an effort ladder without a `budget_tokens`* option (Opus 4.7+, Opus 5.x, Fable, ...) reject `thinking.type=enabled`* with a 400. pi-ai only sends adaptive thinking when- * `compat.forceAdaptiveThinking` is set, and models.dev carries no compat- * record, so derive the flag from the published reasoning options.+ * `compat.forceAdaptiveThinking` is set. Legacy projections can lack that+ * compatibility record, so derive the flag from published reasoning options.*/function requiresAdaptiveThinking(model: Pick<ModelConfig, "reasoning" | "reasoningOptions">,@@ -288,8 +288,15 @@ export function buildProviderModel(const binding = apiBindingForProviderModel(provider);const catalog = provider.modelConfig;const catalogModel = catalog- ? (({ source: _source, ...model }) => model)(catalog)- : genericModelConfig(provider.modelId, provider.baseUrl ?? binding.defaultBaseUrl);+ ? (({ source: _source, nativeCost, ...model }) => ({+ ...model,+ ...(nativeCost ? { cost: nativeCost } : {}),+ }))(catalog)+ : {+ ...genericModelConfig(provider.modelId, provider.baseUrl ?? binding.defaultBaseUrl),+ reasoning: provider.supportsReasoning,+ supportedThinkingLevels: provider.supportedThinkingLevels,+ };const baseUrl = runtimeBaseUrlForApi(binding.api,providerRequestTransport(provider).baseUrl ?? binding.defaultBaseUrl,@@ -346,7 +353,7 @@ export function buildProviderModel(...catalogModel,id: provider.modelId,api: binding.api,- provider: provider.id,+ provider: provider.extensionAgentKey ? provider.id : (provider.vendorKey?.trim() || provider.id),baseUrl,webSearch:resolveNativeWebSearch({@@ -360,45 +367,50 @@ export function buildProviderModel(} as Model<Api>;}-/** A single-model registry for one resolved provider. */+/** Account-local operation registry. Vendor identity stays internal; auth stays row-scoped. */+export function createAccountModels(+ provider: RuntimeProviderConfig,+ operations: Pick<Parameters<typeof createProvider>[0], "models" | "api" | "images" | "classifiers">,+): Models {+ const models = createModels({ authContext: { env: async () => undefined, fileExists: async () => false } });+ const providerId = provider.extensionAgentKey ? provider.id : (provider.vendorKey?.trim() || provider.id);+ models.setProvider(createProvider({+ id: providerId,+ name: provider.name,+ baseUrl: provider.baseUrl,+ ...operations,+ models: operations.models.map((model) => ({ ...model, provider: providerId })),+ auth: {+ apiKey: {+ name: `${provider.name} credential`,+ resolve: async () => ({+ auth: provider.resolveAuth+ ? await provider.resolveAuth()+ : provider.authKind === "none" ? {} : { apiKey: providerRequestKey(provider) },+ }),+ },+ },+ }));+ return models;+}++/** A single account registry for an effective chat binding and optional other operations. */export function createProviderModels(provider: RuntimeProviderConfig,model: Model<Api>,+ operations?: Pick<Parameters<typeof createProvider>[0], "models" | "images" | "classifiers">,): Models {- const requestKey = providerRequestKey(provider);const resolveAuth = provider.resolveAuth;- const models = createModels();- models.setProvider(- createProvider({- id: provider.id,- name: provider.name,- baseUrl: model.baseUrl,- auth: {- apiKey: {- name: `${provider.name} API key`,- // Stored apiKey semantics let each adapter emit its own auth header- // (Bearer for OpenAI-style APIs, x-api-key for Anthropic, …).- //- // A vendor account resolves instead through Electron main, which- // returns the whole `ModelAuth` — token, headers, and the- // per-credential baseUrl GitHub Copilot hands out. pi-ai calls this- // for every request and caches nothing, so a token that rotates- // mid-session is picked up on the next one. Copilot's Anthropic wire- // needs explicit Bearer auth because the model uses a row id.- resolve: async () =>- resolveAuth- ? {- auth: copilotRequestAuth(provider, model.api, await resolveAuth()),- source: "OAuth",- }- : { auth: { apiKey: requestKey } },- },- },- models: [model],- api: apiBindingForProviderModel(provider).adapter(),- }),- );- return models;+ return createAccountModels({+ ...provider,+ resolveAuth: async () => resolveAuth+ ? copilotRequestAuth(provider, model.api, await resolveAuth())+ : { apiKey: providerRequestKey(provider) },+ }, {+ ...operations,+ models: [model, ...(operations?.models ?? [])],+ api: apiBindingForProviderModel(provider).adapter(),+ });}/** Build a pi-ai model collection for a trusted extension-owned agent. */export function createExtensionAgentModels(input: {@@ -407,7 +419,7 @@ export function createExtensionAgentModels(input: {model: Model<Api>;stream: ProviderStreams;}): Models {- const models = createModels();+ const models = createModels({ authContext: { env: async () => undefined, fileExists: async () => false } });models.setProvider(createProvider({id: input.providerId,diff --git a/packages/agent-runtime/src/request-usage.test.ts b/packages/agent-runtime/src/request-usage.test.tsnew file mode 100644index 000000000..b0ad96e1a--- /dev/null+++ b/packages/agent-runtime/src/request-usage.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from "vitest";+import { createAssistantMessageEventStream, type AssistantMessage } from "@earendil-works/pi-ai";+import { accountModelStream } from "./request-usage.js";+import { usageFromPi } from "./agent-messages.js";+import { addUsage, type MessageUsage } from "@pi-desktop/shared";++function response(): AssistantMessage {+ return { role: "assistant", content: [], api: "openai-completions", provider: "openai", model: "physical",+ usage: { input: 12, output: 3, cacheRead: 0, cacheWrite: 0, totalTokens: 15,+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } }, stopReason: "stop", timestamp: 1 };+}++describe("physical request accounting", () => {+ it("reports once across iteration and result and preserves unknown price through replay", async () => {+ const reports: MessageUsage[] = [];+ const stream = accountModelStream({ id: "physical", provider: "openai" }, () => {+ const inner = createAssistantMessageEventStream();+ inner.push({ type: "done", reason: "stop", message: response() });+ inner.end();+ return inner;+ }, { providerId: "account-1", onUsage: (usage) => reports.push(usage) });+ for await (const _event of stream) { /* Consume the actual Pi stream. */ }+ const result = await stream.result();+ expect(reports).toHaveLength(1);+ expect(reports[0]).toMatchObject({ providerId: "account-1", modelId: "physical", usageOrigin: "pi", costStatus: "unknown" });+ expect(reports[0]?.cost).toBeUndefined();+ expect(usageFromPi(result.usage)?.operationId).toBe(reports[0]?.operationId);+ expect(addUsage(reports[0], usageFromPi(result.usage))?.totalTokens).toBe(15);+ });++ it("preserves known free pricing with explicit resolved-model provenance", async () => {+ const stream = accountModelStream({ id: "free", provider: "openai" }, () => {+ const inner = createAssistantMessageEventStream();+ inner.push({ type: "done", reason: "stop", message: response() }); inner.end(); return inner;+ }, { costStatus: "estimated" });+ const usage = usageFromPi((await stream.result()).usage);+ expect(usage?.costStatus).toBe("estimated");+ expect(usage?.cost?.total).toBe(0);+ });++ it("allocates a distinct identity to each paid retry, including failed attempts", async () => {+ const reports: MessageUsage[] = [];+ for (const failed of [true, false]) {+ const stream = accountModelStream({ id: "physical", provider: "openai" }, () => {+ const inner = createAssistantMessageEventStream();+ const message = response();+ if (failed) { message.stopReason = "error"; inner.push({ type: "error", reason: "error", error: message }); }+ else inner.push({ type: "done", reason: "stop", message });+ inner.end(); return inner;+ }, { onUsage: (usage) => reports.push(usage) });+ await stream.result();+ }+ expect(new Set(reports.map((usage) => usage.operationId)).size).toBe(2);+ expect(addUsage(reports[0], reports[1])?.totalTokens).toBe(30);+ });+});++it("does not turn unknown native rates into a zero-dollar request", async () => {+ const stream = accountModelStream({ id: "live-only", provider: "openai" }, () => {+ const inner = createAssistantMessageEventStream();+ inner.push({ type: "done", reason: "stop", message: response() }); inner.end(); return inner;+ }, { costStatus: "estimated", nativeCost: { input: NaN, output: NaN, cacheRead: NaN, cacheWrite: NaN } });+ expect(usageFromPi((await stream.result()).usage)?.costStatus).toBe("unknown");+});diff --git a/packages/agent-runtime/src/request-usage.ts b/packages/agent-runtime/src/request-usage.tsnew file mode 100644index 000000000..c5584ff7b--- /dev/null+++ b/packages/agent-runtime/src/request-usage.ts@@ -0,0 +1,67 @@+import { randomUUID } from "node:crypto";+import type { Api, AssistantMessage, AssistantMessageEventStream, Model } from "@earendil-works/pi-ai";+import type { MessageUsage, UsageProvenance } from "@pi-desktop/shared";+import { usageFromPi, usageToPi } from "./agent-messages.js";++/** Native rates must be present and finite before a zero cost can mean free use. */+export function nativeCostStatus(cost: Model<Api>["cost"] | undefined): UsageProvenance["costStatus"] {+ if (!cost) return undefined;+ return [cost.input, cost.output, cost.cacheRead, cost.cacheWrite].every(rate => Number.isFinite(rate) && rate >= 0)+ ? "estimated" : "unknown";+}++export type UsageObserver = (usage: MessageUsage) => void;++/** Create before dispatch. Each physical retry gets its own identity. */+export function requestUsageIdentity(model: Pick<Model<Api>, "id" | "provider">, providerId?: string): UsageProvenance {+ return { operationId: randomUUID(), usageOrigin: "pi", providerId: providerId ?? model.provider, modelId: model.id };+}++export function accountModelResult(+ message: AssistantMessage,+ identity: UsageProvenance,+ onUsage?: UsageObserver,+): AssistantMessage {+ const usage = usageFromPi(message.usage, identity);+ if (usage) {+ message.usage = usageToPi(usage);+ onUsage?.(usage);+ }+ return message;+}++/**+ * Observe at the real request boundary, inside the retry factory. Intermediate+ * failed paid attempts are reported even when a retry reuses the visible row.+ * The proxy preserves Pi's event stream ownership and cancellation semantics.+ */+export function accountModelStream(+ model: Pick<Model<Api>, "id" | "provider">,+ createStream: () => AssistantMessageEventStream,+ options: { providerId?: string; costStatus?: UsageProvenance["costStatus"]; nativeCost?: Model<Api>["cost"]; onUsage?: UsageObserver } = {},+): AssistantMessageEventStream {+ const costStatus = options.costStatus === "reported" ? "reported"+ : nativeCostStatus(options.nativeCost) ?? options.costStatus;+ const identity = { ...requestUsageIdentity(model, options.providerId),+ ...(costStatus ? { costStatus } : {}) };+ const stream = createStream();+ let reported = false;+ const account = (message: AssistantMessage): AssistantMessage => accountModelResult(message, identity, (usage) => {+ if (reported) return;+ reported = true;+ options.onUsage?.(usage);+ });+ return new Proxy(stream, {+ get(target, property, receiver) {+ if (property === "result") return async () => account(await target.result());+ if (property === Symbol.asyncIterator) return async function* () {+ for await (const event of target) {+ if (event.type === "done") account(event.message);+ if (event.type === "error") account(event.error);+ yield event;+ }+ };+ return Reflect.get(target, property, receiver);+ },+ });+}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 8cb6d815f..3d2fc7e9c 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -5335,7 +5335,7 @@ describe("DesktopAgentRuntime per-turn context protection", () => {const events = onEvent.mock.calls.map(([envelope]) => (envelope as any).event);const endEvent = events.find((e) => e.type === "message_end");expect(endEvent).toBeDefined();- expect(endEvent.message.usage).toEqual({+ expect(endEvent.message.usage).toMatchObject({inputTokens: 200,outputTokens: 80,totalTokens: 280,diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 391512062..e148770e6 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -1,3 +1,4 @@+import { accountModelStream } from "./request-usage.js";import { modeToolDenial, retainModeToolDeclaration, withModeExecutionGuard } from "./mode-tool-access.js";import { restoreHostedSearchReplay } from "./hosted-search-replay.js";import { requestExtensionUi } from "./extensions/ui-request.js";@@ -1976,14 +1977,19 @@ Do not invent objections or turn speculative risks into blockers. Stop when thestallAbort.signal,]),};+ const usageTurnId = this.turnId;const retryStream = createProviderRetryStream(m,context,attemptOptions,- (retryOptions) =>+ (retryOptions) => accountModelStream(m, () =>this.thinkingLevel === "omit"? this.models.stream(omitThinkingModel(m), context, retryOptions)- : this.models.streamSimple(m, context, retryOptions),+ : this.models.streamSimple(m, context, retryOptions), {+ providerId: this.provider.id,+ nativeCost: this.provider.modelConfig?.nativeCost,+ onUsage: (usage) => this.emit({ type: "usage", usage }, usageTurnId),+ }),{claim: (error, phase) => this.claimProviderRetry(error, phase),headers: () => this.providerRetryHeaders,@@ -4725,6 +4731,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst tagged: UiMessage = {...row,parentToolCallId: envelope.parentToolCallId ?? row.parentToolCallId,+ nestedParentToolCallId: envelope.nestedParentToolCallId ?? row.nestedParentToolCallId,agentName: envelope.agentName ?? row.agentName,};const key =@@ -4758,6 +4765,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetoolStatus: event.isError ? "error" : "success",isError: Boolean(event.isError),parentToolCallId: envelope.parentToolCallId,+ nestedParentToolCallId: envelope.nestedParentToolCallId,agentName: envelope.agentName,};}@@ -6848,12 +6856,14 @@ Do not invent objections or turn speculative risks into blockers. Stop when thepreparation: ShapedPreparation,signal: AbortSignal,): Promise<Awaited<ReturnType<typeof compact>>> {+ const usageTurnId = this.turnId;return compact(preparation,// The summary is a provider request like any other turn, but// pi-agent-core builds its options itself and never reaches `streamFn`,// so the headers have to ride on the collection.- withCompactionRequestHeaders(this.models, this.provider, this.sessionId),+ withCompactionRequestHeaders(this.models, this.provider, this.sessionId,+ usage => this.emit({ type: "usage", usage }, usageTurnId)),this.model,undefined,agentThinkingLevel(this.thinkingLevel),diff --git a/packages/agent-runtime/src/subagent-context.ts b/packages/agent-runtime/src/subagent-context.tsindex 43d79fc97..725661f93 100644--- a/packages/agent-runtime/src/subagent-context.ts+++ b/packages/agent-runtime/src/subagent-context.ts@@ -54,6 +54,7 @@ import {reduceSummaryInput,type CompactionSummaryInput,} from "./compaction-summary-input.js";+import type { UsageObserver } from "./request-usage.js";import { withCompactionRequestHeaders } from "./compaction-request.js";import {DEFAULT_MAX_TOKENS,@@ -127,11 +128,13 @@ export function delegateSummaryModels(provider: RuntimeProviderConfig,model: Model<Api>,sessionId: string,+ onUsage?: UsageObserver,): Models {return withCompactionRequestHeaders(createProviderModels(provider, model),provider,sessionId,+ onUsage,);}diff --git a/packages/agent-runtime/src/subagent-model-binding.ts b/packages/agent-runtime/src/subagent-model-binding.tsindex 4f2448704..11c84a605 100644--- a/packages/agent-runtime/src/subagent-model-binding.ts+++ b/packages/agent-runtime/src/subagent-model-binding.ts@@ -1,3 +1,4 @@+import { accountModelStream, type UsageObserver } from "./request-usage.js";import {buildProviderModel,copilotRequestHeaders,@@ -35,6 +36,7 @@ export function subagentModelBinding(opts: {thinkingLevel: SubagentThinkingLevel;sessionId: string;maxTokens?: number;+ onUsage?: UsageObserver;}, retry: SubagentProviderRetryState) {// A definition may cap the delegate's own output (issue #171). The// catalog's published limit keeps applying otherwise, so this is an@@ -100,10 +102,14 @@ export function subagentModelBinding(opts: {m,context,requestOptions,- (retryOptions) =>+ (retryOptions) => accountModelStream(m, () =>omitThinking? models.stream(omitThinkingModel, context, retryOptions)- : models.streamSimple(m, context, retryOptions),+ : models.streamSimple(m, context, retryOptions), {+ providerId: opts.provider.id,+ nativeCost: opts.provider.modelConfig?.nativeCost,+ onUsage: opts.onUsage,+ }),{claim: (error, phase) => retry.claim(error, phase),headers: () => retry.headers,diff --git a/packages/agent-runtime/src/subagent.ts b/packages/agent-runtime/src/subagent.tsindex 8ec003b79..5eef97509 100644--- a/packages/agent-runtime/src/subagent.ts+++ b/packages/agent-runtime/src/subagent.ts@@ -334,6 +334,7 @@ export class SubagentRun {this.provider,preflightModel,this.opts.sessionId,+ usage => this.recordUsage(usage),),systemPrompt: preflightSystemPrompt,tools: preflightTools,@@ -425,6 +426,11 @@ export class SubagentRun {return drop.messages;}+ private recordUsage(usage: MessageUsage): void {+ this.usage = addUsage(this.usage, usage);+ this.emit({ type: "usage", usage });+ }+private bindingFor(provider: RuntimeProviderConfig,thinkingLevel: SubagentThinkingLevel,@@ -434,6 +440,7 @@ export class SubagentRun {thinkingLevel,sessionId: this.opts.sessionId,maxTokens: this.opts.definition.maxTokens,+ onUsage: usage => this.recordUsage(usage),}, this.retryState);}@@ -449,8 +456,6 @@ export class SubagentRun {];if (outcome.kind === "compacted") {this.contextCompactions += 1;- const summaryUsage = usageFromPi(outcome.summaryUsage);- this.usage = addUsage(this.usage, summaryUsage);} else {this.contextDegraded = true;}@@ -477,6 +482,7 @@ export class SubagentRun {this.provider,this.agent.state.model,this.opts.sessionId,+ usage => this.recordUsage(usage),),thinkingLevel: this.agent.state.thinkingLevel,signal: signal ?? this.runSignal(),diff --git a/packages/agent-runtime/src/thinking-level.test.ts b/packages/agent-runtime/src/thinking-level.test.tsindex 673f466aa..220cf042a 100644--- a/packages/agent-runtime/src/thinking-level.test.ts+++ b/packages/agent-runtime/src/thinking-level.test.ts@@ -1,5 +1,33 @@import { describe, expect, it } from "vitest";-import { agentThinkingLevel, clampThinkingLevel, omitThinkingModel } from "./thinking-level.js";+import { clampThinkingLevel as clampPiThinkingLevel } from "@earendil-works/pi-ai";+import { builtinProviders } from "@earendil-works/pi-ai/providers/all";+import { agentThinkingLevel, clampThinkingLevel, omitThinkingModel, requestThinkingLevel } from "./thinking-level.js";++describe("simple request thinking normalization", () => {+ const providers = builtinProviders();++ for (const providerId of ["openai", "azure-openai-responses", "openai-codex"]) {+ it(`normalizes unsupported off using the published ${providerId} model`, () => {+ const model = providers.find((provider) => provider.id === providerId)+ ?.getModels().find((entry) => entry.id === "gpt-6.1-sol");+ expect(model).toBeDefined();+ if (!model) throw new Error(`Missing ${providerId} GPT-6.1 Sol catalog entry`);+ const effective = clampPiThinkingLevel(model, "off");+ expect(effective).not.toBe("off");+ expect(requestThinkingLevel(model, "off")).toBe(effective);+ });+ }++ it("encodes supported off as absent reasoning without changing Agent bookkeeping", () => {+ const model = providers.find((provider) => provider.id === "openai")+ ?.getModels().find((entry) => !entry.reasoning);+ expect(model).toBeDefined();+ if (!model) throw new Error("Missing non-reasoning catalog model");+ expect(requestThinkingLevel(model, "off")).toBeUndefined();+ expect(requestThinkingLevel(model, "omit")).toBeUndefined();+ expect(agentThinkingLevel("off")).toBe("off");+ });+});const reasoning = {supportsReasoning: true,diff --git a/packages/agent-runtime/src/thinking-level.ts b/packages/agent-runtime/src/thinking-level.tsindex 791ddb05a..509bbd316 100644--- a/packages/agent-runtime/src/thinking-level.ts+++ b/packages/agent-runtime/src/thinking-level.ts@@ -1,3 +1,4 @@+import { clampThinkingLevel as clampPiThinkingLevel, type Api, type Model, type SimpleStreamOptions } from "@earendil-works/pi-ai";import type {ModelCost,ModelExperimentalMetadata,@@ -17,12 +18,14 @@ export type ThinkingCapabilitySet = {};/**- * Serializable model metadata resolved in Electron main from models.dev.- * pi-ai consumes this record through its selected transport adapter but does- * not provide model names, limits, modalities, thinking levels, or prices.+ * Serializable projection of the account's effective Pi chat model.+ * Legacy source tags remain readable; no legacy catalog is consulted.*/export type ModelConfig = {- source: "models.dev" | "generic";+ source: "pi" | "models.dev" | "generic";+ inputLimits?: Model<Api>["inputLimits"];+ promptCache?: Model<Api>["promptCache"];+ samplingParams?: Model<Api>["samplingParams"];name: string;baseUrl: string;description?: string;@@ -42,6 +45,8 @@ export type ModelConfig = {modalities?: ModelModalities;openWeights?: boolean;limit?: ModelLimit;+ /** Pi's native request pricing, including tiers; never reconstruct it from UI prices. */+ nativeCost?: Model<Api>["cost"];cost?: ModelCost & {input: number;output: number;@@ -101,6 +106,23 @@ export function omitThinkingModel<T extends { thinkingLevelMap?: Partial<Record<};}+/** Normalize only after resolving the physical request model; never mutate preferences. */+export function effectiveThinkingLevel(+ model: Model<Api>,+ requested: SessionThinkingLevel,+): SessionThinkingLevel {+ return requested === "omit" ? "omit" : clampPiThinkingLevel(model, requested);+}++/** Simple requests encode off by omitting reasoning, unlike Agent bookkeeping. */+export function requestThinkingLevel(+ model: Model<Api>,+ requested: SessionThinkingLevel,+): SimpleStreamOptions["reasoning"] {+ const effective = effectiveThinkingLevel(model, requested);+ return effective === "off" || effective === "omit" ? undefined : effective;+}+/** Apply the canonical nearest-supported-level rule to catalog metadata. */export function clampThinkingLevel(capabilities: ThinkingCapabilitySet,diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.tsindex a1eb165f9..a7919c96f 100644--- a/packages/host-runtime/src/host-ports.ts+++ b/packages/host-runtime/src/host-ports.ts@@ -74,6 +74,7 @@ export function toRacpItem(message: UiMessage): RacpItemSummary {status: message.status === "streaming" ? "streaming" : "completed",createdAt: message.createdAt,...(message.parentToolCallId ? { parentToolCallId: message.parentToolCallId } : {}),+ ...(message.nestedParentToolCallId ? { nestedParentToolCallId: message.nestedParentToolCallId } : {}),...(message.agentName ? { agentName: message.agentName } : {}),content: message,};diff --git a/packages/host-runtime/src/runtime-service.ts b/packages/host-runtime/src/runtime-service.tsindex 675046028..0142038aa 100644--- a/packages/host-runtime/src/runtime-service.ts+++ b/packages/host-runtime/src/runtime-service.ts@@ -182,6 +182,7 @@ export class RuntimeService implements RuntimePort {reason: permission.reason,...(asking?.agentName ? { agentName: asking.agentName } : {}),...(asking?.parentToolCallId ? { parentToolCallId: asking.parentToolCallId } : {}),+ ...(asking?.nestedParentToolCallId ? { nestedParentToolCallId: asking.nestedParentToolCallId } : {}),},},});diff --git a/packages/host-runtime/src/turn-events.test.ts b/packages/host-runtime/src/turn-events.test.tsnew file mode 100644index 000000000..1f8efdd0c--- /dev/null+++ b/packages/host-runtime/src/turn-events.test.ts@@ -0,0 +1,80 @@+import { describe, expect, it } from "vitest";+import type { AgentEventEnvelope, UiMessage } from "@pi-desktop/shared";+import { TurnEventPipeline } from "./turn-events.js";++for (const delegate of [false, true]) {+ describe(`nested tool persistence (${delegate ? "delegate" : "root"})`, () => {+ it("retains tool nesting without changing Task ownership", async () => {+ const written: Array<{ message: UiMessage; turnId: string }> = [];+ const emitted: AgentEventEnvelope[] = [];+ const finished: string[] = [];+ const pipeline = new TurnEventPipeline({+ getHost: () => ({+ async call<T>(method: string, params: unknown): Promise<T> {+ if (method === "session.appendMessage") {+ written.push(params as { message: UiMessage; turnId: string });+ }+ return {} as T;+ },+ }),+ ownership: {+ activeTurnId: () => "turn-1",+ isStaleTerminalEvent: () => false,+ finishTurn: async (sessionId) => { finished.push(sessionId); },+ },+ emit: (event) => emitted.push(event),+ log: () => undefined,+ });+ const lineage = {+ nestedParentToolCallId: "code-1",+ ...(delegate ? { parentToolCallId: "task-1", agentName: "reader" } : {}),+ };+ pipeline.handle({+ sessionId: "s", turnId: "turn-1", ts: 1_000, ...lineage,+ event: { type: "tool_start", toolCallId: "read-1", toolName: "Read", args: { path: "a.ts" } },+ });+ pipeline.handle({+ sessionId: "s", turnId: "turn-1", ts: 1_100, ...lineage,+ event: { type: "tool_end", toolCallId: "read-1", result: "contents" },+ });+ await pipeline.dispose();+ expect(written).toHaveLength(1);+ expect(written[0]?.turnId).toBe("turn-1");+ expect(written[0]?.message).toMatchObject({ toolCallId: "read-1", ...lineage });+ expect(written[0]?.message.parentToolCallId).toBe(delegate ? "task-1" : undefined);+ expect(finished).toEqual([]);+ const completed = emitted.find((envelope) => envelope.event.type === "message_end");+ expect(completed?.nestedParentToolCallId).toBe("code-1");+ expect(completed?.parentToolCallId).toBe(delegate ? "task-1" : undefined);+ });+ });+}+++describe("usage ledger ingress", () => {+ it("unions child reports and parent aggregates, replays idempotently, and isolates late turns", async () => {+ const writes: Array<{ method: string; params: unknown }> = [];+ const pipeline = new TurnEventPipeline({+ getHost: () => ({ async call<T>(method: string, params: unknown): Promise<T> {+ writes.push({ method, params }); return {} as T;+ } }),+ ownership: { activeTurnId: () => "new-turn", isStaleTerminalEvent: () => false, finishTurn: async () => undefined },+ emit: () => undefined, log: () => undefined,+ });+ const child = { operationId: "request-child", usageOrigin: "pi" as const, inputTokens: 10, outputTokens: 2, totalTokens: 12 };+ const classifier = { ...child, operationId: "classifier" };+ const event = { sessionId: "s", turnId: "new-turn", parentToolCallId: "task-1", nestedParentToolCallId: "code-1", ts: 1,+ event: { type: "usage" as const, usage: child } };+ pipeline.handle(event);+ pipeline.handle(event);+ pipeline.handle({ ...event, event: { type: "message_end", message: { id: "child", role: "assistant", content: "done", createdAt: "2026-09-30", usage: child } } });+ pipeline.handle({ sessionId: "s", turnId: "new-turn", ts: 2, event: { type: "turn_end", subagentUsage: {+ inputTokens: 20, outputTokens: 4, totalTokens: 24, aggregation: "aggregate", operations: [child, classifier],+ } } });+ pipeline.handle({ ...event, turnId: "old-turn", event: { type: "usage", usage: { ...child, operationId: "late" } } });+ expect(pipeline.takeTurnUsage("s")?.totalTokens).toBe(24);+ await pipeline.dispose();+ expect(writes.filter((write) => write.method === "session.recordUsage")).toHaveLength(5);+ expect(writes.at(-1)?.params).toMatchObject({ turnId: "old-turn", usage: { operationId: "late" } });+ });+});diff --git a/packages/host-runtime/src/turn-events.ts b/packages/host-runtime/src/turn-events.tsindex 1b74953e2..876937494 100644--- a/packages/host-runtime/src/turn-events.ts+++ b/packages/host-runtime/src/turn-events.ts@@ -1,5 +1,7 @@import {addUsage,+ usageForEvent,+ ownsUsageTurn,applyMessageUpdate,type AgentEventEnvelope,type MessageUsage,@@ -24,6 +26,7 @@ export type ActiveToolCall = {startedAtMs: number;turnId?: string;parentToolCallId?: string;+ nestedParentToolCallId?: string;agentName?: string;};@@ -160,6 +163,7 @@ export class TurnEventPipeline {startedAtMs: envelope.ts,turnId: envelope.turnId ?? this.options.ownership.activeTurnId(envelope.sessionId),...(envelope.parentToolCallId ? { parentToolCallId: envelope.parentToolCallId } : {}),+ ...(envelope.nestedParentToolCallId ? { nestedParentToolCallId: envelope.nestedParentToolCallId } : {}),...(envelope.agentName ? { agentName: envelope.agentName } : {}),});}@@ -179,6 +183,15 @@ export class TurnEventPipeline {const event = envelope.event;const sessionId = envelope.sessionId;const turnId = this.options.ownership.activeTurnId(sessionId);+ const usage = usageForEvent(envelope);+ if (usage) {+ if (ownsUsageTurn(envelope, turnId)) this.addTurnUsage(sessionId, usage);+ const usageTurnId = envelope.turnId ?? turnId;+ if (usageTurnId && (usage.operationId || usage.operations?.length)) {+ void this.persistence.append({ sessionId, turnId: usageTurnId, usage });+ }+ }+const finish = (status: "completed" | "aborted" | "error", errorCode: string | undefined) =>this.options.ownership.finishTurn(sessionId, status, errorCode, { turnId: envelope.turnId ?? "" })@@ -213,7 +226,6 @@ export class TurnEventPipeline {void finish("completed", undefined);return;case "turn_end":- if (!envelope.parentToolCallId) this.addTurnUsage(sessionId, event.subagentUsage);return;case "message_end":return this.persistMessageEnd(envelope, event.message, event.precedingAssistant, turnId);@@ -248,6 +260,7 @@ export class TurnEventPipeline {isError: event.isError,status: "complete",...(started?.parentToolCallId ? { parentToolCallId: started.parentToolCallId } : {}),+ ...(started?.nestedParentToolCallId ? { nestedParentToolCallId: started.nestedParentToolCallId } : {}),...(started?.agentName ? { agentName: started.agentName } : {}),};void this.persistence.append({@@ -284,7 +297,6 @@ export class TurnEventPipeline {}if (message.role === "assistant") {if (!envelope.parentToolCallId) {- if (message.usage) this.addTurnUsage(sessionId, message.usage);this.inflightSnapshots.delete(sessionId);const finalId = message.id;this.checkpointer.observe({ sessionId, turnId: envelope.turnId ?? turnId, message });@@ -321,10 +333,11 @@ function toolKey(sessionId: string, toolCallId: string): string {}function subagentTagged(message: UiMessage, envelope: AgentEventEnvelope): UiMessage {- if (!envelope.parentToolCallId) return message;+ if (!envelope.parentToolCallId && !envelope.nestedParentToolCallId) return message;return {...message,parentToolCallId: envelope.parentToolCallId,+ nestedParentToolCallId: envelope.nestedParentToolCallId,...(envelope.agentName ? { agentName: envelope.agentName } : {}),};}diff --git a/packages/host-runtime/src/turn-persistence.ts b/packages/host-runtime/src/turn-persistence.tsindex 0ebb039e8..98f9cdecc 100644--- a/packages/host-runtime/src/turn-persistence.ts+++ b/packages/host-runtime/src/turn-persistence.ts@@ -1,4 +1,4 @@-import { ErrorCodes, type UiMessage } from "@pi-desktop/shared";+import { ErrorCodes, type MessageUsage, type UiMessage } from "@pi-desktop/shared";import type { HostRpc } from "./host-ports.js";@@ -10,7 +10,8 @@ export type TurnPersistenceLogger = (export type MessageAppend = {sessionId: string;- message: UiMessage;+ message?: UiMessage;+ usage?: MessageUsage;turnId?: string;};@@ -83,9 +84,9 @@ export class TurnPersistence {const host = this.deps.getHost();if (host && (host.isAvailable?.() ?? true)) {try {- await host.call("session.appendMessage", {+ await host.call(entry.usage ? "session.recordUsage" : "session.appendMessage", {sessionId: entry.sessionId,- message: entry.message,+ ...(entry.usage ? { usage: entry.usage } : { message: entry.message }),...(entry.turnId ? { turnId: entry.turnId } : {}),});return;@@ -94,7 +95,7 @@ export class TurnPersistence {if (!isHostUnavailable(error)) {this.deps.log("warn", "transcript append failed", {sessionId: entry.sessionId,- messageId: entry.message.id,+ messageId: entry.message?.id,error: String(error),});return;@@ -105,7 +106,7 @@ export class TurnPersistence {if (attempt >= RETRY_DELAYS_MS.length * 2) {this.deps.log("error", "transcript append abandoned: host unavailable", {sessionId: entry.sessionId,- messageId: entry.message.id,+ messageId: entry.message?.id,});return;}diff --git a/packages/shared/fixtures/racp.schema.json b/packages/shared/fixtures/racp.schema.jsonindex 11063f35a..1dd5b75de 100644--- a/packages/shared/fixtures/racp.schema.json+++ b/packages/shared/fixtures/racp.schema.json@@ -430,6 +430,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"agentName": {"type": "string"},@@ -493,6 +496,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"agentName": {"type": "string"},@@ -941,6 +947,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"agentName": {"type": "string"},@@ -1007,6 +1016,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"agentName": {"type": "string"},@@ -1092,6 +1104,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"title": {"type": "string"},@@ -1201,6 +1216,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"questions": {"type": "array","items": {@@ -1340,6 +1358,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"title": {"type": "string"},@@ -1601,6 +1622,9 @@"parentToolCallId": {"type": "string"},+ "nestedParentToolCallId": {+ "type": "string"+ },"questions": {"type": "array","items": {diff --git a/packages/shared/src/event-usage.test.ts b/packages/shared/src/event-usage.test.tsnew file mode 100644index 000000000..ed95e0344--- /dev/null+++ b/packages/shared/src/event-usage.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";+import { usageForEvent, ownsUsageTurn } from "./event-usage.js";+import type { AgentEventEnvelope } from "./types/agent.js";++const operation = {+ operationId: "image-request", usageOrigin: "pi" as const,+ providerId: "account-a", modelId: "image-model",+ inputTokens: 12, outputTokens: 8, totalTokens: 20,+ costStatus: "unknown" as const,+};+function envelope(result: unknown): AgentEventEnvelope {+ return { sessionId: "session", turnId: "old-turn", ts: 1,+ event: { type: "tool_end", toolCallId: "image-tool", result } };+}+describe("tool operation accounting", () => {+ it("counts a physical image request once even when several artifacts expose it", () => {+ const usage = usageForEvent(envelope({ details: { operations: [+ { usage: operation }, { usage: operation },+ { usage: { ...operation, operationId: "second-request" } },+ ] } }));+ expect(usage?.totalTokens).toBe(40);+ expect(usage?.operations).toHaveLength(2);+ expect(usage?.costStatus).toBe("unknown");+ expect(usage?.operations?.[0].providerId).toBe("account-a");+ });+ it("ignores ordinary tool details and unidentifiable usage", () => {+ for (const result of [null, "text", { details: {} }, { details: { operations: [+ null, { usage: { totalTokens: 20 } },+ { usage: { ...operation, inputTokens: "12" } },+ ] } }]) expect(usageForEvent(envelope(result))).toBeUndefined();+ });+ it("does not debit a later active turn for a late image result", () => {+ expect(ownsUsageTurn(envelope({}), "new-turn")).toBe(false);+ expect(ownsUsageTurn(envelope({}), "old-turn")).toBe(true);+ expect(ownsUsageTurn(envelope({}), undefined)).toBe(false);+ });+});++it("ignores invalid counts in provider-supplied tool operations", () => {+ for (const value of [NaN, Infinity, -1, 0.5]) {+ for (const key of ["inputTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"]) {+ expect(usageForEvent(envelope({ details: { operations: [{ usage: { ...operation, [key]: value } }] } }))).toBeUndefined();+ }+ }+});diff --git a/packages/shared/src/event-usage.ts b/packages/shared/src/event-usage.tsnew file mode 100644index 000000000..ee4722981--- /dev/null+++ b/packages/shared/src/event-usage.ts@@ -0,0 +1,39 @@+import type { AgentEventEnvelope } from "./types/agent.js";+import type { MessageUsage } from "./types/messages.js";+import { addUsage, withUsageIdentity } from "./message-usage.js";++/** Physical identities, not tool ancestry, determine accounting ownership. */+export function usageForEvent(envelope: AgentEventEnvelope): MessageUsage | undefined {+ const event = envelope.event;+ if (event.type === "usage") return event.usage;+ if (event.type === "tool_end") {+ const result = event.result;+ if (!result || typeof result !== "object" || !("details" in result)) return undefined;+ const details = result.details;+ if (!details || typeof details !== "object" || !("operations" in details) || !Array.isArray(details.operations)) return undefined;+ let total: MessageUsage | undefined;+ for (const operation of details.operations) {+ const usage: unknown = operation?.usage;+ if (!usage || typeof usage !== "object" || !("operationId" in usage) || typeof usage.operationId !== "string" || !usage.operationId) continue;+ if (!["inputTokens", "outputTokens", "totalTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens"].every(key => {+ const count = (usage as Record<string, unknown>)[key];+ if (count === undefined && !["inputTokens", "outputTokens", "totalTokens"].includes(key)) return true;+ return typeof count === "number" && Number.isSafeInteger(count) && count >= 0;+ })) continue;+ total = addUsage(total, usage as MessageUsage);+ }+ return total;+ }+ if (event.type === "turn_end") return event.subagentUsage;+ if (event.type !== "message_end" || event.message.role !== "assistant") return undefined;+ return withUsageIdentity(event.message.usage, {+ operationId: `message:${envelope.sessionId}:${event.message.id}`,+ usageOrigin: "legacy",+ providerId: event.message.providerId,+ modelId: event.message.modelId,+ });+}++export function ownsUsageTurn(envelope: AgentEventEnvelope, activeTurnId: string | undefined): boolean {+ return activeTurnId !== undefined && (envelope.turnId === undefined || envelope.turnId === activeTurnId);+}diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.tsindex c044de255..aaf800f89 100644--- a/packages/shared/src/index.ts+++ b/packages/shared/src/index.ts@@ -71,3 +71,5 @@ export * from "./native-web-search-transport.js";export * from "./header-value.js";export * from "./session-todos.js";+export * from "./tool-call-lineage.js";+export * from "./event-usage.js";diff --git a/packages/shared/src/message-usage.test.ts b/packages/shared/src/message-usage.test.tsindex 09c7f60f2..f5aa44f15 100644--- a/packages/shared/src/message-usage.test.ts+++ b/packages/shared/src/message-usage.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { addUsage, type MessageUsage } from "./types.js";+import { addUsage, withUsageIdentity, type MessageUsage } from "./types.js";const parent: MessageUsage = {inputTokens: 200,@@ -29,4 +29,86 @@ describe("addUsage", () => {totalTokens: 440,});});++ const operation = (operationId: string, usage = parent): MessageUsage => ({+ ...usage, operationId, usageOrigin: "pi", aggregation: "operation",+ providerId: "physical-account", modelId: "physical-model",+ cost: { input: 0.2, output: 0.1, cacheRead: 0, cacheWrite: 0, total: 0.3 },+ costStatus: "estimated",+ });++ it("deduplicates replayed message_end and parent turn_end by physical operation", () => {+ const first = operation("parent");+ const child = operation("child", subagent);+ const rollup = addUsage(first, child);+ const replay = addUsage(addUsage(rollup, child), rollup);+ expect(replay).toEqual(rollup);+ expect(replay?.totalTokens).toBe(440);+ expect(replay?.cost?.total).toBe(0.6);+ expect(replay?.operations).toHaveLength(2);+ });++ it("counts classifier, image requests and nested delegates independently, not artifacts", () => {+ const records = ["classifier", "image-request-1", "image-request-1", "image-request-2", "nested-delegate"];+ const usage = records.reduce<MessageUsage | undefined>((acc, id) => addUsage(acc, operation(id)), undefined);+ expect(usage?.totalTokens).toBe(4 * parent.totalTokens);+ expect(usage?.operations?.map((item) => item.operationId)).toEqual([+ "classifier", "image-request-1", "image-request-2", "nested-delegate",+ ]);+ expect(addUsage(usage, JSON.parse(JSON.stringify(usage)))).toEqual(usage);+ });++ it("retains known costs on operations when one request's price is unknown", () => {+ const unknown = withUsageIdentity(subagent, { operationId: "unknown", costStatus: "unknown" });+ const usage = addUsage(operation("known"), unknown);+ expect(usage?.costStatus).toBe("unknown");+ expect(usage?.cost).toBeUndefined();+ expect(usage?.operations?.[0].cost?.total).toBe(0.3);+ expect(addUsage(usage, unknown)).toEqual(usage);+ });++ it("preserves legacy token-only totals when mixed with attributed aggregates", () => {+ const known = operation("new");+ const usage = addUsage(parent, known);+ expect(addUsage(usage, known)?.totalTokens).toBe(560);+ expect(usage?.costStatus).toBe("unknown");+ expect(usage?.cost).toBeUndefined();+ });++ it("attributes legacy messages once and never overwrites a physical identity", () => {+ const legacy = withUsageIdentity(parent, { operationId: "message-id", usageOrigin: "legacy" });+ expect(addUsage(legacy, legacy)?.totalTokens).toBe(parent.totalTokens);+ expect(withUsageIdentity(legacy, { operationId: "tool-parent" })).toBe(legacy);+ const aggregate = addUsage(legacy, operation("another"));+ expect(withUsageIdentity(aggregate, { operationId: "tool-parent" })).toBe(aggregate);+ });++ it("does not replace complete reports with late partial snapshots", () => {+ const complete = operation("request");+ const partial = operation("request", { inputTokens: 1, outputTokens: 1, totalTokens: 2 });+ expect(addUsage(complete, partial)?.totalTokens).toBe(280);+ expect(addUsage(partial, complete)?.totalTokens).toBe(280);+ expect(addUsage(complete, operation("paid-retry"))?.totalTokens).toBe(560);+ });+});++it("an equal-token replay cannot erase a known operation cost", () => {+ const known: MessageUsage = { ...parent, operationId: "request", costStatus: "reported",+ cost: { input: 1, output: 2, cacheRead: 0, cacheWrite: 0, total: 3 } };+ const unknown: MessageUsage = { ...parent, operationId: "request", costStatus: "unknown" };+ for (const [a, b] of [[known, unknown], [unknown, known]]) {+ const result = addUsage(a, b);+ expect(result?.costStatus).toBe("reported");+ expect(result?.cost?.total).toBe(3);+ }+});++it("malformed prices and overflowing cost totals remain unknown", () => {+ const priced = (operationId: string, total: number): MessageUsage => ({ inputTokens: 1, outputTokens: 0, totalTokens: 1,+ operationId, costStatus: "reported", cost: { input: total, output: 0, cacheRead: 0, cacheWrite: 0, total } });+ for (const value of [NaN, Infinity, -1, Number.MAX_VALUE]) {+ const result = addUsage(priced("a", value), priced("b", value));+ expect(result?.costStatus).toBe("unknown");+ expect(result?.cost).toBeUndefined();+ }});diff --git a/packages/shared/src/message-usage.ts b/packages/shared/src/message-usage.tsnew file mode 100644index 000000000..487302d40--- /dev/null+++ b/packages/shared/src/message-usage.ts@@ -0,0 +1,96 @@+import type { MessageUsage, MessageUsageCost, UsageOperation, UsageProvenance } from "./types/messages.js";++const tokenKeys = ["inputTokens", "outputTokens", "cacheReadTokens", "cacheWriteTokens", "reasoningTokens", "totalTokens"] as const;+const costKeys = ["input", "output", "cacheRead", "cacheWrite", "total"] as const;++/** Attribute old token-only rows at ingress, before either persistence or rollup. */+export function withUsageIdentity(+ usage: MessageUsage | undefined,+ identity: UsageProvenance & { operationId: string },+): MessageUsage | undefined {+ if (!usage || usage.operationId || usage.operations?.length) return usage;+ return { ...identity, ...usage, operationId: identity.operationId, aggregation: "operation" };+}++function sumCounts(values: MessageUsage[]): MessageUsage {+ const result: MessageUsage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };+ for (const value of values) {+ for (const key of tokenKeys) {+ if (value[key] !== undefined) result[key] = (result[key] ?? 0) + value[key];+ }+ }+ return result;+}++function atomicRecords(usage: MessageUsage): UsageOperation[] {+ if (usage.operations?.length) return usage.operations;+ if (!usage.operationId) return [];+ const { operations: _operations, aggregation: _aggregation, ...record } = usage;+ return [{ ...record, operationId: usage.operationId }];+}++/** Legacy totals can coexist with a ledger, but cannot be retrospectively attributed. */+function unattributed(usage: MessageUsage, records: UsageOperation[]): MessageUsage | undefined {+ if (!records.length) return usage;+ if (usage.aggregation !== "aggregate") return undefined;+ const attributed = sumCounts(records);+ const remaining = sumCounts([usage]);+ for (const key of tokenKeys) {+ if (remaining[key] !== undefined) remaining[key] = Math.max(0, remaining[key] - (attributed[key] ?? 0));+ }+ return tokenKeys.some((key) => (remaining[key] ?? 0) > 0) ? remaining : undefined;+}++function hasKnownCost(value: MessageUsage): boolean {+ return value.costStatus !== "unknown" && !!value.cost && costKeys.every(key => Number.isFinite(value.cost![key]) && value.cost![key] >= 0);+}++function sumCosts(values: MessageUsage[]): Pick<MessageUsage, "cost" | "costStatus"> {+ // Incomplete totals are unknown, not a misleading partial dollar amount.+ // The individually known costs remain available on the atomic records.+ if (values.some((value) => !hasKnownCost(value))) {+ return { costStatus: "unknown" };+ }+ const cost: MessageUsageCost = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 };+ for (const value of values) {+ for (const key of costKeys) cost[key] += value.cost![key];+ }+ if (costKeys.some(key => !Number.isFinite(cost[key]))) return { costStatus: "unknown" };+ return {+ cost,+ costStatus: values.every((value) => value.costStatus === "reported") ? "reported" : "estimated",+ };+}++/**+ * Union physical operations, then derive totals. Child reports and a parent's+ * aggregate may both arrive (and replay); a physical request is counted once.+ * Legacy records without identities retain their historical additive behavior.+ */+export function addUsage(total: MessageUsage | undefined, next: MessageUsage | undefined): MessageUsage | undefined {+ if (!next) return total;+ if (!total) return next;+ const left = atomicRecords(total);+ const right = atomicRecords(next);+ const legacy = [unattributed(total, left), unattributed(next, right)].filter(+ (value): value is MessageUsage => value !== undefined,+ );+ const operations = new Map<string, UsageOperation>();+ for (const record of [...left, ...right]) {+ const previous = operations.get(record.operationId);+ // A late partial snapshot must not replace an already-complete report.+ if (!previous || record.totalTokens > previous.totalTokens ||+ (record.totalTokens === previous.totalTokens && (+ !hasKnownCost(previous) ||+ (hasKnownCost(record) && record.costStatus === "reported")+ ))) operations.set(record.operationId, record);+ }+ const values = [...legacy, ...operations.values()];+ const counts = sumCounts(values);+ const hasCostMetadata = values.some((value) => value.cost || value.costStatus);+ return {+ ...counts,+ ...(hasCostMetadata ? sumCosts(values) : {}),+ ...(operations.size ? { aggregation: "aggregate" as const, operations: [...operations.values()] } : {}),+ };+}diff --git a/packages/shared/src/racp.ts b/packages/shared/src/racp.tsindex 3caf0234f..a62a67990 100644--- a/packages/shared/src/racp.ts+++ b/packages/shared/src/racp.ts@@ -213,6 +213,7 @@ export const RacpEventEnvelopeSchema = Type.Object({kind: RacpEventKindSchema,occurredAt: Type.String(),parentToolCallId: Type.Optional(Type.String()),+ nestedParentToolCallId: Type.Optional(Type.String()),agentName: Type.Optional(Type.String()),payload: Type.Unknown(),});@@ -237,6 +238,7 @@ export const RacpItemSummarySchema = Type.Object({sequence: Type.Optional(Type.Integer({ minimum: 1 })),createdAt: Type.String(),parentToolCallId: Type.Optional(Type.String()),+ nestedParentToolCallId: Type.Optional(Type.String()),agentName: Type.Optional(Type.String()),content: Type.Unknown(),});@@ -270,6 +272,7 @@ export const RacpApprovalRequestSchema = Type.Object({risk: Type.Optional(Type.Union([Type.Literal("low"), Type.Literal("medium"), Type.Literal("high")])),agentName: Type.Optional(Type.String()),parentToolCallId: Type.Optional(Type.String()),+ nestedParentToolCallId: Type.Optional(Type.String()),title: Type.Optional(Type.String()),question: Type.Optional(Type.String()),artifact: Type.Optional(@@ -326,6 +329,7 @@ export const RacpInputRequestSchema = Type.Object({expiresAt: Type.String(),agentName: Type.Optional(Type.String()),parentToolCallId: Type.Optional(Type.String()),+ nestedParentToolCallId: Type.Optional(Type.String()),questions: Type.Array(Type.Object({id: Type.String({ minLength: 1 }),@@ -679,6 +683,8 @@ export function racpKindForAgentEvent(return { kind: options.interrupted ? "turn.interrupted" : "turn.completed", durable: true };case "error":return { kind: "turn.failed", durable: true };+ case "usage":+ return { kind: "turn.activity", durable: false };case "turn_start":case "turn_end":case "status":@@ -719,6 +725,7 @@ export const LOCAL_AGENT_EVENT_TYPES: readonly AgentEvent["type"][] = ["agent_end","turn_start","turn_end",+ "usage","message_start","message_update","message_end",diff --git a/packages/shared/src/tool-call-lineage.test.ts b/packages/shared/src/tool-call-lineage.test.tsnew file mode 100644index 000000000..80a026791--- /dev/null+++ b/packages/shared/src/tool-call-lineage.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from "vitest";+import { toolCallLineage } from "./tool-call-lineage.js";++describe("terminal tool lineage", () => {+ it("retains recovered start attribution and fills independent terminal nesting", () => {+ expect(toolCallLineage(+ { parentToolCallId: "delegate", agentName: "worker", nestedParentToolCallId: undefined },+ { parentToolCallId: "later-owner", agentName: "later-name", nestedParentToolCallId: "compose" },+ )).toEqual({ parentToolCallId: "delegate", agentName: "worker", nestedParentToolCallId: "compose" });+ });+ it("uses terminal attribution when a restored start has none", () => {+ expect(toolCallLineage({}, { parentToolCallId: "delegate", agentName: "worker" }))+ .toEqual({ parentToolCallId: "delegate", agentName: "worker" });+ });+});diff --git a/packages/shared/src/tool-call-lineage.ts b/packages/shared/src/tool-call-lineage.tsnew file mode 100644index 000000000..d269a6d44--- /dev/null+++ b/packages/shared/src/tool-call-lineage.ts@@ -0,0 +1,32 @@+import type { AgentEventEnvelope, UiMessage } from "./types.js";++/** Task ownership and tool nesting are independent relationships. */+export type ToolCallLineage = Pick<+ AgentEventEnvelope,+ "parentToolCallId" | "nestedParentToolCallId" | "agentName"+>;++export function toolCallLineage(source: ToolCallLineage, fallback: ToolCallLineage = {}): ToolCallLineage {+ source = {+ parentToolCallId: source.parentToolCallId || fallback.parentToolCallId,+ nestedParentToolCallId: source.nestedParentToolCallId || fallback.nestedParentToolCallId,+ agentName: source.agentName || fallback.agentName,+ };+ return {+ ...(source.parentToolCallId ? { parentToolCallId: source.parentToolCallId } : {}),+ ...(source.nestedParentToolCallId+ ? { nestedParentToolCallId: source.nestedParentToolCallId }+ : {}),+ ...(source.agentName ? { agentName: source.agentName } : {}),+ };+}++export function tagMessageToolLineage(+ message: UiMessage,+ source: ToolCallLineage,+): UiMessage {+ if (!source.parentToolCallId && !source.nestedParentToolCallId && !source.agentName) {+ return message;+ }+ return { ...message, ...toolCallLineage(source) };+}diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.tsindex 54e6bf40e..67570b6d4 100644--- a/packages/shared/src/types/agent.ts+++ b/packages/shared/src/types/agent.ts@@ -183,6 +183,8 @@ export type ToolPermissionRequest = {agentName?: string;/** `Task` call that spawned the asking delegate. */parentToolCallId?: string;+ /** Immediate tool parent when this request came from nested execution. */+ nestedParentToolCallId?: string;};export type ToolPermissionResolution = {@@ -263,6 +265,7 @@ export type AgentEvent =| { type: "agent_start" }| { type: "agent_end"; messageIds: string[] }| { type: "turn_start" }+ | { type: "usage"; usage: MessageUsage }| { type: "turn_end"; subagentUsage?: MessageUsage }| { type: "message_start"; message: UiMessage }| {@@ -324,6 +327,8 @@ export type AgentEventEnvelope = {* skips the turn-lifecycle handling that belongs to the parent alone.*/parentToolCallId?: string;+ /** Immediate nested-tool parent; never identifies subagent ownership. */+ nestedParentToolCallId?: string;/** Definition name of the emitting subagent. */agentName?: string;};diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.tsindex 7ba12ef8b..361a476c9 100644--- a/packages/shared/src/types/messages.ts+++ b/packages/shared/src/types/messages.ts@@ -10,47 +10,42 @@ export type VoiceOrigin = {operationId: string;};-export type MessageUsage = {+export type MessageUsageCost = {+ input: number;+ output: number;+ cacheRead: number;+ cacheWrite: number;+ total: number;+};++export type UsageProvenance = {+ /** Identifies one physical request, not a tool, artifact, or logical retry group. */+ operationId?: string;+ usageOrigin?: "pi" | "legacy";+ costStatus?: "reported" | "estimated" | "unknown";+ /** Physical billing binding, not a virtual model alias. */+ providerId?: string;+ modelId?: string;+};++export type MessageUsage = UsageProvenance & {inputTokens: number;outputTokens: number;cacheReadTokens?: number;cacheWriteTokens?: number;reasoningTokens?: number;totalTokens: number;+ cost?: MessageUsageCost;+ aggregation?: "operation" | "aggregate";+ /** Atomic records included in this rollup; never recursively nested. */+ operations?: UsageOperation[];+};++export type UsageOperation = Omit<MessageUsage, "operations" | "aggregation"> & {+ operationId: string;};-/** Sum two provider usage records. Used for turn rollups, never to rewrite a message. */-export function addUsage(- total: MessageUsage | undefined,- next: MessageUsage | undefined,-): MessageUsage | undefined {- if (!next) return total;- if (!total) return next;- return {- inputTokens: total.inputTokens + next.inputTokens,- outputTokens: total.outputTokens + next.outputTokens,- ...(total.cacheReadTokens !== undefined || next.cacheReadTokens !== undefined- ? {- cacheReadTokens:- (total.cacheReadTokens ?? 0) + (next.cacheReadTokens ?? 0),- }- : {}),- ...(total.cacheWriteTokens !== undefined ||- next.cacheWriteTokens !== undefined- ? {- cacheWriteTokens:- (total.cacheWriteTokens ?? 0) + (next.cacheWriteTokens ?? 0),- }- : {}),- ...(total.reasoningTokens !== undefined || next.reasoningTokens !== undefined- ? {- reasoningTokens:- (total.reasoningTokens ?? 0) + (next.reasoningTokens ?? 0),- }- : {}),- totalTokens: total.totalTokens + next.totalTokens,- };-}+export { addUsage, withUsageIdentity } from "../message-usage.js";export type MessageAttachment = {kind: "image" | "file";@@ -128,6 +123,8 @@ export type UiMessage = {* report enters its context.*/parentToolCallId?: string;+ /** Immediate tool-call parent, independent of the owning Task/subagent. */+ nestedParentToolCallId?: string;/** Definition name of the subagent that produced this row. */agentName?: string;/**diff --git a/packages/shared/src/types/models.ts b/packages/shared/src/types/models.tsindex 5b21c5b9c..47d436f6b 100644--- a/packages/shared/src/types/models.ts+++ b/packages/shared/src/types/models.ts@@ -349,7 +349,7 @@ export type ModelInfo = {supportedThinkingLevels?: ThinkingLevel[];source: "bundled" | "discovered" | "user";/** Metadata catalog that supplied this row, when it is a known model. */- catalogSource?: "models.dev";+ catalogSource?: "pi" | "models.dev";};/**diff --git a/patches/@[email protected] b/patches/@[email protected]deleted file mode 100644index fc421f5cc..000000000--- a/patches/@[email protected]+++ /dev/null@@ -1,392 +0,0 @@-diff --git a/dist/agent-loop.js b/dist/agent-loop.js-index 9da16513e8d11e4bb3d7109b6f0ae4c35a3abdbd..e71adc7c61a6b9587e84d37dd04a9ce2f5834bfc 100644---- a/dist/agent-loop.js-+++ b/dist/agent-loop.js-@@ -256,6 +256,12 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc- case "toolcall_start":- case "toolcall_delta":- case "toolcall_end":-+ // Hosted web search (PI-Desktop): the pi-ai adapters push-+ // `hosted_search_update` when a provider-side search block starts-+ // or completes. Forward it like any other progress event so the-+ // application renders each search round as it happens instead of-+ // only learning about searches from the final message.-+ case "hosted_search_update":- if (partialMessage) {- partialMessage = event.partial;- context.messages[context.messages.length - 1] = partialMessage;-diff --git a/dist/agent.js b/dist/agent.js-index 209c9d3a6ed4819c0fc1591892e43caf52c941bf..d5459c927e6117a77211f940253d1fdc64b751a6 100644---- a/dist/agent.js-+++ b/dist/agent.js-@@ -1,3 +1,4 @@-+import { localRequestErrorDetails } from "@earendil-works/pi-ai";- import { createInitialSystemMessage, getCurrentSystemMessage, getCurrentSystemPrompt, toToolDeclaration, } from "@earendil-works/pi-ai";- import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";- import { getDefaultStreamFn } from "./stream-fn.js";-@@ -356,6 +357,7 @@ export class Agent {- }- }- async handleRunFailure(error, aborted) {-+ const errorDetails = aborted ? undefined : localRequestErrorDetails(error);- const failureMessage = {- role: "assistant",- content: [{ type: "text", text: "" }],-@@ -364,7 +366,8 @@ export class Agent {- model: this._state.model.id,- usage: EMPTY_USAGE,- stopReason: aborted ? "aborted" : "error",-- errorMessage: error instanceof Error ? error.message : String(error),-+ errorMessage: errorDetails?.message ?? (error instanceof Error ? error.message : String(error)),-+ ...(errorDetails ? { errorDetails } : {}),- timestamp: Date.now(),- };- await this.processEvents({ type: "message_start", message: failureMessage });-diff --git a/dist/harness/compaction/compaction.d.ts b/dist/harness/compaction/compaction.d.ts-index 85c89e80b879973e125a053f71f4044febd01744..995a28d5eedbf65227d3bd3b8ef62f3814679d68 100644---- a/dist/harness/compaction/compaction.d.ts-+++ b/dist/harness/compaction/compaction.d.ts-@@ -53,12 +53,12 @@ export interface ContextUsageEstimate {- /** Index of the message that provided usage, or null when none exists. */- lastUsageIndex: number | null;- }--/** Estimate context tokens for messages using provider usage when available. */--export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;-+/** Estimate context tokens for messages using provider usage when available. Pass `model` to scope hosted search replay projections to the estimation target. */-+export declare function estimateContextTokens(messages: AgentMessage[], model?: Model<Api>): ContextUsageEstimate;- /** Return whether context usage exceeds the configured compaction threshold. */- export declare function shouldCompact(contextTokens: number, contextWindow: number, settings: CompactionSettings): boolean;--/** Estimate token count for one message using a conservative character heuristic. */--export declare function estimateTokens(message: AgentMessage): number;-+/** Estimate token count for one message using a conservative character heuristic. Pass `model` to scope hosted search replay projections to the estimation target. */-+export declare function estimateTokens(message: AgentMessage, model?: Model<Api>): number;- /** Find the user-visible message that starts the turn containing an entry. */- export declare function findTurnStartIndex(entries: Entry[], entryIndex: number, startIndex: number): number;- /** Cut point selected for compaction. */-diff --git a/dist/harness/compaction/compaction.js b/dist/harness/compaction/compaction.js-index d430a3f966cc9624cc2e78638fd207a83a75b312..1682577b73f847324aa89f4455b27e14bace36dd 100644---- a/dist/harness/compaction/compaction.js-+++ b/dist/harness/compaction/compaction.js-@@ -1,18 +1,12 @@--import { contentText, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";-+import { contentText, retryAssistantCall, uuidv7, LocalRequestError, } from "@earendil-works/pi-ai";-+import { estimateMessageTokens, getLastAssistantUsageInfo } from "@earendil-works/pi-ai/utils/estimate";-+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";- import { getTelemetryContext } from "../context.js";- import { convertToLlm, createBranchSummaryMessage, createCompactionSummaryMessage } from "../messages.js";- import { buildContextEntries, sessionEntryToContextMessages } from "../session/context.js";- import { CompactionError, err, ok } from "../types.js";- import { addUsage } from "../utils/usage.js";- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, serializeConversation, } from "./utils.js";--function safeJsonStringify(value) {-- try {-- return JSON.stringify(value) ?? "undefined";-- }-- catch {-- return "[unserializable]";-- }--}- function extractFileOperations(messages, entries, prevCompactionIndex) {- const fileOps = createFileOps();- if (prevCompactionIndex >= 0) {-@@ -105,21 +99,14 @@ export function getLastAssistantUsage(entries) {- }- return undefined;- }--function getLastAssistantUsageInfo(messages) {-- for (let i = messages.length - 1; i >= 0; i--) {-- const usage = getAssistantUsage(messages[i]);-- if (usage)-- return { usage, index: i };-- }-- return undefined;--}- /** Estimate context tokens for messages using provider usage when available. */--export function estimateContextTokens(messages) {-+export function estimateContextTokens(messages, model) {-+ validateHostedSearchMessages(messages);- const usageInfo = getLastAssistantUsageInfo(messages);- if (!usageInfo) {- let estimated = 0;- for (const message of messages) {-- estimated += estimateTokens(message);-+ estimated += estimateTokens(message, model);- }- return {- tokens: estimated,-@@ -131,7 +118,7 @@ export function estimateContextTokens(messages) {- const usageTokens = calculateContextTokens(usageInfo.usage);- let trailingTokens = 0;- for (let i = usageInfo.index + 1; i < messages.length; i++) {-- trailingTokens += estimateTokens(messages[i]);-+ trailingTokens += estimateTokens(messages[i], model);- }- return {- tokens: usageTokens + trailingTokens,-@@ -163,30 +150,15 @@ function estimateTextAndImageContentChars(content) {- return chars;- }- /** Estimate token count for one message using a conservative character heuristic. */--export function estimateTokens(message) {-+export function estimateTokens(message, model) {- let chars = 0;- switch (message.role) {-- case "user": {-- chars = estimateTextAndImageContentChars(message.content);-- return Math.ceil(chars / 4);-- }-- case "assistant": {-- const assistant = message;-- for (const block of assistant.content) {-- if (block.type === "text") {-- chars += block.text.length;-- }-- else if (block.type === "thinking") {-- chars += block.thinking.length;-- }-- else if (block.type === "toolCall") {-- chars += block.name.length + safeJsonStringify(block.arguments).length;-- }-- }-- return Math.ceil(chars / 4);-- }-- case "custom":-- case "toolResult": {-+ case "system":-+ case "user":-+ case "assistant":-+ case "toolResult":-+ return estimateMessageTokens(message, model);-+ case "custom": {- chars = estimateTextAndImageContentChars(message.content);- return Math.ceil(chars / 4);- }-@@ -200,7 +172,7 @@ export function estimateTokens(message) {- return Math.ceil(chars / 4);- }- }-- return 0;-+ throw new LocalRequestError("context-validation");- }- function findValidCutPoints(entries, startIndex, endIndex) {- const cutPoints = [];-diff --git a/dist/harness/compaction/utils.js b/dist/harness/compaction/utils.js-index f7c6a26ac39539cfb578d79c79c071bfd9fbdcd9..a5de5589fcc9395ea2cb031453359c468f6579a0 100644---- a/dist/harness/compaction/utils.js-+++ b/dist/harness/compaction/utils.js-@@ -1,4 +1,5 @@- import { contentText } from "@earendil-works/pi-ai";-+import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";- /** Create an empty file-operation accumulator. */- export function createFileOps() {- return {-@@ -86,6 +87,7 @@ export function serializeConversation(messages) {- else if (msg.role === "assistant") {- const thinkingParts = [];- const toolCalls = [];-+ const hostedSearchParts = [];- for (const block of msg.content) {- if (block.type === "thinking") {- thinkingParts.push(block.thinking);-@@ -97,6 +99,13 @@ export function serializeConversation(messages) {- .join(", ");- toolCalls.push(`${block.name}(${argsStr})`);- }-+ else if (block.type === "hostedSearch") {-+ // Keep the hosted search replay buffer explicit: the projection is the raw wire block, never a toolCall.-+ const projection = hostedSearchReplayProjection(block);-+ if (projection !== undefined) {-+ hostedSearchParts.push(safeJsonStringify(projection));-+ }-+ }- }- if (thinkingParts.length > 0) {- parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);-@@ -107,6 +116,9 @@ export function serializeConversation(messages) {- if (toolCalls.length > 0) {- parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);- }-+ if (hostedSearchParts.length > 0) {-+ parts.push(`[Assistant hosted search]: ${hostedSearchParts.join("\n")}`);-+ }- }- else if (msg.role === "toolResult") {- const content = contentText(msg.content, "");-diff --git a/dist/harness/pico3/kinds/collapse.d.ts b/dist/harness/pico3/kinds/collapse.d.ts-index 736c315ec001a7d3b526ac019d08e59b43711205..4517456d3a141e45f03269b47ef2123edaa94b90 100644---- a/dist/harness/pico3/kinds/collapse.d.ts-+++ b/dist/harness/pico3/kinds/collapse.d.ts-@@ -1,5 +1,5 @@- import type { Context } from "@earendil-works/chord";--import { type CoreKind, type Entry, type HookInfo, type HookResult, type Id, type ModelRef, type RetryPolicy, type ThinkingLevel } from "../types.ts";-+import { type CoreKind, type Entry, type HookInfo, type HookResult, type Id, type Model, type ModelRef, type RetryPolicy, type ThinkingLevel } from "../types.ts";- export type CollapseInput = {- reason: "threshold" | "manual" | "overflow";- through: Id;-@@ -44,6 +44,7 @@ export declare const collapseConfig: {- export declare const collapse: CoreKind<CollapseInput, CollapseCheckpoint, {- summary: Id;- }, CollapseFailure, null, CollapseHooks, typeof collapseConfig>;--export declare function chooseThrough(entries: Entry[], keepRecent: number): Id | undefined;-+/** Select the collapse cutoff. Pass `model` to scope hosted search replay projections to the target model. */-+export declare function chooseThrough(entries: Entry[], keepRecent: number, model?: Model): Id | undefined;- export {};- //# sourceMappingURL=collapse.d.ts.map-\ No newline at end of file-diff --git a/dist/harness/pico3/kinds/collapse.js b/dist/harness/pico3/kinds/collapse.js-index 2fa0e3570797cedf43e2b1e2f1052bc4b62e6d9c..1a22a7d33caf1e46f7ad8930e5dd0000b2a86c9b 100644---- a/dist/harness/pico3/kinds/collapse.js-+++ b/dist/harness/pico3/kinds/collapse.js-@@ -2,7 +2,7 @@ import { estimateContextTokens } from "@earendil-works/pi-ai/utils/estimate";- import { effectiveTools } from "../system.js";- import { toStored, } from "../types.js";- import { retryDecision } from "./generation.js";--const estimate = (messages) => estimateContextTokens(messages.filter((message) => message.role !== "system")).tokens;-+const estimate = (messages, model) => estimateContextTokens(messages.filter((message) => message.role !== "system"), model).tokens;- export const collapseConfig = { rewindable: { threshold: 0, keepRecent: 20_000 } };- const failed = (reason, detail) => ({- status: "failed",-@@ -159,12 +159,12 @@ function afterFailure(base, message, detail, runtime) {- },- };- }--export function chooseThrough(entries, keepRecent) {-+export function chooseThrough(entries, keepRecent, model) {- const exchanges = [];- let open;- for (const entry of entries) {- const role = entry.model?.[0]?.role;-- const tokens = estimate((entry.model ?? []));-+ const tokens = estimate((entry.model ?? []), model);- if (role === "assistant") {- open = { last: entry.id, tokens };- exchanges.push(open);-diff --git a/dist/harness/pico3/kinds/frames.js b/dist/harness/pico3/kinds/frames.js-index f34eede37d69d0ceaad068d6a01812a1ca5fee7d..fc0191d71ee32aec8260a31a38fa7952b2e4a64b 100644---- a/dist/harness/pico3/kinds/frames.js-+++ b/dist/harness/pico3/kinds/frames.js-@@ -1,3 +1,4 @@-+import { normalizeHostedSearchContent } from "@earendil-works/pi-ai";- /**- * Apply one encoded frame to the tracked output. Same switch as pi-ai's- * reduceAssistantMessageFrames (the test oracle); no buffering, no second copy.-@@ -12,6 +13,21 @@ export function applyFrame(o, frame) {- throw new Error(`${frame.type} before start`);- const c = m.content;- switch (frame.type) {-+ case "hosted_search_update": {-+ // Search snapshots are not tool calls: preserve indices and detach mutable encoder objects.-+ const index = frame.contentIndex;-+ if (!Number.isInteger(index) || index < 0 || index > c.length)-+ throw new Error("Invalid hosted search frame content index or gap");-+ const content = normalizeHostedSearchContent(structuredClone(frame.content));-+ // Match the encoder's optional-field snapshot rather than materializing a default.-+ if (content.phase === "web_search_tool_result" && frame.content.isError === undefined)-+ delete content.isError;-+ const previous = c[index];-+ if (previous && (previous.type !== "hostedSearch" || previous.phase !== content.phase || previous.blockId !== content.blockId))-+ throw new Error("Hosted search frame changed block identity");-+ c[index] = content;-+ return;-+ }- case "text_start":- c[frame.contentIndex] = { ...frame.content };- return;-diff --git a/dist/harness/pico3/kinds/generation.js b/dist/harness/pico3/kinds/generation.js-index 01ffaa587dbf91bce9a8ade5fb5ed09e174267e3..73970f394690526941efce6714f1647499e81fb3 100644---- a/dist/harness/pico3/kinds/generation.js-+++ b/dist/harness/pico3/kinds/generation.js-@@ -1,3 +1,4 @@-+import { localRequestErrorDetails } from "@earendil-works/pi-ai";- import { AssistantMessageFrameEncoder, isRetryableAssistantError } from "@earendil-works/pi-ai";- import { estimateContextTokens } from "@earendil-works/pi-ai/utils/estimate";- import { planManagedEntry, prepareDraft, sameSnapshot, takeSnapshot } from "../system.js";-@@ -28,8 +29,8 @@ const failStep = (task, reason, detail) => ({- },- });- /** pi-ai drops system messages and aborted/error assistant messages before sending; estimate what is sent. */--const estimate = (messages) => estimateContextTokens(messages.filter((m) => m.role !== "system" &&-- !(m.role === "assistant" && (m.stopReason === "aborted" || m.stopReason === "error")))).tokens;-+const estimate = (messages, model) => estimateContextTokens(messages.filter((m) => m.role !== "system" &&-+ !(m.role === "assistant" && (m.stopReason === "aborted" || m.stopReason === "error"))), model).tokens;- const emptyUsage = () => ({- input: 0,- output: 0,-@@ -93,8 +94,8 @@ export const generation = {- if (model === undefined)- return failStep(task, "no_model", `model ${cp.model.provider}/${cp.model.modelId} unavailable`);- const derived = await derive(task, cp, rt, ctx);-- if (estimate(derived.messages) > model.contextWindow - model.maxTokens)-- return overflow(task, rt);-+ if (estimate(derived.messages, model) > model.contextWindow - model.maxTokens)-+ return overflow(task, rt, model);- const attempt = cp.attempt + 1;- await rt.commit((tx) => {- tx.checkpoint({ ...cp, phase: "requesting", attempt });-@@ -280,6 +281,7 @@ async function stream(cp, model, messages, rt, ctx) {- catch (error) {- if (ctx.abortSignal?.aborted)- throw error;-+ const errorDetails = localRequestErrorDetails(error);- terminal = {- role: "assistant",- content: [],-@@ -288,7 +290,8 @@ async function stream(cp, model, messages, rt, ctx) {- model: model.id,- usage: emptyUsage(),- stopReason: "error",-- errorMessage: String(error),-+ errorMessage: errorDetails?.message ?? String(error),-+ ...(errorDetails ? { errorDetails } : {}),- timestamp: rt.now(),- };- }-@@ -342,7 +345,7 @@ async function classify(task, cp, message, rt, ctx) {- return {- done: async (tx, current) => {- const c = current.conversationId;-- const collapseThrough = await thresholdCollapseThrough(tx, c, message); // read BEFORE the append-+ const collapseThrough = await thresholdCollapseThrough(tx, c, message, rt.models.resolve(cp.model)); // read BEFORE the append- const assistant = tx.appendEntry(c, {- kind: "pi.assistant",- model: [stored],-@@ -379,7 +382,7 @@ async function classify(task, cp, message, rt, ctx) {- return {- done: async (tx, current) => {- const c = current.conversationId;-- const collapseThrough = await thresholdCollapseThrough(tx, c, message); // read BEFORE the append-+ const collapseThrough = await thresholdCollapseThrough(tx, c, message, rt.models.resolve(cp.model)); // read BEFORE the append- const head = await tx.newestEntry(c, { withHead: true });- const assistant = tx.appendEntry(c, { kind: "pi.assistant", model: [stored], data: { attempt: cp.attempt } });- tx.emit({ type: "generation.completed", taskId: current.id, entry: assistant, toolCalls: 0 });-@@ -455,25 +458,25 @@ export function retryDecision(cp, message, now) {- // Collapse triggers- // ---------------------------------------------------------------------------- /** Read-side of threshold collapse: computed before the assistant is appended, applied after. */--async function thresholdCollapseThrough(tx, conversationId, message) {-+async function thresholdCollapseThrough(tx, conversationId, message, model) {- if ((await tx.tasks({ conversationId, kind: "pi.collapse", status: ["pending", "running"] })).length > 0)- return undefined;- const state = tx.rewindable(conversationId);- if (state.threshold <= 0)- return undefined;- const { entries, messages } = await tx.context(conversationId);-- const used = Math.max((message.usage?.input ?? 0) + (message.usage?.output ?? 0), estimate([...messages, toStored(message)]));-+ const used = Math.max((message.usage?.input ?? 0) + (message.usage?.output ?? 0), estimate([...messages, toStored(message)], model));- if (used <= state.threshold)- return undefined;-- return chooseThrough(entries, state.keepRecent);-+ return chooseThrough(entries, state.keepRecent, model);- }--function overflow(task, rt) {-+function overflow(task, rt, model) {- return {- done: async (tx, current) => {- const c = current.conversationId;- const state = tx.rewindable(c);- const { entries, head } = await tx.context(c);-- const through = chooseThrough(entries, state.keepRecent);-+ const through = chooseThrough(entries, state.keepRecent, model);- tx.sticky(c).turn = { tools: [] };- if (through === undefined) {- await tx.write(c, {diff --git a/patches/@[email protected] b/patches/@[email protected]similarity index 97%rename from patches/@[email protected]rename to patches/@[email protected]index b43ea190d..b86f94477 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,8 +1,8 @@diff --git a/dist/agent-loop.js b/dist/agent-loop.js-index 4bbd0ce..5bf74e7 100644+index edcfba73a..4374aa013 100644--- a/dist/agent-loop.js+++ b/dist/agent-loop.js-@@ -292,6 +292,12 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunc+@@ -294,6 +294,12 @@ async function streamAssistantResponse(context, config, signal, emit, streamFunccase "toolcall_start":case "toolcall_delta":case "toolcall_end":@@ -16,7 +16,7 @@ index 4bbd0ce..5bf74e7 100644partialMessage = event.partial;context.messages[context.messages.length - 1] = partialMessage;diff --git a/dist/agent.js b/dist/agent.js-index a2f462f..a3b8a7f 100644+index a8ccfc0bd..0f98e4736 100644--- a/dist/agent.js+++ b/dist/agent.js@@ -1,3 +1,4 @@@@ -24,7 +24,7 @@ index a2f462f..a3b8a7f 100644import { createInitialSystemMessage, getCurrentSystemMessage, getCurrentSystemPrompt, toToolDeclaration, } from "@earendil-works/pi-ai";import { runAgentLoop, runAgentLoopContinue } from "./agent-loop.js";import { getDefaultStreamFn } from "./stream-fn.js";-@@ -359,6 +360,7 @@ export class Agent {+@@ -362,6 +363,7 @@ export class Agent {}}async handleRunFailure(error, aborted) {@@ -32,7 +32,7 @@ index a2f462f..a3b8a7f 100644const failureMessage = {role: "assistant",content: [{ type: "text", text: "" }],-@@ -367,7 +369,8 @@ export class Agent {+@@ -370,7 +372,8 @@ export class Agent {model: this._state.model.id,usage: EMPTY_USAGE,stopReason: aborted ? "aborted" : "error",@@ -43,7 +43,7 @@ index a2f462f..a3b8a7f 100644};await this.processEvents({ type: "message_start", message: failureMessage });diff --git a/dist/harness/compaction/compaction.d.ts b/dist/harness/compaction/compaction.d.ts-index 85c89e8..995a28d 100644+index 85c89e80b..995a28d5e 100644--- a/dist/harness/compaction/compaction.d.ts+++ b/dist/harness/compaction/compaction.d.ts@@ -53,12 +53,12 @@ export interface ContextUsageEstimate {@@ -64,7 +64,7 @@ index 85c89e8..995a28d 100644export declare function findTurnStartIndex(entries: Entry[], entryIndex: number, startIndex: number): number;/** Cut point selected for compaction. */diff --git a/dist/harness/compaction/compaction.js b/dist/harness/compaction/compaction.js-index d430a3f..1682577 100644+index d430a3f96..1682577b7 100644--- a/dist/harness/compaction/compaction.js+++ b/dist/harness/compaction/compaction.js@@ -1,18 +1,12 @@@@ -171,7 +171,7 @@ index d430a3f..1682577 100644function findValidCutPoints(entries, startIndex, endIndex) {const cutPoints = [];diff --git a/dist/harness/compaction/utils.js b/dist/harness/compaction/utils.js-index f7c6a26..a5de558 100644+index f7c6a26ac..a5de5589f 100644--- a/dist/harness/compaction/utils.js+++ b/dist/harness/compaction/utils.js@@ -1,4 +1,5 @@@@ -213,7 +213,7 @@ index f7c6a26..a5de558 100644else if (msg.role === "toolResult") {const content = contentText(msg.content, "");diff --git a/dist/harness/pico3/kinds/collapse.d.ts b/dist/harness/pico3/kinds/collapse.d.ts-index 736c315..4517456 100644+index 736c315ec..4517456d3 100644--- a/dist/harness/pico3/kinds/collapse.d.ts+++ b/dist/harness/pico3/kinds/collapse.d.ts@@ -1,5 +1,5 @@@@ -234,7 +234,7 @@ index 736c315..4517456 100644//# sourceMappingURL=collapse.d.ts.map\ No newline at end of filediff --git a/dist/harness/pico3/kinds/collapse.js b/dist/harness/pico3/kinds/collapse.js-index 2fa0e35..1a22a7d 100644+index 2fa0e3570..1a22a7d33 100644--- a/dist/harness/pico3/kinds/collapse.js+++ b/dist/harness/pico3/kinds/collapse.js@@ -2,7 +2,7 @@ import { estimateContextTokens } from "@earendil-works/pi-ai/utils/estimate";@@ -262,7 +262,7 @@ index 2fa0e35..1a22a7d 100644open = { last: entry.id, tokens };exchanges.push(open);diff --git a/dist/harness/pico3/kinds/frames.js b/dist/harness/pico3/kinds/frames.js-index f34eede..fc0191d 100644+index f34eede37..fc0191d71 100644--- a/dist/harness/pico3/kinds/frames.js+++ b/dist/harness/pico3/kinds/frames.js@@ -1,3 +1,4 @@@@ -293,7 +293,7 @@ index f34eede..fc0191d 100644c[frame.contentIndex] = { ...frame.content };return;diff --git a/dist/harness/pico3/kinds/generation.js b/dist/harness/pico3/kinds/generation.js-index 01ffaa5..73970f3 100644+index 01ffaa587..73970f394 100644--- a/dist/harness/pico3/kinds/generation.js+++ b/dist/harness/pico3/kinds/generation.js@@ -1,3 +1,4 @@diff --git a/patches/@[email protected] b/patches/@[email protected]deleted file mode 100644index c55a27c04..000000000--- a/patches/@[email protected]+++ /dev/null@@ -1,1597 +0,0 @@-diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js-index d462f30bd8e5ebcbaf3cf3e0563cb0915d0d1aea..3d3dab193f57dfa82c4ab7c3bd780f22f0c0d9c7 100644---- a/dist/api/anthropic-messages.js-+++ b/dist/api/anthropic-messages.js-@@ -1,3 +1,6 @@-+import { hostedSearchReplayProjection, validateHostedSearchMessages } from "../utils/hosted-search.js";-+import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";-+import { withLocalRequestErrors } from "../utils/local-request-stream.js";- import Anthropic from "@anthropic-ai/sdk";- import { calculateCost } from "../models.js";- import { appendAssistantMessageDiagnostic } from "../utils/diagnostics.js";-@@ -332,8 +335,6 @@ async function* iterateAnthropicEvents(response, signal) {- }- export const stream = (model, context, options) => {- const stream = new AssistantMessageEventStream();-- const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);-- const currentTools = getCurrentTools(normalizedContext.messages);- (async () => {- const providerThinkingLevel = model.compat?.supportsMidConvoEffort ? (options?.effort ?? "high") : undefined;- const output = {-@@ -354,7 +355,11 @@ export const stream = (model, context, options) => {- stopReason: "pending",- timestamp: Date.now(),- };-+ let preparingRequest = true;- try {-+ const normalizedContext = resolveTranscript(context, getAnthropicCompat(model).supportsMidConvoSystemMessages);-+ validateHostedSearchMessages(normalizedContext.messages);-+ const currentTools = getCurrentTools(normalizedContext.messages);- let client;- let isOAuth;- let usageModel = model;-@@ -390,6 +395,8 @@ export const stream = (model, context, options) => {- ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),- maxRetries: 0,- };-+ JSON.stringify(params);-+ preparingRequest = false;- const response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {- maxRetries: options?.maxRetries,- maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -474,17 +481,50 @@ export const stream = (model, context, options) => {- output.content.push(block);- stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });- }-+ // Hosted web search (PI-Desktop): server-side search blocks-+ // are captured whole. The paired `server_tool_use` +-+ // `web_search_tool_result` blocks round-trip verbatim via-+ // the hostedSearch block so multi-turn conversations keep-+ // their grounding (encrypted content included).-+ else if (event.content_block.type === "server_tool_use") {-+ const block = {-+ type: "hostedSearch",-+ phase: "server_tool_use",-+ blockId: event.content_block.id,-+ name: event.content_block.name,-+ input: event.content_block.input,-+ inputJson: "",-+ index: event.index,-+ };-+ output.content.push(block);-+ stream.push({ type: "hosted_search_update", contentIndex: output.content.length - 1, partial: output });-+ }-+ else if (event.content_block.type === "web_search_tool_result" ||-+ event.content_block.type === "web_search_tool_result_error") {-+ const isError = event.content_block.type === "web_search_tool_result_error";-+ const block = {-+ type: "hostedSearch",-+ phase: "web_search_tool_result",-+ blockId: event.content_block.tool_use_id,-+ isError,-+ // The raw block is the replay payload; keep it verbatim.-+ wire: event.content_block,-+ index: event.index,-+ };-+ output.content.push(block);-+ stream.push({ type: "hosted_search_update", contentIndex: output.content.length - 1, partial: output });-+ }- }- else if (event.type === "content_block_delta") {- if (event.delta.type === "text_delta") {- const index = blocks.findIndex((b) => b.index === event.index);- const block = blocks[index];- if (block && block.type === "text") {-- block.text += event.delta.text;-+ block.text += event.delta.text ?? "";- stream.push({- type: "text_delta",- contentIndex: index,-- delta: event.delta.text,-+ delta: event.delta.text ?? "",- partial: output,- });- }-@@ -493,11 +533,11 @@ export const stream = (model, context, options) => {- const index = blocks.findIndex((b) => b.index === event.index);- const block = blocks[index];- if (block && block.type === "thinking") {-- block.thinking += event.delta.thinking;-+ block.thinking += event.delta.thinking ?? "";- stream.push({- type: "thinking_delta",- contentIndex: index,-- delta: event.delta.thinking,-+ delta: event.delta.thinking ?? "",- partial: output,- });- }-@@ -506,12 +546,24 @@ export const stream = (model, context, options) => {- const index = blocks.findIndex((b) => b.index === event.index);- const block = blocks[index];- if (block && block.type === "toolCall") {-- block.partialJson += event.delta.partial_json;-+ block.partialJson += event.delta.partial_json ?? "";- block.arguments = parseStreamingJson(block.partialJson);- stream.push({- type: "toolcall_delta",- contentIndex: index,-- delta: event.delta.partial_json,-+ delta: event.delta.partial_json ?? "",-+ partial: output,-+ });-+ }-+ // Hosted web search (PI-Desktop): server_tool_use input-+ // (the query) streams as input_json_delta like any tool-+ // call; accumulate it so the row can show the query live.-+ else if (block && block.type === "hostedSearch" && block.phase === "server_tool_use") {-+ block.inputJson = (block.inputJson ?? "") + (event.delta.partial_json ?? "");-+ block.input = parseStreamingJson(block.inputJson);-+ stream.push({-+ type: "hosted_search_update",-+ contentIndex: index,- partial: output,- });- }-@@ -521,7 +573,19 @@ export const stream = (model, context, options) => {- const block = blocks[index];- if (block && block.type === "thinking") {- block.thinkingSignature = block.thinkingSignature || "";-- block.thinkingSignature += event.delta.signature;-+ block.thinkingSignature += event.delta.signature ?? "";-+ }-+ }-+ // Hosted web search (PI-Desktop): citations arrive as deltas-+ // on the text block that follows the search result. Collect-+ // them on the message for the application to render.-+ else if (event.delta.type === "citations_delta") {-+ const citation = event.delta.citation;-+ // Document citations are not hosted-search URL citations.-+ if (citation && typeof citation === "object" && typeof citation.url === "string" && citation.url.length > 0 &&-+ (citation.title === undefined || typeof citation.title === "string")) {-+ output.hostedSearchCitations = output.hostedSearchCitations ?? [];-+ output.hostedSearchCitations.push(citation);- }- }- }-@@ -558,6 +622,12 @@ export const stream = (model, context, options) => {- partial: output,- });- }-+ // Hosted search blocks carry no streaming scratch-+ // state; closing one just drops the index marker.-+ else if (block.type === "hostedSearch") {-+ delete block.index;-+ delete block.inputJson;-+ }- }- }- else if (event.type === "message_delta") {-@@ -625,13 +695,18 @@ export const stream = (model, context, options) => {- stream.end();- }- catch (error) {-+ if (preparingRequest && !options?.signal?.aborted)-+ error = asLocalRequestError(error, "request-preparation");-+ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);-+ if (errorDetails)-+ output.errorDetails = errorDetails;- for (const block of output.content) {- delete block.index;- // partialJson is only a streaming scratch buffer; never persist it.- delete block.partialJson;- }- output.stopReason = options?.signal?.aborted ? "aborted" : "error";-- output.errorMessage = error instanceof Error ? error.message : JSON.stringify(error);-+ output.errorMessage = errorDetails?.message ?? (error instanceof Error ? error.message : JSON.stringify(error));- stream.push({ type: "error", reason: output.stopReason, error: output });- stream.end();- }-@@ -659,7 +734,7 @@ function mapThinkingLevelToEffort(model, level) {- return "high";- }- }--export const streamSimple = (model, context, options) => {-+export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {- assertRequestAuth(model.provider, options?.apiKey, options?.headers);- const base = {- ...buildBaseOptions(model, context, options, options?.apiKey),-@@ -691,7 +766,7 @@ export const streamSimple = (model, context, options) => {- thinkingEnabled: true,- thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),- });--};-+});- function isOAuthToken(apiKey) {- return apiKey.includes("sk-ant-oat");- }-@@ -868,6 +943,15 @@ function buildParams(model, context, isOAuthToken, options) {- params.tools = convertTools(tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl);- }- }-+ // Hosted web search (PI-Desktop): attach the server-side tool when the-+ // model record opts in. A hosted tool has no client execute; its blocks-+ // are extracted by the stream loop below and replayed by convertMessages.-+ if (model.webSearch === true) {-+ params.tools = [-+ ...(params.tools ?? []),-+ { type: "web_search_20250305", name: "web_search" },-+ ];-+ }- // Managed effort models always use adaptive thinking so prefix mismatches can- // be dropped instead of surfacing as persistent 400 responses.- if (model.compat?.supportsMidConvoEffort === true) {-@@ -1072,6 +1156,15 @@ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowE- input: block.arguments ?? {},- });- }-+ // Hosted web search (PI-Desktop): replay both halves of the-+ // pair in place, in their original order. `server_tool_use`-+ // carries the query; the result block carries the encrypted-+ // content Anthropic requires verbatim on later turns.-+ else if (block.type === "hostedSearch") {-+ const projection = hostedSearchReplayProjection(block, { api: "anthropic-messages" });-+ if (projection !== undefined)-+ blocks.push(projection);-+ }- }- if (blocks.length === 0)- continue;-diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-responses.js-index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d09ef5644b 100644---- a/dist/api/azure-openai-responses.js-+++ b/dist/api/azure-openai-responses.js-@@ -1,3 +1,5 @@-+import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";-+import { withLocalRequestErrors } from "../utils/local-request-stream.js";- import { AzureOpenAI } from "openai";- import { clampThinkingLevel } from "../models.js";- import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";-@@ -45,10 +47,8 @@ function formatAzureOpenAIError(error) {- */- export const stream = (model, context, options) => {- const stream = new AssistantMessageEventStream();-- const normalizedContext = resolveTranscript(context, model.compat?.supportsMidConvoSystemMessages);- // Start async processing- (async () => {-- const deploymentName = resolveDeploymentName(model, options);- const output = {- role: "assistant",- content: [],-@@ -66,7 +66,10 @@ export const stream = (model, context, options) => {- stopReason: "pending",- timestamp: Date.now(),- };-+ let preparingRequest = true;- try {-+ const normalizedContext = resolveTranscript(context, model.compat?.supportsMidConvoSystemMessages);-+ const deploymentName = resolveDeploymentName(model, options);- // Create Azure OpenAI client- const apiKey = options?.apiKey;- if (!apiKey) {-@@ -84,6 +87,8 @@ export const stream = (model, context, options) => {- ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),- maxRetries: 0,- };-+ JSON.stringify(params);-+ preparingRequest = false;- const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {- maxRetries: options?.maxRetries,- maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -105,6 +110,11 @@ export const stream = (model, context, options) => {- stream.end();- }- catch (error) {-+ if (preparingRequest && !options?.signal?.aborted)-+ error = asLocalRequestError(error, "request-preparation");-+ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);-+ if (errorDetails)-+ output.errorDetails = errorDetails;- for (const block of output.content) {- delete block.index;- // Streaming scratch buffers are only used during parsing; never persist them.-@@ -112,14 +122,14 @@ export const stream = (model, context, options) => {- delete block.customInput;- }- output.stopReason = options?.signal?.aborted ? "aborted" : "error";-- output.errorMessage = formatAzureOpenAIError(error);-+ output.errorMessage = errorDetails?.message ?? formatAzureOpenAIError(error);- stream.push({ type: "error", reason: output.stopReason, error: output });- stream.end();- }- })();- return stream;- };--export const streamSimple = (model, context, options) => {-+export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {- const apiKey = options?.apiKey;- if (!apiKey) {- throw new Error(`No API key for provider: ${model.provider}`);-@@ -134,7 +144,7 @@ export const streamSimple = (model, context, options) => {- ...base,- reasoningEffort,- });--};-+});- function normalizeAzureBaseUrl(baseUrl) {- const trimmed = baseUrl.trim().replace(/\/+$/, "");- let url;-@@ -235,6 +245,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr- if (options?.toolChoice !== undefined) {- params.tool_choice = options.toolChoice;- }-+ // Hosted web search (PI-Desktop): same opt-in as openai-responses; the-+ // azure adapter reuses the shared stream processor, which already knows-+ // how to extract web_search_call items.-+ if (model.webSearch === true) {-+ params.tools = [...(params.tools ?? []), { type: "web_search" }];-+ }- if (model.reasoning) {- if (options?.reasoningEffort || options?.reasoningSummary) {- const effort = options?.reasoningEffort-@@ -252,6 +268,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr- };- }- }-+ // Hosted web search (PI-Desktop): sources ride the opt-in `include`-+ // channel; merged here because the reasoning block above assigns-+ // `params.include` outright.-+ if (model.webSearch === true) {-+ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];-+ }- // Last so custom keys override the named request fields.- if (options?.samplingParams) {- Object.assign(params, options.samplingParams);-diff --git a/dist/api/mistral-conversations.js b/dist/api/mistral-conversations.js-index 3106c5d470dc3610c05d8ee153026df20f86f66e..8b209bb46809c394ffebfd11d5dfd2731c204310 100644---- a/dist/api/mistral-conversations.js-+++ b/dist/api/mistral-conversations.js-@@ -645,6 +645,9 @@ function toChatMessages(messages, supportsImages) {- }- continue;- }-+ // Mistral 不回放托管搜索;只把真正的客户端工具调用转换为 function。-+ if (block.type !== "toolCall")-+ continue;- toolCalls.push({- id: block.id,- type: "function",-diff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js-index fd459fddd20380242bbe37ec16e260097c9e4236..dff3e9b3d04a95eec40dd2483b297a53823afe14 100644---- a/dist/api/openai-completions.js-+++ b/dist/api/openai-completions.js-@@ -1039,21 +1039,27 @@ export function convertMessages(model, context, compat, options) {- if (preservedReasoningDetails) {- assistantMsg.reasoning_details = preservedReasoningDetails;- }-- if (compat.requiresReasoningContentOnAssistantMessages &&-- model.reasoning &&-- assistantMsg.reasoning_content === undefined) {-- assistantMsg.reasoning_content = "";-- }-+ // Catalogue-model empty fill moved to the history-wide pass below so-+ // empty-string (#223) and non-empty placeholder (strict relays) share one path.-+- // Skip assistant messages that have no content and no tool calls.- // Some providers require "either content or tool_calls, but not none".- // Other providers also don't accept empty assistant messages.- // This handles aborted assistant responses that got no content.-+ // Keep reasoning-only assistants (#296 retained thinking): map a-+ // minimal content stand-in so the already-set reasoning_* field-+ // still reaches the wire.- const content = assistantMsg.content;- const hasContent = content !== null &&- content !== undefined &&- (typeof content === "string" ? content.length > 0 : content.length > 0);-+ const hasReasoningReplay = OPENAI_COMPLETIONS_REASONING_FIELDS.some((field) => typeof assistantMsg[field] === "string" &&-+ assistantMsg[field].length > 0);- if (!hasContent && !assistantMsg.tool_calls) {-- continue;-+ if (!hasReasoningReplay) {-+ continue;-+ }-+ assistantMsg.content = ".";- }- params.push(assistantMsg);- }-@@ -1121,6 +1127,41 @@ export function convertMessages(model, context, compat, options) {- }- lastRole = msg.role;- }-+ // DeepSeek-style endpoints reject a history in which only some assistant-+ // messages carry a reasoning field, while all-or-none is accepted. Prefer-+ // the field already present on the history (reasoning_content,-+ // reasoning_text, or reasoning). Relayed models outside the catalogue are-+ // often not flagged `reasoning`, so this pass also covers them (#223).-+ // Official DeepSeek accepts ""; OpenCode/third-party relays that require a-+ // real echo set requiresNonEmptyReasoningReplay and receive a documented-+ // placeholder instead of a silent empty string (#296).-+ // Placeholder text must match DEEPSEEK_REASONING_REPLAY_PLACEHOLDER in-+ // @pi-desktop/shared provider-presets.-+ const reasoningFields = ["reasoning_content", "reasoning_text", "reasoning"];-+ if (compat.requiresReasoningContentOnAssistantMessages) {-+ let activeField;-+ for (const field of reasoningFields) {-+ if (params.some((m) => m.role === "assistant" &&-+ typeof m[field] === "string" &&-+ m[field].length > 0)) {-+ activeField = field;-+ break;-+ }-+ }-+ if (!activeField && model.reasoning) {-+ activeField = "reasoning_content";-+ }-+ if (activeField) {-+ const fill = compat.requiresNonEmptyReasoningReplay-+ ? "[reasoning not retained for this turn]"-+ : "";-+ for (const m of params) {-+ if (m.role === "assistant" && m[activeField] === undefined) {-+ m[activeField] = fill;-+ }-+ }-+ }-+ }- return params;- }- function convertTools(tools, compat) {-@@ -1265,6 +1306,9 @@ function detectCompat(model) {- requiresAssistantAfterToolResult: false,- requiresThinkingAsText: false,- requiresReasoningContentOnAssistantMessages: isDeepSeek,-+ // Relays that reject an empty reasoning echo must set this explicitly:-+ // no endpoint can be auto-detected as requiring a real one.-+ requiresNonEmptyReasoningReplay: undefined,- thinkingFormat: isDeepSeek- ? "deepseek"- : isZai-@@ -1317,6 +1361,8 @@ function getCompat(model) {- requiresThinkingAsText: model.compat.requiresThinkingAsText ?? detected.requiresThinkingAsText,- requiresReasoningContentOnAssistantMessages: model.compat.requiresReasoningContentOnAssistantMessages ??- detected.requiresReasoningContentOnAssistantMessages,-+ requiresNonEmptyReasoningReplay: model.compat.requiresNonEmptyReasoningReplay ??-+ detected.requiresNonEmptyReasoningReplay,- thinkingFormat: model.compat.thinkingFormat ?? detected.thinkingFormat,- openRouterRouting: model.compat.openRouterRouting ?? {},- vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,-diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js-index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c8173ad108a 100644---- a/dist/api/openai-responses-shared.js-+++ b/dist/api/openai-responses-shared.js-@@ -1,3 +1,4 @@-+import { hostedSearchReplayProjection, validateHostedSearchMessages } from "../utils/hosted-search.js";- import { calculateCost } from "../models.js";- import { shortHash } from "../utils/hash.js";- import { parseStreamingJson } from "../utils/json-parse.js";-@@ -62,6 +63,7 @@ function convertToolResultOutput(model, content) {- // =============================================================================- export function convertResponsesMessages(model, context, allowedToolCallProviders, options) {- const normalizedContext = resolveTranscript(context, options?.supportsMidConvoSystemMessages);-+ validateHostedSearchMessages(normalizedContext.messages);- const messages = [];- const normalizeIdPart = (part) => {- const sanitized = part.replace(/[^a-zA-Z0-9_-]/g, "_");-@@ -202,6 +204,13 @@ export function convertResponsesMessages(model, context, allowedToolCallProvider- phase: parsedSignature?.phase,- });- }-+ // Hosted web search (PI-Desktop): replay the search item in-+ // place so follow-up turns keep the search state.-+ else if (block.type === "hostedSearch") {-+ const projection = hostedSearchReplayProjection(block, { api: "openai-responses", isSameModel });-+ if (projection !== undefined)-+ output.push(projection);-+ }- else if (block.type === "toolCall") {- const toolCall = block;- const [callId, itemIdRaw] = toolCall.id.split("|");-@@ -405,6 +414,28 @@ export async function processResponsesStream(openaiStream, output, stream, model- stream.push({ type: "toolcall_start", contentIndex: slot.contentIndex, partial: output });- return slot;- }-+ // Hosted web search (PI-Desktop): a server-side search call. The raw-+ // item is kept whole; `response.web_search_call.*` status events and-+ // the done item update the same slot. Replay pushes the item back as-+ // an output item so multi-turn search state survives.-+ if (item.type === "web_search_call") {-+ const block = {-+ type: "hostedSearch",-+ phase: "web_search_call",-+ blockId: item.id,-+ status: item.status ?? "in_progress",-+ wire: item,-+ };-+ output.content.push(block);-+ const slot = {-+ type: "hostedSearch",-+ block,-+ contentIndex: output.content.length - 1,-+ };-+ outputSlots.set(outputIndex, slot);-+ stream.push({ type: "hosted_search_update", contentIndex: slot.contentIndex, partial: output });-+ return slot;-+ }- return undefined;- };- const getOrCreateSlot = (outputIndex, item) => {-@@ -485,11 +516,11 @@ export async function processResponsesStream(openaiStream, output, stream, model- const slot = getSlot(event.output_index, "thinking");- if (!slot)- continue;-- slot.block.thinking += event.delta;-+ slot.block.thinking += event.delta ?? "";- stream.push({- type: "thinking_delta",- contentIndex: slot.contentIndex,-- delta: event.delta,-+ delta: event.delta ?? "",- partial: output,- });- }-@@ -509,11 +540,11 @@ export async function processResponsesStream(openaiStream, output, stream, model- const slot = getSlot(event.output_index, "thinking");- if (!slot)- continue;-- slot.block.thinking += event.delta;-+ slot.block.thinking += event.delta ?? "";- stream.push({- type: "thinking_delta",- contentIndex: slot.contentIndex,-- delta: event.delta,-+ delta: event.delta ?? "",- partial: output,- });- }-@@ -521,23 +552,44 @@ export async function processResponsesStream(openaiStream, output, stream, model- const slot = getSlot(event.output_index, "text");- if (!slot)- continue;-- slot.block.text += event.delta;-+ slot.block.text += event.delta ?? "";- stream.push({- type: "text_delta",- contentIndex: slot.contentIndex,-- delta: event.delta,-+ delta: event.delta ?? "",- partial: output,- });- }-+ // Hosted web search (PI-Desktop): citation annotations arrive while-+ // the text streams. They are collected on the output message so the-+ // application can render sources without parsing text offsets.-+ else if (event.type === "response.output_text.annotation.added") {-+ const annotation = event.annotation;-+ if (annotation?.type === "url_citation" && typeof annotation.url === "string") {-+ output.hostedSearchCitations = output.hostedSearchCitations ?? [];-+ output.hostedSearchCitations.push({-+ url: annotation.url,-+ title: typeof annotation.title === "string" ? annotation.title : undefined,-+ });-+ }-+ }-+ // Hosted web search status transitions (`response.web_search_call.in_progress`-+ // / `.completed` / `.failed`); the payload mirrors the item.-+ else if (typeof event.type === "string" && event.type.startsWith("response.web_search_call.")) {-+ const item = event.item ?? event.output_item;-+ if (item && typeof item === "object" && item.type === "web_search_call") {-+ getOrCreateSlot(event.output_index, item);-+ }-+ }- else if (event.type === "response.refusal.delta") {- const slot = getSlot(event.output_index, "text");- if (!slot)- continue;-- slot.block.text += event.delta;-+ slot.block.text += event.delta ?? "";- stream.push({- type: "text_delta",- contentIndex: slot.contentIndex,-- delta: event.delta,-+ delta: event.delta ?? "",- partial: output,- });- }-@@ -545,9 +597,9 @@ export async function processResponsesStream(openaiStream, output, stream, model- const slot = getSlot(event.output_index, "toolCall");- if (!slot || slot.block.partialJson === undefined)- continue;-- slot.block.partialJson += event.delta;-+ slot.block.partialJson += event.delta ?? "";- slot.block.arguments = parseStreamingJson(slot.block.partialJson);-- pushToolCallDelta(slot, event.delta);-+ pushToolCallDelta(slot, event.delta ?? "");- }- else if (event.type === "response.function_call_arguments.done") {- const slot = getSlot(event.output_index, "toolCall");-@@ -633,9 +685,25 @@ export async function processResponsesStream(openaiStream, output, stream, model- });- outputSlots.delete(event.output_index);- }-+ // Hosted web search (PI-Desktop): finalize the slot with the-+ // done item so replay carries the server's final representation.-+ else if (item.type === "web_search_call" && slot?.type === "hostedSearch") {-+ slot.block.status = item.status ?? slot.block.status;-+ slot.block.wire = item;-+ stream.push({-+ type: "hosted_search_update",-+ contentIndex: slot.contentIndex,-+ partial: output,-+ });-+ outputSlots.delete(event.output_index);-+ }- }- else if (event.type === "response.completed" || event.type === "response.incomplete") {- finalizeResponse(event.response);-+ // The response is fully delivered: stop consuming the stream so the-+ // request does not hang when the server (or a reverse proxy) never-+ // closes the connection after the terminal event.-+ break;- }- else if (event.type === "error") {- throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");-diff --git a/dist/api/openai-responses.js b/dist/api/openai-responses.js-index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15bc29cdf4 100644---- a/dist/api/openai-responses.js-+++ b/dist/api/openai-responses.js-@@ -1,3 +1,5 @@-+import { asLocalRequestError, localRequestErrorDetails } from "../utils/local-request-error.js";-+import { withLocalRequestErrors } from "../utils/local-request-stream.js";- import OpenAI from "openai";- import { clampThinkingLevel } from "../models.js";- import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";-@@ -81,7 +83,6 @@ function getPromptCacheOptions(compat, cacheRetention) {- */- export const stream = (model, context, options) => {- const stream = new AssistantMessageEventStream();-- const normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);- // Start async processing- (async () => {- const output = {-@@ -101,7 +102,9 @@ export const stream = (model, context, options) => {- stopReason: "pending",- timestamp: Date.now(),- };-+ let preparingRequest = true;- try {-+ const normalizedContext = resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages);- // Create OpenAI client- const apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);- const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);-@@ -119,6 +122,9 @@ export const stream = (model, context, options) => {- ...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),- maxRetries: 0,- };-+ // 在进入网络边界前验证可序列化性,不把网络 TypeError 当作本地错误。-+ JSON.stringify(params);-+ preparingRequest = false;- const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {- maxRetries: options?.maxRetries,- maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -144,6 +150,11 @@ export const stream = (model, context, options) => {- stream.end();- }- catch (error) {-+ if (preparingRequest && !options?.signal?.aborted)-+ error = asLocalRequestError(error, "request-preparation");-+ const errorDetails = options?.signal?.aborted ? undefined : localRequestErrorDetails(error);-+ if (errorDetails)-+ output.errorDetails = errorDetails;- for (const block of output.content) {- delete block.index;- // Streaming scratch buffers are only used during parsing; never persist them.-@@ -151,14 +162,14 @@ export const stream = (model, context, options) => {- delete block.customInput;- }- output.stopReason = options?.signal?.aborted ? "aborted" : "error";-- output.errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);-+ output.errorMessage = errorDetails?.message ?? formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);- stream.push({ type: "error", reason: output.stopReason, error: output });- stream.end();- }- })();- return stream;- };--export const streamSimple = (model, context, options) => {-+export const streamSimple = (model, context, options) => withLocalRequestErrors(model, options, () => {- getClientApiKey(model.provider, options?.apiKey, options?.headers);- const base = {- ...buildBaseOptions(model, context, options, options?.apiKey),-@@ -170,7 +181,7 @@ export const streamSimple = (model, context, options) => {- ...base,- reasoningEffort,- });--};-+});- function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId) {- const compat = getCompat(model);- const headers = { "User-Agent": getPiUserAgent(), ...model.headers };-@@ -242,6 +253,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar- supportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,- });- }-+ // Hosted web search (PI-Desktop): attach the server-side tool when the-+ // model record opts in. The Responses `web_search` tool definition is a-+ // bare tagged object; it never passes through convertResponsesTools.-+ if (model.webSearch === true) {-+ params.tools = [...(params.tools ?? []), { type: "web_search" }];-+ }- if (options?.toolChoice !== undefined) {- params.tool_choice = options.toolChoice;- }-@@ -264,6 +281,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar- if (model.provider === "xai")- params.include = ["reasoning.encrypted_content"];- }-+ // Hosted web search (PI-Desktop): sources ride the opt-in `include`-+ // channel; merged here because the reasoning block above assigns-+ // `params.include` outright.-+ if (model.webSearch === true) {-+ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];-+ }- // Last so custom keys override the named request fields.- if (options?.samplingParams) {- Object.assign(params, options.samplingParams);-diff --git a/dist/api/simple-options.js b/dist/api/simple-options.js-index 216a45feebc02acef047d1ff133729fb0751b76c..23528b801d65e33d22eb1d63ea49945d24a5e658 100644---- a/dist/api/simple-options.js-+++ b/dist/api/simple-options.js-@@ -4,7 +4,7 @@ const MIN_MAX_TOKENS = 1;- export function clampMaxTokensToContext(model, context, maxTokens) {- if (model.contextWindow <= 0)- return Math.max(MIN_MAX_TOKENS, maxTokens);-- const available = model.contextWindow - estimateContextTokens(context).tokens - CONTEXT_SAFETY_TOKENS;-+ const available = model.contextWindow - estimateContextTokens(context, model).tokens - CONTEXT_SAFETY_TOKENS;- return Math.min(maxTokens, Math.max(MIN_MAX_TOKENS, available));- }- export function buildBaseOptions(model, context, options, apiKey) {-diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js-index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ed7e81f2a 100644---- a/dist/auth/oauth/anthropic.js-+++ b/dist/auth/oauth/anthropic.js-@@ -140,21 +140,90 @@ async function startCallbackServer(expectedState) {- });- });- }--async function postJson(url, body, signal) {-- const response = await fetch(url, {-- method: "POST",-- headers: {-- "Content-Type": "application/json",-- Accept: "application/json",-- },-- body: JSON.stringify(body),-- signal: AbortSignal.any([signal, AbortSignal.timeout(30_000)]),-+class AnthropicOAuthTokenError extends Error {-+ constructor(status, code, grantType) {-+ const recovery = grantType === "authorization_code"-+ ? "Wait, close this dialog, and start a new sign-in attempt."-+ : "Wait before retrying. If the problem continues, sign in again.";-+ const reason = code === "invalid_grant"-+ ? "Anthropic rejected the authorization grant. Please sign in again."-+ : code === "invalid_response"-+ ? `Anthropic returned an invalid token response. ${recovery}`-+ : status === 429-+ ? `Anthropic token requests are rate limited. ${recovery}`-+ : `Anthropic token request failed (HTTP ${status}). ${recovery}`;-+ super(reason);-+ this.name = "AnthropicOAuthTokenError";-+ this.status = status;-+ this.code = code;-+ }-+}-+function tokenRetryDelay(header, attempt) {-+ const fallback = 1000 * 2 ** attempt;-+ const value = header?.trim();-+ if (!value || value.length > 128)-+ return fallback;-+ const serverDelay = /^\d+$/.test(value)-+ ? Number(value) * 1000-+ : /^[A-Za-z]{3}, /.test(value)-+ ? Date.parse(value) - Date.now()-+ : NaN;-+ return Number.isNaN(serverDelay) ? fallback : Math.max(fallback, serverDelay);-+}-+function waitForTokenRetry(delay, signal) {-+ signal.throwIfAborted();-+ return new Promise((resolve, reject) => {-+ const timer = setTimeout(() => {-+ signal.removeEventListener("abort", abort);-+ resolve();-+ }, delay);-+ const abort = () => {-+ clearTimeout(timer);-+ signal.removeEventListener("abort", abort);-+ reject(signal.reason);-+ };-+ signal.addEventListener("abort", abort, { once: true });- });-- const responseBody = await response.text();-- if (!response.ok) {-- throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);-+}-+async function postJson(url, body, signal) {-+ // Keep one deadline for all attempts, including response bodies and waits.-+ // The caller's signal can impose an earlier refresh deadline or cancellation.-+ const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30_000)]);-+ const deadline = performance.now() + 30_000;-+ const serialized = JSON.stringify(body);-+ for (let attempt = 0; ; attempt++) {-+ requestSignal.throwIfAborted();-+ const response = await fetch(url, {-+ method: "POST",-+ headers: {-+ "Content-Type": "application/json",-+ Accept: "application/json",-+ },-+ body: serialized,-+ signal: requestSignal,-+ });-+ const responseBody = await response.text();-+ if (response.ok)-+ return responseBody;-+ // Never put a token endpoint's response body in an error or log.-+ let invalidGrant = false;-+ try {-+ const data = JSON.parse(responseBody);-+ invalidGrant = data?.error === "invalid_grant" || data?.error?.type === "invalid_grant";-+ }-+ catch { /* Non-JSON errors are reported by status only. */ }-+ const failure = new AnthropicOAuthTokenError(response.status,-+ invalidGrant ? "invalid_grant" : response.status === 429 ? "rate_limited" : "http_error",-+ body.grant_type);-+ // Only an explicit rate-limit rejection is replayed. Network errors,-+ // 5xx and invalid_grant may follow a consumed/rotated grant: do not retry.-+ if (response.status !== 429 || invalidGrant || attempt >= 2)-+ throw failure;-+ const delay = tokenRetryDelay(response.headers.get("Retry-After"), attempt);-+ if (delay >= deadline - performance.now())-+ throw failure; // Never shorten the server's requested wait.-+ await waitForTokenRetry(delay, requestSignal);- }-- return responseBody;- }- async function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {- let responseBody;-@@ -169,6 +238,8 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig- }, signal);- }- catch (error) {-+ if (error instanceof AnthropicOAuthTokenError || error?.name === "AbortError" || error?.name === "TimeoutError")-+ throw error;- throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`);- }- let tokenData;-@@ -176,7 +247,7 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig- tokenData = JSON.parse(responseBody);- }- catch (error) {-- throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);-+ throw new AnthropicOAuthTokenError(0, "invalid_response", "authorization_code");- }- return {- type: "oauth",-@@ -280,6 +351,8 @@ async function refreshAnthropicToken(refreshToken, signal) {- }, signal);- }- catch (error) {-+ if (error instanceof AnthropicOAuthTokenError || error?.name === "AbortError" || error?.name === "TimeoutError")-+ throw error;- throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);- }- let data;-@@ -287,7 +360,7 @@ async function refreshAnthropicToken(refreshToken, signal) {- data = JSON.parse(responseBody);- }- catch (error) {-- throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`);-+ throw new AnthropicOAuthTokenError(0, "invalid_response", "refresh_token");- }- return {- type: "oauth",-diff --git a/dist/index.d.ts b/dist/index.d.ts-index 5e8403dd62895d30eb7d8e3f95b87d6535221839..50f728e4427e1cadb9aded7e35f3e44611eefc85 100644---- a/dist/index.d.ts-+++ b/dist/index.d.ts-@@ -34,4 +34,7 @@ export * from "./utils/transcript.ts";- export * from "./utils/typebox-helpers.ts";- export { uuidv7 } from "./utils/uuid.ts";- export * from "./utils/validation.ts";-+export { LocalRequestError, localRequestErrorDetails } from "./utils/local-request-error.ts";-+export type { LocalRequestErrorDetails, LocalRequestErrorPhase } from "./utils/local-request-error.ts";-+export * from "./utils/hosted-search.ts";- //# sourceMappingURL=index.d.ts.map-\ No newline at end of file-diff --git a/dist/index.js b/dist/index.js-index cf46c043b854412d56c5d65230a509165229806e..0fe002385c3d9906709be1cce6867d0c30a3a151 100644---- a/dist/index.js-+++ b/dist/index.js-@@ -21,4 +21,6 @@ export * from "./utils/transcript.js";- export * from "./utils/typebox-helpers.js";- export { uuidv7 } from "./utils/uuid.js";- export * from "./utils/validation.js";-+export { LocalRequestError, localRequestErrorDetails } from "./utils/local-request-error.js";-+export * from "./utils/hosted-search.js";- //# sourceMappingURL=index.js.map-\ No newline at end of file-diff --git a/dist/types.d.ts b/dist/types.d.ts-index 49f2a3262e19aea105f95424cdec08444a7f5748..a4d5e56dce4c4ba654b6c4cee1bb516c3d41580f 100644---- a/dist/types.d.ts-+++ b/dist/types.d.ts-@@ -267,6 +267,30 @@ export interface ToolCall {- /** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */- namespace?: string;- }-+export interface HostedSearchCitation {-+ url: string;-+ title?: string;-+}-+export type HostedSearchContent = {-+ type: "hostedSearch";-+ phase: "server_tool_use";-+ blockId: string;-+ name: string;-+ input: JsonObject;-+} | {-+ type: "hostedSearch";-+ phase: "web_search_tool_result";-+ blockId: string;-+ isError?: boolean;-+ wire: JsonObject;-+} | {-+ type: "hostedSearch";-+ phase: "web_search_call";-+ blockId: string;-+ status?: string;-+ /** Legacy records without wire replay the minimal completed search item. */-+ wire?: JsonObject;-+};- export interface Usage {- input: number;- output: number;-@@ -352,7 +376,7 @@ export interface UserMessage {- }- export interface AssistantMessage {- role: "assistant";-- content: (TextContent | ThinkingContent | ToolCall)[];-+ content: (TextContent | ThinkingContent | ToolCall | HostedSearchContent)[];- api: Api;- provider: ProviderId;- model: string;-@@ -365,6 +389,8 @@ export interface AssistantMessage {- stopReason: StopReason;- deferred?: DeferredHandle;- errorMessage?: string;-+ errorDetails?: import("./utils/local-request-error.ts").LocalRequestErrorDetails;-+ hostedSearchCitations?: HostedSearchCitation[];- rawStopReason?: string;- /**- * Provider indication of whether the model explicitly ended its turn.-@@ -512,6 +538,10 @@ export type AssistantMessageEvent = {- contentIndex: number;- toolCall: ToolCall;- partial: AssistantMessage;-+} | {-+ type: "hosted_search_update";-+ contentIndex: number;-+ partial: AssistantMessage;- } | {- type: "done";- reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;-@@ -546,6 +576,12 @@ export interface OpenAICompletionsCompat {- requiresThinkingAsText?: boolean;- /** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. Default: auto-detected from URL. */- requiresReasoningContentOnAssistantMessages?: boolean;-+ /**-+ * Whether a replayed assistant message that carries no reasoning must send a documented-+ * non-empty placeholder instead of an empty string. Some relays reject the empty echo.-+ * Default: false; only an explicit model.compat opt-in enables it.-+ */-+ requiresNonEmptyReasoningReplay?: boolean;- /** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "deepseek" uses thinking: { type } plus reasoning_effort when supported, "together" uses reasoning: { enabled } plus reasoning_effort when supported, "baseten" uses configurable chat_template_args plus reasoning_effort when supported, "zai" uses thinking: { type }, "qwen" uses top-level enable_thinking: boolean, "qwen-chat-template" uses chat_template_kwargs.enable_thinking and preserve_thinking, "chat-template" uses configurable chat_template_kwargs, "string-thinking" uses top-level thinking: string, and "ant-ling" uses reasoning: { effort } only when the mapped effort is non-null. Default: "openai". */- thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "baseten" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling";- /** Kwargs to send as `chat_template_kwargs` when `thinkingFormat` is `chat-template`. Use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values. */-@@ -789,6 +825,8 @@ export interface Model<TApi extends Api> {- provider: ProviderId;- baseUrl: string;- reasoning: boolean;-+ /** Opt in to hosted search on the existing Anthropic/Responses adapters. */-+ webSearch?: boolean;- /**- * Maps pi thinking levels to provider/model-specific values.- * Missing keys use provider defaults. null marks a level as unsupported.-diff --git a/dist/utils/assistant-message-frame.d.ts b/dist/utils/assistant-message-frame.d.ts-index 08207197acab532d0f5f596363700a2d15a687d8..0584f6898e1d842c4414869b9080505b63c3a7b7 100644---- a/dist/utils/assistant-message-frame.d.ts-+++ b/dist/utils/assistant-message-frame.d.ts-@@ -1,4 +1,4 @@--import type { AssistantMessage, AssistantMessageEvent, TextContent, ThinkingContent, ToolCall } from "../types.ts";-+import type { AssistantMessage, AssistantMessageEvent, HostedSearchContent, TextContent, ThinkingContent, ToolCall } from "../types.ts";- /**- * Compact, replayable assistant-message progress. Terminal settlement is- * intentionally excluded and must be persisted separately.-@@ -53,6 +53,11 @@ export type AssistantMessageFrame = {- arguments: ToolCall["arguments"];- thoughtSignature?: string;- namespace?: string;-+} | {-+ type: "hosted_search_update";-+ contentIndex: number;-+ /** Complete detached snapshot, replacing the same search block on later updates. */-+ content: HostedSearchContent;- };- /**- * Encodes one assistant stream. `partial` remains a shared live accumulator;-diff --git a/dist/utils/assistant-message-frame.js b/dist/utils/assistant-message-frame.js-index c0e00197b2bdd4c815106daa036d844c07aca800..a86f5939accd25110d7a4d1e0d268646691d321d 100644---- a/dist/utils/assistant-message-frame.js-+++ b/dist/utils/assistant-message-frame.js-@@ -1,15 +1,30 @@-+import { normalizeHostedSearchContent } from "./hosted-search.js";- import { parseStreamingJson } from "./json-parse.js";-+-+// A gateway that re-serializes provider events with `omitempty` (Go) or drops-+// `undefined` (JS) hands a text / thinking / tool-call delta over with the-+// string field missing. The frame protocol requires a string there, and the only-+// value that can be dropped that way is the empty one, so a non-string payload-+// reads as "". Reading `.length` off it used to throw a bare TypeError that the-+// runtime surfaced as a retriable provider failure and then reproduced on every-+// later turn of the session.-+function textValue(value) {-+ return typeof value === "string" ? value : "";-+}-+function textLength(value) {-+ return typeof value === "string" ? value.length : 0;-+}- function cloneTextContent(content) {- return {- type: "text",-- text: content.text,-+ text: textValue(content.text),- ...(content.textSignature === undefined ? {} : { textSignature: content.textSignature }),- };- }- function cloneThinkingContent(content) {- return {- type: "thinking",-- thinking: content.thinking,-+ thinking: textValue(content.thinking),- ...(content.thinkingSignature === undefined ? {} : { thinkingSignature: content.thinkingSignature }),- ...(content.redacted === undefined ? {} : { redacted: content.redacted }),- };-@@ -24,6 +39,24 @@ function cloneToolCall(toolCall) {- ...(toolCall.namespace === undefined ? {} : { namespace: toolCall.namespace }),- };- }-+function cloneHostedSearchContent(content) {-+ const block = normalizeHostedSearchContent(content);-+ const base = { type: "hostedSearch", phase: block.phase, blockId: block.blockId };-+ // Deep-copy declared wire/input fields so mutable partials and parser buffers cannot alter old frames.-+ if (block.phase === "server_tool_use")-+ return { ...base, name: block.name, input: structuredClone(block.input) };-+ if (block.phase === "web_search_tool_result")-+ return { ...base, ...(content.isError === undefined ? {} : { isError: block.isError }), wire: structuredClone(block.wire) };-+ return {-+ ...base,-+ ...(block.status === undefined ? {} : { status: block.status }),-+ ...(block.wire == null ? {} : { wire: structuredClone(block.wire) }),-+ };-+}-+function assertSameHostedSearch(previous, current) {-+ if (previous.phase !== current.phase || previous.blockId !== current.blockId)-+ throw new Error("Hosted search update changes block identity");-+}- function cloneStartMessage(message) {- return {- role: "assistant",-@@ -105,6 +138,19 @@ export class AssistantMessageFrameEncoder {- if (!this.started)- throw new Error(`Assistant message ${event.type} event appears before start`);- switch (event.type) {-+ case "hosted_search_update": {-+ const content = cloneHostedSearchContent(eventBlock(event));-+ const state = this.blocks.get(event.contentIndex);-+ if (state === undefined) {-+ this.startBlock(event.contentIndex, { kind: "hostedSearch", phase: content.phase, blockId: content.blockId });-+ }-+ else {-+ this.block(event.contentIndex, "hostedSearch");-+ assertSameHostedSearch(state, content);-+ }-+ // Search events are snapshots: completed wire data can arrive later without a synthetic end state.-+ return { type: "hosted_search_update", contentIndex: event.contentIndex, content };-+ }- case "text_start": {- const content = eventBlock(event);- if (content.type !== "text") {-@@ -112,7 +158,7 @@ export class AssistantMessageFrameEncoder {- }- this.startBlock(event.contentIndex, {- kind: "text",-- coveredChars: content.text.length,-+ coveredChars: textLength(content.text),- deltaChars: 0,- });- return { type: "text_start", contentIndex: event.contentIndex, content: cloneTextContent(content) };-@@ -139,7 +185,7 @@ export class AssistantMessageFrameEncoder {- }- this.startBlock(event.contentIndex, {- kind: "thinking",-- coveredChars: content.thinking.length,-+ coveredChars: textLength(content.thinking),- deltaChars: 0,- });- return {-@@ -183,12 +229,13 @@ export class AssistantMessageFrameEncoder {- const state = this.block(event.contentIndex, "toolCall");- if (state.kind !== "toolCall")- throw new Error("Unreachable tool-call encoder state");-+ const delta = textValue(event.delta);- if (state.caughtUp) {-- return event.delta.length === 0-+ return delta.length === 0- ? undefined-- : { type: "toolcall_delta", contentIndex: event.contentIndex, delta: event.delta };-+ : { type: "toolcall_delta", contentIndex: event.contentIndex, delta };- }-- state.catchupJson += event.delta;-+ state.catchupJson += delta;- const argumentsValue = parseStreamingJson(state.catchupJson);- if (serializedArguments(argumentsValue) !== state.snapshotArguments) {- // Legacy grammar calls include the initial input in toolcall_start, but their-@@ -254,12 +301,13 @@ export class AssistantMessageFrameEncoder {- const state = this.block(contentIndex, kind);- if (state.kind === "toolCall")- throw new Error("Unreachable text encoder state");-+ const text = textValue(delta);- const deltaStart = state.deltaChars;-- state.deltaChars += delta.length;-+ state.deltaChars += text.length;- const covered = Math.max(0, state.coveredChars - deltaStart);-- if (covered >= delta.length)-+ if (covered >= text.length)- return undefined;-- const uncovered = covered === 0 ? delta : delta.slice(covered);-+ const uncovered = covered === 0 ? text : text.slice(covered);- return kind === "text"- ? { type: "text_delta", contentIndex, delta: uncovered }- : { type: "thinking_delta", contentIndex, delta: uncovered };-@@ -311,6 +359,20 @@ export function reduceAssistantMessageFrames(frames) {- continue;- }- switch (frame.type) {-+ case "hosted_search_update": {-+ const content = cloneHostedSearchContent(frame.content);-+ assertContentIndex(frame.contentIndex);-+ if (frame.contentIndex >= message.content.length) {-+ // Preserve the original content index; appendBlock still rejects actual gaps.-+ appendBlock(message, states, frame.contentIndex, content, { kind: "hostedSearch", ended: false });-+ }-+ else {-+ const { block } = activeBlock(message, states, frame.contentIndex, "hostedSearch", frame.type);-+ assertSameHostedSearch(block, content);-+ message.content[frame.contentIndex] = content;-+ }-+ break;-+ }- case "text_start":- if (frame.content.type !== "text") {- throw new Error(`text_start frame contains ${frame.content.type} content`);-diff --git a/dist/utils/estimate.d.ts b/dist/utils/estimate.d.ts-index 6dcca6eff16b95b83e047a6e27b65d9d7694bf2c..5ccaaf2358a0afeea3ce354e5799255ae8508f3d 100644---- a/dist/utils/estimate.d.ts-+++ b/dist/utils/estimate.d.ts-@@ -1,4 +1,4 @@--import type { ImageContent, Message, TextContent, TranscriptContext, Usage } from "../types.ts";-+import type { Api, Model, ImageContent, Message, TextContent, TranscriptContext, Usage } from "../types.ts";- export interface ContextUsageEstimate {- /** Estimated total context tokens. */- tokens: number;-@@ -12,6 +12,7 @@ export interface ContextUsageEstimate {- export declare function calculateContextTokens(usage: Usage): number;- export declare function estimateTextTokens(text: string): number;- export declare function estimateTextAndImageContentTokens(content: string | Array<TextContent | ImageContent>): number;--export declare function estimateMessageTokens(message: Message): number;--export declare function estimateContextTokens(context: TranscriptContext | readonly Message[]): ContextUsageEstimate;-+export declare function estimateMessageTokens(message: Message, model?: Model<Api>): number;-+export declare function estimateContextTokens(context: TranscriptContext | readonly Message[], model?: Model<Api>): ContextUsageEstimate;-+export declare function getLastAssistantUsageInfo(messages: readonly { role: string; timestamp: number }[]): { usage: Usage; index: number } | undefined;- //# sourceMappingURL=estimate.d.ts.map-\ No newline at end of file-diff --git a/dist/utils/estimate.js b/dist/utils/estimate.js-index d04ff22cbe8d7357404b938e228b8e3a2dbdcb1d..28564cc73798163f7590290123b7476573d5bee5 100644---- a/dist/utils/estimate.js-+++ b/dist/utils/estimate.js-@@ -1,95 +1,114 @@- import { getSystemMessageText } from "./text.js";-+import { hostedSearchReplayProjection, validateHostedSearchMessages } from "./hosted-search.js";-+import { LocalRequestError, prepareLocalRequest } from "./local-request-error.js";- const CHARS_PER_TOKEN = 4;- const ESTIMATED_IMAGE_CHARS = 4800;- export function calculateContextTokens(usage) {- return usage.totalTokens || usage.input + usage.output + usage.cacheRead + usage.cacheWrite;- }--function safeJsonStringify(value) {-- try {-- return JSON.stringify(value) ?? "undefined";-- }-- catch {-- return "[unserializable]";-- }-+function jsonStringify(value) {-+ return JSON.stringify(value) ?? "undefined";- }- function estimateTextAndImageContentChars(content) {- if (typeof content === "string")- return content.length;- let chars = 0;-- for (const block of content)-- chars += block.type === "text" ? block.text.length : ESTIMATED_IMAGE_CHARS;-+ for (const block of content) {-+ if (block.type === "text" && typeof block.text === "string")-+ chars += block.text.length;-+ else if (block.type === "image")-+ chars += ESTIMATED_IMAGE_CHARS;-+ else-+ throw new LocalRequestError("context-validation");-+ }- return chars;- }- export function estimateTextTokens(text) {- return Math.ceil(text.length / CHARS_PER_TOKEN);- }- export function estimateTextAndImageContentTokens(content) {-- return Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN);-+ return prepareLocalRequest("context-estimation", () => Math.ceil(estimateTextAndImageContentChars(content) / CHARS_PER_TOKEN));- }--export function estimateMessageTokens(message) {-- let chars = 0;-- if (message.role === "system") {-- return (estimateTextTokens(getSystemMessageText(message)) +-- estimateToolsTokens(message.toolsAdded) +-- estimateToolsTokens(message.toolsRemoved));-- }-- if (message.role === "user")-- return estimateTextAndImageContentTokens(message.content);-- if (message.role === "toolResult")-- return estimateTextAndImageContentTokens(message.content);-- for (const block of message.content) {-- if (block.type === "text") {-- chars += block.text.length;-- }-- else if (block.type === "thinking") {-- chars += block.thinking.length;-+/** @param {import('../types.js').Message} message @param {import('../types.js').Model<import('../types.js').Api>} [model] */-+export function estimateMessageTokens(message, model) {-+ return prepareLocalRequest("context-estimation", () => {-+ let chars = 0;-+ switch (message.role) {-+ case "system":-+ return estimateTextTokens(getSystemMessageText(message)) + estimateToolsTokens(message.toolsAdded) + estimateToolsTokens(message.toolsRemoved);-+ case "user":-+ case "toolResult":-+ return estimateTextAndImageContentTokens(message.content);-+ case "assistant":-+ validateHostedSearchMessages([message]);-+ break;-+ default:-+ throw new LocalRequestError("context-validation");- }-- else {-- chars += block.name.length + safeJsonStringify(block.arguments).length;-+ for (const block of message.content) {-+ switch (block.type) {-+ case "text": chars += block.text.length; break;-+ case "thinking": chars += block.thinking.length; break;-+ case "toolCall": chars += block.name.length + jsonStringify(block.arguments).length; break;-+ case "hostedSearch": {-+ const projection = hostedSearchReplayProjection(block, model ? {-+ api: model.api,-+ isSameModel: message.api === model.api && message.provider === model.provider && message.model === model.id,-+ } : undefined);-+ if (projection !== undefined)-+ chars += jsonStringify(projection).length;-+ break;-+ }-+ default: throw new LocalRequestError("context-validation");-+ }- }-- }-- return Math.ceil(chars / CHARS_PER_TOKEN);-+ return Math.ceil(chars / CHARS_PER_TOKEN);-+ });- }--function getLastAssistantUsageInfo(messages) {-+export function getLastAssistantUsageInfo(messages) {- let latestPrefixTimestamp = Number.NEGATIVE_INFINITY;- let usageInfo;- for (let i = 0; i < messages.length; i++) {- const message = messages[i];-+ // Missing/non-finite timestamps cannot establish a prefix or poison later usage with NaN.-+ // Never manufacture timestamps; valid zero and equal timestamps retain their semantics.-+ if (!Number.isFinite(message.timestamp))-+ throw new LocalRequestError("context-validation");- if (message.role === "assistant") {- const assistant = message;-- // A newer prefix message was inserted after this response (for example, a-- // compaction summary), so its usage cannot describe the current prefix.-+ // A newly inserted prefix (such as a compaction summary) invalidates older usage.- const usageAppliesToPrefix = assistant.timestamp >= latestPrefixTimestamp;-- if (usageAppliesToPrefix &&-- assistant.stopReason !== "aborted" &&-- assistant.stopReason !== "error" &&-- calculateContextTokens(assistant.usage) > 0) {-+ if (usageAppliesToPrefix && assistant.stopReason !== "aborted" && assistant.stopReason !== "error" &&-+ assistant.usage && Number.isFinite(calculateContextTokens(assistant.usage)) && calculateContextTokens(assistant.usage) > 0) {- usageInfo = { usage: assistant.usage, index: i };- }- }-+ // A tail system update affects later candidates, not a preceding valid usage anchor.- latestPrefixTimestamp = Math.max(latestPrefixTimestamp, message.timestamp);- }- return usageInfo;- }--export function estimateContextTokens(context) {-- const messages = "messages" in context ? context.messages : context;-- const usageInfo = getLastAssistantUsageInfo(messages);-- if (usageInfo) {-- const usageTokens = calculateContextTokens(usageInfo.usage);-- let trailingTokens = 0;-- for (let i = usageInfo.index + 1; i < messages.length; i++) {-- trailingTokens += estimateMessageTokens(messages[i]);-+export function estimateContextTokens(context, model) {-+ return prepareLocalRequest("context-estimation", () => {-+ const messages = "messages" in context ? context.messages : context;-+ // A usage fast path must not conceal malformed search history.-+ validateHostedSearchMessages(messages);-+ const usageInfo = getLastAssistantUsageInfo(messages);-+ if (usageInfo) {-+ const usageTokens = calculateContextTokens(usageInfo.usage);-+ let trailingTokens = 0;-+ for (let i = usageInfo.index + 1; i < messages.length; i++)-+ trailingTokens += estimateMessageTokens(messages[i], model);-+ return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };- }-- return { tokens: usageTokens + trailingTokens, usageTokens, trailingTokens, lastUsageIndex: usageInfo.index };-- }-- let tokens = 0;-- for (const message of messages)-- tokens += estimateMessageTokens(message);-- return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };-+ let tokens = 0;-+ for (const message of messages)-+ tokens += estimateMessageTokens(message, model);-+ return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };-+ });- }- function estimateToolsTokens(tools) {- if (!tools || tools.length === 0)- return 0;-- return estimateTextTokens(safeJsonStringify(tools));-+ return estimateTextTokens(jsonStringify(tools));- }--//# sourceMappingURL=estimate.js.map-\ No newline at end of file-diff --git a/dist/utils/hosted-search.d.ts b/dist/utils/hosted-search.d.ts-new file mode 100644-index 0000000000000000000000000000000000000000..a76ae5269313931b8476e1f153e76792875ad54c---- /dev/null-+++ b/dist/utils/hosted-search.d.ts-@@ -0,0 +1,10 @@-+import type { Api, HostedSearchContent, JsonObject, Message } from "../types.ts";-+export interface HostedSearchReplayOptions {-+ api: Api;-+ isSameModel?: boolean;-+}-+/** Validate and normalize legacy persisted shapes without manufacturing tool-call fields. */-+export declare function normalizeHostedSearchContent(value: unknown): HostedSearchContent;-+/** The exact provider replay block; undefined means this target does not replay it. */-+export declare function hostedSearchReplayProjection(value: unknown, options?: HostedSearchReplayOptions): JsonObject | undefined;-+export declare function validateHostedSearchMessages(messages: readonly Message[]): void;-diff --git a/dist/utils/hosted-search.js b/dist/utils/hosted-search.js-new file mode 100644-index 0000000000000000000000000000000000000000..b177a2608c5c4ba6d66d6a3fcaef5895e646933b---- /dev/null-+++ b/dist/utils/hosted-search.js-@@ -0,0 +1,97 @@-+import { LocalRequestError, prepareLocalRequest } from "./local-request-error.js";-+const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value);-+const nonempty = (value) => typeof value === "string" && value.length > 0;-+function requireValid(valid) {-+ if (!valid)-+ throw new LocalRequestError("context-validation");-+}-+function validateJson(value, ancestors = new Set()) {-+ if (value === null || typeof value === "string" || typeof value === "boolean")-+ return;-+ if (typeof value === "number") {-+ requireValid(Number.isFinite(value));-+ return;-+ }-+ requireValid(typeof value === "object" && !ancestors.has(value));-+ requireValid(Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);-+ ancestors.add(value);-+ for (const entry of Object.values(value))-+ validateJson(entry, ancestors);-+ ancestors.delete(value);-+}-+export function normalizeHostedSearchContent(value) {-+ return prepareLocalRequest("context-validation", () => {-+ requireValid(record(value) && value.type === "hostedSearch");-+ const wire = value.wire;-+ requireValid(wire == null || record(wire));-+ const blockId = value.blockId ?? wire?.id ?? wire?.tool_use_id;-+ requireValid(nonempty(blockId));-+ switch (value.phase) {-+ case "server_tool_use": {-+ requireValid(nonempty(value.name));-+ const input = value.input ?? {};-+ requireValid(record(input));-+ validateJson(input);-+ return { ...value, blockId, input };-+ }-+ case "web_search_tool_result":-+ requireValid(record(wire));-+ requireValid(wire.type === undefined || wire.type === "web_search_tool_result" || wire.type === "web_search_tool_result_error");-+ requireValid(wire.tool_use_id === undefined || nonempty(wire.tool_use_id));-+ requireValid(wire.content !== undefined);-+ requireValid(value.isError === undefined || typeof value.isError === "boolean");-+ validateJson(wire);-+ return { ...value, blockId, isError: value.isError ?? wire.type === "web_search_tool_result_error" };-+ case "web_search_call":-+ if (wire != null) {-+ requireValid(wire.type === "web_search_call" && nonempty(wire.id));-+ validateJson(wire);-+ }-+ requireValid(value.status === undefined || typeof value.status === "string");-+ return { ...value, blockId };-+ default:-+ throw new LocalRequestError("context-validation");-+ }-+ });-+}-+export function hostedSearchReplayProjection(value, options) {-+ const block = normalizeHostedSearchContent(value);-+ // One projection for estimation and replay avoids counting wire plus display summaries twice.-+ // Without a target, estimate conservatively; with one, preserve the adapter's model boundary.-+ const api = options?.api ?? (block.phase === "web_search_call" ? "openai-responses" : "anthropic-messages");-+ if (block.phase === "web_search_call") {-+ if ((api !== "openai-responses" && api !== "azure-openai-responses") || options?.isSameModel === false)-+ return undefined;-+ return { ...(block.wire ?? { type: "web_search_call", id: block.blockId, status: "completed" }) };-+ }-+ if (api !== "anthropic-messages")-+ return undefined;-+ if (block.phase === "server_tool_use")-+ return { type: "server_tool_use", id: block.blockId, name: block.name, input: block.input };-+ const { type: _type, ...wire } = block.wire;-+ return {-+ type: block.isError ? "web_search_tool_result_error" : "web_search_tool_result",-+ tool_use_id: block.blockId,-+ ...wire,-+ };-+}-+export function validateHostedSearchMessages(messages) {-+ for (const message of messages) {-+ if (message.role !== "assistant")-+ continue;-+ requireValid(Array.isArray(message.content));-+ for (const block of message.content) {-+ requireValid(record(block));-+ switch (block.type) {-+ case "hostedSearch": normalizeHostedSearchContent(block); break;-+ case "text": requireValid(typeof block.text === "string"); break;-+ case "thinking": requireValid(typeof block.thinking === "string"); break;-+ case "toolCall":-+ requireValid(nonempty(block.name) && nonempty(block.id) && record(block.arguments));-+ validateJson(block.arguments);-+ break;-+ default: throw new LocalRequestError("context-validation");-+ }-+ }-+ }-+}-diff --git a/dist/utils/local-request-error.d.ts b/dist/utils/local-request-error.d.ts-new file mode 100644-index 0000000000000000000000000000000000000000..a72f65b33c64b89f118a59bd286e62624711fd90---- /dev/null-+++ b/dist/utils/local-request-error.d.ts-@@ -0,0 +1,15 @@-+export type LocalRequestErrorPhase = "context-validation" | "context-estimation" | "request-preparation";-+export interface LocalRequestErrorDetails {-+ code: "LOCAL_REQUEST_ERROR";-+ phase: LocalRequestErrorPhase;-+ message: string;-+ causeName?: string;-+}-+export declare class LocalRequestError extends Error {-+ readonly code: "LOCAL_REQUEST_ERROR";-+ readonly phase: LocalRequestErrorPhase;-+ constructor(phase: LocalRequestErrorPhase, options?: ErrorOptions);-+}-+export declare function localRequestErrorDetails(error: unknown): LocalRequestErrorDetails | undefined;-+export declare function asLocalRequestError(error: unknown, phase: LocalRequestErrorPhase): unknown;-+export declare function prepareLocalRequest<T>(phase: LocalRequestErrorPhase, prepare: () => T): T;-diff --git a/dist/utils/local-request-error.js b/dist/utils/local-request-error.js-new file mode 100644-index 0000000000000000000000000000000000000000..4d276ddc8caee98dfeeeeaa9bcd234ad63dc414b---- /dev/null-+++ b/dist/utils/local-request-error.js-@@ -0,0 +1,38 @@-+const messages = {-+ "context-validation": "Local request context validation failed",-+ "context-estimation": "Local request context estimation failed",-+ "request-preparation": "Local request preparation failed",-+};-+export class LocalRequestError extends Error {-+ code = "LOCAL_REQUEST_ERROR";-+ constructor(phase, options) {-+ // Expose only fixed descriptions; retain original data and underlying errors in cause.-+ super(messages[phase], options);-+ this.name = "LocalRequestError";-+ this.phase = phase;-+ }-+}-+export function localRequestErrorDetails(error) {-+ // Explicit markers work across packages/realms; never infer origin from TypeError, text, or absent responses.-+ if (!error || typeof error !== "object" || error.code !== "LOCAL_REQUEST_ERROR" ||-+ !Object.hasOwn(messages, error.phase))-+ return undefined;-+ return {-+ code: "LOCAL_REQUEST_ERROR",-+ phase: error.phase,-+ message: messages[error.phase],-+ ...(error.cause instanceof Error ? { causeName: error.cause.name } :-+ typeof error.causeName === "string" ? { causeName: error.causeName } : {}),-+ };-+}-+export function asLocalRequestError(error, phase) {-+ return localRequestErrorDetails(error) ? error : new LocalRequestError(phase, { cause: error });-+}-+export function prepareLocalRequest(phase, prepare) {-+ try {-+ return prepare();-+ }-+ catch (error) {-+ throw asLocalRequestError(error, phase);-+ }-+}-diff --git a/dist/utils/local-request-stream.d.ts b/dist/utils/local-request-stream.d.ts-new file mode 100644-index 0000000000000000000000000000000000000000..879b78cbecb0cc2c4322049ed2c7d61f77be9375---- /dev/null-+++ b/dist/utils/local-request-stream.d.ts-@@ -0,0 +1,3 @@-+import type { Api, AssistantMessageEventStream, Model } from "../types.ts";-+/** Guard synchronous adapter setup without classifying transport errors. */-+export declare function withLocalRequestErrors(model: Model<Api>, options: { signal?: AbortSignal } | undefined, prepare: () => AssistantMessageEventStream): AssistantMessageEventStream;-diff --git a/dist/utils/local-request-stream.js b/dist/utils/local-request-stream.js-new file mode 100644-index 0000000000000000000000000000000000000000..5c63b882ae4cb618e964c5d2ce8d3c18e0fe4688---- /dev/null-+++ b/dist/utils/local-request-stream.js-@@ -0,0 +1,24 @@-+import { AssistantMessageEventStream } from "./event-stream.js";-+import { asLocalRequestError, localRequestErrorDetails } from "./local-request-error.js";-+export function withLocalRequestErrors(model, options, prepare) {-+ try {-+ return prepare();-+ }-+ catch (error) {-+ // 只包围同步 setup/buildBaseOptions;网络及响应解析仍由原 adapter 处理。-+ const details = localRequestErrorDetails(asLocalRequestError(error, "request-preparation"));-+ const aborted = options?.signal?.aborted === true;-+ const message = {-+ role: "assistant", content: [], api: model.api, provider: model.provider, model: model.id,-+ usage: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0,-+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 } },-+ stopReason: aborted ? "aborted" : "error", timestamp: Date.now(),-+ errorMessage: aborted ? "Request was aborted" : details.message,-+ ...(aborted ? {} : { errorDetails: details }),-+ };-+ const stream = new AssistantMessageEventStream();-+ stream.push({ type: "error", reason: message.stopReason, error: message });-+ stream.end();-+ return stream;-+ }-+}diff --git a/patches/@[email protected] b/patches/@[email protected]similarity index 93%rename from patches/@[email protected]rename to patches/@[email protected]index 02559264e..df5da3d0d 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,5 +1,5 @@diff --git a/dist/api/anthropic-messages.js b/dist/api/anthropic-messages.js-index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e10c564a96 100644+index 501971b2a..a72110c70 100644--- a/dist/api/anthropic-messages.js+++ b/dist/api/anthropic-messages.js@@ -1,3 +1,6 @@@@ -39,7 +39,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1const response = await retryProviderRequest(() => client.beta.messages.create(params, requestOptions).asResponse(), {maxRetries: options?.maxRetries,maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -474,17 +481,50 @@ export const stream = (model, context, options) => {+@@ -475,17 +482,50 @@ export const stream = (model, context, options) => {output.content.push(block);stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output });}@@ -92,7 +92,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1partial: output,});}-@@ -493,11 +533,11 @@ export const stream = (model, context, options) => {+@@ -494,11 +534,11 @@ export const stream = (model, context, options) => {const index = blocks.findIndex((b) => b.index === event.index);const block = blocks[index];if (block && block.type === "thinking") {@@ -106,7 +106,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1partial: output,});}-@@ -506,12 +546,24 @@ export const stream = (model, context, options) => {+@@ -507,12 +547,24 @@ export const stream = (model, context, options) => {const index = blocks.findIndex((b) => b.index === event.index);const block = blocks[index];if (block && block.type === "toolCall") {@@ -133,7 +133,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1partial: output,});}-@@ -521,7 +573,19 @@ export const stream = (model, context, options) => {+@@ -522,7 +574,19 @@ export const stream = (model, context, options) => {const block = blocks[index];if (block && block.type === "thinking") {block.thinkingSignature = block.thinkingSignature || "";@@ -154,7 +154,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1}}}-@@ -558,6 +622,12 @@ export const stream = (model, context, options) => {+@@ -559,6 +623,12 @@ export const stream = (model, context, options) => {partial: output,});}@@ -167,7 +167,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1}}else if (event.type === "message_delta") {-@@ -625,13 +695,18 @@ export const stream = (model, context, options) => {+@@ -631,13 +701,18 @@ export const stream = (model, context, options) => {stream.end();}catch (error) {@@ -187,7 +187,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1stream.push({ type: "error", reason: output.stopReason, error: output });stream.end();}-@@ -659,7 +734,7 @@ function mapThinkingLevelToEffort(model, level) {+@@ -665,7 +740,7 @@ function mapThinkingLevelToEffort(model, level) {return "high";}}@@ -196,7 +196,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1assertRequestAuth(model.provider, options?.apiKey, options?.headers);const base = {...buildBaseOptions(model, context, options, options?.apiKey),-@@ -691,7 +766,7 @@ export const streamSimple = (model, context, options) => {+@@ -697,7 +772,7 @@ export const streamSimple = (model, context, options) => {thinkingEnabled: true,thinkingBudgetTokens: Math.min(adjusted.thinkingBudget, Math.max(0, maxTokens - 1024)),});@@ -205,7 +205,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1function isOAuthToken(apiKey) {return apiKey.includes("sk-ant-oat");}-@@ -868,6 +943,15 @@ function buildParams(model, context, isOAuthToken, options) {+@@ -874,6 +949,15 @@ function buildParams(model, context, isOAuthToken, options) {params.tools = convertTools(tools, isOAuthToken, compat.supportsEagerToolInputStreaming, compat.supportsStrictTools, toolCacheControl);}}@@ -221,7 +221,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1// Managed effort models always use adaptive thinking so prefix mismatches can// be dropped instead of surfacing as persistent 400 responses.if (model.compat?.supportsMidConvoEffort === true) {-@@ -1072,6 +1156,15 @@ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowE+@@ -1078,6 +1162,15 @@ function convertMessages(transformedMessages, isOAuthToken, cacheControl, allowEinput: block.arguments ?? {},});}@@ -238,7 +238,7 @@ index 5dd85f19db51b73dcd0c5c4cd8c28ad99e09ee6f..b7a8cfcac811512c1007c88f7e9d51e1if (blocks.length === 0)continue;diff --git a/dist/api/azure-openai-responses.js b/dist/api/azure-openai-responses.js-index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d09ef5644b 100644+index dc2d8f9be..e43cc048c 100644--- a/dist/api/azure-openai-responses.js+++ b/dist/api/azure-openai-responses.js@@ -1,3 +1,5 @@@@ -278,7 +278,7 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {maxRetries: options?.maxRetries,maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -105,6 +110,11 @@ export const stream = (model, context, options) => {+@@ -108,6 +113,11 @@ export const stream = (model, context, options) => {stream.end();}catch (error) {@@ -290,7 +290,7 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0for (const block of output.content) {delete block.index;// Streaming scratch buffers are only used during parsing; never persist them.-@@ -112,14 +122,14 @@ export const stream = (model, context, options) => {+@@ -115,14 +125,14 @@ export const stream = (model, context, options) => {delete block.customInput;}output.stopReason = options?.signal?.aborted ? "aborted" : "error";@@ -307,7 +307,7 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0const apiKey = options?.apiKey;if (!apiKey) {throw new Error(`No API key for provider: ${model.provider}`);-@@ -134,7 +144,7 @@ export const streamSimple = (model, context, options) => {+@@ -137,7 +147,7 @@ export const streamSimple = (model, context, options) => {...base,reasoningEffort,});@@ -316,7 +316,7 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0function normalizeAzureBaseUrl(baseUrl) {const trimmed = baseUrl.trim().replace(/\/+$/, "");let url;-@@ -235,6 +245,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr+@@ -238,6 +248,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPrif (options?.toolChoice !== undefined) {params.tool_choice = options.toolChoice;}@@ -329,7 +329,7 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0if (model.reasoning) {if (options?.reasoningEffort || options?.reasoningSummary) {const effort = options?.reasoningEffort-@@ -252,6 +268,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr+@@ -255,6 +271,12 @@ function buildParams(model, context, options, deploymentName, grammarToolInputPr};}}@@ -339,14 +339,14 @@ index ec1e2069102ed3165b2d702b9fc4105d5cf8f4e1..572dce7f2c1775a48bea869fcc0df7d0+ if (model.webSearch === true) {+ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];+ }- // Last so custom keys override the named request fields.- if (options?.samplingParams) {- Object.assign(params, options.samplingParams);+ // Last so custom keys override the named request fields. Per-request keys override model defaults.+ Object.assign(params, model.samplingParams, options?.samplingParams);+ return params;diff --git a/dist/api/mistral-conversations.js b/dist/api/mistral-conversations.js-index 3106c5d470dc3610c05d8ee153026df20f86f66e..8b209bb46809c394ffebfd11d5dfd2731c204310 100644+index fbcc5e25e..92b07a1a1 100644--- a/dist/api/mistral-conversations.js+++ b/dist/api/mistral-conversations.js-@@ -645,6 +645,9 @@ function toChatMessages(messages, supportsImages) {+@@ -658,6 +658,9 @@ function toChatMessages(messages, supportsImages) {}continue;}@@ -357,7 +357,7 @@ index 3106c5d470dc3610c05d8ee153026df20f86f66e..8b209bb46809c394ffebfd11d5dfd273id: block.id,type: "function",diff --git a/dist/api/openai-codex-responses.js b/dist/api/openai-codex-responses.js-index dfdb6ec3651febbba6b8788f16118ecbf4b38fa8..9a3ad78a58359e8669d8a42a3f9264942044c5fd 100644+index 40014b3b7..f8b215d3a 100644--- a/dist/api/openai-codex-responses.js+++ b/dist/api/openai-codex-responses.js@@ -411,6 +411,12 @@ function buildRequestBody(model, context, options, cacheSessionId, grammarToolIn@@ -374,7 +374,7 @@ index dfdb6ec3651febbba6b8788f16118ecbf4b38fa8..9a3ad78a58359e8669d8a42a3f926494const effort = options.reasoningEffort === "none"? model.thinkingLevelMap?.off === undefineddiff --git a/dist/api/openai-completions.js b/dist/api/openai-completions.js-index fc8e89382b75f259eb4f041b522840b0d603c033..ff54f13831eb17711b95c1984ad1b31c2d866ef8 100644+index eecd83c75..2390122f7 100644--- a/dist/api/openai-completions.js+++ b/dist/api/openai-completions.js@@ -1041,21 +1041,27 @@ export function convertMessages(model, context, compat, options) {@@ -473,7 +473,7 @@ index fc8e89382b75f259eb4f041b522840b0d603c033..ff54f13831eb17711b95c1984ad1b31copenRouterRouting: model.compat.openRouterRouting ?? {},vercelGatewayRouting: model.compat.vercelGatewayRouting ?? detected.vercelGatewayRouting,diff --git a/dist/api/openai-responses-shared.js b/dist/api/openai-responses-shared.js-index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c8173ad108a 100644+index 3e3b48a9e..7bd0d1498 100644--- a/dist/api/openai-responses-shared.js+++ b/dist/api/openai-responses-shared.js@@ -1,3 +1,4 @@@@ -532,7 +532,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81return undefined;};const getOrCreateSlot = (outputIndex, item) => {-@@ -485,11 +516,11 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -486,11 +517,11 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "thinking");if (!slot)continue;@@ -546,7 +546,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81partial: output,});}-@@ -509,11 +540,11 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -510,11 +541,11 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "thinking");if (!slot)continue;@@ -560,7 +560,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81partial: output,});}-@@ -521,23 +552,44 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -522,23 +553,44 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "text");if (!slot)continue;@@ -609,7 +609,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81partial: output,});}-@@ -545,9 +597,9 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -546,9 +598,9 @@ export async function processResponsesStream(openaiStream, output, stream, modelconst slot = getSlot(event.output_index, "toolCall");if (!slot || slot.block.partialJson === undefined)continue;@@ -621,7 +621,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81}else if (event.type === "response.function_call_arguments.done") {const slot = getSlot(event.output_index, "toolCall");-@@ -633,9 +685,25 @@ export async function processResponsesStream(openaiStream, output, stream, model+@@ -634,9 +686,25 @@ export async function processResponsesStream(openaiStream, output, stream, model});outputSlots.delete(event.output_index);}@@ -648,7 +648,7 @@ index 53597d2c3becdd2c03d4fd265c213a36b403f26b..763f99a6e7d726ff9fc1ed59a45f6c81else if (event.type === "error") {throw new Error(`Error Code ${event.code}: ${event.message}` || "Unknown error");diff --git a/dist/api/openai-responses.js b/dist/api/openai-responses.js-index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15bc29cdf4 100644+index 4d58c9772..c928c3f64 100644--- a/dist/api/openai-responses.js+++ b/dist/api/openai-responses.js@@ -1,3 +1,5 @@@@ -657,7 +657,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15import OpenAI from "openai";import { clampThinkingLevel } from "../models.js";import { formatProviderError, normalizeProviderError } from "../utils/error-body.js";-@@ -81,7 +83,6 @@ function getPromptCacheOptions(compat, cacheRetention) {+@@ -92,7 +94,6 @@ function getPromptCacheOptions(compat, cacheRetention) {*/export const stream = (model, context, options) => {const stream = new AssistantMessageEventStream();@@ -665,7 +665,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15// Start async processing(async () => {const output = {-@@ -101,7 +102,9 @@ export const stream = (model, context, options) => {+@@ -112,7 +113,9 @@ export const stream = (model, context, options) => {stopReason: "pending",timestamp: Date.now(),};@@ -675,7 +675,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15// Create OpenAI clientconst apiKey = getClientApiKey(model.provider, options?.apiKey, options?.headers);const cacheRetention = resolveCacheRetention(options?.cacheRetention, options?.env);-@@ -119,6 +122,9 @@ export const stream = (model, context, options) => {+@@ -130,6 +133,9 @@ export const stream = (model, context, options) => {...(options?.timeoutMs !== undefined ? { timeout: options.timeoutMs } : {}),maxRetries: 0,};@@ -685,7 +685,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15const { data: openaiStream, response } = await retryProviderRequest(() => client.responses.create(params, requestOptions).withResponse(), {maxRetries: options?.maxRetries,maxRetryDelayMs: options?.maxRetryDelayMs,-@@ -144,6 +150,11 @@ export const stream = (model, context, options) => {+@@ -156,6 +162,11 @@ export const stream = (model, context, options) => {stream.end();}catch (error) {@@ -697,15 +697,16 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15for (const block of output.content) {delete block.index;// Streaming scratch buffers are only used during parsing; never persist them.-@@ -151,14 +162,14 @@ export const stream = (model, context, options) => {+@@ -163,7 +174,7 @@ export const stream = (model, context, options) => {delete block.customInput;}output.stopReason = options?.signal?.aborted ? "aborted" : "error";-- output.errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);-+ output.errorMessage = errorDetails?.message ?? formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);- stream.push({ type: "error", reason: output.stopReason, error: output });- stream.end();- }+- const errorMessage = formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);++ const errorMessage = errorDetails?.message ?? formatProviderError(normalizeProviderError(error), `${model.provider === "openai" ? "OpenAI" : model.provider} API error`);+ // Sign in with ChatGPT shares the subscription's usage limit with other apps.+ output.errorMessage = errorMessage.includes("subscription_sharing_usage_limit_exceeded")+ ? `${errorMessage}\nCheck your ChatGPT usage: ${CHATGPT_USAGE_URL}`+@@ -174,7 +185,7 @@ export const stream = (model, context, options) => {})();return stream;};@@ -714,7 +715,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15getClientApiKey(model.provider, options?.apiKey, options?.headers);const base = {...buildBaseOptions(model, context, options, options?.apiKey),-@@ -170,7 +181,7 @@ export const streamSimple = (model, context, options) => {+@@ -186,7 +197,7 @@ export const streamSimple = (model, context, options) => {...base,reasoningEffort,});@@ -723,7 +724,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15function createClient(model, context, apiKey, optionsHeaders, fetch, sessionId) {const compat = getCompat(model);const headers = { "User-Agent": getPiUserAgent(), ...model.headers };-@@ -242,6 +253,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar+@@ -260,6 +271,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammarsupportsOpenAIGrammarTools: compat.supportsOpenAIGrammarTools,});}@@ -736,7 +737,7 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15if (options?.toolChoice !== undefined) {params.tool_choice = options.toolChoice;}-@@ -264,6 +281,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammar+@@ -282,6 +299,12 @@ function buildParams(model, context, options, compat = getCompat(model), grammarif (model.provider === "xai")params.include = ["reasoning.encrypted_content"];}@@ -746,11 +747,11 @@ index 1396c8d57ffb0e300382281a026d878e6a96b43a..39d201fc29deaa3cf19a8aaafe57ff15+ if (model.webSearch === true) {+ params.include = [...new Set([...(params.include ?? []), "web_search_call.action.sources"])];+ }- // Last so custom keys override the named request fields.- if (options?.samplingParams) {- Object.assign(params, options.samplingParams);+ // Last so custom keys override the named request fields. Per-request keys override model defaults.+ Object.assign(params, model.samplingParams, options?.samplingParams);+ return params;diff --git a/dist/api/simple-options.js b/dist/api/simple-options.js-index 216a45feebc02acef047d1ff133729fb0751b76c..23528b801d65e33d22eb1d63ea49945d24a5e658 100644+index da0fc83be..d56ef2ab9 100644--- a/dist/api/simple-options.js+++ b/dist/api/simple-options.js@@ -4,7 +4,7 @@ const MIN_MAX_TOKENS = 1;@@ -763,12 +764,12 @@ index 216a45feebc02acef047d1ff133729fb0751b76c..23528b801d65e33d22eb1d63ea49945d}export function buildBaseOptions(model, context, options, apiKey) {diff --git a/dist/auth/oauth/anthropic.js b/dist/auth/oauth/anthropic.js-index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ed7e81f2a 100644+index 94c8f0035..e5b6f72dd 100644--- a/dist/auth/oauth/anthropic.js+++ b/dist/auth/oauth/anthropic.js-@@ -140,21 +140,90 @@ async function startCallbackServer(expectedState) {- });- });+@@ -61,21 +61,90 @@ function formatErrorDetails(error) {+ }+ return String(error);}-async function postJson(url, body, signal) {- const response = await fetch(url, {@@ -870,7 +871,7 @@ index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182e}async function exchangeAuthorizationCode(code, state, verifier, redirectUri, signal) {let responseBody;-@@ -169,6 +238,8 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig+@@ -90,6 +159,8 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig}, signal);}catch (error) {@@ -879,7 +880,7 @@ index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ethrow new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`);}let tokenData;-@@ -176,7 +247,7 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sig+@@ -97,7 +168,7 @@ async function exchangeAuthorizationCode(code, state, verifier, redirectUri, sigtokenData = JSON.parse(responseBody);}catch (error) {@@ -888,7 +889,7 @@ index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182e}return {type: "oauth",-@@ -280,6 +351,8 @@ async function refreshAnthropicToken(refreshToken, signal) {+@@ -171,6 +242,8 @@ async function refreshAnthropicToken(refreshToken, signal) {}, signal);}catch (error) {@@ -897,7 +898,7 @@ index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ethrow new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`);}let data;-@@ -287,7 +360,7 @@ async function refreshAnthropicToken(refreshToken, signal) {+@@ -178,7 +251,7 @@ async function refreshAnthropicToken(refreshToken, signal) {data = JSON.parse(responseBody);}catch (error) {@@ -907,10 +908,10 @@ index 8692e906caa2609396bdccae98d4d593e024ecf6..029138715f58dbb2e5825f9a2d0c182ereturn {type: "oauth",diff --git a/dist/index.d.ts b/dist/index.d.ts-index 5e8403dd62895d30eb7d8e3f95b87d6535221839..50f728e4427e1cadb9aded7e35f3e44611eefc85 100644+index 75c0d7ba7..b0bf6975c 100644--- a/dist/index.d.ts+++ b/dist/index.d.ts-@@ -34,4 +34,7 @@ export * from "./utils/transcript.ts";+@@ -33,4 +33,7 @@ export * from "./utils/transcript.ts";export * from "./utils/typebox-helpers.ts";export { uuidv7 } from "./utils/uuid.ts";export * from "./utils/validation.ts";@@ -920,10 +921,10 @@ index 5e8403dd62895d30eb7d8e3f95b87d6535221839..50f728e4427e1cadb9aded7e35f3e446//# sourceMappingURL=index.d.ts.map\ No newline at end of filediff --git a/dist/index.js b/dist/index.js-index cf46c043b854412d56c5d65230a509165229806e..0fe002385c3d9906709be1cce6867d0c30a3a151 100644+index 4fafddad7..2e4ed41e5 100644--- a/dist/index.js+++ b/dist/index.js-@@ -21,4 +21,6 @@ export * from "./utils/transcript.js";+@@ -20,4 +20,6 @@ export * from "./utils/transcript.js";export * from "./utils/typebox-helpers.js";export { uuidv7 } from "./utils/uuid.js";export * from "./utils/validation.js";@@ -932,10 +933,10 @@ index cf46c043b854412d56c5d65230a509165229806e..0fe002385c3d9906709be1cce6867d0c//# sourceMappingURL=index.js.map\ No newline at end of filediff --git a/dist/types.d.ts b/dist/types.d.ts-index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09274c271c 100644+index 68aa0553d..d6d73b0ca 100644--- a/dist/types.d.ts+++ b/dist/types.d.ts-@@ -267,6 +267,30 @@ export interface ToolCall {+@@ -286,6 +286,30 @@ export interface ToolCall {/** OpenAI Responses namespace for calls to dynamically loaded or namespaced tools. */namespace?: string;}@@ -966,7 +967,7 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09export interface Usage {input: number;output: number;-@@ -352,7 +376,7 @@ export interface UserMessage {+@@ -371,7 +395,7 @@ export interface UserMessage {}export interface AssistantMessage {role: "assistant";@@ -975,7 +976,7 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09api: Api;provider: ProviderId;model: string;-@@ -365,6 +389,8 @@ export interface AssistantMessage {+@@ -386,6 +410,8 @@ export interface AssistantMessage {stopReason: StopReason;deferred?: DeferredHandle;errorMessage?: string;@@ -984,7 +985,7 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09rawStopReason?: string;/*** Provider indication of whether the model explicitly ended its turn.-@@ -512,6 +538,10 @@ export type AssistantMessageEvent = {+@@ -606,6 +632,10 @@ export type AssistantMessageEvent = {contentIndex: number;toolCall: ToolCall;partial: AssistantMessage;@@ -995,7 +996,7 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09} | {type: "done";reason: Extract<StopReason, "stop" | "length" | "toolUse" | "deferred">;-@@ -546,6 +576,12 @@ export interface OpenAICompletionsCompat {+@@ -640,6 +670,12 @@ export interface OpenAICompletionsCompat {requiresThinkingAsText?: boolean;/** Whether all replayed assistant messages must include an empty reasoning_content field when reasoning is enabled. Default: auto-detected from URL. */requiresReasoningContentOnAssistantMessages?: boolean;@@ -1008,9 +1009,9 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09/** Format for reasoning/thinking parameter. "openai" uses reasoning_effort, "openrouter" uses reasoning: { effort }, "deepseek" uses thinking: { type } plus reasoning_effort when supported, "together" uses reasoning: { enabled } plus reasoning_effort when supported, "baseten" uses configurable chat_template_args plus reasoning_effort when supported, "zai" uses thinking: { type }, "qwen" uses top-level enable_thinking: boolean, "qwen-chat-template" uses chat_template_kwargs.enable_thinking and preserve_thinking, "chat-template" uses configurable chat_template_kwargs, "string-thinking" uses top-level thinking: string, and "ant-ling" uses reasoning: { effort } only when the mapped effort is non-null. Default: "openai". */thinkingFormat?: "openai" | "openrouter" | "deepseek" | "together" | "baseten" | "zai" | "qwen" | "chat-template" | "qwen-chat-template" | "string-thinking" | "ant-ling";/** Kwargs to send as `chat_template_kwargs` when `thinkingFormat` is `chat-template`. Use `{ "$var": "thinking.enabled" }`, `{ "$var": "thinking.effort" }`, or `{ "$var": "thinking.budget" }` for pi-controlled thinking values. */-@@ -809,6 +845,8 @@ export interface Model<TApi extends Api> {- provider: ProviderId;- baseUrl: string;+@@ -918,6 +954,8 @@ export interface Model<TApi extends Api> extends BaseModel<TApi> {+ */+ type?: "chat";reasoning: boolean;+ /** Opt in to hosted search on the existing Anthropic/Responses adapters. */+ webSearch?: boolean;@@ -1018,7 +1019,7 @@ index 5915ca64b161bc7bcebdb14d2ad1a2c18cde942e..f5d4114e94a27d72b33ba83cc45f1d09* Maps pi thinking levels to provider/model-specific values.* Missing keys use provider defaults. null marks a level as unsupported.diff --git a/dist/utils/assistant-message-frame.d.ts b/dist/utils/assistant-message-frame.d.ts-index 08207197acab532d0f5f596363700a2d15a687d8..0584f6898e1d842c4414869b9080505b63c3a7b7 100644+index 08207197a..0584f6898 100644--- a/dist/utils/assistant-message-frame.d.ts+++ b/dist/utils/assistant-message-frame.d.ts@@ -1,4 +1,4 @@@@ -1040,7 +1041,7 @@ index 08207197acab532d0f5f596363700a2d15a687d8..0584f6898e1d842c4414869b9080505b/*** Encodes one assistant stream. `partial` remains a shared live accumulator;diff --git a/dist/utils/assistant-message-frame.js b/dist/utils/assistant-message-frame.js-index c0e00197b2bdd4c815106daa036d844c07aca800..a86f5939accd25110d7a4d1e0d268646691d321d 100644+index c0e00197b..a86f5939a 100644--- a/dist/utils/assistant-message-frame.js+++ b/dist/utils/assistant-message-frame.js@@ -1,15 +1,30 @@@@ -1195,7 +1196,7 @@ index c0e00197b2bdd4c815106daa036d844c07aca800..a86f5939accd25110d7a4d1e0d268646if (frame.content.type !== "text") {throw new Error(`text_start frame contains ${frame.content.type} content`);diff --git a/dist/utils/estimate.d.ts b/dist/utils/estimate.d.ts-index 6dcca6eff16b95b83e047a6e27b65d9d7694bf2c..5ccaaf2358a0afeea3ce354e5799255ae8508f3d 100644+index 6dcca6eff..5ccaaf235 100644--- a/dist/utils/estimate.d.ts+++ b/dist/utils/estimate.d.ts@@ -1,4 +1,4 @@@@ -1216,7 +1217,7 @@ index 6dcca6eff16b95b83e047a6e27b65d9d7694bf2c..5ccaaf2358a0afeea3ce354e5799255a//# sourceMappingURL=estimate.d.ts.map\ No newline at end of filediff --git a/dist/utils/estimate.js b/dist/utils/estimate.js-index d04ff22cbe8d7357404b938e228b8e3a2dbdcb1d..28564cc73798163f7590290123b7476573d5bee5 100644+index d04ff22cb..28564cc73 100644--- a/dist/utils/estimate.js+++ b/dist/utils/estimate.js@@ -1,95 +1,114 @@@@ -1391,7 +1392,7 @@ index d04ff22cbe8d7357404b938e228b8e3a2dbdcb1d..28564cc73798163f7590290123b74765\ No newline at end of filediff --git a/dist/utils/hosted-search.d.ts b/dist/utils/hosted-search.d.tsnew file mode 100644-index 0000000000000000000000000000000000000000..a76ae5269313931b8476e1f153e76792875ad54c+index 000000000..a76ae5269--- /dev/null+++ b/dist/utils/hosted-search.d.ts@@ -0,0 +1,10 @@@@ -1407,7 +1408,7 @@ index 0000000000000000000000000000000000000000..a76ae5269313931b8476e1f153e76792+export declare function validateHostedSearchMessages(messages: readonly Message[]): void;diff --git a/dist/utils/hosted-search.js b/dist/utils/hosted-search.jsnew file mode 100644-index 0000000000000000000000000000000000000000..b98cb8d128310273014e4490e9c26144f45b56af+index 000000000..b98cb8d12--- /dev/null+++ b/dist/utils/hosted-search.js@@ -0,0 +1,97 @@@@ -1510,7 +1511,7 @@ index 0000000000000000000000000000000000000000..b98cb8d128310273014e4490e9c26144+}diff --git a/dist/utils/local-request-error.d.ts b/dist/utils/local-request-error.d.tsnew file mode 100644-index 0000000000000000000000000000000000000000..a72f65b33c64b89f118a59bd286e62624711fd90+index 000000000..a72f65b33--- /dev/null+++ b/dist/utils/local-request-error.d.ts@@ -0,0 +1,15 @@@@ -1531,7 +1532,7 @@ index 0000000000000000000000000000000000000000..a72f65b33c64b89f118a59bd286e6262+export declare function prepareLocalRequest<T>(phase: LocalRequestErrorPhase, prepare: () => T): T;diff --git a/dist/utils/local-request-error.js b/dist/utils/local-request-error.jsnew file mode 100644-index 0000000000000000000000000000000000000000..4d276ddc8caee98dfeeeeaa9bcd234ad63dc414b+index 000000000..4d276ddc8--- /dev/null+++ b/dist/utils/local-request-error.js@@ -0,0 +1,38 @@@@ -1575,7 +1576,7 @@ index 0000000000000000000000000000000000000000..4d276ddc8caee98dfeeeeaa9bcd234ad+}diff --git a/dist/utils/local-request-stream.d.ts b/dist/utils/local-request-stream.d.tsnew file mode 100644-index 0000000000000000000000000000000000000000..879b78cbecb0cc2c4322049ed2c7d61f77be9375+index 000000000..879b78cbe--- /dev/null+++ b/dist/utils/local-request-stream.d.ts@@ -0,0 +1,3 @@@@ -1584,7 +1585,7 @@ index 0000000000000000000000000000000000000000..879b78cbecb0cc2c4322049ed2c7d61f+export declare function withLocalRequestErrors(model: Model<Api>, options: { signal?: AbortSignal } | undefined, prepare: () => AssistantMessageEventStream): AssistantMessageEventStream;diff --git a/dist/utils/local-request-stream.js b/dist/utils/local-request-stream.jsnew file mode 100644-index 0000000000000000000000000000000000000000..5c63b882ae4cb618e964c5d2ce8d3c18e0fe4688+index 000000000..5c63b882a--- /dev/null+++ b/dist/utils/local-request-stream.js@@ -0,0 +1,24 @@diff --git a/patches/@[email protected] b/patches/@[email protected]deleted file mode 100644index 22c3f4176..000000000--- a/patches/@[email protected]+++ /dev/null@@ -1,279 +0,0 @@-diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js-index 638646dacdbcb9c00bbc0de14f28abb700c8dc3f..8e8d0643d6e341a17243adae220bc9658a1eecb5 100644---- a/dist/core/agent-session.js-+++ b/dist/core/agent-session.js-@@ -62,10 +62,10 @@ function withoutDeletedHeaders(headers) {- ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))- : undefined;- }--function estimateMessagesTokens(messages) {-+function estimateMessagesTokens(messages, model) {- let tokens = 0;- for (const message of messages) {-- tokens += estimateTokens(message);-+ tokens += estimateTokens(message, model);- }- return tokens;- }-@@ -284,7 +284,7 @@ export class AgentSession {- const settings = this.settingsManager.getCompactionSettings(model);- if (!model ||- model.contextWindow <= 0 ||-- !shouldCompact(estimateContextTokens(context.messages).tokens, model.contextWindow, settings)) {-+ !shouldCompact(estimateContextTokens(context.messages, model).tokens, model.contextWindow, settings)) {- return context;- }- await this._runAutoCompaction("threshold", false);-@@ -1658,7 +1658,7 @@ export class AgentSession {- const newEntries = this.sessionManager.getEntries();- const sessionContext = this.sessionManager.buildSessionContext();- this.agent.state.messages = sessionContext.messages;-- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);-+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages, requestModel);- // Get the saved compaction entry for the extension event- const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);- if (this._extensionRunner && savedCompactionEntry) {-@@ -1820,7 +1820,7 @@ export class AgentSession {- const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;- if (assistantMessage.stopReason === "error" || directContextTokens === 0) {- const messages = this.agent.state.messages;-- const estimate = estimateContextTokens(messages);-+ const estimate = estimateContextTokens(messages, this.model ?? undefined);- // Without provider usage, estimate.tokens is the pure message-size estimate.- // Only usage-backed estimates need the stale pre-compaction check.- if (estimate.lastUsageIndex !== null) {-@@ -1925,7 +1925,7 @@ export class AgentSession {- const newEntries = this.sessionManager.getEntries();- const sessionContext = this.sessionManager.buildSessionContext();- this.agent.state.messages = sessionContext.messages;-- const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages);-+ const estimatedTokensAfter = estimateMessagesTokens(sessionContext.messages, requestModel);- // Get the saved compaction entry for the extension event- const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);- if (this._extensionRunner && savedCompactionEntry) {-@@ -2852,7 +2852,7 @@ export class AgentSession {- return { tokens: null, contextWindow, percent: null };- }- }-- const estimate = estimateContextTokens(this.messages);-+ const estimate = estimateContextTokens(this.messages, model);- const percent = (estimate.tokens / contextWindow) * 100;- return {- tokens: estimate.tokens,-diff --git a/dist/core/bug-report.js b/dist/core/bug-report.js-index bf7729fffd57d7168ae03945ea07631f76cc7325..794ec01736eec36bdb3141a223bcac7e05fad11c 100644---- a/dist/core/bug-report.js-+++ b/dist/core/bug-report.js-@@ -232,12 +232,12 @@ Numbered list, as specific as the transcript allows.- Tool calls involved, files touched, model behavior, anything else that helps a developer reproduce or locate the problem.-- Do not include file contents, secrets, or credentials from the transcript; refer to files by path only. Keep the report factual and concise.`;--function selectMessages(messages, tokenBudget) {-+function selectMessages(messages, tokenBudget, model) {- const selected = [];- let tokens = 0;- for (let index = messages.length - 1; index >= 0; index--) {- const message = messages[index];-- const next = estimateTokens(message);-+ const next = estimateTokens(message, model);- if (selected.length > 0 && tokens + next > tokenBudget)- break;- selected.push(message);-@@ -249,7 +249,7 @@ function selectMessages(messages, tokenBudget) {- export async function generateBugReportSummary(options) {- const { model } = options;- const contextWindow = model.contextWindow > 0 ? model.contextWindow : 128_000;-- const messages = selectMessages(options.messages, Math.floor(contextWindow * 0.6));-+ const messages = selectMessages(options.messages, Math.floor(contextWindow * 0.6), model);- const hint = options.hint?.trim();- const prompt = [- messages.length < options.messages.length-diff --git a/dist/core/compaction/compaction.d.ts b/dist/core/compaction/compaction.d.ts-index e6bfb766ea2659180c7182ee0307d0a015dd7e0b..a9a814d8701eb2ab0f535aa187923f87975a3c28 100644---- a/dist/core/compaction/compaction.d.ts-+++ b/dist/core/compaction/compaction.d.ts-@@ -6,7 +6,7 @@- */- import type { AgentMessage, StreamFn, ThinkingLevel } from "@earendil-works/pi-agent-core";- import { type RetryCallbacks, type RetryPolicy } from "@earendil-works/pi-ai";--import type { AssistantMessage, Model, SimpleStreamOptions, TranscriptContext, Usage } from "@earendil-works/pi-ai/compat";-+import type { Api, AssistantMessage, Model, SimpleStreamOptions, TranscriptContext, Usage } from "@earendil-works/pi-ai/compat";- import { type SessionEntry } from "../session-manager.ts";- import { type FileOperations } from "./utils.ts";- /** Details stored in CompactionEntry.details for file tracking */-@@ -49,8 +49,9 @@ export interface ContextUsageEstimate {- /**- * Estimate context tokens from messages, using the last assistant usage when available.- * If there are messages after the last usage, estimate their tokens with estimateTokens.-+ * Pass `model` to scope hosted search replay projections to the estimation target.- */--export declare function estimateContextTokens(messages: AgentMessage[]): ContextUsageEstimate;-+export declare function estimateContextTokens(messages: AgentMessage[], model?: Model<Api>): ContextUsageEstimate;- /**- * Check if compaction should trigger based on context usage.- */-@@ -58,8 +59,10 @@ export declare function shouldCompact(contextTokens: number, contextWindow: numb- /**- * Estimate token count for a message using chars/4 heuristic.- * This is conservative (overestimates tokens).-+ * Standard provider roles delegate to the pi-ai estimator; pass `model` to scope-+ * hosted search replay projections to the estimation target.- */--export declare function estimateTokens(message: AgentMessage): number;-+export declare function estimateTokens(message: AgentMessage, model?: Model<Api>): number;- /**- * Find the context-visible user-role message that starts the turn containing the given entry index.- * Returns -1 if no turn start found before the index.-diff --git a/dist/core/compaction/compaction.js b/dist/core/compaction/compaction.js-index 3141f9416d52f49cc1dac0ef94deb53a28db0173..cd8009dd728b6a916703caef2a8d886f4eb9cf60 100644---- a/dist/core/compaction/compaction.js-+++ b/dist/core/compaction/compaction.js-@@ -4,8 +4,10 @@- * Pure functions for compaction logic. The session manager handles I/O,- * and after compaction the session is reloaded.- */--import { contentText, normalizeContext, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";-+import { contentText, LocalRequestError, normalizeContext, retryAssistantCall, uuidv7, } from "@earendil-works/pi-ai";- import { completeSimple } from "@earendil-works/pi-ai/compat";-+import { estimateMessageTokens, getLastAssistantUsageInfo } from "@earendil-works/pi-ai/utils/estimate";-+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";- import { convertToLlm } from "../messages.js";- import { buildSessionContext, sessionEntryToContextMessages, } from "../session-manager.js";- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";-@@ -118,24 +120,19 @@ export function getLastAssistantUsage(entries) {- }- return undefined;- }--function getLastAssistantUsageInfo(messages) {-- for (let i = messages.length - 1; i >= 0; i--) {-- const usage = getAssistantUsage(messages[i]);-- if (usage)-- return { usage, index: i };-- }-- return undefined;--}- /**- * Estimate context tokens from messages, using the last assistant usage when available.- * If there are messages after the last usage, estimate their tokens with estimateTokens.-+ * Provider-role estimation is delegated to pi-ai so hosted search replay projections and-+ * the prefix-timestamp usage anchor stay consistent with the provider request path.- */--export function estimateContextTokens(messages) {-+export function estimateContextTokens(messages, model) {-+ validateHostedSearchMessages(messages);- const usageInfo = getLastAssistantUsageInfo(messages);- if (!usageInfo) {- let estimated = 0;- for (const message of messages) {-- estimated += estimateTokens(message);-+ estimated += estimateTokens(message, model);- }- return {- tokens: estimated,-@@ -147,7 +144,7 @@ export function estimateContextTokens(messages) {- const usageTokens = calculateContextTokens(usageInfo.usage);- let trailingTokens = 0;- for (let i = usageInfo.index + 1; i < messages.length; i++) {-- trailingTokens += estimateTokens(messages[i]);-+ trailingTokens += estimateTokens(messages[i], model);- }- return {- tokens: usageTokens + trailingTokens,-@@ -186,31 +183,22 @@ function estimateTextAndImageContentChars(content) {- /**- * Estimate token count for a message using chars/4 heuristic.- * This is conservative (overestimates tokens).-+ *-+ * Standard provider roles (system/user/assistant/toolResult) delegate to the pi-ai-+ * estimator so hosted search replay projections stay identical to the provider-+ * request path; custom session roles keep their local adapters below. `model`-+ * optionally scopes hosted search projection to the target model so a model-+ * switch cannot overcount replay blocks the target would drop.- */--export function estimateTokens(message) {-+export function estimateTokens(message, model) {- let chars = 0;- switch (message.role) {-- case "user": {-- chars = estimateTextAndImageContentChars(message.content);-- return Math.ceil(chars / 4);-- }-- case "assistant": {-- const assistant = message;-- for (const block of assistant.content) {-- if (block.type === "text") {-- chars += block.text.length;-- }-- else if (block.type === "thinking") {-- chars += block.thinking.length;-- }-- else if (block.type === "toolCall") {-- chars += block.name.length + JSON.stringify(block.arguments).length;-- }-- }-- return Math.ceil(chars / 4);-- }-- case "custom":-- case "toolResult": {-+ case "system":-+ case "user":-+ case "assistant":-+ case "toolResult":-+ return estimateMessageTokens(message, model);-+ case "custom": {- chars = estimateTextAndImageContentChars(message.content);- return Math.ceil(chars / 4);- }-@@ -224,7 +212,7 @@ export function estimateTokens(message) {- return Math.ceil(chars / 4);- }- }-- return 0;-+ throw new LocalRequestError("context-validation");- }- function isCutPointMessage(message) {- switch (message.role) {-diff --git a/dist/core/compaction/utils.js b/dist/core/compaction/utils.js-index bbbb6d1c80d66e2f4f539aed8dc263f30307b113..7d71b571f787d27d0d78b471a79ead7a7028f473 100644---- a/dist/core/compaction/utils.js-+++ b/dist/core/compaction/utils.js-@@ -2,6 +2,7 @@- * Shared utilities for compaction and branch summarization.- */- import { contentText } from "@earendil-works/pi-ai";-+import { hostedSearchReplayProjection } from "@earendil-works/pi-ai/utils/hosted-search";- export function createFileOps() {- return {- read: new Set(),-@@ -102,6 +103,7 @@ export function serializeConversation(messages) {- else if (msg.role === "assistant") {- const thinkingParts = [];- const toolCalls = [];-+ const hostedSearchParts = [];- for (const block of msg.content) {- if (block.type === "thinking") {- thinkingParts.push(block.thinking);-@@ -113,6 +115,13 @@ export function serializeConversation(messages) {- .join(", ");- toolCalls.push(`${block.name}(${argsStr})`);- }-+ else if (block.type === "hostedSearch") {-+ // Keep the hosted search replay buffer explicit: the projection is the raw wire block, never a toolCall.-+ const projection = hostedSearchReplayProjection(block);-+ if (projection !== undefined) {-+ hostedSearchParts.push(JSON.stringify(projection));-+ }-+ }- }- if (thinkingParts.length > 0) {- parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);-@@ -123,6 +132,9 @@ export function serializeConversation(messages) {- if (toolCalls.length > 0) {- parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);- }-+ if (hostedSearchParts.length > 0) {-+ parts.push(`[Assistant hosted search]: ${hostedSearchParts.join("\n")}`);-+ }- }- else if (msg.role === "toolResult") {- const content = contentText(msg.content, "");diff --git a/patches/@[email protected] b/patches/@[email protected]similarity index 89%rename from patches/@[email protected]rename to patches/@[email protected]index 7f7abae59..f755032b6 100644--- a/patches/@[email protected]+++ b/patches/@[email protected]@@ -1,8 +1,8 @@diff --git a/dist/core/agent-session.js b/dist/core/agent-session.js-index 36fdb31..322876f 100644+index 07af8cf3c..b98c7f38c 100644--- a/dist/core/agent-session.js+++ b/dist/core/agent-session.js-@@ -64,10 +64,10 @@ function withoutDeletedHeaders(headers) {+@@ -67,10 +67,10 @@ function withoutDeletedHeaders(headers) {? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null)): undefined;}@@ -15,16 +15,16 @@ index 36fdb31..322876f 100644}return tokens;}-@@ -300,7 +300,7 @@ export class AgentSession {+@@ -397,7 +397,7 @@ export class AgentSession {+ _exceedsCompactionThreshold(model, projection) {+ if (model.contextWindow <= 0)+ return false;+- return shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, this.settingsManager.getCompactionSettings(this.model));++ return shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch(), model).tokens, model.contextWindow, this.settingsManager.getCompactionSettings(this.model));+ }+ async _compactBeforeNextAssistantResponse(context) {const projection = this.sessionManager.buildSessionProjection();- if (!model ||- model.contextWindow <= 0 ||-- !shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch()).tokens, model.contextWindow, settings)) {-+ !shouldCompact(estimateProjectedContextTokens(projection, this.sessionManager.getBranch(), model).tokens, model.contextWindow, settings)) {- return { ...context, messages: projection.messages };- }- await this._runAutoCompaction("threshold", false);-@@ -438,7 +438,7 @@ export class AgentSession {+@@ -569,7 +569,7 @@ export class AgentSession {entryId = manager.appendContextEdit(draft.targetId, draft.replacement);break;case "compaction": {@@ -33,25 +33,25 @@ index 36fdb31..322876f 100644entryId = manager.appendCompaction(draft.summary, draft.firstKeptEntryId, tokensBefore, draft.details, true, draft.usage);break;}-@@ -1876,7 +1876,7 @@ export class AgentSession {+@@ -2110,7 +2110,7 @@ export class AgentSession {+ }const settings = this.settingsManager.getCompactionSettings(model);- const { model: requestModel, apiKey, headers, env, } = await this._getSummarizationRequestAuth(model, this._compactionAbortController.signal);const pathEntries = this.sessionManager.getBranch();- const preparation = prepareCompaction(pathEntries, settings);-+ const preparation = prepareCompaction(pathEntries, settings, requestModel);++ const preparation = prepareCompaction(pathEntries, settings, model);if (!preparation) {// Check why we can't compactconst lastEntry = pathEntries[pathEntries.length - 1];-@@ -1933,7 +1933,7 @@ export class AgentSession {+@@ -2167,7 +2167,7 @@ export class AgentSession {this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);const newEntries = this.sessionManager.getEntries();this._refreshFinalizedContext();- const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);-+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages, requestModel);++ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages, model);// Get the saved compaction entry for the extension eventconst savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);if (this._extensionRunner && savedCompactionEntry) {-@@ -2111,11 +2111,11 @@ export class AgentSession {+@@ -2350,11 +2350,11 @@ export class AgentSession {const hasContextEdits = projection.entries.some((entry) => entry.sourceEntry.type === "context_edit");const directContextTokens = assistantMessage.usage ? calculateContextTokens(assistantMessage.usage) : 0;if (hasContextEdits) {@@ -65,7 +65,7 @@ index 36fdb31..322876f 100644// Without provider usage, estimate.tokens is the pure message-size estimate.// Only usage-backed estimates need the stale pre-compaction check.if (estimate.lastUsageIndex !== null) {-@@ -2161,7 +2161,7 @@ export class AgentSession {+@@ -2400,7 +2400,7 @@ export class AgentSession {return false;}const pathEntries = this.sessionManager.getBranch();@@ -74,16 +74,16 @@ index 36fdb31..322876f 100644if (!preparation) {return false;}-@@ -2219,7 +2219,7 @@ export class AgentSession {+@@ -2456,7 +2456,7 @@ export class AgentSession {this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);const newEntries = this.sessionManager.getEntries();this._refreshFinalizedContext();- const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages);-+ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages, requestModel);++ const estimatedTokensAfter = estimateMessagesTokens(this.sessionManager.buildSessionProjection().messages, model);// Get the saved compaction entry for the extension eventconst savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);if (this._extensionRunner && savedCompactionEntry) {-@@ -3122,7 +3122,7 @@ export class AgentSession {+@@ -3383,7 +3383,7 @@ export class AgentSession {if (!hasPostCompactionUsage)return { tokens: null, contextWindow, percent: null };}@@ -93,7 +93,7 @@ index 36fdb31..322876f 100644return {tokens: estimate.tokens,diff --git a/dist/core/bug-report.js b/dist/core/bug-report.js-index bf7729f..794ec01 100644+index bc4af31b5..24a4f8e28 100644--- a/dist/core/bug-report.js+++ b/dist/core/bug-report.js@@ -232,12 +232,12 @@ Numbered list, as specific as the transcript allows.@@ -121,7 +121,7 @@ index bf7729f..794ec01 100644const prompt = [messages.length < options.messages.lengthdiff --git a/dist/core/compaction/branch-summarization.d.ts b/dist/core/compaction/branch-summarization.d.ts-index 12cb88e..6ff7356 100644+index 12cb88ef5..6ff73567b 100644--- a/dist/core/compaction/branch-summarization.d.ts+++ b/dist/core/compaction/branch-summarization.d.ts@@ -6,7 +6,7 @@@@ -143,7 +143,7 @@ index 12cb88e..6ff7356 100644* Generate a summary of abandoned branch entries.*diff --git a/dist/core/compaction/branch-summarization.js b/dist/core/compaction/branch-summarization.js-index 3f98859..b68f7ad 100644+index 3f98859dd..b68f7adb1 100644--- a/dist/core/compaction/branch-summarization.js+++ b/dist/core/compaction/branch-summarization.js@@ -95,7 +95,7 @@ function getMessageFromEntry(entry) {@@ -174,7 +174,7 @@ index 3f98859..b68f7ad 100644return { summary: "No content to summarize" };}diff --git a/dist/core/compaction/compaction.d.ts b/dist/core/compaction/compaction.d.ts-index 04416da..fdf79d9 100644+index 04416da43..fdf79d9f2 100644--- a/dist/core/compaction/compaction.d.ts+++ b/dist/core/compaction/compaction.d.ts@@ -6,7 +6,7 @@@@ -229,7 +229,7 @@ index 04416da..fdf79d9 100644* Generate summaries for compaction using prepared data.* Returns CompactionResult - SessionManager adds uuid/parentUuid when saving.diff --git a/dist/core/compaction/compaction.js b/dist/core/compaction/compaction.js-index b86498c..1034f8a 100644+index e4992e8d2..0797ad50e 100644--- a/dist/core/compaction/compaction.js+++ b/dist/core/compaction/compaction.js@@ -4,8 +4,10 @@@@ -243,8 +243,8 @@ index b86498c..1034f8a 100644+import { validateHostedSearchMessages } from "@earendil-works/pi-ai/utils/hosted-search";import { convertToLlm } from "../messages.js";import { buildSessionProjection, sessionEntryToContextMessages, } from "../session-manager.js";- import { computeFileLists, createFileOps, extractFileOpsFromMessage, formatFileOperations, SUMMARIZATION_SYSTEM_PROMPT, serializeConversation, } from "./utils.js";-@@ -116,24 +118,19 @@ export function getLastAssistantUsage(entries) {+ import { combineUsage } from "../usage-totals.js";+@@ -95,24 +97,19 @@ export function getLastAssistantUsage(entries) {}return undefined;}@@ -274,7 +274,7 @@ index b86498c..1034f8a 100644}return {tokens: estimated,-@@ -145,7 +142,7 @@ export function estimateContextTokens(messages) {+@@ -124,7 +121,7 @@ export function estimateContextTokens(messages) {const usageTokens = calculateContextTokens(usageInfo.usage);let trailingTokens = 0;for (let i = usageInfo.index + 1; i < messages.length; i++) {@@ -283,7 +283,7 @@ index b86498c..1034f8a 100644}return {tokens: usageTokens + trailingTokens,-@@ -155,8 +152,8 @@ export function estimateContextTokens(messages) {+@@ -134,8 +131,8 @@ export function estimateContextTokens(messages) {};}/** Estimate projected context without trusting usage captured before a later edit or compaction. */@@ -294,7 +294,7 @@ index b86498c..1034f8a 100644if (estimate.lastUsageIndex !== null) {let projectedMessageIndex = 0;let usageEntryId;-@@ -181,10 +178,10 @@ export function estimateProjectedContextTokens(projection, branchEntries) {+@@ -160,10 +157,10 @@ export function estimateProjectedContextTokens(projection, branchEntries) {return estimate;}const currentSystem = getCurrentSystemMessage(projection.messages);@@ -307,7 +307,7 @@ index b86498c..1034f8a 100644}return { tokens, usageTokens: 0, trailingTokens: tokens, lastUsageIndex: null };}-@@ -219,43 +216,15 @@ function estimateTextAndImageContentChars(content) {+@@ -198,43 +195,15 @@ function estimateTextAndImageContentChars(content) {* Estimate token count for a message using chars/4 heuristic.* This is conservative (overestimates tokens).*/@@ -358,7 +358,7 @@ index b86498c..1034f8a 100644chars = estimateTextAndImageContentChars(message.content);return Math.ceil(chars / 4);}-@@ -269,7 +238,7 @@ export function estimateTokens(message) {+@@ -248,7 +217,7 @@ export function estimateTokens(message) {return Math.ceil(chars / 4);}}@@ -367,7 +367,7 @@ index b86498c..1034f8a 100644}function isCutPointMessage(message) {switch (message.role) {-@@ -352,7 +321,7 @@ export function findTurnStartIndex(entries, entryIndex, startIndex) {+@@ -331,7 +300,7 @@ export function findTurnStartIndex(entries, entryIndex, startIndex) {** Only considers entries between `startIndex` and `endIndex` (exclusive).*/@@ -376,7 +376,7 @@ index b86498c..1034f8a 100644const cutPoints = findValidCutPoints(entries, startIndex, endIndex);if (cutPoints.length === 0) {return { firstKeptEntryIndex: startIndex, turnStartIndex: -1, isSplitTurn: false };-@@ -362,7 +331,7 @@ export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {+@@ -341,7 +310,7 @@ export function findCutPoint(entries, startIndex, endIndex, keepRecentTokens) {let cutIndex = cutPoints[0]; // Default: keep from first message (not header)for (let i = endIndex - 1; i >= startIndex; i--) {const entry = entries[i];@@ -385,7 +385,7 @@ index b86498c..1034f8a 100644if (messageTokens === 0)continue;accumulatedTokens += messageTokens;-@@ -570,7 +539,7 @@ function findProjectedTurnStartIndex(entries, entryIndex, startIndex) {+@@ -549,7 +518,7 @@ function findProjectedTurnStartIndex(entries, entryIndex, startIndex) {}return -1;}@@ -394,7 +394,7 @@ index b86498c..1034f8a 100644const cutPoints = [];for (let i = startIndex; i < endIndex; i++) {const entry = entries[i];-@@ -584,7 +553,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)+@@ -563,7 +532,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)let exceededBudget = false;let cutIndex = cutPoints[0];for (let i = endIndex - 1; i >= startIndex; i--) {@@ -403,7 +403,7 @@ index b86498c..1034f8a 100644if (messageTokens === 0)continue;accumulatedTokens += messageTokens;-@@ -624,7 +593,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)+@@ -603,7 +572,7 @@ function findProjectedCutPoint(entries, startIndex, endIndex, keepRecentTokens)isSplitTurn: !startsTurn && turnStartIndex !== -1,};}@@ -412,7 +412,7 @@ index b86498c..1034f8a 100644if (pathEntries.length > 0 && pathEntries[pathEntries.length - 1].type === "compaction") {return undefined;}-@@ -642,8 +611,8 @@ export function prepareCompaction(pathEntries, settings) {+@@ -621,8 +590,8 @@ export function prepareCompaction(pathEntries, settings) {boundaryStart = prevCompactionIndex + 1;}const boundaryEnd = projectedEntries.length;@@ -424,7 +424,7 @@ index b86498c..1034f8a 100644if (!firstKeptEntry?.id)return undefined;diff --git a/dist/core/compaction/utils.js b/dist/core/compaction/utils.js-index bbbb6d1..7d71b57 100644+index 92ee18e6a..ef4df7671 100644--- a/dist/core/compaction/utils.js+++ b/dist/core/compaction/utils.js@@ -2,6 +2,7 @@@@ -435,7 +435,7 @@ index bbbb6d1..7d71b57 100644export function createFileOps() {return {read: new Set(),-@@ -102,6 +103,7 @@ export function serializeConversation(messages) {+@@ -109,6 +110,7 @@ export function serializeConversation(messages) {else if (msg.role === "assistant") {const thinkingParts = [];const toolCalls = [];@@ -443,7 +443,7 @@ index bbbb6d1..7d71b57 100644for (const block of msg.content) {if (block.type === "thinking") {thinkingParts.push(block.thinking);-@@ -113,6 +115,13 @@ export function serializeConversation(messages) {+@@ -120,6 +122,13 @@ export function serializeConversation(messages) {.join(", ");toolCalls.push(`${block.name}(${argsStr})`);}@@ -457,7 +457,7 @@ index bbbb6d1..7d71b57 100644}if (thinkingParts.length > 0) {parts.push(`[Assistant thinking]: ${thinkingParts.join("\n")}`);-@@ -123,6 +132,9 @@ export function serializeConversation(messages) {+@@ -130,6 +139,9 @@ export function serializeConversation(messages) {if (toolCalls.length > 0) {parts.push(`[Assistant tool calls]: ${toolCalls.join("; ")}`);}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 6265d9825..10c2d4e6a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -16,15 +16,15 @@ overrides:vite@5: '>=6.4.3 <7'patchedDependencies:- '@earendil-works/[email protected]':- hash: fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344- path: patches/@[email protected]- '@earendil-works/[email protected]':- hash: 6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8- path: patches/@[email protected]- '@earendil-works/[email protected]':- hash: f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e- path: patches/@[email protected]+ '@earendil-works/[email protected]':+ hash: b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7+ path: patches/@[email protected]+ '@earendil-works/[email protected]':+ hash: c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4+ path: patches/@[email protected]+ '@earendil-works/[email protected]':+ hash: 0e05051778ef4ffca9bac7ec68cae64f1d659d4b8640eeeb1a121e0f620a6abe+ path: patches/@[email protected]importers:@@ -50,8 +50,11 @@ importers:version: 0.2.2devDependencies:'@earendil-works/pi-ai':- specifier: 0.87.1- version: 0.87.1(patch_hash=6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8)([email protected])([email protected])+ specifier: 0.99.1+ version: 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-mcp':+ specifier: 0.99.1+ version: 0.99.1'@pi-desktop/agent-host':specifier: workspace:*version: link:../../packages/agent-host@@ -239,14 +242,14 @@ importers:packages/agent-runtime:dependencies:'@earendil-works/pi-agent-core':- specifier: 0.87.1- version: 0.87.1(patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])+ specifier: 0.99.1+ version: 0.99.1(patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-ai':- specifier: 0.87.1- version: 0.87.1(patch_hash=6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8)([email protected])([email protected])+ specifier: 0.99.1+ version: 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])'@earendil-works/pi-coding-agent':- specifier: 0.87.1- version: 0.87.1(patch_hash=f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e)([email protected])([email protected])+ specifier: 0.99.1+ version: 0.99.1(patch_hash=0e05051778ef4ffca9bac7ec68cae64f1d659d4b8640eeeb1a121e0f620a6abe)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])'@pi-desktop/shared':specifier: workspace:*version: link:../shared@@ -755,30 +758,38 @@ packages:search-insights:optional: true- '@earendil-works/[email protected]':- resolution: {integrity: sha512-bg7IkJGFcEaMqqYgOGUiq5Ky9RghpRfrlZ8I/v/1b4bBZ02A7t3E+6uhPRbadwWb/kWsnVFbZsqOKRN4a3LLCg==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-4xyn0IBzJ+Xu/iOGi2hjXJGAR61QEhEWZsIqTDqr+GmItdquYwBO5jYFnqGiBaTqlY12/EpM7QHoEKSHbyvOug==}engines: {node: '>=22.19.0'}- '@earendil-works/[email protected]':- resolution: {integrity: sha512-Zev3B0HK7YS5A4EZQ2XnEqiJuirx6QBiltJ+LpmjV5a/+2IU0cfKtIfnkNkORK707XOvKBY2WRtk7cAwHpbh2Q==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-zywvWnj5FujeuFI/x/CJHwwxhcLIQgjqseTA+bQgX4O8gJTcgjRd/I8SZnQDqJvxC9QcV12ujiGLviv6EgwcCg==}engines: {node: '>=22.19.0'}- '@earendil-works/[email protected]':- resolution: {integrity: sha512-X/3PfQBnnoeVdO9Cv8zHghUMglzlgNZYGNzoPnbRoGnHl3Rw3TlA2UKSUB7BRHUOxMryHXYa8dnjWZlbRheDZA==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-4nV9JKc94iPX8bwdGPc2nTuVPKIPsffhnp3WoN9NYCNqbtoOF8LhYcIs/+Sn/alroqJK/5QRu6/Z6Ck+n0hyBA==}engines: {node: '>=22.19.0'}hasBin: true- '@earendil-works/[email protected]':- resolution: {integrity: sha512-m8ArJUtVcQMSe1lLE/Ei7vX/JV7O39sWmWBsXV2NOU70F0qCp8GubA24pT3LnwTmM6LL2xV80/h6sQg85n69ew==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-oh8TMsBI3SWTN3xTQtX8u5n+BKhnVXcFagroWumfn6/WWfBnDYL/LmeQtjLb83WRTb9rcu+ZdK8rFa4vggvCJg==}+ engines: {node: '>=22.19.0'}++ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-cWUrTOqA5M73cOYMgsh9PlhDrsBhavd+n5kVY6F7BGbGl1RjqCteVCoeVMVqhngoGACVDyw1tbLjajL8l9jrHg==}engines: {node: '>=22.19.0'}hasBin: true- '@earendil-works/[email protected]':- resolution: {integrity: sha512-MC6TRQH5lgMXpcN+Vku2WMI2T8BsiUPzMQHGo81uqFZD3/9O79WWJAysEDGuzduP6R4tvtgwMLwmqIxynM10JQ==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-YCFGPkmDzLwQuIzwfbP6Vuk/g/ukKpZhwTpbcfzomuI1Fkiu6hHRkOGwAqsO3G8cTkZWkM8vmOkFJjStQNC4qA==}+ engines: {node: '>=22.19.0'}++ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-9PBPjGk+TXRtuMianpqBbHBpYpyKusESF6rwdmgD0WTZSTUQXhcKEO0hAINRLuSwy4V7yPvXV+EVV0ONY7mbpQ==}engines: {node: '>=22.19.0'}- '@earendil-works/[email protected]':- resolution: {integrity: sha512-YEH2vRyOeiO7hhN6j6AE6YwKSq2Kz2f3XR8bj1TbR+aGE/JsnY1hLPMI2pvaZfRM1n9Y00tejxFQ4zbzvF7nkQ==}+ '@earendil-works/[email protected]':+ resolution: {integrity: sha512-gZp0Guat96Fr1AuC/xqVz5B2lulZakp/PxD1lXx3lSgBdjiqmwYhJbcQ0HRrGAfy0WtMGn9b05RJr5qJf7oIuw==}engines: {node: '>=22.19.0'}'@electron-internal/[email protected]':@@ -3725,12 +3736,25 @@ packages:resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==}- resolution: {integrity: sha512-MWtTjd/gQt4jpbji61NTgFWJLoY/PdRJ6wG9/ZDRMYNMlBKrCrSlkLI+KgHP1vR1qT6LKSAyAqIxno6lcK9JiA==}+ resolution: {integrity: sha512-MX2s3u2L5racTO0CC/SWpCOasJQBCJrqLKXK+l82cAhdeF8mPMBEe/gxMm0ZFa2xpKpOFLRjxv5afYEZbBXmbQ==}+ engines: {node: '>=22.0.0'}peerDependencies:- ws: ^8.18.0+ '@aws-sdk/credential-provider-node': '>=3.972.0 <4'+ '@smithy/hash-node': '>=4.3.0 <5'+ '@smithy/signature-v4': '>=5.4.0 <6'+ undici: '>=6.28.0 <7'+ ws: ^8.21.0zod: ^3.25 || ^4.0peerDependenciesMeta:+ '@aws-sdk/credential-provider-node':+ optional: true+ '@smithy/hash-node':+ optional: true+ '@smithy/signature-v4':+ optional: true+ undici:+ optional: truews:optional: truezod:@@ -3881,6 +3905,9 @@ packages:resolution: {integrity: sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==}engines: {node: '>=10'}+ resolution: {integrity: sha512-FCqGtGOrMgzUiIrMNMA2YnsOxCNwo31dzqXvclXUC6xeT35NJLKXQJsvbeCTjvoFAwZgEAPg8U6+KAPDGXn8Mg==}+resolution: {integrity: sha512-rVprimfGBG3DR+Tq0IQG2DT5PxKth1WIGDmj5yPmlzr4YBe7uyE+Du4oVqTDXZSHGGGXRtTJEGSSePyQCMBglQ==}peerDependencies:@@ -5118,55 +5145,94 @@ snapshots:transitivePeerDependencies:- '@algolia/client-search'- '@earendil-works/[email protected]':+ '@earendil-works/[email protected]':dependencies:esbuild: 0.28.2- '@earendil-works/[email protected](patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':dependencies:- '@earendil-works/chord': 0.87.1- '@earendil-works/pi-ai': 0.87.1(patch_hash=6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8)([email protected])([email protected])- '@earendil-works/pi-telemetry': 0.87.1+ '@earendil-works/chord': 0.99.1+ '@earendil-works/pi-ai': 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-telemetry': 0.99.1diff: 8.0.4ignore: 7.0.8typebox: 1.3.27yaml: 2.9.0transitivePeerDependencies:+ - '@aws-sdk/credential-provider-node'+ - '@modelcontextprotocol/sdk'+ - '@smithy/hash-node'+ - '@smithy/signature-v4'+ - bufferutil+ - kerberos+ - supports-color+ - undici+ - utf-8-validate+ - ws+ - zod++ '@earendil-works/[email protected](patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':+ dependencies:+ '@anthropic-ai/sdk': 0.124.0([email protected])+ '@aws-sdk/client-bedrock-runtime': 3.1127.0+ '@earendil-works/pi-telemetry': 0.99.1+ '@google/genai': 2.21.0+ '@smithy/node-http-handler': 4.12.1+ http-proxy-agent: 9.1.0+ https-proxy-agent: 9.1.0+ openai: 7.19.0(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ partial-json: 0.1.7+ typebox: 1.3.27+ transitivePeerDependencies:+ - '@aws-sdk/credential-provider-node'- '@modelcontextprotocol/sdk'+ - '@smithy/hash-node'+ - '@smithy/signature-v4'- bufferutil- kerberos- supports-color+ - undici- utf-8-validate- ws- zod- '@earendil-works/[email protected](patch_hash=6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8)([email protected])([email protected])':+ '@earendil-works/[email protected](patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])':dependencies:'@anthropic-ai/sdk': 0.124.0([email protected])'@aws-sdk/client-bedrock-runtime': 3.1127.0- '@earendil-works/pi-telemetry': 0.87.1+ '@earendil-works/pi-telemetry': 0.99.1'@google/genai': 2.21.0'@smithy/node-http-handler': 4.12.1http-proxy-agent: 9.1.0https-proxy-agent: 9.1.0- openai: 6.40.0([email protected])([email protected])+ openai: 7.19.0(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])partial-json: 0.1.7typebox: 1.3.27transitivePeerDependencies:+ - '@aws-sdk/credential-provider-node'- '@modelcontextprotocol/sdk'+ - '@smithy/hash-node'+ - '@smithy/signature-v4'- bufferutil- kerberos- supports-color+ - undici- utf-8-validate- ws- zod- '@earendil-works/[email protected](patch_hash=f343e44e55203618be186df28a5ae64e8d84992452b456169afc57b2eed5310e)([email protected])([email protected])':+ '@earendil-works/[email protected]':dependencies:- '@earendil-works/chord': 0.87.1- '@earendil-works/pi-agent-core': 0.87.1(patch_hash=fd68dba636417b7920f03503bb8148d4f218bf3469babffa9d7c7863f956f344)([email protected])([email protected])- '@earendil-works/pi-ai': 0.87.1(patch_hash=6cf3998c09e8bba22cd63ceebe74a33332d9fd0c9ef3d5046941cb53513973f8)([email protected])([email protected])- '@earendil-works/pi-tui': 0.87.1+ quickjs-wasi: 3.6.2++ '@earendil-works/[email protected](patch_hash=0e05051778ef4ffca9bac7ec68cae64f1d659d4b8640eeeb1a121e0f620a6abe)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])':+ dependencies:+ '@earendil-works/chord': 0.99.1+ '@earendil-works/pi-agent-core': 0.99.1(patch_hash=b98bc9f5653147d34650f4be892612c7b34f7c553a58cb70457cf900310347d7)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-ai': 0.99.1(patch_hash=c9e66480f4eefd4a5d3ac998d3b65bf761fb22a17a238cb44c76d31448454ec4)(@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected])+ '@earendil-works/pi-codemode': 0.99.1+ '@earendil-works/pi-mcp': 0.99.1+ '@earendil-works/pi-tui': 0.99.1'@silvia-odwyer/photon-node': 0.3.4chalk: 6.0.0cross-spawn: 7.0.6@@ -5178,12 +5244,16 @@ snapshots:jiti: 2.7.0minimatch: 10.2.6proper-lockfile: 4.1.2+ quickjs-wasi: 3.6.2semver: 7.8.5typebox: 1.3.27undici: 8.10.2yaml: 2.9.0transitivePeerDependencies:+ - '@aws-sdk/credential-provider-node'- '@modelcontextprotocol/sdk'+ - '@smithy/hash-node'+ - '@smithy/signature-v4'- bufferutil- kerberos- supports-color@@ -5191,9 +5261,13 @@ snapshots:- ws- zod- '@earendil-works/[email protected]': {}+ '@earendil-works/[email protected]':+ dependencies:+ cross-spawn: 7.0.6++ '@earendil-works/[email protected]': {}- '@earendil-works/[email protected]':+ '@earendil-works/[email protected]':dependencies:get-east-asian-width: 1.6.0marked: 18.0.11@@ -8411,8 +8485,19 @@ snapshots:regex: 6.1.0regex-recursion: 6.0.2+ [email protected](@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected]):optionalDependencies:+ '@aws-sdk/credential-provider-node': 3.972.83+ '@smithy/signature-v4': 5.7.3+ undici: 6.28.0+ ws: 8.21.1+ zod: 4.4.3++ [email protected](@aws-sdk/[email protected])(@smithy/[email protected])([email protected])([email protected])([email protected]):+ optionalDependencies:+ '@aws-sdk/credential-provider-node': 3.972.83+ '@smithy/signature-v4': 5.7.3+ undici: 8.10.2ws: 8.21.1zod: 4.4.3@@ -8556,6 +8641,8 @@ snapshots:+ [email protected]: {}+dependencies:react: 19.2.8diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 953e2209b..7595fd09c 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -12,12 +12,12 @@ allowBuilds:# Drop this list once the pinned @earendil-works packages are older than# pnpm's supply-chain age gate (packages published within the last day).minimumReleaseAgeExclude:- - '@earendil-works/[email protected]'- - '@earendil-works/[email protected]'- - '@earendil-works/[email protected]'- - '@earendil-works/[email protected]'- - '@earendil-works/[email protected]'- - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'+ - '@earendil-works/[email protected]'# Advisory fixes for transitives whose parents still resolve the vulnerable# version. Drop each one once its parent ships a release that resolves the# patched version on its own.@@ -46,9 +46,9 @@ overrides:# `docs:dev` (serves 200); drop it for vitepress 2 once that ships stable.vite@5: '>=6.4.3 <7'patchedDependencies:- '@earendil-works/[email protected]': patches/@[email protected]- '@earendil-works/[email protected]': patches/@[email protected]- '@earendil-works/[email protected]': patches/@[email protected]+ '@earendil-works/[email protected]': patches/@[email protected]+ '@earendil-works/[email protected]': patches/@[email protected]+ '@earendil-works/[email protected]': patches/@[email protected]# pnpm defaults to `lowest-direct`, which makes a plain `pnpm update` resolve# every range to its floor — silently downgrading dependencies instead of# refreshing them. Pin the intent: `pnpm update` means "newest within range".diff --git a/scripts/check-release-docs.mjs b/scripts/check-release-docs.mjsindex 45d9f0514..d9fec3111 100644--- a/scripts/check-release-docs.mjs+++ b/scripts/check-release-docs.mjs@@ -79,22 +79,16 @@ for (const [relPath, pattern, label] of [}}-// 2. Bundled models.dev snapshot.-const modelsDevCatalogPath = "apps/desktop/resources/models.dev/api.json";+// 2. Settings-only operation metadata. Runtime chat metadata is supplied by Pi.+const operationMetadataPath = "apps/desktop/electron/main/settings-operation-metadata.json";try {- const catalog = JSON.parse(read(modelsDevCatalogPath));- if (- !catalog ||- Array.isArray(catalog) ||- typeof catalog !== "object" ||- !Object.values(catalog).some(- (provider) => provider && typeof provider === "object" && provider.models,- )- ) {- fail(modelsDevCatalogPath, "contains no provider model records");- }+ const catalog = JSON.parse(read(operationMetadataPath));+ if (!Array.isArray(catalog) || catalog.length === 0 || catalog.some(model =>+ !model.vendor || !model.id || !model.modalities?.output?.length ||+ (model.modalities.input?.includes("text") && model.modalities.output.every(value => value === "text")) || model.cost || model.api || model.baseUrl || model.auth+ )) fail(operationMetadataPath, "expected display-only non-chat metadata");} catch (error) {- fail(modelsDevCatalogPath, `could not parse bundled catalog: ${error.message}`);+ fail(operationMetadataPath, `could not parse settings metadata: ${error.message}`);}// 3. Shipped-locale in-app changelog. Compile the source catalog in a temporarydiff --git a/scripts/e2e-hosted-search.mjs b/scripts/e2e-hosted-search.mjsindex 3b8f66191..64581c7b8 100644--- a/scripts/e2e-hosted-search.mjs+++ b/scripts/e2e-hosted-search.mjs@@ -73,11 +73,13 @@ when the run ends; any change between the two fails the run.`);fingerprint = async () => {const tracked = listGit(["ls-files", "-z", "--", ...sourceScope]);const untracked = listGit(["ls-files", "-z", "--others", "--exclude-standard", "--", ...sourceScope]);- if (!tracked || !untracked) return null;+ const deleted = listGit(["ls-files", "-z", "--deleted", "--", ...sourceScope]);+ if (!tracked || !untracked || !deleted) return null;+ const deletedFiles = new Set(deleted);const files = [...new Set([...tracked, ...untracked])].filter((path) => !generated.test(path)).sort();const digests = [];for (const path of files) {- digests.push(`${path} ${await hash(join(root, path))}`);+ digests.push(`${path} ${deletedFiles.has(path) ? "deleted" : await hash(join(root, path))}`);}return { files: files.length, sha256: createHash("sha256").update(digests.join("\n")).digest("hex") };};@@ -87,7 +89,7 @@ when the run ends; any change between the two fails the run.`);for (const name of ["pi-ai", "pi-agent-core", "pi-coding-agent"]) {const manifest = JSON.parse(await readFile(join(root, "packages/agent-runtime/node_modules/@earendil-works", name, "package.json"), "utf8"));evidence.installedDependencies[name] = manifest.version;- assert.equal(manifest.version, "0.87.1", `${name} must match the locked pi version`);+ assert.equal(manifest.version, "0.99.1", `${name} must match the locked pi version`);}evidence.lockfileSha256 = await hash(join(root, "pnpm-lock.yaml"));evidence.head = git("rev-parse", "HEAD");diff --git a/scripts/release.mjs b/scripts/release.mjsindex 3b2d7eafa..48de4d83f 100644--- a/scripts/release.mjs+++ b/scripts/release.mjs@@ -11,7 +11,7 @@** BEFORE running this for a stable release, update every version-bearing* document (D164 + D260, docs/spec/06-delivery/06-release-runbook.md section 4.1):- * - apps/desktop/resources/models.dev/api.json is refreshed from models.dev+ * - the pinned Pi packages supply the model catalog* and committed with the release tag* - packages/shared/src/changelog*.ts (one entry for <version> in every* shipped locale, matching highlight counts) and its newest-first list in@@ -30,7 +30,7 @@** git push origin <branch> v<version>*/-import { mkdirSync, readdirSync, readFileSync, renameSync, unlinkSync, writeFileSync, existsSync } from "node:fs";+import { readdirSync, readFileSync, writeFileSync, existsSync } from "node:fs";import { execFileSync } from "node:child_process";import { fileURLToPath } from "node:url";import path from "node:path";@@ -49,70 +49,6 @@ if (!version || !/^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(version)) {}const changed = [];-const modelsDevCatalogRelPath = "apps/desktop/resources/models.dev/api.json";-const modelsDevCatalogPath = path.join(root, modelsDevCatalogRelPath);--async function refreshBundledModelsDevCatalog() {- const response = await fetch("https://models.dev/api.json", {- headers: { Accept: "application/json" },- });- if (!response.ok) {- throw new Error(`models.dev request failed (${response.status})`);- }- const text = await response.text();- const body = JSON.parse(text);- if (- !body ||- Array.isArray(body) ||- typeof body !== "object" ||- !Object.values(body).some(- (provider) => provider && typeof provider === "object" && provider.models,- )- ) {- throw new Error("models.dev response contains no provider model records");- }- // Store a deterministic minified snapshot: it keeps every models.dev field- // while avoiding formatting churn and reducing the packaged resource size.- const content = `${JSON.stringify(body)}\n`;- const current = existsSync(modelsDevCatalogPath)- ? readFileSync(modelsDevCatalogPath, "utf8")- : "";- if (current === content) return;- mkdirSync(path.dirname(modelsDevCatalogPath), { recursive: true });- const tempPath = `${modelsDevCatalogPath}.tmp-${process.pid}`;- try {- writeFileSync(tempPath, content, "utf8");- renameSync(tempPath, modelsDevCatalogPath);- } catch (error) {- try {- unlinkSync(tempPath);- } catch {- // The original error is more useful than best-effort cleanup failure.- }- throw error;- }- changed.push(modelsDevCatalogRelPath);-}--// Refresh the checked-in model catalog before changing version surfaces. The-// release commit must contain the exact public snapshot used by the artifacts;-// unlike user settings, this path is never written at runtime. A deliberate-// --skip-docs-check bump may run offline: the failure is reported, not fatal.-try {- await refreshBundledModelsDevCatalog();-} catch (error) {- if (skipDocsCheck) {- console.warn(- `Warning: could not refresh ${modelsDevCatalogRelPath} (${error.message}); ` +- "continuing because --skip-docs-check was given. Refresh it before a stable release.",- );- } else {- console.error(`Could not refresh ${modelsDevCatalogRelPath}: ${error.message}`);- console.error("Pass --skip-docs-check for a deliberate offline, non-release bump.");- process.exit(1);- }-}-function bumpPackageJson(relPath) {const file = path.join(root, relPath);if (!existsSync(file)) return;