Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Add an opt-in model-selecting agent tool (#5095)

Casey Gowrie9d1998f7a96c
diff --git a/.changeset/model-selecting-agent-tool.md b/.changeset/model-selecting-agent-tool.md
new file mode 100644
index 000000000..c8f7147fb
--- /dev/null
+++ b/.changeset/model-selecting-agent-tool.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Export `agentWithModel` for `agent/tools/agent.ts` to opt into a root-copy tool whose model-facing input selects the AI Gateway model for each task.
diff --git a/docs/concepts/built-in-tools.md b/docs/concepts/built-in-tools.md
index fe09e6317..db85aa587 100644
--- a/docs/concepts/built-in-tools.md
+++ b/docs/concepts/built-in-tools.md
@@ -291,7 +291,25 @@ eve add tool/agent
export { default } from "eve/tools/agent";
```
-An authored tool at `agent/tools/agent.ts` replaces the framework behavior. Re-export the definition above to restore direct root-copy delegation, export another tool such as `agentRouter()` to change the model-facing behavior, or disable the slot. `agentRouter()` runs each call as a [task](/docs/tools/workflows#run-calls-as-tasks-task), which adds `eve__task_wait` and `eve__task_cancel`:
+To let the model choose an AI Gateway model for each root-copy task, export `agentWithModel` from the same slot:
+
+```ts title="agent/tools/agent.ts"
+export { agentWithModel as default } from "eve/tools/agent";
+```
+
+This is a separate workflow tool that calls `ctx.agent("agent", { model })`. The default `agent` tool remains unchanged and does not gain a `model` parameter. The opt-in definition accepts:
+
+```ts
+{
+ message: string;
+ model: string; // AI Gateway model id for the child session
+ taskId?: string;
+}
+```
+
+It otherwise has the default tool's task behavior: a call returns a receipt, the result arrives later, and `taskId` continues the same root-copy session. The selected model applies to every turn in that session. A continuation must repeat the original model; start a new task to use another one. Because the parent model controls this value, use this tool only when it may choose among every model your AI Gateway credentials and policies allow.
+
+An authored tool at `agent/tools/agent.ts` replaces the framework behavior. Re-export the default definition above to restore direct root-copy delegation, export `agentWithModel` to expose model selection, export another tool such as `agentRouter()` to change the model-facing behavior, or disable the slot. `agentRouter()` runs each call as a [task](/docs/tools/workflows#run-calls-as-tasks-task), which adds `eve__task_wait` and `eve__task_cancel`:
```ts title="agent/tools/agent.ts"
import { disableTool } from "eve/tools";
diff --git a/docs/subagents/index.mdx b/docs/subagents/index.mdx
index 67a001f83..f8151e5d0 100644
--- a/docs/subagents/index.mdx
+++ b/docs/subagents/index.mdx
@@ -34,7 +34,7 @@ The copy uses the root's instructions, connections, auth, and sandbox. It receiv
The 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.
+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 default model-facing tool does not accept a model choice; an authored [`agentWithModel` tool](./concepts/built-in-tools#agent) can expose that choice in its input.
To prevent the root session from delegating to a fresh copy of itself, set `tool: false` on the root agent:
@@ -212,7 +212,7 @@ The root built-in `agent` tool is the exception. Its children reuse the root's s
## What the parent sees
-eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, taskId? }` shape. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, open a session with it from an authored workflow tool with [`ctx.agent(name)`](./tools/workflows#delegate-work-ctxagent) and pass `outputSchema` to `send()`; the schema applies to that turn, and the session accepts follow-up messages until the workflow run finishes.
+By default, eve lowers every tool-enabled subagent visible to the current agent (the root built-in copy, declared, or [remote](./guides/remote-agents)) into a model-visible tool with the same `{ message, taskId? }` shape. The opt-in [`agentWithModel` root-copy tool](./concepts/built-in-tools#agent) instead uses `{ message, model, taskId? }`. The parent packs `message` with everything the child needs, since the child never sees the parent's history. To require structured output from a child, open a session with it from an authored workflow tool with [`ctx.agent(name)`](./tools/workflows#delegate-work-ctxagent) and pass `outputSchema` to `send()`; the schema applies to that turn, and the session accepts follow-up messages until the workflow run finishes.
Declared subagents can call nested subagents defined under their own directories. eve does not apply a separate depth limit; nesting ends where the authored directory tree ends. The built-in `agent` follows the stricter root-only rule above, so `limits.maxSubagentDepth` no longer exists.
diff --git a/e2e/fixtures/agent-subagents/agent/agent.ts b/e2e/fixtures/agent-subagents/agent/agent.ts
index c56f9b7c8..8d5c97a73 100644
--- a/e2e/fixtures/agent-subagents/agent/agent.ts
+++ b/e2e/fixtures/agent-subagents/agent/agent.ts
@@ -1,8 +1,13 @@
import { e2eAgentConfig } from "@eve-e2e/config";
+import { latestTaskResult } from "@eve-e2e/config/mock-script";
import { defineAgent, defineDynamic } from "eve";
import { mockModel } from "eve/evals";
-import { WORKSPACE_FORWARDING_MARKER, WORKSPACE_LOOKUP_MESSAGE } from "../constants";
+import {
+ MODEL_AGENT_SELECTED_MODEL,
+ WORKSPACE_FORWARDING_MARKER,
+ WORKSPACE_LOOKUP_MESSAGE,
+} from "../constants";
import {
REMOTE_QUESTION_DIRECTIVE,
respondToRemoteQuestion,
@@ -27,6 +32,7 @@ if (process.env.EVE_E2E_MODEL === "mock") {
}
const TOOL_FALSE_PROBE = "E2E_TOOL_FALSE_SUBAGENT";
+const MODEL_AGENT_PROBE = "E2E_MODEL_SELECTING_AGENT_TOOL";
const DISABLED_TOOL_PROBE = "E2E_DISABLED_SUBAGENT";
const hiddenSubagentProbe = mockModel({
modelId: "hidden-subagent-probe",
@@ -53,6 +59,42 @@ const hiddenSubagentProbe = mockModel({
const base = e2eAgentConfig();
const { model, modelContextWindowTokens, ...agentConfig } = base;
const defaultModel = typeof model === "string" ? model : `${model.provider}/${model.modelId}`;
+const modelSelectingParent = mockModel({
+ modelId: "model-selecting-agent-parent",
+ respond(request) {
+ if (hasInputProperty(request.tools, "agent", "model")) {
+ throw new Error("The default agent tool exposed a model input.");
+ }
+ if (!hasInputProperty(request.tools, "model_agent", "model")) {
+ throw new Error("The custom model_agent tool did not expose its model input.");
+ }
+ const defaultResult = latestTaskResult(request, "agent");
+ const selectedResult = latestTaskResult(request, "model_agent");
+ if (defaultResult !== undefined && selectedResult !== undefined) {
+ return `${defaultResult}\n${selectedResult}`;
+ }
+ if (request.toolResults.some((result) => ["agent", "model_agent"].includes(result.name))) {
+ return { toolCalls: [{ name: "eve__task_wait", input: {} }] };
+ }
+ return {
+ toolCalls: [
+ {
+ id: "default-agent-call",
+ name: "agent",
+ input: { message: "Reply with exactly DEFAULT_AGENT_MODEL_OK" },
+ },
+ {
+ id: "model-agent-call",
+ name: "model_agent",
+ input: {
+ message: "Reply with exactly SELECTED_AGENT_MODEL_OK",
+ model: MODEL_AGENT_SELECTED_MODEL,
+ },
+ },
+ ],
+ };
+ },
+});
const workspaceReader = mockModel({
modelId: "principal-forwarding-workspace-reader",
respond: ({ messages }) => {
@@ -116,6 +158,17 @@ const surveyToolParent = mockModel({
});
// The remote keeper is a root session of this deployment, reached through remote-loopback.
const notebookKeeper = mockModel({ modelId: "notebook-keeper", respond: respondAsNotebookKeeper });
+function hasInputProperty(
+ tools: readonly { readonly inputSchema?: unknown; readonly name: string }[],
+ toolName: string,
+ property: string,
+): boolean {
+ const schema = tools.find((tool) => tool.name === toolName)?.inputSchema;
+ if (typeof schema !== "object" || schema === null) return false;
+ const properties = Reflect.get(schema, "properties");
+ return typeof properties === "object" && properties !== null && property in properties;
+}
+
/** Reads the id of a tool's task from the latest framework-injected `[Tasks]` note. */
function findListedTaskId(
messages: readonly { readonly role: string; readonly text: string }[],
@@ -141,6 +194,9 @@ export default defineAgent({
: message.content.map((part) => (part.type === "text" ? part.text : "")).join(""),
];
});
+ if (messages.some((message) => message.includes(MODEL_AGENT_PROBE))) {
+ return { model: modelSelectingParent, modelContextWindowTokens: 1_000_000 };
+ }
if (
messages.some(
(message) =>
diff --git a/e2e/fixtures/agent-subagents/agent/tools/model_agent.ts b/e2e/fixtures/agent-subagents/agent/tools/model_agent.ts
new file mode 100644
index 000000000..a8a3cad5c
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/agent/tools/model_agent.ts
@@ -0,0 +1 @@
+export { agentWithModel as default } from "eve/tools/agent";
diff --git a/e2e/fixtures/agent-subagents/constants.ts b/e2e/fixtures/agent-subagents/constants.ts
index 4b7394404..ae44eabf7 100644
--- a/e2e/fixtures/agent-subagents/constants.ts
+++ b/e2e/fixtures/agent-subagents/constants.ts
@@ -5,6 +5,8 @@ export const WORKSPACE_LOOKUP_MESSAGE = [
].join(" ");
export const WORKSPACE_FORWARDING_MARKER = "Shared workspace membership check.";
+export const MODEL_AGENT_SELECTED_MODEL = "openai/gpt-6.1-sol";
+
/** The directive words of the notebook scripts, one per parent turn. */
export const NOTEBOOK_DIRECTIVES = [
"NOTEBOOK-REMEMBER",
diff --git a/e2e/fixtures/agent-subagents/evals/model-selecting-agent-tool.eval.ts b/e2e/fixtures/agent-subagents/evals/model-selecting-agent-tool.eval.ts
new file mode 100644
index 000000000..9f5508b01
--- /dev/null
+++ b/e2e/fixtures/agent-subagents/evals/model-selecting-agent-tool.eval.ts
@@ -0,0 +1,63 @@
+import {
+ isCurrentTurnBoundaryEvent,
+ type AgentStartedStreamEvent,
+ type MessageStreamEvent,
+} from "eve/client";
+import { defineEval, type EveEvalContext, type EveEvalTurn } from "eve/evals";
+import { satisfies } from "eve/evals/expect";
+
+import { MODEL_AGENT_SELECTED_MODEL } from "../constants";
+
+export default defineEval({
+ description:
+ "An opt-in custom agent tool selects a child model while the default agent tool keeps its original input.",
+ async test(t) {
+ const turn = await t.send(
+ "E2E_MODEL_SELECTING_AGENT_TOOL Alice asks two root copies to review the same sample plan.",
+ );
+
+ turn.expectOk();
+ turn.messageIncludes("DEFAULT_AGENT_MODEL_OK");
+ turn.messageIncludes("SELECTED_AGENT_MODEL_OK");
+ turn.calledTool("model_agent", {
+ count: 1,
+ input: {
+ message: "Reply with exactly SELECTED_AGENT_MODEL_OK",
+ model: MODEL_AGENT_SELECTED_MODEL,
+ },
+ });
+
+ const started = await requireSelectedChild(t, turn);
+ const childEvents: MessageStreamEvent[] = [];
+ for await (const event of turn.session.agent(started).stream()) {
+ childEvents.push(event);
+ if (isCurrentTurnBoundaryEvent(event)) break;
+ }
+
+ await t.require(
+ childEvents,
+ satisfies(
+ (events: readonly MessageStreamEvent[]) =>
+ events.some(
+ (event) =>
+ event.type === "step.started" && event.data.modelId === MODEL_AGENT_SELECTED_MODEL,
+ ),
+ `the custom agent tool starts its child with ${MODEL_AGENT_SELECTED_MODEL}`,
+ ),
+ );
+ t.succeeded();
+ t.noFailedActions();
+ },
+});
+
+async function requireSelectedChild(
+ t: EveEvalContext,
+ turn: EveEvalTurn,
+): Promise<AgentStartedStreamEvent> {
+ for (const event of turn.events) {
+ if (event.type === "agent.started" && event.data.callId === "model-agent-call") return event;
+ }
+ return await t.target
+ .watchTurn(turn.sessionId, { startIndex: turn.session.state.streamIndex })
+ .waitForEvent("agent.started", { data: { callId: "model-agent-call" } });
+}
diff --git a/packages/eve/src/public/tools/agent.test.ts b/packages/eve/src/public/tools/agent.test.ts
new file mode 100644
index 000000000..ee1b343a5
--- /dev/null
+++ b/packages/eve/src/public/tools/agent.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+
+import { agent, agentWithModel } from "#public/tools/agent.js";
+import { agentWithModelServeWorkflow } from "#runtime/subagents/workflow.js";
+import { serializeInputSchema } from "#tools/schema.js";
+
+describe("agentWithModel", () => {
+ it("does not change the default agent tool input", () => {
+ expect(serializeInputSchema(agent.inputSchema)).toMatchObject({
+ properties: { message: { type: "string" } },
+ required: ["message"],
+ });
+ expect(serializeInputSchema(agent.inputSchema)).not.toHaveProperty("properties.model");
+ });
+
+ it("defines a root-only serve tool with a required model input", () => {
+ expect(agentWithModel.availableInSubagents).toBe(false);
+ expect(agentWithModel.serve).toBe(agentWithModelServeWorkflow);
+ expect(serializeInputSchema(agentWithModel.inputSchema)).toMatchObject({
+ properties: {
+ message: { type: "string" },
+ model: { type: "string" },
+ },
+ required: ["message", "model"],
+ });
+ });
+});
diff --git a/packages/eve/src/public/tools/agent.ts b/packages/eve/src/public/tools/agent.ts
index 5e32eeb57..ff18163e8 100644
--- a/packages/eve/src/public/tools/agent.ts
+++ b/packages/eve/src/public/tools/agent.ts
@@ -1 +1,49 @@
-export { agent, agent as default } from "#tools/framework/agent.js";
+import {
+ agentWithModelServeWorkflow,
+ type AgentWithModelToolInput,
+} from "#runtime/subagents/workflow.js";
+import { agent } from "#tools/framework/agent.js";
+import { frameworkTool } from "#tools/provided/framework-tool.js";
+import { defineJsonSchema } from "#tools/schema.js";
+import {
+ defineWorkflowTool,
+ type WorkflowServeToolDefinition,
+} from "#tools/workflow-definition.js";
+
+export { agent, agent as default };
+export type { AgentWithModelToolInput };
+
+export type AgentWithModelTool = WorkflowServeToolDefinition<AgentWithModelToolInput, unknown>;
+
+const inputSchema = defineJsonSchema<AgentWithModelToolInput>({
+ type: "object",
+ properties: {
+ message: {
+ type: "string",
+ description: "The message to send to the agent, with everything it needs to do the work.",
+ },
+ model: {
+ type: "string",
+ minLength: 1,
+ description:
+ "AI Gateway model id for a new child session. When continuing a task, use its original model.",
+ },
+ },
+ required: ["message", "model"],
+ additionalProperties: false,
+});
+
+/** Root-copy agent tool whose model-facing input selects the model for each new task. */
+export const agentWithModel: AgentWithModelTool = frameworkTool(
+ defineWorkflowTool({
+ availableInSubagents: false,
+ description: [
+ "Delegate a focused subtask to a copy of yourself using the selected AI Gateway model.",
+ "Each call starts a task, so start independent tasks before waiting for them.",
+ "A continuation keeps its task's original model.",
+ "In message, state the goal, what to return, and whether it may change files.",
+ ].join(" "),
+ inputSchema,
+ serve: agentWithModelServeWorkflow,
+ }),
+);
diff --git a/packages/eve/src/runtime/subagents/workflow.test.ts b/packages/eve/src/runtime/subagents/workflow.test.ts
index d6730ff5e..a642fb90f 100644
--- a/packages/eve/src/runtime/subagents/workflow.test.ts
+++ b/packages/eve/src/runtime/subagents/workflow.test.ts
@@ -12,18 +12,30 @@ import type { TokenUsage } from "#shared/token-usage.js";
/** The agent's side of the task: the messages it read and the turns it owes a reply. */
const agent = vi.hoisted(() => ({
delivered: [] as WorkflowToolRunMessage[],
+ models: [] as Array<string | undefined>,
read: [] as string[],
turns: [] as Array<(payload: RuntimeActionResultHookPayload) => void>,
}));
vi.mock("#execution/workflow-registry.js", async () => {
- const { agentToolServeWorkflow } = await import("#runtime/subagents/workflow.js");
- return { readRegisteredWorkflow: () => agentToolServeWorkflow };
+ const { agentToolServeWorkflow, agentWithModelServeWorkflow } =
+ await import("#runtime/subagents/workflow.js");
+ return {
+ readRegisteredWorkflow: (workflowId: string) =>
+ workflowId.includes("agentWithModel") ? agentWithModelServeWorkflow : agentToolServeWorkflow,
+ };
});
vi.mock("#execution/agent-sessions/steps.js", () => ({
cancelAgentSessionTurnStep: async () => {},
endAgentSessionsStep: async () => {},
- openAgentSessionStep: async ({ message }: { readonly message: string }) => {
+ openAgentSessionStep: async ({
+ message,
+ model,
+ }: {
+ readonly message: string;
+ readonly model?: string;
+ }) => {
+ agent.models.push(model);
agent.read.push(message);
return { kind: "local", name: "reviewer", nodeId: "reviewer", sessionId: "reviewer-session" };
},
@@ -123,6 +135,7 @@ function replies(): Array<{ readonly callId: string; readonly output: unknown }>
/** Alice asks the reviewer for a review; the reviewer has read her message. */
async function startReview(): Promise<ReturnType<typeof startServeBody>> {
agent.delivered.length = 0;
+ agent.models.length = 0;
agent.read.length = 0;
agent.turns.length = 0;
const started = startServeBody(input);
@@ -130,6 +143,18 @@ async function startReview(): Promise<ReturnType<typeof startServeBody>> {
return started;
}
+async function startModelReview(model: string): Promise<ReturnType<typeof startServeBody>> {
+ agent.delivered.length = 0;
+ agent.models.length = 0;
+ agent.read.length = 0;
+ agent.turns.length = 0;
+ return startServeBody({
+ ...input,
+ input: { message: "Review the release plan.", model },
+ workflowId: "workflow//eve//agentWithModelServeWorkflow",
+ });
+}
+
/** Alice's next message: check the plan against the Friday freeze. */
const fridayCheck = {
call: {
@@ -176,6 +201,39 @@ async function sendAsTheTurnEnds(offset: number, { cancelled }: { readonly cance
return { read: [...agent.read], repliedFirst, replies: replies() };
}
+it("opens the custom agent tool's root copy with its model input", async () => {
+ const started = await startModelReview("anthropic/claude-opus-5.5");
+ await settle();
+
+ expect(agent.models).toEqual(["anthropic/claude-opus-5.5"]);
+
+ started.control.apply({ kind: "end", reason: "The session ended." });
+ await started.outcome;
+});
+
+it("rejects a different model when continuing the custom agent task", async () => {
+ const started = await startModelReview("anthropic/claude-opus-5.5");
+ await settle();
+ started.control.apply({
+ ...fridayCheck,
+ call: {
+ ...fridayCheck.call,
+ input: {
+ message: fridayCheck.call.input.message,
+ model: "anthropic/claude-sonnet-5",
+ },
+ },
+ });
+
+ await expect(started.outcome).resolves.toMatchObject({
+ error: {
+ message:
+ "An agent task keeps the model it started with. This task has ended; start a new task to use another model.",
+ },
+ status: "failed",
+ });
+});
+
it("forwards a message that reaches the task at any point as the agent's turn ends", async () => {
// From joining the running turn to arriving after its reply, every arrival
// point is covered: the sweep stops once the first reply precedes the
diff --git a/packages/eve/src/runtime/subagents/workflow.ts b/packages/eve/src/runtime/subagents/workflow.ts
index febd1fd7e..76b6d45cb 100644
--- a/packages/eve/src/runtime/subagents/workflow.ts
+++ b/packages/eve/src/runtime/subagents/workflow.ts
@@ -11,10 +11,18 @@ export interface AgentToolInput {
readonly message: string;
}
+export interface AgentWithModelToolInput extends AgentToolInput {
+ readonly model: string;
+}
+
type AgentToolCall = WorkflowServeCall<AgentToolInput>;
type AgentToolReceive = WorkflowServeReceive<AgentToolInput>;
+type AgentWithModelToolCall = WorkflowServeCall<AgentWithModelToolInput>;
+
+type AgentWithModelToolReceive = WorkflowServeReceive<AgentWithModelToolInput>;
+
/** One turn of the agent's session, and the signal of the calls it answers. */
interface AgentTurn {
readonly result: Promise<AgentMessageResult>;
@@ -26,6 +34,10 @@ type AgentTurnEvent =
| { readonly kind: "call"; readonly call: AgentToolCall }
| { readonly kind: "result"; readonly result: AgentMessageResult };
+type AgentWithModelTurnEvent =
+ | { readonly kind: "call"; readonly call: AgentWithModelToolCall }
+ | { readonly kind: "result"; readonly result: AgentMessageResult };
+
/**
* The `serve` body of every agent tool: local, remote, dynamic, and the
* `agent` copy of the root. Each task talks to one session with the agent. A
@@ -74,6 +86,45 @@ export async function agentToolServeWorkflow(
}
}
+/** The opt-in root-copy tool whose model-facing input selects the child model. */
+export async function agentWithModelServeWorkflow(
+ receive: AgentWithModelToolReceive,
+ ctx: WorkflowServeContext<string>,
+): Promise<never> {
+ "use workflow";
+
+ const first = await receive();
+ const model = first.input.model.trim();
+ if (model === "") throw new TypeError("agent model must not be empty.");
+ const agent = ctx.agent("agent", { model });
+ let turn = sendToModelAgent(agent, first, model);
+ let next = receive();
+ for (;;) {
+ const event = await nextModelCallOrResult(next, turn);
+ if (event.kind === "call") {
+ turn = await forwardModelCall(agent, turn, event.call, model);
+ next = receive();
+ continue;
+ }
+ if (!turn.signal.aborted) {
+ if (event.result.status === "failed") {
+ throw new Error(
+ `The agent's turn failed: ${event.result.error?.message ?? "no reason given"}\nThis task has ended; to retry, call ${ctx.toolName} without taskId.`,
+ );
+ }
+ const following = receive();
+ if (following !== next) {
+ turn = sendToModelAgent(agent, await next, model);
+ next = following;
+ continue;
+ }
+ ctx.reply(event.result.message ?? "");
+ }
+ turn = sendToModelAgent(agent, await next, model);
+ next = receive();
+ }
+}
+
/** A cancel aborts the call's `abortSignal`, which cancels the agent's turn. */
function sendToAgent(agent: AgentSession, call: AgentToolCall): AgentTurn {
const result = agent
@@ -82,6 +133,22 @@ function sendToAgent(agent: AgentSession, call: AgentToolCall): AgentTurn {
return { result, signal: call.abortSignal };
}
+function sendToModelAgent(
+ agent: AgentSession,
+ call: AgentWithModelToolCall,
+ model: string,
+): AgentTurn {
+ if (call.input.model !== model) {
+ throw new Error(
+ "An agent task keeps the model it started with. This task has ended; start a new task to use another model.",
+ );
+ }
+ const result = agent
+ .send(call.input.message, { signal: call.abortSignal })
+ .then((response) => response.result());
+ return { result, signal: call.abortSignal };
+}
+
/** `next` may take a call even when the turn's result wins, so the loop keeps it until it's read. */
async function nextCallOrResult(
next: Promise<AgentToolCall>,
@@ -93,6 +160,16 @@ async function nextCallOrResult(
]);
}
+async function nextModelCallOrResult(
+ next: Promise<AgentWithModelToolCall>,
+ turn: AgentTurn,
+): Promise<AgentWithModelTurnEvent> {
+ return await Promise.race([
+ turn.result.then((result) => ({ kind: "result", result }) as const),
+ next.then((call) => ({ call, kind: "call" }) as const),
+ ]);
+}
+
/**
* The message joins the running turn, or starts the next one if it just
* ended. A cancelled turn is left to end first, so the message starts a turn
@@ -106,3 +183,13 @@ async function forwardCall(
if (turn.signal.aborted) await turn.result.catch(() => undefined);
return sendToAgent(agent, call);
}
+
+async function forwardModelCall(
+ agent: AgentSession,
+ turn: AgentTurn,
+ call: AgentWithModelToolCall,
+ model: string,
+): Promise<AgentTurn> {
+ if (turn.signal.aborted) await turn.result.catch(() => undefined);
+ return sendToModelAgent(agent, call, model);
+}
diff --git a/research/ctx-agent-model-override.md b/research/ctx-agent-model-override.md
index 937d5eabe..afdbe2485 100644
--- a/research/ctx-agent-model-override.md
+++ b/research/ctx-agent-model-override.md
@@ -20,6 +20,13 @@ 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.
+A root can also opt into a model-facing `agent` variant whose input includes the model:
+
+```ts
+// agent/tools/agent.ts
+export { agentWithModel as default } from "eve/tools/agent";
+```
+
## Semantics
- The override applies to local targets, including the built-in root copy and declared or dynamic subagents.
@@ -43,6 +50,8 @@ The override is separate from `DynamicSubagentAgentConfig`. Dynamic subagent con
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.
+`agentWithModel` is a separate authored workflow tool; the default agent tool keeps its existing schema. Its model-visible schema is `{ message, model, taskId? }`, and its serve body opens the root-copy session through `ctx.agent("agent", { model })`. It shares the default agent tool's task lifecycle; a continuation must repeat the original model because the child session keeps that model for its lifetime.
+
## 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.