The Open Framework for Building Agents
Allow ctx.agent to override local child models (#5087)
Casey Gowrie8aba0f6a6ee3
diff --git a/.changeset/ctx-agent-model-override.md b/.changeset/ctx-agent-model-override.mdnew file mode 100644index 000000000..f1edb3b1a--- /dev/null+++ b/.changeset/ctx-agent-model-override.md@@ -0,0 +1,5 @@+---+"eve": patch+---++Allow authored workflow tools to select an AI Gateway model when they open a local session with `ctx.agent()`. The child keeps the target agent's other configuration, and the selected model applies for the session's lifetime.diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdxindex aaa7e5f19..67a001f83 100644--- a/docs/subagents/index.mdx+++ b/docs/subagents/index.mdx@@ -34,6 +34,8 @@ The copy uses the root's instructions, connections, auth, and sandbox. It receivThe parent transfers data to the child through the `message` input it gives the subagent. Do not include sensitive data in a subagent request unless that child and its inherited tools, connections, sandbox, and telemetry path are appropriate for that data.+An authored workflow can open the same root-copy target through `ctx.agent("agent")`. To keep the copied configuration but use another model for that child session, pass a [model override to `ctx.agent`](./tools/workflows#delegate-work-ctxagent). The model-facing built-in tool does not accept a model choice.+To prevent the root session from delegating to a fresh copy of itself, set `tool: false` on the root agent:```ts title="agent/agent.ts"diff --git a/docs/tools/workflows.mdx b/docs/tools/workflows.mdxindex eccfd22b7..f2451c207 100644--- a/docs/tools/workflows.mdx+++ b/docs/tools/workflows.mdx@@ -502,9 +502,9 @@ and can only show the model's input. Both compose: `approval` before the run, `c## Delegate work: `ctx.agent`-`ctx.agent(name)` returns a session with an agent, shaped like the TypeScript client's session. The-session opens on its first `send`, and each `response.result()` resolves when that message's turn-ends:+`ctx.agent(name, options?)` returns a session with an agent, shaped like the TypeScript client's+session. The session opens on its first `send`, and each `response.result()` resolves when that+message's turn ends:```tsimport { z } from "zod";@@ -517,6 +517,37 @@ const response = await reviewer.send("Review the deployment plan for security riconst { data, message, status } = await response.result();```+Set `model` when the workflow should run a local child with a different AI Gateway model. The+selection belongs to the returned session, so every message sent through that handle uses it:++```ts+const reviewer = ctx.agent("agent", {+ model: "anthropic/claude-opus-5.5",+});++const response = await reviewer.send("Review the migration plan.", {+ signal: ctx.abortSignal,+});+```++The override changes only the model. The child keeps the target agent's instructions, tools, skills,+connections, sandbox behavior, limits, reasoning, and explicit compaction model. Pass a selection+object to override model-specific settings too:++```ts+const reviewer = ctx.agent("agent", {+ model: {+ model: "anthropic/claude-opus-5.5",+ modelContextWindowTokens: 200_000,+ reasoning: "high",+ },+});+```++The selection must contain an AI Gateway model id. A live AI SDK `LanguageModel` cannot cross the+durable workflow boundary. A remote agent rejects the option because its deployment owns its model+configuration.+The name is an available agent target. On the root agent, `"agent"` starts a copy of the root agent.A declared subagent uses its path-derived name and remains callable when hidden with `tool: false`or `disableTool()`. Delegated root copies and declared subagent contexts do not expose the built-in@@ -544,8 +575,8 @@ client's `MessageResult` fields, plus `error` when the turn failed:| `status` | `"waiting"` when the session waits for its next message, `"completed"` when the session ended with the turn, or `"failed"` when the turn failed. A cancelled turn is `"waiting"` with neither `data` nor `message`. || `error` | `{ message }` with the reason the turn failed, present only when `status` is `"failed"`. |-Every `ctx.agent(name)` call returns a new session that only the workflow run can address. The model-does not see it; it sees what the tool returns. A local child runs as the caller's principal with the+Every `ctx.agent(name, options?)` call returns a new session that only the workflow run can address.+The model does not see it; it sees what the tool returns. A local child runs as the caller's principal with thecaller's capabilities. A remote child does not inherit the caller's session principal by default;the receiving deployment determines its identity from the outbound request. To forward the caller'sidentity, set `forwardPrincipal: true` on the remote agent and configure the receiver'sdiff --git a/e2e/fixtures/agent-agent-tool-controls/agent/agent.ts b/e2e/fixtures/agent-agent-tool-controls/agent/agent.tsindex fd048d4fd..27525bacf 100644--- a/e2e/fixtures/agent-agent-tool-controls/agent/agent.ts+++ b/e2e/fixtures/agent-agent-tool-controls/agent/agent.ts@@ -18,7 +18,14 @@ export default defineAgent({const inspectAgents = request.userMessages.some((message) =>message.includes("E2E_INSPECT_WORKFLOW_AGENTS"),);- const toolName = inspectAgents ? "inspect-agents" : "invoke-self";+ const modelOverride = request.userMessages.some((message) =>+ message.includes("E2E_MODEL_OVERRIDE_ROOT_COPY"),+ );+ const toolName = inspectAgents+ ? "inspect-agents"+ : modelOverride+ ? "invoke-self-with-model"+ : "invoke-self";const result = request.toolResults.find((entry) => entry.name === toolName);return result === undefined? { toolCalls: [{ name: toolName, input: {} }] }diff --git a/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self-with-model.ts b/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self-with-model.tsnew file mode 100644index 000000000..4418b6879--- /dev/null+++ b/e2e/fixtures/agent-agent-tool-controls/agent/tools/invoke-self-with-model.ts@@ -0,0 +1,28 @@+import {+ defineWorkflowTool,+ type WorkflowToolContext,+ type WorkflowToolDefinition,+} from "eve/tools";++import { CTX_AGENT_SELECTED_MODEL } from "../../constants";++async function execute(+ _input: Record<string, unknown>,+ ctx: WorkflowToolContext,+): Promise<string | null> {+ "use workflow";++ const response = await ctx+ .agent("agent", { model: CTX_AGENT_SELECTED_MODEL })+ .send("Review Alice's sample plan and reply when the review is complete.");+ const { message } = await response.result();+ return message ?? null;+}++const tool: WorkflowToolDefinition<Record<string, unknown>, string | null> = defineWorkflowTool({+ description: "Invoke a root copy with an authored model override.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ execute,+});++export default tool;diff --git a/e2e/fixtures/agent-agent-tool-controls/constants.ts b/e2e/fixtures/agent-agent-tool-controls/constants.tsnew file mode 100644index 000000000..7c9c7e297--- /dev/null+++ b/e2e/fixtures/agent-agent-tool-controls/constants.ts@@ -0,0 +1 @@+export const CTX_AGENT_SELECTED_MODEL = "openai/gpt-6.1-sol";diff --git a/e2e/fixtures/agent-agent-tool-controls/evals/ctx-agent-model-override.eval.ts b/e2e/fixtures/agent-agent-tool-controls/evals/ctx-agent-model-override.eval.tsnew file mode 100644index 000000000..acb8392b5--- /dev/null+++ b/e2e/fixtures/agent-agent-tool-controls/evals/ctx-agent-model-override.eval.ts@@ -0,0 +1,17 @@+import { defineEval } from "eve/evals";++export default defineEval({+ tags: ["real-model"],+ description: "An authored workflow opens a root copy with a model override.",+ async test(t) {+ const turn = await t.send(+ "E2E_MODEL_OVERRIDE_ROOT_COPY Alice asks a root copy to review a sample plan.",+ );++ turn.expectOk();+ turn.calledTool("invoke-self-with-model", { count: 1 });+ turn.event("agent.started", { count: 1, data: { name: "agent" } });+ t.succeeded();+ t.noFailedActions();+ },+});diff --git a/packages/eve/extension-contracts/compatibility/tool/v95.ts b/packages/eve/extension-contracts/compatibility/tool/v95.tsnew file mode 100644index 000000000..c16ec5a60--- /dev/null+++ b/packages/eve/extension-contracts/compatibility/tool/v95.ts@@ -0,0 +1,11 @@+// Epoch 95 workflow tools can continue opening agent sessions without options.+import { defineWorkflowTool } from "#public/tools/index.js";++export default defineWorkflowTool({+ description: "Ask the reviewer to inspect a deployment.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false },+ async execute(_input, ctx) {+ const response = await ctx.agent("reviewer").send("Review the deployment.");+ return await response.result();+ },+});diff --git a/packages/eve/extension-contracts/reports/tool/v96.json b/packages/eve/extension-contracts/reports/tool/v96.jsonnew file mode 100644index 000000000..d81a643a8--- /dev/null+++ b/packages/eve/extension-contracts/reports/tool/v96.json@@ -0,0 +1,29 @@+{+ "kind": "eve-extension-capability-contract",+ "capability": "tool",+ "epoch": 96,+ "sha256": "6716ec0ac2b62f2d4c4045ce2d3543e89febb82effc7aea82852026a352db488",+ "exports": [+ "AgentRouterInput",+ "AgentRouterTool",+ "WorkflowStepToolContext",+ "WorkflowTool",+ "WorkflowToolDefinition",+ "WorkflowToolInput",+ "WorkflowToolOptions",+ "agentRouter",+ "decide",+ "defaultWebSearch",+ "defineTool",+ "defineWorkflowTool",+ "disableTool",+ "isDisabledToolSentinel",+ "isWebSearchToolDefinition",+ "serializeModelInputSchema",+ "toolOutput",+ "toolOutputPart",+ "toolResultFrom",+ "webSearch",+ "workflow"+ ]+}diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.tsindex a1171c976..556463373 100644--- a/packages/eve/src/compiler/extension-compatibility.ts+++ b/packages/eve/src/compiler/extension-compatibility.ts@@ -22,10 +22,10 @@ interface ExtensionCapabilityContract {const EXTENSION_CAPABILITY_CONTRACTS = {extension: { current: 1, supported: [1], dropped: {} },tool: {- current: 95,+ current: 96,supported: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 29, 30, 31, 32, 34, 35, 76, 77, 78, 80, 81, 82, 84,- 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,+ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,],dropped: {14: "TaskExec.delegated was removed; migrate to workflow-backed background tools",diff --git a/packages/eve/src/context/keys.ts b/packages/eve/src/context/keys.tsindex 87089736b..1f4fa9e08 100644--- a/packages/eve/src/context/keys.ts+++ b/packages/eve/src/context/keys.ts@@ -29,6 +29,7 @@ import type { InstrumentationChannelDeliveryRef } from "#instrumentation/lifecycimport type { UserModelMessage } from "#harness/messages.js";import type { HandleEventFn } from "#harness/types.js";import type { PersistedDynamicToolMetadata } from "#context/dynamic-tool-metadata.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import type { DynamicRemoteAgentConfig } from "#runtime/subagents/dynamic-remote-agent-config.js";import type { SandboxAccess, SandboxSessionEndReason } from "#sandbox/state.js";@@ -344,6 +345,10 @@ export const DynamicSubagentAgentConfigKey = new ContextKey<DynamicSubagentAgent"eve.dynamicSubagentAgentConfig",);+export const AgentSessionRuntimeOverridesKey = new ContextKey<AgentSessionRuntimeOverrides>(+ "eve.agentSessionRuntimeOverrides",+);+// ---------------------------------------------------------------------------// Dynamic skill keys// ---------------------------------------------------------------------------diff --git a/packages/eve/src/execution/agent-sessions/runtime-overrides.ts b/packages/eve/src/execution/agent-sessions/runtime-overrides.tsnew file mode 100644index 000000000..98a71b560--- /dev/null+++ b/packages/eve/src/execution/agent-sessions/runtime-overrides.ts@@ -0,0 +1,6 @@+import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";++/** Invocation-bound configuration applied after the target agent is resolved. */+export interface AgentSessionRuntimeOverrides {+ readonly model: RuntimeModelReference;+}diff --git a/packages/eve/src/execution/agent-sessions/session.ts b/packages/eve/src/execution/agent-sessions/session.tsindex 0d1da8eac..a5206142f 100644--- a/packages/eve/src/execution/agent-sessions/session.ts+++ b/packages/eve/src/execution/agent-sessions/session.ts@@ -25,6 +25,7 @@ import type {AgentResponse,AgentSendOptions,AgentSession,+ AgentSessionOptions,} from "#tools/workflow-definition.js";type AgentTurnReply = AgentSessionRequest | RuntimeActionResultHookPayload;@@ -43,18 +44,18 @@ export function createAgentSessions(usage: RunUsageTally,): {readonly close: () => Promise<void>;- readonly open: (name: string) => AgentSession;+ readonly open: (name: string, options?: AgentSessionOptions) => AgentSession;} {const sessions: OpenedAgentSession[] = [];let handles = 0;return {- open: (name) => {+ open: (name, options = {}) => {if (typeof name !== "string" || name.trim() === "") {throw new TypeError("ctx.agent() requires a non-empty agent name.");}const key = `${run.from.runId}:${String(handles)}`;handles += 1;- return new RunAgentSession({ key, name, run, sessions, usage });+ return new RunAgentSession({ key, name, options, run, sessions, usage });},close: async () => {if (sessions.length === 0) return;@@ -76,6 +77,7 @@ interface AwaitedReply {class RunAgentSession implements AgentSession {readonly #key: string;readonly #name: string;+ readonly #options: AgentSessionOptions;readonly #run: WorkflowToolRunContext;/** Every session the run opened, which it ends when it finishes. */readonly #sessions: OpenedAgentSession[];@@ -88,12 +90,14 @@ class RunAgentSession implements AgentSession {constructor(input: {readonly key: string;readonly name: string;+ readonly options: AgentSessionOptions;readonly run: WorkflowToolRunContext;readonly sessions: OpenedAgentSession[];readonly usage: RunUsageTally;}) {this.#key = input.key;this.#name = input.name;+ this.#options = input.options;this.#run = input.run;this.#sessions = input.sessions;this.#usage = input.usage;@@ -229,6 +233,7 @@ class RunAgentSession implements AgentSession {...message,context,key: this.#key,+ model: this.#options.model,name: this.#name,});const opened = { address, context, key: this.#key };diff --git a/packages/eve/src/execution/agent-sessions/steps.test.ts b/packages/eve/src/execution/agent-sessions/steps.test.tsindex b9b5e436b..13c58b6aa 100644--- a/packages/eve/src/execution/agent-sessions/steps.test.ts+++ b/packages/eve/src/execution/agent-sessions/steps.test.ts@@ -1,5 +1,6 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import { FatalError } from "#compiled/@workflow/core/index.js";import { HookNotFoundError } from "#compiled/@workflow/errors/index.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import {@@ -14,6 +15,8 @@ const mocks = vi.hoisted(() => ({createSession: vi.fn(),dispatch: vi.fn(),resolveSessionInbox: vi.fn(),+ runtimeConfig: undefined as unknown,+ targetKind: "local" as "local" | "remote",waitForCommandHookOwner: vi.fn(),waitForSessionInbox: vi.fn(),}));@@ -24,7 +27,10 @@ vi.mock("#compiled/@workflow/core/index.js", async (importOriginal) => ({}));vi.mock("#execution/workflow-runtime.js", async (importOriginal) => ({...(await importOriginal<typeof import("#execution/workflow-runtime.js")>()),- createWorkflowRuntime: () => ({ createSession: mocks.createSession }),+ createWorkflowRuntime: (config: unknown) => {+ mocks.runtimeConfig = config;+ return { createSession: mocks.createSession };+ },dispatchWorkflowSessionCommand: mocks.dispatch,waitForCommandHookOwner: mocks.waitForCommandHookOwner,waitForSessionInbox: mocks.waitForSessionInbox,@@ -43,7 +49,10 @@ vi.mock("#execution/agent-sessions/target.js", () => {const action = { callId: "call-1", name: "reviewer", nodeId: "reviewer" };return {resolveAgentAction: () => action,- resolveAgentStartTarget: () => ({ action, kind: "local", source: { type: "declared" } }),+ resolveAgentStartTarget: () =>+ mocks.targetKind === "remote"+ ? { action, kind: "remote" }+ : { action, kind: "local", source: { type: "declared" } },};});vi.mock("#subagents/tool.js", () => ({@@ -83,6 +92,8 @@ const message = {beforeEach(() => {vi.resetAllMocks();mocks.attempt = 1;+ mocks.runtimeConfig = undefined;+ mocks.targetKind = "local";});describe("openAgentSessionStep", () => {@@ -111,6 +122,54 @@ describe("openAgentSessionStep", () => {expect.stringContaining("subagent:run-1:0"),);});++ it("binds a model override to the local child runtime", async () => {+ mocks.createSession.mockResolvedValue({ sessionId: "child-1" });++ await openAgentSessionStep({+ ...message,+ model: {+ model: "anthropic/claude-opus-5.5",+ modelContextWindowTokens: 200_000,+ reasoning: "high",+ },+ name: "reviewer",+ });++ expect(mocks.runtimeConfig).toMatchObject({+ agentSessionRuntimeOverrides: {+ model: {+ contextWindowTokens: 200_000,+ id: "anthropic/claude-opus-5.5",+ reasoning: "high",+ },+ },+ });+ });++ it("rejects a model override for a remote target without retrying", async () => {+ mocks.targetKind = "remote";++ await expect(+ openAgentSessionStep({+ ...message,+ model: "anthropic/claude-opus-5.5",+ name: "reviewer",+ }),+ ).rejects.toBeInstanceOf(FatalError);+ expect(mocks.createSession).not.toHaveBeenCalled();+ });++ it("rejects an invalid model selection without retrying", async () => {+ await expect(+ openAgentSessionStep({+ ...message,+ model: "",+ name: "reviewer",+ }),+ ).rejects.toBeInstanceOf(FatalError);+ expect(mocks.createSession).not.toHaveBeenCalled();+ });});describe("commands to a session that opened without waiting", () => {diff --git a/packages/eve/src/execution/agent-sessions/steps.ts b/packages/eve/src/execution/agent-sessions/steps.tsindex 34db0b8e7..bcc26111c 100644--- a/packages/eve/src/execution/agent-sessions/steps.ts+++ b/packages/eve/src/execution/agent-sessions/steps.ts@@ -1,8 +1,13 @@-import { getStepMetadata, getWorkflowMetadata } from "#compiled/@workflow/core/index.js";+import {+ FatalError,+ getStepMetadata,+ getWorkflowMetadata,+} from "#compiled/@workflow/core/index.js";import { SessionStrandedError } from "#channel/session-stranded-error.js";import { ContextContainer, contextStorage } from "#context/container.js";import type { SessionAuth } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import {resolveAgentAction,resolveAgentStartTarget,@@ -26,7 +31,12 @@ import { createEveCallbackRoutePath } from "#protocol/routes.js";import { resolveDurableCompiledArtifactsSource } from "#runtime/durable-compiled-artifacts-source.js";import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import {+ InvalidRuntimeModelSelectionError,+ resolveRuntimeModelSelection,+} from "#runtime/agent/resolve-model.js";import type { ResolvedRuntimeRemoteAgentNode } from "#runtime/types.js";+import { toErrorMessage } from "#shared/errors.js";import type { JsonObject } from "#shared/json.js";import type { SubagentParentContext } from "#subagents/invocation.js";import {@@ -40,6 +50,7 @@ import { buildSubagentRunInput } from "#subagents/tool.js";import { resolveConversationId } from "#shared/conversation-identity.js";import { stubToolPath } from "#tool-stubs/target.js";import { agentDelegation } from "#tracing/eve/delegation.js";+import type { AgentSessionModelSelection } from "#tools/workflow-definition.js";const log = createLogger("execution.agent-sessions");@@ -96,6 +107,7 @@ export async function openAgentSessionStep(input: AgentSessionMessage & {readonly context: AgentSessionContext;readonly key: string;+ readonly model?: AgentSessionModelSelection;readonly name: string;},): Promise<AgentSessionAddress> {@@ -115,7 +127,23 @@ export async function openAgentSessionStep(dynamicSelections: context.dynamicSelections,isRootSession: context.parent.rootSessionId === context.parent.sessionId,});- const start = { auth: input.auth, bundle, context, key: input.key, replyTo: input.replyTo };+ if (input.model !== undefined && target.kind === "remote") {+ throw new FatalError(+ `ctx.agent("${input.name}", { model }) cannot override a remote agent's model. Configure the model on the receiving agent.`,+ );+ }+ const runtimeOverrides =+ input.model === undefined+ ? undefined+ : await normalizeRuntimeOverrides(input.name, input.model);+ const start = {+ auth: input.auth,+ bundle,+ context,+ key: input.key,+ replyTo: input.replyTo,+ runtimeOverrides,+ };const execute = () =>target.kind === "remote"? startRemoteSession({ ...start, target })@@ -123,6 +151,27 @@ export async function openAgentSessionStep(return await agentDelegation.resume({ context, agentName: action.name }, execute);}+async function normalizeRuntimeOverrides(+ name: string,+ model: AgentSessionModelSelection,+): Promise<AgentSessionRuntimeOverrides> {+ try {+ const selection = await resolveRuntimeModelSelection({+ durability: "durable",+ selection: model,+ state: new ContextContainer(),+ });+ return { model: selection.reference };+ } catch (error) {+ if (error instanceof InvalidRuntimeModelSelectionError) {+ throw new FatalError(+ `ctx.agent("${name}", { model }) could not resolve the model selection: ${toErrorMessage(error)}`,+ );+ }+ throw error;+ }+}+/*** Sends a later message; it joins the session's running turn or starts the* next. It keeps the session's lineage and carries its own auth.@@ -260,6 +309,7 @@ interface SessionStart<Target extends SubagentStartTarget> {readonly context: AgentSessionContext;readonly key: string;readonly replyTo: string;+ readonly runtimeOverrides?: AgentSessionRuntimeOverrides;readonly target: Target;}@@ -290,6 +340,7 @@ async function startLocalSession(source: target.source,});const childRuntime = createWorkflowRuntime({+ agentSessionRuntimeOverrides: input.runtimeOverrides,compiledArtifactsSource: bundle.compiledArtifactsSource,dynamicSubagentAgentConfig: target.dynamicSubagentAgentConfig,nodeId: action.nodeId,diff --git a/packages/eve/src/execution/create-session-step.ts b/packages/eve/src/execution/create-session-step.tsindex b82cc24bf..b70a70d38 100644--- a/packages/eve/src/execution/create-session-step.ts+++ b/packages/eve/src/execution/create-session-step.ts@@ -13,6 +13,7 @@ import { resolveInheritedTokenLimit } from "#execution/run-session-limits.js";import type { RunSessionLimits } from "#channel/types.js";import type { JsonObject } from "#shared/json.js";import { resolveEffectiveAgentRuntimeFromConfig } from "#execution/effective-agent-config.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { withPendingHistory } from "#execution/session/pending-history.js";import type { SessionHistoryMessage } from "#shared/session-history.js";@@ -35,6 +36,7 @@ export interface CreateSessionStepResult {* the root agent.*/export async function createSessionStep(input: {+ readonly agentSessionRuntimeOverrides?: AgentSessionRuntimeOverrides;readonly compiledArtifactsSource: DurableCompiledArtifactsSource;readonly continuationToken: string;readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;@@ -55,6 +57,7 @@ export async function createSessionStep(input: {const effectiveAgent = resolveEffectiveAgentRuntimeFromConfig(bundle,input.dynamicSubagentAgentConfig,+ input.agentSessionRuntimeOverrides,);// Both token axes resolve tighter-wins against the cap inherited from thediff --git a/packages/eve/src/execution/effective-agent-config.test.ts b/packages/eve/src/execution/effective-agent-config.test.tsindex 368b4f449..f4ccfc1c4 100644--- a/packages/eve/src/execution/effective-agent-config.test.ts+++ b/packages/eve/src/execution/effective-agent-config.test.ts@@ -1,7 +1,7 @@import { describe, expect, it } from "vitest";import { ContextContainer } from "#context/container.js";-import { DynamicSubagentAgentConfigKey } from "#context/keys.js";+import { AgentSessionRuntimeOverridesKey, DynamicSubagentAgentConfigKey } from "#context/keys.js";import { resolveEffectiveAgentRuntime } from "#execution/effective-agent-config.js";describe("resolveEffectiveAgentRuntime", () => {@@ -50,4 +50,82 @@ describe("resolveEffectiveAgentRuntime", () => {expect(effective.turnAgent.instructions).toEqual(["Research carefully."]);expect(effective.turnAgent.tools).toBe(tools);});++ it("overrides only the selected agent model for a ctx.agent session", () => {+ const ctx = new ContextContainer();+ ctx.set(DynamicSubagentAgentConfigKey, {+ compaction: {+ model: { id: "anthropic/claude-haiku-4.5" },+ thresholdPercent: 0.75,+ },+ description: "Perform deep research.",+ limits: { sessionTimeoutMs: 120_000 },+ model: { id: "anthropic/claude-opus-4.6" },+ reasoning: "high",+ });+ ctx.set(AgentSessionRuntimeOverridesKey, {+ model: { id: "openai/gpt-5.5", reasoning: "low" },+ });++ const effective = resolveEffectiveAgentRuntime(+ {+ resolvedAgent: { config: {} },+ turnAgent: {+ configResolver: true,+ id: "researcher",+ instructions: ["Research carefully."],+ tools: [{ name: "search" }],+ workspaceSpec: {} as never,+ },+ } as never,+ ctx,+ );++ expect(effective).toMatchObject({+ limits: { sessionTimeoutMs: 120_000 },+ thresholdPercent: 0.75,+ turnAgent: {+ compactionModel: { id: "anthropic/claude-haiku-4.5" },+ instructions: ["Research carefully."],+ model: { id: "openai/gpt-5.5", reasoning: "low" },+ reasoning: "high",+ tools: [{ name: "search" }],+ },+ });+ expect(effective.turnAgent).not.toHaveProperty("configResolver");+ expect(effective.turnAgent).not.toHaveProperty("dynamicModel");+ });++ it("takes precedence over an authored dynamic model", () => {+ const ctx = new ContextContainer();+ ctx.set(AgentSessionRuntimeOverridesKey, {+ model: { id: "anthropic/claude-opus-5.5" },+ });++ const effective = resolveEffectiveAgentRuntime(+ {+ resolvedAgent: { config: {} },+ turnAgent: {+ dynamicModel: {+ eventNames: ["turn.started"],+ logicalPath: "agent/agent.ts",+ sourceId: "agent-config",+ },+ id: "root",+ instructions: ["Help the user."],+ tools: [{ name: "search" }],+ workspaceSpec: {} as never,+ },+ } as never,+ ctx,+ );++ expect(effective.turnAgent).toMatchObject({+ id: "root",+ instructions: ["Help the user."],+ model: { id: "anthropic/claude-opus-5.5" },+ tools: [{ name: "search" }],+ });+ expect(effective.turnAgent).not.toHaveProperty("dynamicModel");+ });});diff --git a/packages/eve/src/execution/effective-agent-config.ts b/packages/eve/src/execution/effective-agent-config.tsindex 2ee8f5633..d14c399c1 100644--- a/packages/eve/src/execution/effective-agent-config.ts+++ b/packages/eve/src/execution/effective-agent-config.ts@@ -1,8 +1,9 @@import type { ContextReader } from "#context/key.js";-import { DynamicSubagentAgentConfigKey } from "#context/keys.js";+import { AgentSessionRuntimeOverridesKey, DynamicSubagentAgentConfigKey } from "#context/keys.js";import type { RuntimeTurnAgent } from "#runtime/agent/bootstrap.js";import type { CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";import type { AgentLimitsDefinition } from "#shared/agent-definition.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";interface EffectiveAgentRuntime {@@ -15,39 +16,57 @@ export function resolveEffectiveAgentRuntime(bundle: Pick<CompiledBundle, "resolvedAgent" | "turnAgent">,context: ContextReader,): EffectiveAgentRuntime {- return resolveEffectiveAgentRuntimeFromConfig(bundle, context.get(DynamicSubagentAgentConfigKey));+ return resolveEffectiveAgentRuntimeFromConfig(+ bundle,+ context.get(DynamicSubagentAgentConfigKey),+ context.get(AgentSessionRuntimeOverridesKey),+ );}export function resolveEffectiveAgentRuntimeFromConfig(bundle: Pick<CompiledBundle, "resolvedAgent" | "turnAgent">,config: DynamicSubagentAgentConfig | undefined,+ overrides?: AgentSessionRuntimeOverrides,): EffectiveAgentRuntime {+ let effective: EffectiveAgentRuntime;if (config === undefined) {if (bundle.turnAgent.configResolver === true) {throw new Error("Dynamic subagent execution requires a selected concrete agent config.");}- return {+ effective = {limits: bundle.resolvedAgent.config?.limits,thresholdPercent: bundle.resolvedAgent.config?.compaction?.thresholdPercent,turnAgent: bundle.turnAgent,};+ } else {+ const {+ compactionModel: _compiledCompactionModel,+ configResolver: _configResolver,+ dynamicModel: _dynamicModel,+ model: _compiledModel,+ ...turnAgent+ } = bundle.turnAgent;+ effective = {+ limits: config.limits,+ thresholdPercent: config.compaction?.thresholdPercent,+ turnAgent: {+ ...turnAgent,+ compactionModel: config.compaction?.model,+ model: config.model,+ reasoning: config.reasoning,+ },+ };}+ if (overrides === undefined) return effective;const {- compactionModel: _compiledCompactionModel,configResolver: _configResolver,dynamicModel: _dynamicModel,- model: _compiledModel,+ model: _configuredModel,...turnAgent- } = bundle.turnAgent;+ } = effective.turnAgent;return {- limits: config.limits,- thresholdPercent: config.compaction?.thresholdPercent,- turnAgent: {- ...turnAgent,- compactionModel: config.compaction?.model,- model: config.model,- reasoning: config.reasoning,- },+ ...effective,+ turnAgent: { ...turnAgent, model: overrides.model },};}diff --git a/packages/eve/src/execution/runtime-context.ts b/packages/eve/src/execution/runtime-context.tsindex bdf471f50..e7ba05676 100644--- a/packages/eve/src/execution/runtime-context.ts+++ b/packages/eve/src/execution/runtime-context.ts@@ -2,6 +2,7 @@ import type { RunInput, SessionAuthContext } from "#channel/types.js";import { ContextContainer, contextStorage } from "#context/container.js";import { setChannelContext } from "#execution/channel-context.js";import {+ AgentSessionRuntimeOverridesKey,AuthKey,ToolStubsKey,CapabilitiesKey,@@ -25,6 +26,7 @@ import {} from "#context/keys.js";import { deriveSessionTitle } from "#execution/eve-workflow-attributes.js";import { BundleKey, type CompiledBundle } from "#runtime/sessions/runtime-context-keys.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { readConversationId } from "#shared/conversation-identity.js";import { buildConversationContext } from "#channel/conversation-context.js";@@ -35,6 +37,7 @@ import { resolveInstrumentationEnvironment } from "#internal/application/dev-env* Builds the bootstrap {@link ContextContainer} for one run.*/export function buildRunContext(input: {+ readonly agentSessionRuntimeOverrides?: AgentSessionRuntimeOverrides;readonly bundle: CompiledBundle;readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;readonly run: RunInput;@@ -81,6 +84,9 @@ export function buildRunContext(input: {if (input.dynamicSubagentAgentConfig !== undefined) {ctx.set(DynamicSubagentAgentConfigKey, input.dynamicSubagentAgentConfig);}+ if (input.agentSessionRuntimeOverrides !== undefined) {+ ctx.set(AgentSessionRuntimeOverridesKey, input.agentSessionRuntimeOverrides);+ }if (run.capabilities !== undefined) {ctx.set(CapabilitiesKey, run.capabilities);diff --git a/packages/eve/src/execution/session/entry.ts b/packages/eve/src/execution/session/entry.tsindex df6ce8f0b..b591ca7c7 100644--- a/packages/eve/src/execution/session/entry.ts+++ b/packages/eve/src/execution/session/entry.ts@@ -22,6 +22,7 @@ import {} from "#execution/session/timeout-control.js";import { createTurnControl, type TurnControl } from "#execution/session/turn-control.js";import { hasDelegatedSessionContext } from "#execution/delegated-session-context.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { attachClientContext, readClientContext } from "#internal/client-context.js";import { settleContinuationConflictStep } from "#execution/continuation-conflict-step.js";@@ -177,6 +178,9 @@ export async function bootInitialOwner(let owner: OwnedInitialSession | undefined;try {const sessionCreationPromise = createSessionStep({+ agentSessionRuntimeOverrides: serializedContext["eve.agentSessionRuntimeOverrides"] as+ | AgentSessionRuntimeOverrides+ | undefined,compiledArtifactsSource: serializedBundle.source,continuationToken,dynamicSubagentAgentConfig: serializedContext["eve.dynamicSubagentAgentConfig"] asdiff --git a/packages/eve/src/execution/tools/workflow/body.ts b/packages/eve/src/execution/tools/workflow/body.tsindex 1fd87d7eb..5c6463e78 100644--- a/packages/eve/src/execution/tools/workflow/body.ts+++ b/packages/eve/src/execution/tools/workflow/body.ts@@ -7,11 +7,7 @@ import type { SessionContext } from "#context/session-context.js";import type { AgentSessionContext } from "#execution/agent-sessions/context.js";import { createAgentSessions } from "#execution/agent-sessions/session.js";import { createRunUsageTally, type RunUsageTally } from "#execution/agent-sessions/usage.js";-import type {- AgentSession,- WorkflowSharedContext,- WorkflowToolContext,-} from "#tools/workflow-definition.js";+import type { WorkflowSharedContext, WorkflowToolContext } from "#tools/workflow-definition.js";import {ask,attachWorkflowToolRunContext,@@ -273,7 +269,7 @@ export function resolveWorkflowEntryPoint<TEntryPoint>(input: WorkflowBodyInput)*/export function createSharedContext(input: WorkflowBodyInput,- agent: (name: string) => AgentSession,+ agent: WorkflowSharedContext["agent"],askPerson: WorkflowSharedContext["ask"],): Omit<ToolContext & WorkflowSharedContext,@@ -318,7 +314,7 @@ export function createAgentsView(context: AgentSessionContext): WorkflowSharedCofunction createCallContext(input: WorkflowBodyInput,signals: WorkflowCallSignals,- agent: (name: string) => AgentSession,+ agent: WorkflowSharedContext["agent"],): WorkflowCallContext {const ctx: WorkflowCallContext = {...createSharedContext(input, agent, (request, options) => ask(ctx, request, options)),diff --git a/packages/eve/src/execution/tools/workflow/serve.ts b/packages/eve/src/execution/tools/workflow/serve.tsindex e55e1b451..c70598e0b 100644--- a/packages/eve/src/execution/tools/workflow/serve.ts+++ b/packages/eve/src/execution/tools/workflow/serve.ts@@ -35,7 +35,6 @@ import type { JsonValue } from "#shared/json.js";import type { TokenUsage } from "#shared/token-usage.js";import type { ToolContext } from "#tools/definition.js";import type {- AgentSession,WorkflowServeCall,WorkflowServeContext,WorkflowServeReceive,@@ -405,7 +404,7 @@ async function executeServeBody(function createServeContext(input: WorkflowBodyInput,calls: WorkflowServeCalls,- agent: (name: string) => AgentSession,+ agent: WorkflowSharedContext["agent"],): ServeContext {const ctx: ServeContext = {...createSharedContext(input, agent, (request, options) => {diff --git a/packages/eve/src/execution/workflow-runtime.test.ts b/packages/eve/src/execution/workflow-runtime.test.tsindex ec7164a06..80e93ee41 100644--- a/packages/eve/src/execution/workflow-runtime.test.ts+++ b/packages/eve/src/execution/workflow-runtime.test.ts@@ -729,6 +729,33 @@ describe("createWorkflowRuntime#createSession", () => {});});+ it("serializes a ctx.agent model override for the child workflow", async () => {+ const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;+ mockBundleAndRun(compiledArtifactsSource, 86_400_000);+ startMock.mockResolvedValue({ runId: "owner-run" });++ await createWorkflowRuntime({+ agentSessionRuntimeOverrides: {+ model: { contextWindowTokens: 200_000, id: "anthropic/claude-opus-5.5" },+ },+ compiledArtifactsSource,+ nodeId: "subagents/researcher",+ }).createSession({+ adapter,+ auth: null,+ input: { message: "research this" },+ });++ const [, [workflowInput]] = startMock.mock.calls[0]!;+ expect(workflowInput).toMatchObject({+ serializedContext: {+ "eve.agentSessionRuntimeOverrides": {+ model: { contextWindowTokens: 200_000, id: "anthropic/claude-opus-5.5" },+ },+ },+ });+ });+it("serializes the channel request id into workflow context", async () => {vi.stubEnv("VERCEL_DEPLOYMENT_ID", "dpl_current");const compiledArtifactsSource = {} as RuntimeCompiledArtifactsSource;diff --git a/packages/eve/src/execution/workflow-runtime.ts b/packages/eve/src/execution/workflow-runtime.tsindex cbe910cba..df796db07 100644--- a/packages/eve/src/execution/workflow-runtime.ts+++ b/packages/eve/src/execution/workflow-runtime.ts@@ -77,6 +77,7 @@ import {StrandedSessionOwnerError,} from "#execution/session-inbox/owner.js";import { describeStrandedSession, SessionStrandedError } from "#channel/session-stranded-error.js";+import type { AgentSessionRuntimeOverrides } from "#execution/agent-sessions/runtime-overrides.js";import type { DynamicSubagentAgentConfig } from "#runtime/subagents/dynamic-agent-config.js";import { initializeSessionInstrumentation } from "#instrumentation/runtime.js";import {@@ -133,6 +134,7 @@ export const connectionEventDeliveryWorkflowReference = {* whose original run retains the public event stream across owner handoffs.*/export function createWorkflowRuntime(config: {+ readonly agentSessionRuntimeOverrides?: AgentSessionRuntimeOverrides;readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;readonly dynamicSubagentAgentConfig?: DynamicSubagentAgentConfig;readonly nodeId?: string;@@ -151,6 +153,7 @@ export function createWorkflowRuntime(config: {validateToolStubTargets(input.toolStubs.rules, bundle.graph);}const ctx = buildRunContext({+ agentSessionRuntimeOverrides: config.agentSessionRuntimeOverrides,bundle,dynamicSubagentAgentConfig: config.dynamicSubagentAgentConfig,run: input,diff --git a/packages/eve/src/public/tools/index.ts b/packages/eve/src/public/tools/index.tsindex 1fe85cb6f..20f16bb90 100644--- a/packages/eve/src/public/tools/index.ts+++ b/packages/eve/src/public/tools/index.ts@@ -52,6 +52,8 @@ export {type AgentResponse,type AgentSendOptions,type AgentSession,+ type AgentSessionModelSelection,+ type AgentSessionOptions,type WorkflowAgentMetadata,} from "#tools/workflow-definition.js";export type {diff --git a/packages/eve/src/runtime/agent/resolve-model.test.ts b/packages/eve/src/runtime/agent/resolve-model.test.tsindex 84be2dc0d..5c57fb565 100644--- a/packages/eve/src/runtime/agent/resolve-model.test.ts+++ b/packages/eve/src/runtime/agent/resolve-model.test.ts@@ -9,6 +9,7 @@ import { deserializeContext, serializeContext } from "#context/serialize.js";import { defineDynamic } from "#dynamic/definition.js";import type { RuntimeModelCatalog } from "#runtime/agent/model-catalog.js";import {+ InvalidRuntimeModelSelectionError,loadDynamicRuntimeModelDefinition,resolveRuntimeModelReference,resolveRuntimeModelSelection,@@ -43,10 +44,25 @@ describe("dynamic runtime model resolution", () => {durability: "live",state: new ContextContainer(),}),- ).rejects.toThrow("invalid reasoning");+ ).rejects.toBeInstanceOf(InvalidRuntimeModelSelectionError);expect(catalog.getByGatewayId).not.toHaveBeenCalled();});+ it("keeps catalog failures retryable", async () => {+ const catalog = createCatalog();+ const failure = new Error("AI Gateway catalog is temporarily unavailable.");+ catalog.getByGatewayId.mockRejectedValue(failure);++ await expect(+ resolveRuntimeModelSelection({+ catalog,+ selection: "openai/gpt-5.5",+ durability: "durable",+ state: new ContextContainer(),+ }),+ ).rejects.toBe(failure);+ });+it("carries prompt cache options on a direct provider selection", async () => {const result = await resolveRuntimeModelSelection({selection: {diff --git a/packages/eve/src/runtime/agent/resolve-model.ts b/packages/eve/src/runtime/agent/resolve-model.tsindex c3b4e5afa..cd7b03843 100644--- a/packages/eve/src/runtime/agent/resolve-model.ts+++ b/packages/eve/src/runtime/agent/resolve-model.ts@@ -39,6 +39,14 @@ import {export { shouldMockAuthoredRuntimeModels };+/** A deterministic authoring or selection error that retrying cannot repair. */+export class InvalidRuntimeModelSelectionError extends Error {+ constructor(message: string, options?: ErrorOptions) {+ super(message, options);+ this.name = "InvalidRuntimeModelSelectionError";+ }+}+/** Loaded compiled-module scope used to resolve source-backed runtime models. */export interface RuntimeModelResolutionScope {readonly moduleMap: CompiledModuleMap;@@ -156,24 +164,31 @@ export async function resolveRuntimeModelSelection(input: {readonly state: ContextAccessor;}): Promise<ResolvedRuntimeModelSelection> {if (input.selection === null || input.selection === undefined) {- throw new Error(+ throw new InvalidRuntimeModelSelectionError("Dynamic model resolver returned no model. Every matching dynamic model handler must return a concrete model selection.",);}- const selection = normalizeDynamicModelSelection(input.selection);- validateDynamicModelSelection(selection);- const providerOptions =- selection.modelOptions?.providerOptions === undefined- ? undefined- : parseProviderOptionsRecord(selection.modelOptions.providerOptions);- const promptCache =- selection.modelOptions?.promptCache === undefined- ? undefined- : normalizeAgentPromptCache(- selection.modelOptions.promptCache,- "Dynamic model resolver returned an invalid selection.",- );+ let selection: PublicAgentModelSelectionDefinition;+ let providerOptions: Record<string, JsonObject> | undefined;+ let promptCache: ReturnType<typeof normalizeAgentPromptCache> | undefined;+ try {+ selection = normalizeDynamicModelSelection(input.selection);+ validateDynamicModelSelection(selection);+ providerOptions =+ selection.modelOptions?.providerOptions === undefined+ ? undefined+ : parseProviderOptionsRecord(selection.modelOptions.providerOptions);+ promptCache =+ selection.modelOptions?.promptCache === undefined+ ? undefined+ : normalizeAgentPromptCache(+ selection.modelOptions.promptCache,+ "Dynamic model resolver returned an invalid selection.",+ );+ } catch (error) {+ throw invalidSelectionError(error);+ }const selectedModel = selection.model;const catalog = input.catalog ?? runtimeModelCatalogForState(input.state);@@ -201,7 +216,7 @@ export async function resolveRuntimeModelSelection(input: {validateRuntimeLanguageModel(selectedModel);if (input.durability === "durable") {- throw new Error(+ throw new InvalidRuntimeModelSelectionError('Dynamic model selection returned a provider object, but durable model selections must be serializable. Return a model id string, or use a "step.started" model resolver.',);}@@ -239,8 +254,16 @@ export async function resolveRuntimeModelSelection(input: {};}+function invalidSelectionError(error: unknown): InvalidRuntimeModelSelectionError {+ if (error instanceof InvalidRuntimeModelSelectionError) return error;+ return new InvalidRuntimeModelSelectionError(+ error instanceof Error ? error.message : String(error),+ { cause: error },+ );+}+function gatewayPromptCacheError(modelId: string): Error {- return new Error(+ return new InvalidRuntimeModelSelectionError(`Dynamic model resolver returned modelOptions.promptCache for "${modelId}", which routes through AI Gateway. promptCache applies only to models eve calls directly; Gateway manages its own prompt caching through providerOptions.gateway.caching.`,);}@@ -281,7 +304,7 @@ async function resolveSelectionMetadata(input: {const resolved = await input.load(input.catalog);if (resolved === null) {- throw new Error(+ throw new InvalidRuntimeModelSelectionError(`Cannot select model "${input.modelLabel}" because AI Gateway did not provide context window metadata. Return modelContextWindowTokens with this selection for an unlisted or custom model.`,);}@@ -358,7 +381,7 @@ function isModelSelectionDefinition(value: unknown): value is PublicAgentModelSefunction validateRuntimeLanguageModel(model: unknown): asserts model is LanguageModel {if (!isRuntimeLanguageModel(model)) {- throw new Error(+ throw new InvalidRuntimeModelSelectionError("Dynamic model resolver returned an invalid model. Return an AI Gateway model id string, an AI SDK language model, or { model, modelContextWindowTokens?, modelOptions? }.",);}diff --git a/packages/eve/src/tools/workflow-definition.test.ts b/packages/eve/src/tools/workflow-definition.test.tsindex 67d13c4f4..af81a75bd 100644--- a/packages/eve/src/tools/workflow-definition.test.ts+++ b/packages/eve/src/tools/workflow-definition.test.ts@@ -29,6 +29,13 @@ describe("defineWorkflowTool", () => {expectTypeOf(await review.result()).toEqualTypeOf<AgentMessageResult<{ findings: string[]; score?: number | undefined }>>();+ void ctx.agent("agent", {+ model: {+ model: "anthropic/claude-opus-5.5",+ modelContextWindowTokens: 200_000,+ reasoning: "high",+ },+ });// @ts-expect-error The message is sent with send(), not passed to ctx.agent().void ctx.agent("researcher", { message: "Review the deployment." });// Token capabilities are available when this context is passed into a step.diff --git a/packages/eve/src/tools/workflow-definition.ts b/packages/eve/src/tools/workflow-definition.tsindex ac0fc2e81..176f4ec64 100644--- a/packages/eve/src/tools/workflow-definition.ts+++ b/packages/eve/src/tools/workflow-definition.ts@@ -4,6 +4,10 @@ import type {} from "#compiled/@standard-schema/spec/index.js";import type { ToolApproval } from "#approval/definition.js";import type { MessageResult, SendTurnOptions } from "#client/types.js";+import type {+ AgentModelOptionsDefinition,+ AgentReasoningDefinition,+} from "#shared/agent-definition.js";import type { JsonObject } from "#shared/json.js";import {stampToolDefinition,@@ -25,6 +29,22 @@ export interface WorkflowAgentMetadata {readonly description: string;}+/** A serializable model selection for a local `ctx.agent` session. */+export type AgentSessionModelSelection =+ | string+ | {+ readonly model: string;+ readonly modelContextWindowTokens?: number;+ readonly modelOptions?: AgentModelOptionsDefinition;+ readonly reasoning?: AgentReasoningDefinition;+ };++/** Options that bind to a `ctx.agent` session when it opens. */+export interface AgentSessionOptions {+ /** Override the model for every turn in this local agent session. */+ readonly model?: AgentSessionModelSelection;+}+/** Context capabilities available inside an authored `"use step"` helper. */export type WorkflowStepToolContext = Pick<ToolContext,@@ -85,7 +105,7 @@ export type WorkflowSharedContext = Pick<* Returns a new session with the agent of this invocation name. Nothing* starts until the first `send`.*/- agent(name: string): AgentSession;+ agent(name: string, options?: AgentSessionOptions): AgentSession;/** Metadata for agents callable by this workflow, including hidden agents. */agents: Readonly<Record<string, WorkflowAgentMetadata>>;/**diff --git a/research/ctx-agent-model-override.md b/research/ctx-agent-model-override.mdnew file mode 100644index 000000000..937d5eabe--- /dev/null+++ b/research/ctx-agent-model-override.md@@ -0,0 +1,48 @@+---+issue: TBD+status: implemented+last_updated: "2026-10-20"+---++# `ctx.agent` model override++## Goal++Let an authored workflow choose the model for a local agent session without exposing that choice in a model-facing agent tool or duplicating the agent as one declared subagent per model.++```ts+const worker = ctx.agent("agent", {+ model: "anthropic/claude-opus-5.5",+});++const response = await worker.send("Review the migration plan.");+```++The option binds to the session, not an individual message. Every turn sent through the returned handle uses the selected model. Omitting it preserves the target agent's configured model behavior.++## Semantics++- The override applies to local targets, including the built-in root copy and declared or dynamic subagents.+- It replaces only the turn model. Instructions, tools, skills, connections, sandbox behavior, limits, reasoning, and explicit compaction configuration continue to come from the target agent.+- A selection object can set model-specific reasoning, context-window metadata, and provider options, using the same serializable shape as a durable dynamic model selection.+- The model must be an AI Gateway model id. A live AI SDK `LanguageModel` cannot cross the durable workflow boundary.+- Remote targets reject the option because the receiving deployment owns their model configuration.+- The selected model is fixed when the session opens. Later `send()` calls cannot change it.++## Design++`ctx.agent(name, options?)` stores the authored selection on the lazy session handle. The first `send()` resolves the target. For a local target, eve normalizes the selection into the same durable runtime model reference used by dynamic subagents and dynamic model resolvers, then carries a narrow session override into the child workflow.++```text+compiled target configuration+ -> dynamic subagent configuration, when present+ -> invocation-bound model override, when present+```++The override is separate from `DynamicSubagentAgentConfig`. Dynamic subagent configuration selects the target's complete runtime definition and controls its availability. Reusing that object for an invocation override would accidentally replace unrelated limits, reasoning, compaction, and description fields. A narrow runtime override composes after either the compiled or dynamic target configuration and changes only the model.++The child workflow persists the normalized reference in its context before session creation. Workflow replay therefore opens the same child model even if catalog metadata or the target's authored dynamic model changes later.++## Validation++The owning tests should prove that effective runtime resolution replaces the model while retaining the target configuration, and that the public workflow context accepts a serializable model selection. Existing agent-session coverage owns lazy opening, local and remote target resolution, and child workflow startup; extend that boundary only for propagation and the remote rejection rather than duplicating its lifecycle matrix.