Dynamic Capabilities

defineDynamic(fn) builds a model, subagent, connection, tool, skill, or instructions from the caller, the conversation, or external data. The function returns the definition, or null to leave it out. Import defineDynamic from eve or from the entry point of what you define, such as eve/tools.

eve runs the function before every ordinary model call, including when a turn continues after steering, a sign-in, or an approval. It doesn't run for compaction's summary call or auto()'s routing call. Introspection reads the values it last returned.

Because the function runs before every model call, not once per turn, a turn with 20 model calls runs it 20 times. Wrap every network request, database query, API call, and sandbox read in ctx.memo. Outside a memo, each of those calls adds its latency to every model call and counts against the service's rate limits every time. Choose the memo key for how long the result should stay fixed; see Choose a lifetime.

The module's top-level code runs at build time and at runtime, so keep caller-specific work inside the function. See Authored module lifecycle.

Context and memoization

Every dynamic function receives:

FieldContents
ctx.sessionSession ID, authenticated caller and initiator, and optional schedule and predecessor.
ctx.session.parentIn a delegated session: the parent session, its turn, the call that opened this session, and rootSessionId. Absent in a root session.
ctx.channelChannel kind, continuation token, and metadata. Narrow typed metadata with isChannel.
ctx.conversationWhere the conversation happens: its audience and, when the channel reports one, its space.
ctx.viewRead-only view of the session so far. Read it with selectors from eve/events, such as turns(ctx.view).
ctx.turnLatest turn, with its ID, input, and status; null before the first turn.
ctx.nowTime of the latest recorded session event, as a Date.
ctx.model.idSelected model ID. Unavailable inside the model field, before the model is chosen.
await ctx.messages()The conversation so far, assembled only when you call it.
await ctx.memo(key, fn)A saved JSON result for a key.
await ctx.getSandbox()The session's sandbox, started on first use. Unavailable inside the model field. Call it inside a memo; see Read the sandbox.

For session state inside a dynamic function, query ctx.view with selectors from eve/events instead of reconstructing it yourself. See Session views & selectors.

Before a model call, ctx.messages() includes the task results and [Tasks] note that call will receive. A dynamic model can react to a background task's result in the same step, without waiting for another call.

For each call, eve prepares task results once with the tool definitions available before dynamic functions run. Those functions configure the upcoming model and tools without changing the prepared task results. If a dynamic function fails, pending results remain available for a later call.

Code outside a memo runs every time eve runs the function. Put a fetch or decision inside a memo when its answer should stay fixed for a key:

agent/tools/query.ts
import { defineDynamic, defineTool } from "eve/tools";
import { z } from "zod";
import { listTables, runReadOnly } from "../lib/warehouse";

export default defineDynamic(async (ctx) => {
  const tables = await ctx.memo(ctx.session.id, listTables);
  return Object.fromEntries(
    tables.map((table) => [
      table.name,
      defineTool({
        description: `Query ${table.name}. Columns: ${table.columns.join(", ")}`,
        inputSchema: z.object({ sql: z.string() }),
        execute: ({ sql }) => runReadOnly(table.name, sql),
      }),
    ]),
  );
});

After a cold start, eve runs the function again. The memo returns the saved tables without querying the database, and ordinary code rebuilds the tools and their callbacks.

Choose a lifetime

KeyObservation runs
No memoEvery run of the function
ctx.turn?.id ?? nullOnce per turn
ctx.session.idOnce per session, until a deployment change
A caller or tenant IDWhen that key changes

The key sets a lifetime, not a dependency list. A change in context that the callback reads doesn't clear a saved result.

Memo rules

  • Keys compare as canonical JSON. A top-level undefined key means null; undefined inside a key is rejected. Use tenantId ?? null to represent a missing value explicitly. A key is at most 64 KB and a result at most 1 MB. Save plain JSON, not clients, functions, dates, or schemas.
  • Each definition or hook retains at most 4 MB of memo JSON, including keys. Memoize a collection rather than each row, and keep IDs instead of whole records.
  • Identity includes the session and mounted definition. Separate files do not share memo results.
  • Give multiple memos distinct keys, usually tuples such as ["tables", tenantId] and ["flags", ctx.turn?.id ?? null]. Reusing a key in one run of the function throws.
  • eve keeps only the keys that the latest successful run used. A skipped branch loses its saved results; returning to it runs the callback again.
  • A failing memo keeps no result. Successful memos survive a later error in the definition if they fit alongside its earlier memo results. If they don't fit within 4 MB, eve keeps the earlier results, and the new memos run again next time.
  • Deployment changes discard memos. Memos are a cache, not a record of side effects.
  • Memos can run concurrently with Promise.all, but cannot nest. Await every memo before returning.
  • Memo results are saved privately with the session and never appear on the stream.
  • Key a dynamic tool's memos on the turn or the session. If a key changes within a turn, such as a key on a call ID, eve can refuse an approved call to the tool after a restart, and the model has to request the call again.

A memo callback receives { idempotencyKey, abortSignal }. Pass idempotencyKey to an external service that supports idempotency, because an interrupted step can run again before eve saves its result. The key is stable per session, definition, and memo key. It repeats when a deployment change or skipped branch runs the memo again, so send your own key when a run needs a fresh response. Perform side effects in hooks or tool execution, not while computing a definition.

Read the sandbox

ctx.getSandbox() returns the session's sandbox, the same handle tools and hooks get. eve runs a dynamic function before every model call, so a sandbox call outside a memo makes every model call wait for the sandbox, and the first one waits for the sandbox to start. Read the sandbox inside a memo, keyed on something in the session that changes when the files might have changed.

This instruction reads the repository's AGENTS.md once after each completed checkout call:

agent/instructions/repo-guidelines.ts
import { calls } from "eve/events";
import { defineDynamic, defineInstructions } from "eve/instructions";

export default defineDynamic(async (ctx) => {
  const checkout = calls(ctx.view, { name: "checkout" })
    .filter((call) => call.state === "completed")
    .at(-1);
  if (!checkout) return null;
  const guidelines = await ctx.memo(["agents-md", checkout.callId], async () => {
    const sandbox = await ctx.getSandbox();
    return sandbox.readTextFile({ path: "AGENTS.md" });
  });
  return guidelines ? defineInstructions({ content: guidelines, role: "user" }) : null;
});

Reading ctx.view doesn't touch the sandbox, so the function starts no sandbox before the first checkout, and reads the file once per checkout after that. A run after a cold start reuses the saved result instead of reading the sandbox again. The memo doesn't notice later edits to the file, such as a bash or write_file call; add those calls to the key when edits matter.

Return content read from the sandbox as a user instruction. It comes from the workspace rather than from the agent's own instructions, and a user instruction joins the conversation only when its content changes, which keeps the prompt cached.

Dynamic models

The agent's model field accepts a dynamic function that returns a model ID, a provider instance, or a selection containing model and optional model settings. A missing or invalid model fails the turn. ctx.model is unavailable here.

agent/agent.ts
import { defineAgent, defineDynamic } from "eve";

export default defineAgent({
  model: defineDynamic(async (ctx) => {
    const hasImage = (await ctx.messages()).some(
      (message) =>
        message.role === "user" &&
        Array.isArray(message.content) &&
        message.content.some(
          (part) =>
            part.type === "image" || (part.type === "file" && part.mediaType.startsWith("image/")),
        ),
    );
    return hasImage ? "google/gemini-3.5-flash" : "zai/glm-5.2";
  }),
});

Changing models can reduce prompt-cache reuse. Use a session- or turn-keyed memo for a decision that should stay fixed. See Choose the model dynamically.

Dynamic subagents

A declared subagent's agent.ts can return a child configuration or null:

agent/subagents/finance/agent.ts
import { defineAgent, defineDynamic } from "eve";

export default defineDynamic((ctx) =>
  ctx.session.auth.current?.attributes.plan === "enterprise"
    ? defineAgent({ description: "Analyze financial data.", model: ctx.model.id })
    : null,
);

The child's tools, instructions, skills, and nested subagents still build from the filesystem; the returned config supplies runtime settings. A local child config requires a string model ID. Put build settings such as build.externalDependencies on the root agent, because build and Workflow world settings can't be chosen at runtime.

A single-file remote subagent returns defineRemoteAgent(...) or null. Compute the URL string in the function. Credentials can use memo results, and later requests to the same child rebuild them from the session as it was when the child opened. See Dynamic remote agents for the rebuild rules.

Hiding a subagent doesn't authorize anything: sensitive child tools still need authorization and approval checks.

Dynamic connections

Return a defineMcpClientConnection(...), a defineOpenAPIConnection(...), a map of definitions, or null. Select accounts and endpoints from authenticated identity or application-owned data, not untrusted conversation URLs.

agent/connections/accounts.ts
import { defineDynamic, defineMcpClientConnection } from "eve/connections";
import { listEnabledAccounts, mintAccountToken } from "../lib/accounts";

export default defineDynamic(async (ctx) => {
  const principal = ctx.session.auth.current;
  if (principal?.principalType !== "user") return null;
  const accounts = await ctx.memo(principal, () => listEnabledAccounts(principal));
  return Object.fromEntries(
    accounts.map((account) => [
      account.slug,
      defineMcpClientConnection({
        url: "https://mcp.cloud.example.com",
        description: account.label,
        instanceKey: account.accountId,
        auth: {
          principalType: "user",
          getToken: ({ principal }) => mintAccountToken(principal, account),
        },
      }),
    ]),
  );
});

The memo saves account metadata, not tokens; auth and header callbacks run when needed. Set instanceKey to a stable, non-secret account identifier, and change it when the endpoint, account, or auth provider changes. eve rejects a waiting sign-in callback if its connection's name, URL, or instanceKey changed.

Dynamic connections take the same filtering, provided arguments, and approval options as static MCP and OpenAPI connections. Each run refreshes connection callbacks and may replace clients, so don't rely on a dynamic MCP protocol session surviving between model calls. Models discover connection tools through eve__search and call them through eve__tool.

Dynamic tools

Return a single defineTool(...), a map of tools, or null. Executors receive the same ToolContext as static tools, including ctx.getToken and ctx.requireAuth. Validators, including refinements and transformations, and an endsTurn function run as they do on a static tool.

Return a workflow tool

A dynamic function can also return a workflow tool, so a tool that waits for a person, a webhook, or a timer is offered only on some calls. Assign the defineWorkflowTool() to a top-level const, so the build compiles its body, and return that const:

agent/tools/support.ts
import { defineDynamic, defineWorkflowTool } from "eve/tools";
import { z } from "zod";

const escalate = defineWorkflowTool({
  description: "Escalate a support case once someone confirms.",
  inputSchema: z.object({ summary: z.string() }),
  async execute({ summary }, ctx) {
    "use workflow";
    return await ctx.ask({ prompt: `Escalate this case? ${summary}` });
  },
});

export default defineDynamic((ctx) =>
  ctx.session.auth.current?.attributes.team === "support" ? { escalate } : null,
);

The entry point can also reference a top-level async function that starts with "use workflow", in the same module or an imported one. eve compiles an inline body as a top-level function named after the const and the entry point, such as escalate$execute, so renaming the const changes the workflow's ID, as renaming a static tool's entry point does.

A workflow can't read the variables around it, so a defineWorkflowTool() created inside the dynamic function, and an entry point without "use workflow", fail the build. An imported entry point is checked when the tool is offered: if it isn't a compiled workflow, the turn fails with an error that names the tool. A call that has started keeps running when a later model call no longer offers the tool, and its result still reaches the turn; while its task runs, the model keeps eve__task_wait and eve__task_cancel. A task's result that arrives after the function stops returning the tool skips the tool's toModelOutput, so the model reads the raw output. eve's built-in workflow tools, such as agent({ models }), only work as static tools, so returning one fails the turn.

Author replayable callbacks

Build callbacks and schemas with ordinary code. Save observations in memos when a fresh process must rebuild from the same data, because values fetched outside a memo are fetched again. Avoid Math.random() and Date.now() in declarations unless memoized; use ctx.now for commit time.

Create dynamic tools in a package

Packages can return ordinary defineTool values, including callbacks made by factories. Prefer an extension when distributing a namespaced collection of capabilities.

Identity and redeploys

A fresh process rebuilds tools from their definitions and saved memo results. A deployment change discards the results and runs the new code. Approved work runs before the functions run for the next model call. Check authorization inside execution when a check must also stop already-approved work.

A call waiting for approval or sign-in runs only if its dynamic tool, connection, or subagent is unchanged. eve compares what the model was offered, a connection's target, or a subagent's selection, plus the memo results its definition used. If any changed, the call returns a tool error saying the tool changed since it was offered, and the model can request it again.

Naming

A single tool takes the file's slug. A map uses bare keys, with no automatic file prefix: agent/tools/tenant.ts returning { query, export } exposes query and export.

Names use ASCII letters, digits, underscores, and dashes, start with a letter, and contain at most 64 characters. eve and the eve__ prefix are reserved. A connection reserves its name and its <name>__ prefix, so tools cannot take those names.

Conflicts

A dynamic connection or skill overrides a static one of the same kind and name. Two dynamic connection definitions can't emit the same name. A tool name belongs to one tool: when a dynamic tool returns the name of a static tool or of another dynamic tool, the first keeps it and eve logs an error for the other. Static tools come first. The same rule applies to duplicate dynamic skill names. To replace a built-in or extension tool, add agent/tools/<name>.ts instead. Dynamic tools can't take the names of static workflow tools or subagents. Other invalid results and name conflicts fail the turn.

Steering and sign-in

Because eve runs dynamic functions before every model call, they see a steering message or completed sign-in without a new turn. A turn-keyed memo stays fixed until the next turn.

Execution order

Hooks finish first, then model selection, then instructions, connections, subagents, tools, and skills. Don't depend on the order in which files run; each definition computes its own value.

Because hooks finish first, state a turn.started hook writes is what the turn's dynamic functions read, from its first model call on. See Hooks.

A tool with deferred: true stays out of the model's tool list. It is found with eve__search and called with eve__tool, like a static deferred tool.

Dynamic skills

Return a defineSkill(...), a map, or null. A single skill takes the file slug; map entries use bare keys, with the same name constraints as tools.

agent/skills/team_playbook.ts
import { defineDynamic, defineSkill } from "eve/skills";
import { PLAYBOOKS } from "../lib/playbooks";

export default defineDynamic((ctx) => {
  const team = ctx.session.auth.current?.attributes.team;
  const content = team ? PLAYBOOKS[team] : undefined;
  return content ? defineSkill({ content, description: "The team's playbook." }) : null;
});

A skill with only content doesn't start a sandbox. A skill with files installs its package in the sandbox, and a changed package replaces the earlier files:

  • The model call doesn't wait for the install. A tool or hook that uses the sandbox waits for it.
  • If the install fails twice in a row, eve logs a warning and retries on the next model call.
  • When the session detects a recreated sandbox, the next run reinstalls the package. A replacement made by a subagent or workflow step sharing the sandbox may go undetected, and then the files aren't rewritten until the package changes.
  • Omitting files from a skill that stays available keeps its installed files; withdraw the skill to remove them.

deferred: true keeps a skill out of the announcement, while leaving it discoverable through eve__search and loadable with eve__skill.

Dynamic instructions

Return defineInstructions({ content, role? }) or null. System instructions apply while the function returns them and stay outside history. User instructions join the conversation history only when their content changes:

agent/instructions/brief.ts
import { defineDynamic, defineInstructions } from "eve/instructions";
import { loadBrief } from "../lib/briefs";

export default defineDynamic(async (ctx) => {
  if (!ctx.turn) return null;
  const brief = await ctx.memo(ctx.turn.id, () => loadBrief(ctx.session.auth.current));
  return brief ? defineInstructions({ content: brief, role: "user" }) : null;
});

Before a turn's first model call, new user content joins just before the turn's input; mid-turn changes append at the current position. Returning null adds nothing and resets content tracking, so returning the earlier content later adds it again, but it doesn't remove earlier history. Unchanged content isn't added again after a deployment, or after a compaction that keeps it in the history; a clear or compaction that removes it adds it again.

Errors and recovery

An unhandled error in a dynamic function or memo fails the turn with REACTION_FAILED. Catch optional work and return null when it should contribute nothing. A catch around await ctx.memo(...) leaves the failure uncached, so a later run tries it again. A catch inside the memo that returns null caches that null for the key's lifetime. A failed turn's input is not replayed.

With EVE_LOG_LEVEL=debug, eve logs each memo run with its file, key digest, reason (new key or deployment change), and duration, and whether each run's value changed. Logs never include the key. The digest is an unsalted hash, so someone who can guess a key, such as a tenant ID, can confirm it against the digest.