The Open Framework for Building Agents
[1/2] refactor(eve): centralize model profile checks (#4546)
Ben Pankow8c7bb6480559
diff --git a/.changeset/model-profile.md b/.changeset/model-profile.mdnew file mode 100644index 000000000..7f4cfc73a--- /dev/null+++ b/.changeset/model-profile.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Provider options, web search, and prompt caching now read one description of the resolved model. A dynamically selected model gets provider-specific options, such as OpenAI and Anthropic safety identifiers, for the model actually called rather than its catalog id.diff --git a/packages/eve/src/harness/compaction/step.ts b/packages/eve/src/harness/compaction/step.tsindex b9176bfea..120a6d7f8 100644--- a/packages/eve/src/harness/compaction/step.ts+++ b/packages/eve/src/harness/compaction/step.ts@@ -34,6 +34,7 @@ import {} from "#protocol/message.js";import { drainMemoryCommit, prepareMemoryCompaction } from "#context/memory-lifecycle.js";import { gatewayModelId } from "#harness/model-call/usage.js";+import { resolveModelProfile } from "#harness/model-profile.js";import { getRequestEnvelopeTokens } from "#harness/request-envelope.js";import { idle } from "#harness/session-machine/transitions.js";import { resolveCallProviderOptions } from "#harness/provider-safety.js";@@ -169,13 +170,11 @@ export async function maybeCompact(input: {modelReference: requireSessionModelReference(session),resolveModel: input.resolveModel,});- const compactionModelReference =- session.agent.compactionModelReference ?? requireSessionModelReference(session);+ const profile = resolveModelProfile(compaction.model);const providerOptions = resolveCallProviderOptions({auth: input.auth,conversationId: resolveConversationId(session.rootSessionId ?? session.sessionId),- model: compaction.model,- modelReference: compactionModelReference,+ profile,providerOptions: compaction.providerOptions,}) as Parameters<typeof compactMessages>[3];@@ -227,7 +226,7 @@ export async function maybeCompact(input: {historyCompaction,providerOptions,input.telemetry,- buildGatewayAttributionHeaders(compaction.model, input.runtimeIdentity),+ buildGatewayAttributionHeaders(profile, input.runtimeIdentity),input.abortSignal,input.force === true,input.requestEnvelopeTokens === undefineddiff --git a/packages/eve/src/harness/model-call/call.ts b/packages/eve/src/harness/model-call/call.tsindex 3bc9f3197..fea086b37 100644--- a/packages/eve/src/harness/model-call/call.ts+++ b/packages/eve/src/harness/model-call/call.ts@@ -24,12 +24,7 @@ import {ContentFilteredModelResponseError,EmptyModelResponseError,} from "#harness/model-call/errors.js";-import {- type AnthropicCacheMarker,- detectPromptCachePath,- getAnthropicCacheMarker,- type PromptCachePath,-} from "#harness/prompt-cache.js";+import { type ModelProfile, resolveModelProfile } from "#harness/model-profile.js";import { estimateRequestEnvelope } from "#harness/request-envelope.js";import { summarizeKnownError } from "#harness/semantic-errors/index.js";import { discardAttempt } from "#harness/session-machine/transitions.js";@@ -111,8 +106,7 @@ interface ModelCallerInput {* may first compact the prompt, which rewrites the durable messages the step later commits.*/export class ModelCaller {- readonly cachePath: PromptCachePath;- readonly marker: AnthropicCacheMarker | undefined;+ readonly profile: ModelProfile;private readonly attributionHeaders: Record<string, string> | undefined;/** The prompt as the model reads it, projected for its history view. */private projectedMessages: HarnessModelMessage[];@@ -137,11 +131,9 @@ export class ModelCaller {this.prompt = prompt;this.input = input;- this.cachePath = detectPromptCachePath(input.model);- this.marker =- this.cachePath.kind === "anthropic-direct" ? getAnthropicCacheMarker() : undefined;+ this.profile = resolveModelProfile(input.model);this.attributionHeaders = buildGatewayAttributionHeaders(- input.model,+ this.profile,step.config.runtimeIdentity,);this.projectedMessages = input.projectedMessages;@@ -240,8 +232,8 @@ export class ModelCaller {private instructions(extraSystemNote: string | undefined) {return modelInstructions({+ anthropicCache: this.profile.anthropicCache,extraSystemNote,- marker: this.marker,session: this.step.session,systemMessages: this.request.systemMessages,});@@ -249,11 +241,10 @@ export class ModelCaller {private async prepare(options: ModelCallOptions): Promise<ModelTools> {const tools = await prepareModelTools(this.step, {- model: this.input.model,approvedTools: this.input.approvedTools,disabledProviderTools: options.disabledProviderTools,generation: this.input.generation,- marker: this.marker,+ profile: this.profile,});this.tools = tools;this.request = this.buildRequest(tools.coordinationTools);@@ -324,11 +315,7 @@ export class ModelCaller {generation.begin();// Hydrate `eve-sandbox:` file refs for this call only; history keeps the refs.this.modelMessages = await hydrateSandboxAttachments(this.request.nonSystemMessages);- if (- typeof this.input.model !== "string" &&- typeof this.input.model.provider === "string" &&- this.input.model.provider.endsWith(".chat")- ) {+ if (this.profile.filesOutsideToolResults) {this.modelMessages = moveToolResultFilesToUserMessages(this.modelMessages);}const instructions = this.instructions(options.extraSystemNote);@@ -357,8 +344,7 @@ export class ModelCaller {const hooks = buildStepHooks({auth: step.ctx?.get(AuthKey) ?? null,- cachePath: this.cachePath,- marker: this.marker,+ profile: this.profile,session: step.session,startStep: options.suppressStepStartedEmission === true ? undefined : this.input.startStep,});diff --git a/packages/eve/src/harness/model-call/model.ts b/packages/eve/src/harness/model-call/model.tsindex e0c8bb608..95bb0f3c8 100644--- a/packages/eve/src/harness/model-call/model.ts+++ b/packages/eve/src/harness/model-call/model.ts@@ -4,25 +4,24 @@ import type { CompactionConfig, HarnessSession, ToolLoopHarnessConfig } from "#himport type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import { contextStorage } from "#context/container.js";import { getEffectiveModelSelection } from "#context/effective-model.js";-import { resolveProviderHeaders } from "#internal/gateway.js";+import type { ModelProfile } from "#harness/model-profile.js";+import { appendPackageUserAgent } from "#internal/user-agent.js";+/**- * Builds AI Gateway app attribution headers when the model is gateway-routed.- *- * Bare model ids and `gateway.*` model instances route through AI Gateway.- * Direct-provider model instances receive no Gateway-specific headers.+ * Builds AI Gateway app attribution headers, including eve's User-Agent product token, for a+ * Gateway-routed model. Direct-provider models receive no Gateway-specific headers.*/export function buildGatewayAttributionHeaders(- model: LanguageModel,+ profile: ModelProfile,runtimeIdentity: ToolLoopHarnessConfig["runtimeIdentity"],): Record<string, string> | undefined {- const providerHeaders = resolveProviderHeaders(model);- if (providerHeaders === undefined) return undefined;+ if (!profile.gateway) return undefined;const title = runtimeIdentity?.agentName ?? runtimeIdentity?.agentId;const deploymentHost = process.env.VERCEL_PROJECT_PRODUCTION_URL || process.env.VERCEL_URL;const referer = deploymentHost ? `https://${deploymentHost}` : undefined;- const headers: Record<string, string> = { ...providerHeaders };+ const headers: Record<string, string> = Object.fromEntries(appendPackageUserAgent(new Headers()));if (title) headers["x-title"] = title;if (referer) headers["http-referer"] = referer;return headers;diff --git a/packages/eve/src/harness/model-call/request.ts b/packages/eve/src/harness/model-call/request.tsindex 70f13aded..7849776ca 100644--- a/packages/eve/src/harness/model-call/request.ts+++ b/packages/eve/src/harness/model-call/request.ts@@ -11,7 +11,7 @@ import {type HarnessModelMessage,type UserModelMessage,} from "#harness/messages.js";-import { type AnthropicCacheMarker, applySystemCacheBreakpoint } from "#harness/prompt-cache.js";+import { applySystemCacheBreakpoint } from "#harness/prompt-cache.js";import type { Step } from "#harness/step/context.js";import type { HarnessSession, HarnessToolMap } from "#harness/types.js";@@ -57,7 +57,7 @@ export function requestMessages(export function modelInstructions(input: {readonly session: HarnessSession;readonly systemMessages: readonly SystemModelMessage[];- readonly marker: AnthropicCacheMarker | undefined;+ readonly anthropicCache: boolean;readonly extraSystemNote?: string;}): SystemModelMessage | string | undefined {const { session } = input;@@ -72,7 +72,7 @@ export function modelInstructions(input: {: [];const instructions = [...extra, ...base, ...input.systemMessages];return mergeSystemInstructions(- input.marker ? applySystemCacheBreakpoint(instructions, input.marker) : instructions,+ input.anthropicCache ? applySystemCacheBreakpoint(instructions) : instructions,);}diff --git a/packages/eve/src/harness/model-call/tools.ts b/packages/eve/src/harness/model-call/tools.tsindex 75683b698..45e1e01ee 100644--- a/packages/eve/src/harness/model-call/tools.ts+++ b/packages/eve/src/harness/model-call/tools.ts@@ -1,4 +1,3 @@-import { resolveModelProvider } from "#internal/gateway.js";import type { ToolSet } from "ai";import { buildDynamicTools } from "#context/build-dynamic-tools.js";@@ -8,11 +7,12 @@ import { getAdvertisedTools } from "#harness/advertised-tools.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";import type { GenerationSteering } from "#harness/generation-steering.js";-import { type AnthropicCacheMarker, applyLastToolCacheBreakpoint } from "#harness/prompt-cache.js";+import type { ModelProfile } from "#harness/model-profile.js";+import { applyLastToolCacheBreakpoint } from "#harness/prompt-cache.js";import type { Step } from "#harness/step/context.js";import { buildToolSetFromDefinitions, buildToolSetWithProviderTools } from "#harness/tools.js";import { isTurnCancellation } from "#harness/turn-cancellation.js";-import { type HarnessToolMap, requireSessionModelReference } from "#harness/types.js";+import type { HarnessToolMap } from "#harness/types.js";import { createLogger, logError } from "#internal/logging.js";import { toModelSchema } from "#tools/schema.js";@@ -40,14 +40,13 @@ export async function prepareModelTools(step: Step,input: {readonly approvedTools: ReadonlySet<string>;- readonly model: import("ai").LanguageModel;readonly disabledProviderTools?: ReadonlySet<string>;readonly generation: GenerationSteering;- readonly marker: AnthropicCacheMarker | undefined;+ readonly profile: ModelProfile;},): Promise<ModelTools> {const { ctx } = step;- const { approvedTools, disabledProviderTools, marker } = input;+ const { approvedTools, disabledProviderTools, profile } = input;const coordinationTools = withTaskTools(getAdvertisedTools({session: step.session,@@ -58,8 +57,7 @@ export async function prepareModelTools(const flatTools = await buildToolSetWithProviderTools({approvedTools,disabledProviderTools,- modelProvider: resolveModelProvider(input.model),- modelReference: requireSessionModelReference(step.session),+ profile,tools: coordinationTools,});@@ -120,7 +118,9 @@ export async function prepareModelTools(}}- const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;+ const effectiveTools = profile.anthropicCache+ ? applyLastToolCacheBreakpoint(modelTools)+ : modelTools;for (const tool of Object.values(effectiveTools)) {// Whatever produced this tool, the AI SDK must only receive its own// schema type; see toModelSchema.diff --git a/packages/eve/src/harness/model-profile.test.ts b/packages/eve/src/harness/model-profile.test.tsnew file mode 100644index 000000000..abe5921a9--- /dev/null+++ b/packages/eve/src/harness/model-profile.test.ts@@ -0,0 +1,57 @@+import { createGateway, type LanguageModel } from "ai";+import { MockLanguageModelV3 } from "ai/test";+import { describe, expect, it } from "vitest";++import { type ModelProfile, resolveModelProfile } from "#harness/model-profile.js";++function model(provider: string, modelId = "test-model"): LanguageModel {+ return new MockLanguageModelV3({ modelId, provider });+}++const direct = { anthropicCache: false, filesOutsideToolResults: false, gateway: false };++describe("resolveModelProfile", () => {+ it.each<[string, LanguageModel, ModelProfile]>([+ ["a bare Gateway id", "openai/gpt-5", { ...direct, gateway: true, provider: "openai" }],+ [+ "a Gateway instance used by local auth",+ createGateway({ apiKey: "test-key" })("anthropic/claude-opus-5"),+ { ...direct, gateway: true, provider: "anthropic" },+ ],+ [+ "a namespaced Gateway provider",+ model("gateway.language-model", "google/gemini-3"),+ { ...direct, gateway: true, provider: "google" },+ ],+ [+ "direct Anthropic",+ model("anthropic.messages"),+ { ...direct, anthropicCache: true, provider: "anthropic" },+ ],+ [+ "Vertex Anthropic",+ model("vertex.anthropic"),+ { ...direct, anthropicCache: true, provider: "vertex" },+ ],+ [+ "Bedrock Converse with an Anthropic model id",+ model("amazon-bedrock", "ANTHROPIC.claude-3-5-sonnet-20241022-v2:0"),+ { ...direct, anthropicCache: true, provider: "amazon-bedrock" },+ ],+ [+ "Bedrock Converse with another model id",+ model("amazon-bedrock", "amazon.nova-pro-v1:0"),+ { ...direct, provider: "amazon-bedrock" },+ ],+ ["OpenAI Responses", model("openai.responses"), { ...direct, provider: "openai" }],+ [+ "OpenAI Chat Completions",+ model("openai.chat"),+ { ...direct, filesOutsideToolResults: true, provider: "openai" },+ ],+ ["the ChatGPT subscription", model("codex.responses"), { ...direct, provider: "codex" }],+ ["a provider-less test double", {} as LanguageModel, { ...direct, provider: "" }],+ ])("describes %s", (_, input, expected) => {+ expect(resolveModelProfile(input)).toEqual(expected);+ });+});diff --git a/packages/eve/src/harness/model-profile.ts b/packages/eve/src/harness/model-profile.tsnew file mode 100644index 000000000..0bc97527d--- /dev/null+++ b/packages/eve/src/harness/model-profile.ts@@ -0,0 +1,52 @@+import type { LanguageModel } from "ai";++/**+ * What eve assumes about the model serving one call. Every decision that shapes a request for+ * its provider reads this record, so a step and its compaction agree about the model.+ */+export interface ModelProfile {+ /** Routed through AI Gateway, which caches automatically and serves Gateway tools. */+ readonly gateway: boolean;+ /**+ * Who serves the request: a Gateway id's vendor (`openai/gpt-5` → `openai`), which Gateway+ * translates for whichever host it routes to, otherwise the SDK provider's top-level name+ * (`anthropic`, `amazon-bedrock`, `vertex`, `azure`). It names the host, not the model family:+ * hosts of the same family accept different things (Bedrock and Vertex reject Anthropic's web+ * search tool), so a capability a host shares with its family gets its own flag, like+ * `anthropicCache`.+ */+ readonly provider: string;+ /** Takes Anthropic prompt-cache breakpoints. */+ readonly anthropicCache: boolean;+ /** Chat Completions APIs can't carry files in tool results, so they move to user messages. */+ readonly filesOutsideToolResults: boolean;+}++export function resolveModelProfile(model: LanguageModel): ModelProfile {+ const provider = typeof model === "string" ? "gateway" : lowerCaseOrEmpty(model.provider);+ const modelId = typeof model === "string" ? model : lowerCaseOrEmpty(model.modelId);+ const topLevelProvider = provider.split(".")[0]!;+ if (topLevelProvider === "gateway") {+ return {+ anthropicCache: false,+ filesOutsideToolResults: false,+ gateway: true,+ provider: modelId.split("/")[0]!,+ };+ }+ return {+ // The Bedrock Converse provider reports `amazon-bedrock` and carries the Anthropic identity+ // in the model id (`anthropic.claude-…`).+ anthropicCache:+ provider.includes("anthropic") ||+ (provider.includes("bedrock") && modelId.includes("anthropic")),+ filesOutsideToolResults: provider.endsWith(".chat"),+ gateway: false,+ provider: topLevelProvider,+ };+}++/** A test double may omit `provider` or `modelId`; it reads as a direct model with no known provider. */+function lowerCaseOrEmpty(value: unknown): string {+ return typeof value === "string" ? value.toLowerCase() : "";+}diff --git a/packages/eve/src/harness/prompt-cache.test.ts b/packages/eve/src/harness/prompt-cache.test.tsindex 773783c50..35c58e9b1 100644--- a/packages/eve/src/harness/prompt-cache.test.ts+++ b/packages/eve/src/harness/prompt-cache.test.ts@@ -1,125 +1,16 @@-import { createGateway, type LanguageModel, type ModelMessage, type ToolSet } from "ai";+import type { ModelMessage, ToolSet } from "ai";import { describe, expect, it } from "vitest";import {applyConversationCacheControl,applyLastToolCacheBreakpoint,- detectPromptCachePath,- getAnthropicCacheMarker,mergeGatewayAutoCaching,} from "#harness/prompt-cache.js";-function makeObjectModel(provider: string, modelId = "test-model"): LanguageModel {- return {- provider,- modelId,- specificationVersion: "v3",- } as unknown as LanguageModel;-}--describe("detectPromptCachePath", () => {- it("keeps automatic caching for Gateway provider objects used by local auth", () => {- const model = createGateway({ apiKey: "test-key" })("anthropic/claude-opus-5");- expect(detectPromptCachePath(model)).toEqual({ kind: "gateway-auto" });- });-- it("recognizes namespaced Gateway providers", () => {- expect(detectPromptCachePath(makeObjectModel("gateway.language-model"))).toEqual({- kind: "gateway-auto",- });- });-- it("returns gateway-auto for any string model id", () => {- expect(detectPromptCachePath("anthropic/claude-sonnet-4-5")).toEqual({- kind: "gateway-auto",- });- expect(detectPromptCachePath("bedrock/anthropic.claude-3-5-sonnet-20241022-v2:0")).toEqual({- kind: "gateway-auto",- });- expect(detectPromptCachePath("vertex/claude-sonnet-4-5")).toEqual({- kind: "gateway-auto",- });- expect(detectPromptCachePath("openai/gpt-5")).toEqual({ kind: "gateway-auto" });- });-- it("returns anthropic-direct for a direct Anthropic provider instance", () => {- expect(detectPromptCachePath(makeObjectModel("anthropic.messages"))).toEqual({- kind: "anthropic-direct",- });- });-- it("returns anthropic-direct for the Bedrock Anthropic subpath", () => {- expect(detectPromptCachePath(makeObjectModel("bedrock.anthropic"))).toEqual({- kind: "anthropic-direct",- });- });-- it("returns anthropic-direct for the Vertex Anthropic subpath", () => {- expect(detectPromptCachePath(makeObjectModel("vertex.anthropic"))).toEqual({- kind: "anthropic-direct",- });- });-- it("returns anthropic-direct regardless of case", () => {- expect(detectPromptCachePath(makeObjectModel("Anthropic.Messages"))).toEqual({- kind: "anthropic-direct",- });- });-- it("returns none for a direct OpenAI provider instance", () => {- expect(detectPromptCachePath(makeObjectModel("openai.chat"))).toEqual({ kind: "none" });- });-- it("returns none for a direct Google Gemini provider instance", () => {- expect(detectPromptCachePath(makeObjectModel("google.generative-ai"))).toEqual({- kind: "none",- });- });-- it("returns none for generic Bedrock Converse (no anthropic subpath)", () => {- expect(detectPromptCachePath(makeObjectModel("bedrock"))).toEqual({ kind: "none" });- });-- it("returns anthropic-direct for a Bedrock Converse model whose id is Anthropic", () => {- // `@ai-sdk/amazon-bedrock` reports provider `amazon-bedrock` and carries- // the Anthropic identity in the model id.- expect(- detectPromptCachePath(- makeObjectModel("amazon-bedrock", "anthropic.claude-3-5-sonnet-20241022-v2:0"),- ),- ).toEqual({ kind: "anthropic-direct" });- });-- it("matches the Bedrock Anthropic model id regardless of case", () => {- expect(- detectPromptCachePath(makeObjectModel("amazon-bedrock", "ANTHROPIC.CLAUDE-3-5-SONNET")),- ).toEqual({ kind: "anthropic-direct" });- });-- it("returns none for a non-Anthropic Bedrock Converse model id", () => {- expect(- detectPromptCachePath(makeObjectModel("amazon-bedrock", "amazon.nova-pro-v1:0")),- ).toEqual({ kind: "none" });- });-});--describe("getAnthropicCacheMarker", () => {- it("returns the Anthropic cache marker shape", () => {- expect(getAnthropicCacheMarker()).toEqual({- anthropic: { cacheControl: { type: "ephemeral" } },- bedrock: { cachePoint: { type: "default" } },- });- });-- it("returns a deeply frozen object", () => {- const marker = getAnthropicCacheMarker();- expect(Object.isFrozen(marker)).toBe(true);- expect(Object.isFrozen(marker.anthropic)).toBe(true);- expect(Object.isFrozen(marker.anthropic.cacheControl)).toBe(true);- expect(Object.isFrozen(marker.bedrock)).toBe(true);- expect(Object.isFrozen(marker.bedrock.cachePoint)).toBe(true);- });-});+const marker = {+ anthropic: { cacheControl: { type: "ephemeral" } },+ bedrock: { cachePoint: { type: "default" } },+};describe("mergeGatewayAutoCaching", () => {it("creates a fresh gateway block when base is undefined", () => {@@ -159,11 +50,9 @@ describe("mergeGatewayAutoCaching", () => {});describe("applyLastToolCacheBreakpoint", () => {- const marker = getAnthropicCacheMarker();-it("is a no-op for an empty tool set", () => {const tools = {} as ToolSet;- expect(applyLastToolCacheBreakpoint(tools, marker)).toEqual({});+ expect(applyLastToolCacheBreakpoint(tools)).toEqual({});});it("attaches the marker only to the last tool", () => {@@ -173,7 +62,7 @@ describe("applyLastToolCacheBreakpoint", () => {gamma: { description: "third" },} as unknown as ToolSet;- const result = applyLastToolCacheBreakpoint(tools, marker) as Record<+ const result = applyLastToolCacheBreakpoint(tools) as Record<string,{ description: string; providerOptions?: unknown }>;@@ -194,7 +83,7 @@ describe("applyLastToolCacheBreakpoint", () => {},} as unknown as ToolSet;- const result = applyLastToolCacheBreakpoint(tools, marker) as Record<+ const result = applyLastToolCacheBreakpoint(tools) as Record<string,{ providerOptions: Record<string, unknown> } | undefined>;@@ -213,24 +102,22 @@ describe("applyLastToolCacheBreakpoint", () => {two: { description: "second" },} as unknown as ToolSet;const snapshot = JSON.parse(JSON.stringify(tools));- applyLastToolCacheBreakpoint(tools, marker);+ applyLastToolCacheBreakpoint(tools);expect(tools).toEqual(snapshot);});});describe("applyConversationCacheControl", () => {- const marker = getAnthropicCacheMarker();-it("returns a fresh empty array for empty input", () => {const input: readonly ModelMessage[] = [];- const out = applyConversationCacheControl(input, marker);+ const out = applyConversationCacheControl(input);expect(out).toEqual([]);expect(out).not.toBe(input);});it("marks a sole user message", () => {const messages: ModelMessage[] = [{ role: "user", content: "hi" }];- const out = applyConversationCacheControl(messages, marker);+ const out = applyConversationCacheControl(messages);expect(out[0]).toEqual({role: "user",content: "hi",@@ -245,7 +132,7 @@ describe("applyConversationCacheControl", () => {{ role: "user", content: "hi2" },{ role: "assistant", content: "yo2" },];- const out = applyConversationCacheControl(messages, marker);+ const out = applyConversationCacheControl(messages);expect(out[0]).toEqual({ role: "user", content: "hi" });expect(out[1]).toEqual({@@ -280,7 +167,7 @@ describe("applyConversationCacheControl", () => {],},];- const out = applyConversationCacheControl(messages, marker);+ const out = applyConversationCacheControl(messages);// The trailing tool-result message carries the final breakpoint.expect((out[2] as { providerOptions?: unknown }).providerOptions).toEqual({ ...marker });@@ -300,7 +187,7 @@ describe("applyConversationCacheControl", () => {providerOptions: { openai: { someKey: "someValue" } },},];- const out = applyConversationCacheControl(messages, marker);+ const out = applyConversationCacheControl(messages);expect((out[0] as { providerOptions: Record<string, unknown> }).providerOptions).toEqual({openai: { someKey: "someValue" },...marker,@@ -316,7 +203,7 @@ describe("applyConversationCacheControl", () => {const originalRef0 = messages[0];const originalRef1 = messages[1];- const out = applyConversationCacheControl(messages, marker);+ const out = applyConversationCacheControl(messages);expect(messages).toEqual(snapshot);expect(messages[0]).toBe(originalRef0);diff --git a/packages/eve/src/harness/prompt-cache.ts b/packages/eve/src/harness/prompt-cache.tsindex 4e0929949..010046034 100644--- a/packages/eve/src/harness/prompt-cache.ts+++ b/packages/eve/src/harness/prompt-cache.ts@@ -1,16 +1,7 @@-import type { LanguageModel, ModelMessage, SystemModelMessage, ToolSet } from "ai";-import { isGatewayModel } from "#internal/gateway.js";+import type { ModelMessage, SystemModelMessage, ToolSet } from "ai";/**- * The caching strategy to apply for one harness step.- */-export type PromptCachePath =- | { readonly kind: "gateway-auto" }- | { readonly kind: "anthropic-direct" }- | { readonly kind: "none" };--/**- * Cache marker injected on the Anthropic-direct path.+ * Cache marker for models that take Anthropic prompt-cache breakpoints.** The marker carries two provider namespaces because Anthropic models are* reachable through providers that read different provider-options keys:@@ -22,22 +13,10 @@ export type PromptCachePath =* Converse provider, which does not understand `anthropic.cacheControl`.** A provider ignores namespaces it does not own, so carrying both is safe on- * every Anthropic-direct request regardless of which provider serves it.- */-export interface AnthropicCacheMarker {- readonly anthropic: {- readonly cacheControl: { readonly type: "ephemeral" };- };- readonly bedrock: {- readonly cachePoint: { readonly type: "default" };- };-}--/**- * Shared frozen marker. All direct-Anthropic breakpoints in the harness share- * this instance to avoid allocating per-message.+ * every request regardless of which provider serves it. Every breakpoint shares+ * this frozen instance.*/-const ANTHROPIC_CACHE_MARKER: AnthropicCacheMarker = Object.freeze({+const ANTHROPIC_CACHE_MARKER = Object.freeze({anthropic: Object.freeze({cacheControl: Object.freeze({ type: "ephemeral" as const }),}),@@ -46,41 +25,6 @@ const ANTHROPIC_CACHE_MARKER: AnthropicCacheMarker = Object.freeze({}),});-/**- * Detects which prompt caching path applies to a resolved model.- *- * Runs once per harness step right after `resolveModel()`.- */-export function detectPromptCachePath(model: LanguageModel): PromptCachePath {- if (typeof model === "string" || isGatewayModel(model)) {- return { kind: "gateway-auto" };- }-- const providerName = typeof model.provider === "string" ? model.provider.toLowerCase() : "";- if (providerName.includes("anthropic")) {- return { kind: "anthropic-direct" };- }-- // The standard `@ai-sdk/amazon-bedrock` Converse provider reports its- // provider as `amazon-bedrock` and carries the Anthropic identity in the- // model id (e.g. `anthropic.claude-3-5-sonnet-20241022-v2:0`), so it must be- // matched on the model id rather than the provider name.- const modelId = typeof model.modelId === "string" ? model.modelId.toLowerCase() : "";- if (providerName.includes("bedrock") && modelId.includes("anthropic")) {- return { kind: "anthropic-direct" };- }-- return { kind: "none" };-}--/**- * Returns the shared Anthropic cache marker used on the `anthropic-direct`- * path. Exposed for unit tests and for the harness wiring layer.- */-export function getAnthropicCacheMarker(): AnthropicCacheMarker {- return ANTHROPIC_CACHE_MARKER;-}-/*** Returns a new `providerOptions` object with* `gateway.caching = "auto"` merged into the existing `gateway` sub-object.@@ -112,17 +56,14 @@ export function mergeGatewayAutoCaching(/*** Returns a new ToolSet where the last tool entry carries the Anthropic- * cache marker on `providerOptions`. Used on the `anthropic-direct` path+ * cache marker on `providerOptions`. Used for Anthropic-cache models* to place a stable breakpoint at the end of the tools block, caching the* full tool definitions across every turn.** No-op when `tools` has no entries. Preserves existing `providerOptions`* on tools (merges the cache marker in via spread).*/-export function applyLastToolCacheBreakpoint(- tools: ToolSet,- marker: AnthropicCacheMarker,-): ToolSet {+export function applyLastToolCacheBreakpoint(tools: ToolSet): ToolSet {const entries = Object.entries(tools);if (entries.length === 0) {return tools;@@ -140,7 +81,7 @@ export function applyLastToolCacheBreakpoint(...tool,providerOptions: {...existingProviderOptions,- ...marker,+ ...ANTHROPIC_CACHE_MARKER,},};} else {@@ -162,7 +103,6 @@ export function applyLastToolCacheBreakpoint(*/export function applySystemCacheBreakpoint(instructions: readonly SystemModelMessage[],- marker: AnthropicCacheMarker,): SystemModelMessage[] {if (instructions.length === 0) return [...instructions];@@ -172,7 +112,7 @@ export function applySystemCacheBreakpoint(...last,providerOptions: {...last.providerOptions,- ...marker,+ ...ANTHROPIC_CACHE_MARKER,},};return result;@@ -200,10 +140,7 @@ export function applySystemCacheBreakpoint(* appends more content blocks than Anthropic's backward boundary scan* covers.*/-export function applyConversationCacheControl(- messages: readonly ModelMessage[],- marker: AnthropicCacheMarker,-): ModelMessage[] {+export function applyConversationCacheControl(messages: readonly ModelMessage[]): ModelMessage[] {if (messages.length === 0) {return [...messages];}@@ -219,7 +156,7 @@ export function applyConversationCacheControl(...message,providerOptions: {...message.providerOptions,- ...marker,+ ...ANTHROPIC_CACHE_MARKER,},};};diff --git a/packages/eve/src/harness/provider-safety.test.ts b/packages/eve/src/harness/provider-safety.test.tsindex a3a6a7148..14b2fb2bc 100644--- a/packages/eve/src/harness/provider-safety.test.ts+++ b/packages/eve/src/harness/provider-safety.test.ts@@ -20,22 +20,18 @@ describe("mergeProviderSafetyIdentifier", () => {openai: { safetyIdentifier: "authored", store: false },};- expect(- mergeProviderSafetyIdentifier({ id: "openai/gpt-5.6-sol" }, providerOptions, auth),- ).toEqual(providerOptions);+ expect(mergeProviderSafetyIdentifier("openai", providerOptions, auth)).toEqual(providerOptions);});it("treats an authored OpenAI null as explicit", () => {const providerOptions = { openai: { safetyIdentifier: null } };- expect(- mergeProviderSafetyIdentifier({ id: "openai/gpt-5.6-sol" }, providerOptions, auth),- ).toEqual(providerOptions);+ expect(mergeProviderSafetyIdentifier("openai", providerOptions, auth)).toEqual(providerOptions);});it("sets the OpenAI safety identifier while preserving other options", () => {const result = mergeProviderSafetyIdentifier(- { id: "openai/gpt-5.6-sol" },+ "openai",{gateway: { caching: "auto" },openai: { store: false },@@ -61,14 +57,14 @@ describe("mergeProviderSafetyIdentifier", () => {},};- expect(- mergeProviderSafetyIdentifier({ id: "anthropic/claude-opus-5" }, providerOptions, auth),- ).toEqual(providerOptions);+ expect(mergeProviderSafetyIdentifier("anthropic", providerOptions, auth)).toEqual(+ providerOptions,+ );});it("sets the Anthropic user ID while preserving other options", () => {const result = mergeProviderSafetyIdentifier(- { id: "anthropic/claude-opus-5" },+ "anthropic",{gateway: { caching: "auto" },anthropic: { thinking: { type: "adaptive" } },@@ -89,16 +85,12 @@ describe("mergeProviderSafetyIdentifier", () => {it("does not add a safety identifier for another provider", () => {const providerOptions = { google: { structuredOutputs: true } };- expect(- mergeProviderSafetyIdentifier({ id: "google/gemini-3.1-pro" }, providerOptions, auth),- ).toBe(providerOptions);+ expect(mergeProviderSafetyIdentifier("google", providerOptions, auth)).toBe(providerOptions);});it("does not add a safety identifier without an active caller", () => {const providerOptions = { anthropic: { thinking: { type: "adaptive" } } };- expect(- mergeProviderSafetyIdentifier({ id: "anthropic/claude-opus-5" }, providerOptions, null),- ).toBe(providerOptions);+ expect(mergeProviderSafetyIdentifier("anthropic", providerOptions, null)).toBe(providerOptions);});});diff --git a/packages/eve/src/harness/provider-safety.ts b/packages/eve/src/harness/provider-safety.tsindex 334b73764..f188a7a06 100644--- a/packages/eve/src/harness/provider-safety.ts+++ b/packages/eve/src/harness/provider-safety.ts@@ -1,8 +1,6 @@-import type { LanguageModel } from "ai";import type { SessionAuthContext } from "#channel/types.js";-import { mergeGatewaySessionId } from "#internal/gateway.js";+import type { ModelProfile } from "#harness/model-profile.js";import { invocationOwnerKey } from "#internal/invocation/metadata.js";-import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import { mergeObjects } from "#shared/objects.js";/**@@ -10,7 +8,7 @@ import { mergeObjects } from "#shared/objects.js";* raw eve principal. Authored provider options take precedence over the default.*/export function mergeProviderSafetyIdentifier(- modelReference: RuntimeModelReference,+ provider: string,providerOptions: Readonly<Record<string, unknown>> | undefined,auth: SessionAuthContext | null,): Record<string, unknown> | undefined {@@ -19,7 +17,6 @@ export function mergeProviderSafetyIdentifier(}const ownerKey = invocationOwnerKey(auth);- const provider = modelReference.id.split("/", 1)[0]?.toLowerCase();const defaults =provider === "openai"? { openai: { safetyIdentifier: ownerKey } }@@ -34,13 +31,35 @@ export function mergeProviderSafetyIdentifier(export function resolveCallProviderOptions(input: {readonly auth: SessionAuthContext | null;readonly conversationId: string;- readonly model: LanguageModel;- readonly modelReference: RuntimeModelReference;+ readonly profile: ModelProfile;readonly providerOptions: Readonly<Record<string, unknown>> | undefined;}): Record<string, unknown> | undefined {- return mergeGatewaySessionId(- input.model,- mergeProviderSafetyIdentifier(input.modelReference, input.providerOptions, input.auth),- input.conversationId,+ const providerOptions = mergeProviderSafetyIdentifier(+ input.profile.provider,+ input.providerOptions,+ input.auth,);+ return input.profile.gateway+ ? mergeGatewaySessionId(providerOptions, input.conversationId)+ : providerOptions;+}++/** Groups Gateway generations under the same identity used by eve's agent spans. */+function mergeGatewaySessionId(+ providerOptions: Readonly<Record<string, unknown>> | undefined,+ conversationId: string,+): Record<string, unknown> | undefined {+ const gateway = providerOptions?.gateway;+ const gatewayOptions =+ gateway !== null && typeof gateway === "object" && !Array.isArray(gateway)+ ? (gateway as Record<string, unknown>)+ : undefined;+ if (typeof gatewayOptions?.sessionId === "string" && gatewayOptions.sessionId.trim()) {+ return providerOptions;+ }++ return {+ ...providerOptions,+ gateway: { ...gatewayOptions, sessionId: conversationId },+ };}diff --git a/packages/eve/src/harness/provider-tools.test.ts b/packages/eve/src/harness/provider-tools.test.tsindex f96f934f3..923b89eff 100644--- a/packages/eve/src/harness/provider-tools.test.ts+++ b/packages/eve/src/harness/provider-tools.test.ts@@ -1,6 +1,8 @@import { beforeEach, describe, expect, it, vi } from "vitest";-import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";+import { MockLanguageModelV3 } from "ai/test";++import { resolveModelProfile } from "#harness/model-profile.js";import {WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,WEB_SEARCH_EXA_OUTPUT_SCHEMA,@@ -87,86 +89,23 @@ describe("resolveWebSearchBackend", () => {openaiWebSearch.mockClear();});- it("returns 'exa' for an OpenAI gateway model by default", () => {- const ref: RuntimeModelReference = { id: "openai/gpt-5.4" };- expect(resolveWebSearchBackend(ref)).toBe("exa");- });-- it("does not use a Gateway backend for a live model from another provider", () => {- const ref: RuntimeModelReference = { id: "openrouter/openai/gpt-5" };- expect(resolveWebSearchBackend(ref, "exa", "openrouter.chat")).toBeNull();+ it.each([+ ["openai/gpt-5.4", undefined, "exa"],+ ["openai/gpt-5.4", "parallel", "parallel"],+ ["anthropic/claude-opus-4.6", undefined, "exa"],+ ] as const)("uses Gateway search for Gateway model %s", (model, provider, expected) => {+ expect(resolveWebSearchBackend(resolveModelProfile(model), provider)).toBe(expected);});- it("returns the configured Parallel provider for a gateway model", () => {- const ref: RuntimeModelReference = { id: "openai/gpt-5.4" };- expect(resolveWebSearchBackend(ref, "parallel")).toBe("parallel");- });-- it("returns 'openai' for a BYO OpenAI model", () => {- const ref: RuntimeModelReference = {- id: "openai.chat/gpt-5.4",- source: {- exportName: "openai",- sourceKind: "module",- logicalPath: "agent.ts",- sourceId: "agent.ts",- },- };- expect(resolveWebSearchBackend(ref, "exa")).toBe("openai");- });-- it("returns 'exa' for an Anthropic gateway model", () => {- const ref: RuntimeModelReference = { id: "anthropic/claude-opus-4.6" };- expect(resolveWebSearchBackend(ref)).toBe("exa");- });-- it("returns 'anthropic' for a BYO Anthropic model", () => {- const ref: RuntimeModelReference = {- id: "anthropic.messages/claude-opus-4.6",- source: {- exportName: "anthropic",- sourceKind: "module",- logicalPath: "agent.ts",- sourceId: "agent.ts",- },- };- expect(resolveWebSearchBackend(ref)).toBe("anthropic");- });-- it("returns 'google' for a BYO Google model", () => {- const ref: RuntimeModelReference = {- id: "google.generative-ai/gemini-3.1-pro",- source: {- exportName: "google",- sourceKind: "module",- logicalPath: "agent.ts",- sourceId: "agent.ts",- },- };- expect(resolveWebSearchBackend(ref)).toBe("google");- });-- it("returns 'exa' for a Google model on AI Gateway", () => {- const ref: RuntimeModelReference = { id: "google/gemini-3.1-pro" };- expect(resolveWebSearchBackend(ref)).toBe("exa");- });-- it("returns 'exa' for any other AI Gateway model", () => {- const ref: RuntimeModelReference = { id: "mistral/mistral-large" };- expect(resolveWebSearchBackend(ref)).toBe("exa");- });-- it("returns null for a BYO non-OpenAI/Anthropic/Google model", () => {- const ref: RuntimeModelReference = {- id: "some-provider/some-model",- source: {- exportName: "model",- sourceKind: "module",- logicalPath: "agent.ts",- sourceId: "agent.ts",- },- };- expect(resolveWebSearchBackend(ref)).toBeNull();+ it.each([+ ["openai.responses", "openai"],+ ["anthropic.messages", "anthropic"],+ ["google.generative-ai", "google"],+ ["openrouter.chat", null],+ ["some-provider", null],+ ] as const)("uses native search for direct provider %s when it has one", (provider, expected) => {+ const model = new MockLanguageModelV3({ provider });+ expect(resolveWebSearchBackend(resolveModelProfile(model), "exa")).toBe(expected);});it("uses Anthropic webSearch_20250305 to avoid the unsupported beta header", async () => {diff --git a/packages/eve/src/harness/provider-tools.ts b/packages/eve/src/harness/provider-tools.tsindex 20355a7e4..2bdfb38e1 100644--- a/packages/eve/src/harness/provider-tools.ts+++ b/packages/eve/src/harness/provider-tools.ts@@ -1,6 +1,6 @@import { jsonSchema, type JSONSchema7, type ToolSet } from "ai";-import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";+import type { ModelProfile } from "#harness/model-profile.js";import {WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,WEB_SEARCH_EXA_OUTPUT_SCHEMA,@@ -71,46 +71,22 @@ export function resolveWebSearchOutputSchema(}/**- * Determines the web search backend for a model reference.- *- * - All AI Gateway models: the configured search provider (Exa by default)- * - Direct/BYO OpenAI models: native OpenAI search- * - Direct/BYO Anthropic models: native Anthropic search- * - Direct/BYO Google models: native Google search grounding- * - Other BYO models: not available (returns `null`)- *- * `modelProvider` is the provider of the resolved AI SDK model. It is needed- * for live dynamic selections because their runtime reference has no source- * metadata to distinguish a direct provider from AI Gateway.+ * Determines the web search backend for a model: the configured search provider (Exa by+ * default) on AI Gateway, the provider's native search for direct OpenAI, Anthropic, and Google+ * models, and none (`null`) for any other direct model.*/export function resolveWebSearchBackend(- modelRef: RuntimeModelReference,+ profile: ModelProfile,gatewayProvider: WebSearchProvider = "exa",- modelProvider?: string,): WebSearchBackend | null {- const providerId =- modelProvider?.split(".")[0] ??- (modelRef.source === undefined ? "gateway" : (modelRef.id.split("/")[0] ?? ""));-- if (providerId === "gateway") {- return gatewayProvider;- }-- if (providerId === "openai" || providerId.startsWith("openai.")) {- return "openai";- }-- if (providerId === "anthropic" || providerId.startsWith("anthropic.")) {- return "anthropic";- }-- if (providerId === "google" || providerId.startsWith("google.")) {- return "google";- }-- return null;+ if (profile.gateway) return gatewayProvider;+ return NATIVE_WEB_SEARCH_PROVIDERS.has(profile.provider)+ ? (profile.provider as WebSearchBackend)+ : null;}+const NATIVE_WEB_SEARCH_PROVIDERS: ReadonlySet<string> = new Set(["anthropic", "google", "openai"]);+/*** Constructs the AI SDK provider tool for web search based on the resolved* backend. Called once per harness step when web search is enabled.diff --git a/packages/eve/src/harness/step-hooks.test.ts b/packages/eve/src/harness/step-hooks.test.tsindex 5e6418072..e5c95d40e 100644--- a/packages/eve/src/harness/step-hooks.test.ts+++ b/packages/eve/src/harness/step-hooks.test.ts@@ -3,6 +3,7 @@ import { MockLanguageModelV3 } from "ai/test";import { describe, expect, it, vi } from "vitest";import { ContextContainer, contextStorage } from "#context/container.js";import { ConversationIdKey } from "#context/keys.js";+import { resolveModelProfile } from "#harness/model-profile.js";import { buildStepHooks } from "#harness/step-hooks.js";import type { HarnessSession } from "#harness/types.js";@@ -24,8 +25,7 @@ describe("buildStepHooks", () => {it("starts the step from onStepStart, not prepareStep", async () => {const startStep = vi.fn(async () => {});const hooks = buildStepHooks({- cachePath: { kind: "none" },- marker: undefined,+ profile: resolveModelProfile("openai/gpt-5"),session: createSession(),startStep,});@@ -65,11 +65,8 @@ describe("buildStepHooks", () => {};const context = new ContextContainer();context.set(ConversationIdKey, "forwarded-conversation");- const prepare = (- model: LanguageModel,- cachePath: Parameters<typeof buildStepHooks>[0]["cachePath"],- ) =>- buildStepHooks({ marker: undefined, cachePath, session }).prepareStep({+ const prepare = (model: LanguageModel) =>+ buildStepHooks({ profile: resolveModelProfile(model), session }).prepareStep({messages: [],model,instructions: undefined,@@ -84,9 +81,7 @@ describe("buildStepHooks", () => {});await contextStorage.run(context, async () => {- expect(- (await prepare("anthropic/claude-sonnet-4-5", { kind: "gateway-auto" }))?.providerOptions,- ).toEqual({+ expect((await prepare("anthropic/claude-sonnet-4-5"))?.providerOptions).toEqual({gateway: { caching: "auto", order: ["bedrock"], sessionId: "forwarded-conversation" },openai: { store: false },});@@ -97,7 +92,6 @@ describe("buildStepHooks", () => {modelId: "anthropic/claude-sonnet-4-5",provider: "gateway.language-model",}),- { kind: "gateway-auto" },))?.providerOptions,).toEqual({@@ -111,7 +105,6 @@ describe("buildStepHooks", () => {modelId: "claude-sonnet-4-5",provider: "anthropic.messages",}),- { kind: "none" },))?.providerOptions,).toEqual({@@ -123,8 +116,7 @@ describe("buildStepHooks", () => {it("preserves an authored Gateway session ID", async () => {const hooks = buildStepHooks({- cachePath: { kind: "none" },- marker: undefined,+ profile: resolveModelProfile("anthropic/claude-sonnet-4-5"),session: {...createSession(),agent: {@@ -150,6 +142,8 @@ describe("buildStepHooks", () => {stepNumber: 0,steps: [],});- expect(prepared?.providerOptions).toEqual({ gateway: { sessionId: "authored-session" } });+ expect(prepared?.providerOptions).toEqual({+ gateway: { caching: "auto", sessionId: "authored-session" },+ });});});diff --git a/packages/eve/src/harness/step-hooks.ts b/packages/eve/src/harness/step-hooks.tsindex 6360d729d..4d3e4ac34 100644--- a/packages/eve/src/harness/step-hooks.ts+++ b/packages/eve/src/harness/step-hooks.ts@@ -25,12 +25,8 @@ import {import type { TurnPosition } from "#harness/session-machine/view.js";import { normalizeAssistantStepFinishReason } from "#harness/finish-reason.js";import { extractToolApprovalInputRequests } from "#harness/input-extraction.js";-import {- type AnthropicCacheMarker,- applyConversationCacheControl,- mergeGatewayAutoCaching,- type PromptCachePath,-} from "#harness/prompt-cache.js";+import type { ModelProfile } from "#harness/model-profile.js";+import { applyConversationCacheControl, mergeGatewayAutoCaching } from "#harness/prompt-cache.js";import { resolveCallProviderOptions } from "#harness/provider-safety.js";import {collectActionPresentation,@@ -84,13 +80,12 @@ export type HarnessStepResult = Pick<*/interface StepHooksInput {readonly auth?: import("#channel/types.js").SessionAuthContext | null;- readonly cachePath: PromptCachePath;+ readonly profile: ModelProfile;/*** Starts the model step the SDK is about to run. Omitted when the step already started, as* it has for a retry of the same step.*/readonly startStep?: (messages: readonly ModelMessage[]) => Promise<void>;- readonly marker: AnthropicCacheMarker | undefined;readonly session: HarnessSession;}@@ -169,26 +164,20 @@ export function buildStepHooks(input: StepHooksInput): StepHooks {// session history — no prepareStep snapshot required.// -------------------------------------------------------------------------- const prepareStep: PrepareStepFunction<ToolSet> = async ({ messages, model }) => {- let processed = messages;-- if (input.cachePath.kind === "anthropic-direct" && input.marker) {- processed = applyConversationCacheControl([...messages], input.marker);- }-+ const prepareStep: PrepareStepFunction<ToolSet> = async ({ messages }) => {+ const { profile } = input;const stepResult: NonNullable<Awaited<ReturnType<PrepareStepFunction<ToolSet>>>> = {- messages: processed,+ messages: profile.anthropicCache ? applyConversationCacheControl(messages) : messages,};const modelReference = requireSessionModelReference(session);const providerOptions = resolveCallProviderOptions({auth: input.auth ?? contextStorage.getStore()?.get(AuthKey) ?? null,conversationId: resolveConversationId(session.rootSessionId ?? session.sessionId),- model,- modelReference,+ profile,providerOptions: modelReference.providerOptions,});- if (input.cachePath.kind === "gateway-auto") {+ if (profile.gateway) {stepResult.providerOptions = mergeGatewayAutoCaching(providerOptions) as NonNullable<typeof stepResult.providerOptions>;diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex a90835317..24cf1d7f9 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -1,4 +1,5 @@-import { asSchema, type JSONSchema7, jsonSchema } from "ai";+import { asSchema, type JSONSchema7, jsonSchema, type LanguageModel } from "ai";+import { MockLanguageModelV3 } from "ai/test";import { describe, expect, it } from "vitest";import { z } from "zod";@@ -7,7 +8,7 @@ import { SessionKey, type Session } from "#context/keys.js";import { SCHEDULE_APP_AUTH } from "#channel/schedule-auth.js";import { always, never, once } from "#tools/approval/policies.js";-import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";+import { resolveModelProfile } from "#harness/model-profile.js";import {WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,WEB_SEARCH_EXA_OUTPUT_SCHEMA,@@ -31,6 +32,10 @@ function getJsonSchema(tool: unknown): unknown {return (tool as { inputSchema: { jsonSchema: unknown } }).inputSchema.jsonSchema;}+function directModel(provider: string): LanguageModel {+ return new MockLanguageModelV3({ provider });+}+function getOutputJsonSchema(tool: unknown): unknown {return (tool as { outputSchema: { jsonSchema: unknown } }).outputSchema.jsonSchema;}@@ -499,51 +504,15 @@ describe("buildToolSet", () => {});it.each([- [{ id: "openai/gpt-5.4" }, "gateway.chat", WEB_SEARCH_EXA_OUTPUT_SCHEMA],- [{ id: "anthropic/claude-opus-4.6" }, "gateway.chat", WEB_SEARCH_EXA_OUTPUT_SCHEMA],- [- {- id: "openai.chat/gpt-5.4",- source: {- exportName: "model",- logicalPath: "agent.ts",- sourceId: "agent.ts",- sourceKind: "module",- },- },- "openai.chat",- WEB_SEARCH_OPENAI_OUTPUT_SCHEMA,- ],- [- {- id: "anthropic.messages/claude-opus-4.6",- source: {- exportName: "model",- logicalPath: "agent.ts",- sourceId: "agent.ts",- sourceKind: "module",- },- },- "anthropic.messages",- WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA,- ],- [- {- id: "google.generative-ai/gemini-3.1-pro",- source: {- exportName: "model",- logicalPath: "agent.ts",- sourceId: "agent.ts",- sourceKind: "module",- },- },- "google.generative-ai",- WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA,- ],- [{ id: "mistral/mistral-large" }, "gateway.chat", WEB_SEARCH_EXA_OUTPUT_SCHEMA],- ] satisfies Array<readonly [RuntimeModelReference, string, JsonObject]>)(+ ["openai/gpt-5.4", WEB_SEARCH_EXA_OUTPUT_SCHEMA],+ ["anthropic/claude-opus-4.6", WEB_SEARCH_EXA_OUTPUT_SCHEMA],+ [directModel("openai.chat"), WEB_SEARCH_OPENAI_OUTPUT_SCHEMA],+ [directModel("anthropic.messages"), WEB_SEARCH_ANTHROPIC_OUTPUT_SCHEMA],+ [directModel("google.generative-ai"), WEB_SEARCH_GOOGLE_OUTPUT_SCHEMA],+ ["mistral/mistral-large", WEB_SEARCH_EXA_OUTPUT_SCHEMA],+ ] satisfies Array<readonly [LanguageModel, JsonObject]>)("injects the selected web_search provider output schema",- async (modelReference, modelProvider, expectedOutputSchema) => {+ async (model, expectedOutputSchema) => {const tools: HarnessToolMap = new Map<string, HarnessToolDefinition>([["web_search",@@ -560,8 +529,7 @@ describe("buildToolSet", () => {]);const result = await buildToolSetWithProviderTools({- modelReference,- modelProvider,+ profile: resolveModelProfile(model),tools,});@@ -586,8 +554,7 @@ describe("buildToolSet", () => {]);const result = await buildToolSetWithProviderTools({- modelReference: { id: "openai/gpt-5.4" },- modelProvider: "gateway.chat",+ profile: resolveModelProfile("openai/gpt-5.4"),tools,});@@ -610,8 +577,7 @@ describe("buildToolSet", () => {],]);const result = await buildToolSetWithProviderTools({- modelReference: { id: "openai/gpt-5.4" },- modelProvider: "gateway.chat",+ profile: resolveModelProfile("openai/gpt-5.4"),tools,});const search = result.web_search!;@@ -630,16 +596,14 @@ describe("buildToolSet", () => {).resolves.toMatchObject({ success: true });const disabled = await buildToolSetWithProviderTools({- modelReference: { id: "openai/gpt-5.4" },- modelProvider: "gateway.chat",+ profile: resolveModelProfile("openai/gpt-5.4"),tools,disabledProviderTools: new Set(["web_search"]),});expect(disabled.web_search).toBeUndefined();const direct = await buildToolSetWithProviderTools({- modelReference: { id: "gpt-5.4" },- modelProvider: "openai.chat",+ profile: resolveModelProfile(directModel("openai.chat")),tools,});expect(direct.web_search).toMatchObject({ id: "openai.web_search" });@@ -662,16 +626,7 @@ describe("buildToolSet", () => {]);const result = await buildToolSetWithProviderTools({- modelReference: {- id: "some-provider/some-model",- source: {- exportName: "model",- logicalPath: "agent.ts",- sourceId: "agent.ts",- sourceKind: "module",- },- },- modelProvider: "some-provider",+ profile: resolveModelProfile(directModel("some-provider")),tools,});diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex 2e842fe72..16a91669a 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -1,6 +1,6 @@import { type ToolApprovalConfiguration, type ToolApprovalStatus, type ToolSet, tool } from "ai";-import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";+import type { ModelProfile } from "#harness/model-profile.js";import { isObject } from "#shared/guards.js";import type { HarnessToolDefinition } from "#harness/execute-tool.js";import { resolveApprovalPolicy, type ApprovalStatus } from "#approval/definition.js";@@ -193,8 +193,7 @@ function normalizeToolExecuteOutput(export async function buildToolSetWithProviderTools(input: {readonly approvedTools?: ReadonlySet<string>;readonly disabledProviderTools?: ReadonlySet<string>;- readonly modelReference: RuntimeModelReference;- readonly modelProvider?: string;+ readonly profile: ModelProfile;readonly tools: HarnessToolMap;}): Promise<ToolSet> {const disabled = input.disabledProviderTools;@@ -213,11 +212,7 @@ export async function buildToolSetWithProviderTools(input: {definition.execute === undefined &&!disabled?.has(definition.name)) {- const backend = resolveWebSearchBackend(- input.modelReference,- handling.provider,- input.modelProvider,- );+ const backend = resolveWebSearchBackend(input.profile, handling.provider);if (backend === null) {delete tools[definition.name];} else {diff --git a/packages/eve/src/internal/gateway.test.ts b/packages/eve/src/internal/gateway.test.tsindex 737ce10d7..3076e37bf 100644--- a/packages/eve/src/internal/gateway.test.ts+++ b/packages/eve/src/internal/gateway.test.ts@@ -1,14 +1,9 @@-import type { LanguageModel } from "ai";-import { MockLanguageModelV3 } from "ai/test";import { describe, expect, it, vi } from "vitest";import {AI_GATEWAY_MODELS_CATALOG_URL,AI_GATEWAY_MODELS_URL,vercelGatewayFetch,- isGatewayModel,- resolveModelProvider,- resolveProviderHeaders,} from "#internal/gateway.js";describe("Gateway endpoints", () => {@@ -32,56 +27,3 @@ describe("vercelGatewayFetch", () => {expect(new Headers(init?.headers).get("user-agent")).toMatch(/^eve\/.+/);});});--describe("resolveProviderHeaders", () => {- it("returns the eve user-agent for bare model ids", () => {- expect(resolveProviderHeaders("anthropic/claude-sonnet-4-5")).toEqual({- "user-agent": expect.stringMatching(/^eve\/.+/),- });- });-- it("returns the eve user-agent for gateway model instances", () => {- const model = new MockLanguageModelV3({- provider: "gateway.language-model",- modelId: "anthropic/claude-sonnet-4-5",- });- expect(resolveProviderHeaders(model)).toEqual({- "user-agent": expect.stringMatching(/^eve\/.+/),- });- });-- it("returns undefined for direct-provider model instances", () => {- const model = new MockLanguageModelV3({- provider: "anthropic.messages",- modelId: "claude-sonnet-4-5",- });- expect(resolveProviderHeaders(model)).toBeUndefined();- });-});--describe("resolveModelProvider", () => {- it("normalizes bare model ids to the Gateway provider", () => {- expect(resolveModelProvider("anthropic/claude-sonnet-4-5")).toBe("gateway");- });-- it("preserves the provider reported by model instances", () => {- const gatewayModel = new MockLanguageModelV3({- provider: "gateway.language-model",- modelId: "anthropic/claude-sonnet-4-5",- });- const directModel = new MockLanguageModelV3({- provider: "anthropic.messages",- modelId: "claude-sonnet-4-5",- });-- expect(resolveModelProvider(gatewayModel)).toBe("gateway.language-model");- expect(resolveModelProvider(directModel)).toBe("anthropic.messages");- });-- it("tolerates provider-less test doubles", () => {- const model = {} as LanguageModel;-- expect(resolveModelProvider(model)).toBeUndefined();- expect(isGatewayModel(model)).toBe(false);- });-});diff --git a/packages/eve/src/internal/gateway.ts b/packages/eve/src/internal/gateway.tsindex dc401ae12..4d95cdf6e 100644--- a/packages/eve/src/internal/gateway.ts+++ b/packages/eve/src/internal/gateway.ts@@ -1,6 +1,4 @@-import type { LanguageModel } from "ai";--import { appendPackageUserAgent, withPackageUserAgent } from "#internal/user-agent.js";+import { withPackageUserAgent } from "#internal/user-agent.js";const GATEWAY_BASE_URL = "https://ai-gateway.vercel.sh";@@ -17,46 +15,3 @@ export const AI_GATEWAY_MODELS_CATALOG_URL = `${GATEWAY_BASE_URL}/v1/models/cata* constructed per call site, so this is a value rather than a factory.*/export const vercelGatewayFetch: typeof globalThis.fetch = withPackageUserAgent();--/**- * Request headers eve attaches for a model's provider, or `undefined` when- * the provider needs none. Gateway-routed models (bare ids and `gateway.*`- * instances) get the eve User-Agent product token so AI Gateway can attribute- * the traffic; direct-provider models get no extra headers.- */-export function resolveProviderHeaders(model: LanguageModel): Record<string, string> | undefined {- if (!isGatewayModel(model)) return undefined;- return Object.fromEntries(appendPackageUserAgent(new Headers()));-}--/** Provider identity reported by the model, normalized for bare Gateway ids. */-export function resolveModelProvider(model: LanguageModel): string | undefined {- return typeof model === "string" ? "gateway" : model.provider;-}--export function isGatewayModel(model: LanguageModel): boolean {- return resolveModelProvider(model)?.split(".")[0] === "gateway";-}--/** Groups Gateway generations under the same identity used by eve's agent spans. */-export function mergeGatewaySessionId(- model: LanguageModel,- providerOptions: Readonly<Record<string, unknown>> | undefined,- conversationId: string,-): Record<string, unknown> | undefined {- if (!isGatewayModel(model)) return providerOptions;-- const gateway = providerOptions?.gateway;- const gatewayOptions =- gateway !== null && typeof gateway === "object" && !Array.isArray(gateway)- ? (gateway as Record<string, unknown>)- : undefined;- if (typeof gatewayOptions?.sessionId === "string" && gatewayOptions.sessionId.trim()) {- return providerOptions;- }-- return {- ...providerOptions,- gateway: { ...gatewayOptions, sessionId: conversationId },- };-}