Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

feat(eve): run one agent tool outside a conversation with invokeTool (#4080)

Rui55d4604d1405
diff --git a/.changeset/route-args-invoke-tool.md b/.changeset/route-args-invoke-tool.md
new file mode 100644
index 000000000..78c4034ca
--- /dev/null
+++ b/.changeset/route-args-invoke-tool.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Channel route handlers now receive `invokeTool(name, input, { auth })`, which runs one of the agent's tools as the given caller outside any conversation, with a sandbox that lasts for the call. Tools whose approval policy asks a person resolve to `approval-required` without running.
diff --git a/docs/channels/custom.mdx b/docs/channels/custom.mdx
index 655811019..194d1f4ba 100644
--- a/docs/channels/custom.mdx
+++ b/docs/channels/custom.mdx
@@ -68,6 +68,7 @@ Each route receives these operation surfaces:
- `to(channel, target).send(message, options)` hands work to another authored channel.
- `params`, `waitUntil`, and `requestIp` provide request metadata and lifetime control.
- `describe()` returns the agent's name, description, and the compiled tools a caller can run outside a turn, with their JSON schemas, sorted by name. It carries no paths, config, or other inspection detail, so a channel can publish it to its callers. Tools that need a turn (framework tools, workflow and provider tools, tools without `execute`) and tools added by dynamic resolvers or subagents are left out.
+- `invokeTool(name, input, { auth })` runs one of those tools as `auth`, outside any conversation: no model, turn, or workflow run. Each call gets its own session. Authored state starts from its initial value and is not kept, and a sandbox the tool opens is deleted when the call ends. It resolves to `completed` with the tool's output, or to `invalid-input`, `denied`, `failed`, `approval-required` when the tool's approval policy asks a person (the tool did not run), or `authorization-required` with the connections the tool needs a sign-in to.
Event handlers receive `(eventData, channel, ctx)`. `ctx.session.id` identifies
the exact session, while `channel.continuation` exposes the current address and
diff --git a/packages/eve/extension-contracts/compatibility/channel/v46.ts b/packages/eve/extension-contracts/compatibility/channel/v46.ts
new file mode 100644
index 000000000..bfb6e481a
--- /dev/null
+++ b/packages/eve/extension-contracts/compatibility/channel/v46.ts
@@ -0,0 +1,12 @@
+import { defineChannel, GET } from "#public/channels/index.js";
+
+// Epoch 46 route handlers had no `invokeTool` arg; epoch 47 adds it.
+export default defineChannel({
+ routes: [
+ GET("/status/:sessionId", async (_request, { attachSession, describe, params, requestIp }) => {
+ const { tools } = await describe();
+ await attachSession(params.sessionId!).cancel();
+ return Response.json({ requestIp, tools: tools.length });
+ }),
+ ],
+});
diff --git a/packages/eve/extension-contracts/reports/channel/v47.json b/packages/eve/extension-contracts/reports/channel/v47.json
new file mode 100644
index 000000000..85858562d
--- /dev/null
+++ b/packages/eve/extension-contracts/reports/channel/v47.json
@@ -0,0 +1,21 @@
+{
+ "kind": "eve-extension-capability-contract",
+ "capability": "channel",
+ "epoch": 47,
+ "sha256": "771aebfd18d8ea32c3e0326454812b0fb42a25e10c20e29d61c0476fb18b83d2",
+ "exports": [
+ "DELETE",
+ "GET",
+ "HEAD",
+ "OPTIONS",
+ "PATCH",
+ "POST",
+ "PUT",
+ "WS",
+ "createWebSocketUpgradeServer",
+ "defineChannel",
+ "disableRoute",
+ "isChannel",
+ "isDisabledRouteSentinel"
+ ]
+}
diff --git a/packages/eve/src/channel/conversation-context.ts b/packages/eve/src/channel/conversation-context.ts
index db73a1deb..d98e1f56d 100644
--- a/packages/eve/src/channel/conversation-context.ts
+++ b/packages/eve/src/channel/conversation-context.ts
@@ -10,8 +10,19 @@ import {
} from "#shared/conversation-context.js";
import { readForwardedTraceAssertion } from "#shared/forwarded-trace-policy.js";
+/** What a conversation context is built from: a run, or a direct tool call's channel and caller. */
+type ConversationSource =
+ | RunInput
+ | (Pick<RunInput, "adapter" | "auth"> &
+ Partial<
+ Pick<
+ RunInput,
+ "audienceAuth" | "channelName" | "inheritedConversation" | "parentTraceContext"
+ >
+ >);
+
export function buildConversationContext(
- run: RunInput,
+ run: ConversationSource,
environment: ConversationEnvironment,
): ConversationContext {
const hasRouteAuth = Object.hasOwn(run, "audienceAuth");
diff --git a/packages/eve/src/channel/invoke-tool.ts b/packages/eve/src/channel/invoke-tool.ts
new file mode 100644
index 000000000..54115daed
--- /dev/null
+++ b/packages/eve/src/channel/invoke-tool.ts
@@ -0,0 +1,37 @@
+import type { SessionAuthContext } from "#channel/types.js";
+import type { ToolModelOutput } from "#tools/model-output.js";
+
+/** Options for one {@link InvokeToolFn} call. */
+export interface InvokeToolOptions {
+ /** The caller this request authenticated. Becomes `ctx.session.auth.current`. */
+ readonly auth: SessionAuthContext;
+ readonly signal?: AbortSignal;
+}
+
+/** Outcome of one {@link InvokeToolFn} call. */
+export type InvokeToolResult =
+ | {
+ readonly status: "completed";
+ readonly output: unknown;
+ readonly modelOutput: ToolModelOutput;
+ }
+ | { readonly status: "failed"; readonly message: string; readonly errorId?: string }
+ | { readonly status: "invalid-input"; readonly message: string }
+ | { readonly status: "denied"; readonly reason?: string }
+ /** The tool's approval policy asks a person. A call has no one to ask, so the tool did not run. */
+ | { readonly status: "approval-required" }
+ /** The tool needs a sign-in to these connections first. The tool stopped where it needed them. */
+ | { readonly status: "authorization-required"; readonly connections: readonly string[] };
+
+/**
+ * Runs one of the agent's tools outside a conversation. No model, turn, or
+ * workflow step is involved, and the call never parks. Each call gets its own
+ * session: `ctx.session.auth.current` is the caller, authored state starts from
+ * its initial value and is not kept, and a sandbox the tool opens is deleted
+ * when the call ends.
+ */
+export type InvokeToolFn = (
+ name: string,
+ input: unknown,
+ options: InvokeToolOptions,
+) => Promise<InvokeToolResult>;
diff --git a/packages/eve/src/channel/routes.ts b/packages/eve/src/channel/routes.ts
index 6fc4f631e..4bc7944ef 100644
--- a/packages/eve/src/channel/routes.ts
+++ b/packages/eve/src/channel/routes.ts
@@ -2,6 +2,7 @@ import type { UserContent } from "ai";
import type { CrossChannelToFn } from "#channel/cross-channel-receive.js";
import type { ChannelFrom, ChannelResolveSession } from "#channel/channel-operations.js";
+import type { InvokeToolFn } from "#channel/invoke-tool.js";
import type { InputResponse } from "#shared/input.js";
import type { Session } from "#channel/session.js";
import type { JsonObject } from "#shared/json.js";
@@ -39,6 +40,8 @@ export interface RouteHandlerArgs<TState = undefined> {
* inspection detail of `GET /eve/v1/info`.
*/
describe(): Promise<AgentDescription>;
+ /** Runs one of the agent's tools as `auth`, outside any conversation. */
+ readonly invokeTool: InvokeToolFn;
}
export interface SendPayload {
diff --git a/packages/eve/src/compiler/extension-compatibility.ts b/packages/eve/src/compiler/extension-compatibility.ts
index 7d3f1b649..4a960bc05 100644
--- a/packages/eve/src/compiler/extension-compatibility.ts
+++ b/packages/eve/src/compiler/extension-compatibility.ts
@@ -114,10 +114,10 @@ const EXTENSION_CAPABILITY_CONTRACTS = {
},
},
channel: {
- current: 46,
+ current: 47,
supported: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 29, 31, 36, 37, 38, 39, 40, 41, 42,
- 43, 44, 45, 46,
+ 43, 44, 45, 46, 47,
],
dropped: {
12: "Message and reasoning append events now expose deltas instead of cumulative snapshots.",
diff --git a/packages/eve/src/execution/invoke-tool.ts b/packages/eve/src/execution/invoke-tool.ts
new file mode 100644
index 000000000..2fa0a0613
--- /dev/null
+++ b/packages/eve/src/execution/invoke-tool.ts
@@ -0,0 +1,367 @@
+import { context as otelContext, trace } from "#compiled/@opentelemetry/api/index.js";
+
+import { resolveApprovalPolicy, type ApprovalStatus } from "#approval/definition.js";
+import type { InvokeToolOptions, InvokeToolResult } from "#channel/invoke-tool.js";
+import {
+ compiledToolOwner,
+ type CompiledToolBindings,
+ isInvocableCompiledTool,
+} from "#channel/tool-eligibility.js";
+import type { SessionAuthContext } from "#channel/types.js";
+import type { CompiledToolDefinition } from "#compiler/manifest.js";
+import { isConnectionAuthorizationFailedError } from "#connections/errors.js";
+import { buildCallbackContext } from "#context/build-callback-context.js";
+import { ContextContainer, contextStorage } from "#context/container.js";
+import { AuthKey, InitiatorAuthKey, SandboxKey, SessionIdKey, SessionKey } from "#context/keys.js";
+import { ensureSandboxAccess } from "#execution/sandbox/ensure.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import {
+ AuthorizationHookKey,
+ CallbackBaseUrlKey,
+ isAuthorizationSignal,
+ modelFacingAuthorizationOutput,
+} from "#harness/authorization.js";
+import { checkToolCallInput, toolCallModelOutput } from "#harness/tool-call-io.js";
+import { normalizeToolJsonOutput } from "#harness/tool-model-output.js";
+import type { HarnessToolMap } from "#harness/types.js";
+import { createLogger, logError } from "#internal/logging.js";
+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import type { RuntimeSandboxRegistry } from "#runtime/sandbox/registry.js";
+import { BundleKey } from "#runtime/sessions/runtime-context-keys.js";
+import type { CompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+import { isAsyncIterable } from "#shared/async-iterable.js";
+import { toErrorMessage } from "#shared/errors.js";
+import type { JsonObject } from "#shared/json.js";
+import type { SandboxAccess } from "#sandbox/state.js";
+import { createUlid } from "#shared/ulid.js";
+import {
+ type InvokeToolObserver,
+ type InvokeToolTraceOrigin,
+ withInvokeToolSpan,
+} from "#tracing/invoke-tool-span.js";
+import type { ToolExecuteOptions } from "#tools/definition.js";
+import type { ToolModelOutput } from "#tools/model-output.js";
+
+const log = createLogger("invoke-tool");
+
+/** What `invokeTool` needs from the agent: its static tools and sandbox. */
+export interface InvokeToolRuntime {
+ /** Present in a deployed agent so framework helpers can reach the compiled graph. */
+ readonly bundle?: CompiledRuntimeAgentBundle;
+ /** Base URL for framework callbacks, such as the page a sign-in lands on. */
+ readonly callbackBaseUrl: string;
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
+ /** The root node's compiled tools and source bindings, which decide invocability. */
+ readonly manifest: InvokeToolManifest;
+ readonly nodeId: string;
+ /** The agent's name, for trace policy and `gen_ai.agent.name`. */
+ readonly agentName: string;
+ /** The channel the call arrived on, for trace policy and span attributes. */
+ readonly origin?: InvokeToolTraceOrigin;
+ readonly sandboxRegistry: RuntimeSandboxRegistry;
+ /** Static tools only: dynamic resolvers never run outside a turn. */
+ readonly tools: HarnessToolMap;
+}
+
+/** The part of a compiled manifest `invokeTool` reads to decide invocability. */
+export interface InvokeToolManifest extends CompiledToolBindings {
+ readonly tools: readonly Pick<
+ CompiledToolDefinition,
+ "behavior" | "hasExecute" | "name" | "sourceId"
+ >[];
+}
+
+/** Why a compiled tool cannot run outside a turn, or `undefined` when it can. */
+function ineligibility(
+ manifest: InvokeToolManifest,
+ tool: InvokeToolManifest["tools"][number],
+): string | undefined {
+ // `isInvocableCompiledTool` is the one rule, shared with `describe()`; the
+ // reason below only words the refusal.
+ if (isInvocableCompiledTool(manifest, tool)) return undefined;
+ if (compiledToolOwner(manifest, tool).kind === "framework") {
+ return "it is a framework tool, which needs a conversation";
+ }
+ if (tool.behavior?.handling !== undefined) {
+ return "the harness or the model provider runs it, not its execute";
+ }
+ return "it has no server-side execute";
+}
+
+/**
+ * Runs one tool outside a turn; see `InvokeToolFn` for the contract. Each call
+ * gets a fresh session id, so nothing it opens is shared with another call.
+ */
+export async function invokeTool(
+ runtime: InvokeToolRuntime,
+ name: string,
+ input: unknown,
+ options: InvokeToolOptions,
+): Promise<InvokeToolResult> {
+ const compiled = runtime.manifest.tools.find((tool) => tool.name === name);
+ const definition = runtime.tools.get(name);
+ if (compiled === undefined || definition === undefined) {
+ return failed(`The agent has no tool named "${name}".`);
+ }
+ const ineligible =
+ ineligibility(runtime.manifest, compiled) ??
+ (definition.execute === undefined ? "it has no server-side execute" : undefined);
+ if (ineligible !== undefined) {
+ return failed(`Tool "${name}" cannot be invoked outside a conversation: ${ineligible}.`);
+ }
+
+ const callId = `call_${createUlid()}`;
+ const sessionId = `call_session_${createUlid()}`;
+ return await withInvokeToolSpan(
+ {
+ agentName: runtime.agentName,
+ auth: options.auth,
+ callId,
+ origin: runtime.origin,
+ sessionId,
+ toolName: name,
+ },
+ (observer) =>
+ runInvocation({ callId, definition, input, name, observer, options, runtime, sessionId }),
+ );
+}
+
+async function runInvocation(input: {
+ readonly callId: string;
+ readonly definition: HarnessToolDefinition;
+ readonly input: unknown;
+ readonly name: string;
+ readonly observer: InvokeToolObserver;
+ readonly options: InvokeToolOptions;
+ readonly runtime: InvokeToolRuntime;
+ readonly sessionId: string;
+}): Promise<InvokeToolResult> {
+ const { callId, definition, name, observer, options, runtime, sessionId } = input;
+ const validated = await checkToolCallInput(definition, input.input, callId);
+ if (validated.kind === "threw") {
+ observer.failedWith(validated.error);
+ return failedFromError(validated.error, name, "input validation failed");
+ }
+ if (validated.kind === "invalid") return { message: validated.message, status: "invalid-input" };
+
+ const sandbox = await callSandbox(runtime, sessionId);
+ const context = createCallContext({
+ auth: options.auth,
+ callId,
+ callbackBaseUrl: runtime.callbackBaseUrl,
+ sessionId,
+ });
+ context.setVirtualContext(SandboxKey, sandbox.access);
+ if (runtime.bundle !== undefined) context.setVirtualContext(BundleKey, runtime.bundle);
+
+ try {
+ return await contextStorage.run(context, () =>
+ runCall({
+ callId,
+ definition,
+ input: validated.value,
+ observer,
+ signal: options.signal,
+ }),
+ );
+ } finally {
+ await sandbox.release().catch((error: unknown) => {
+ logError(log, "failed to delete a call's sandbox", error, { sessionId, toolName: name });
+ });
+ }
+}
+
+/** The call's sandbox: opened on the first `ctx.getSandbox()`, deleted after the call. */
+async function callSandbox(
+ runtime: InvokeToolRuntime,
+ sessionId: string,
+): Promise<{ readonly access: SandboxAccess; release(): Promise<void> }> {
+ const inner = await ensureSandboxAccess({
+ compiledArtifactsSource: runtime.compiledArtifactsSource,
+ nodeId: runtime.nodeId,
+ ownsSandbox: true,
+ registry: runtime.sandboxRegistry,
+ sessionId,
+ state: null,
+ });
+ // The latest requested open, kept before it settles: `execute` can finish
+ // (say, by losing a race against cancellation) while the provider is still
+ // starting, and release must still delete what that start creates.
+ let requested: Promise<unknown> | undefined;
+ return {
+ access: {
+ ...inner,
+ get() {
+ const opening = inner.get();
+ requested = opening;
+ return opening;
+ },
+ },
+ async release() {
+ if (requested === undefined) return;
+ // A failed open left nothing behind; deleting would open one just to delete it.
+ const sandbox = await requested.catch(() => null);
+ if (sandbox !== null) await inner.delete?.();
+ },
+ };
+}
+
+function createCallContext(input: {
+ readonly auth: SessionAuthContext;
+ readonly callId: string;
+ readonly callbackBaseUrl: string;
+ readonly sessionId: string;
+}): ContextContainer {
+ const context = new ContextContainer();
+ context.set(AuthKey, input.auth);
+ context.set(InitiatorAuthKey, input.auth);
+ context.set(SessionIdKey, input.sessionId);
+ // No turn exists; the stand-in names the call, as sandbox setup outside a turn does.
+ context.setVirtualContext(SessionKey, {
+ auth: { current: input.auth, initiator: input.auth },
+ sessionId: input.sessionId,
+ turn: { id: input.callId, sequence: 0 },
+ });
+ context.set(CallbackBaseUrlKey, input.callbackBaseUrl.replace(/\/$/, ""));
+ // Sign-in callbacks have no parked run to resume; the URL is only a landing page.
+ context.setVirtualContext(AuthorizationHookKey, `invoke-tool:${input.callId}`);
+ return context;
+}
+
+async function runCall(input: {
+ readonly callId: string;
+ readonly definition: HarnessToolDefinition;
+ readonly input: JsonObject;
+ readonly observer: InvokeToolObserver;
+ readonly signal: AbortSignal | undefined;
+}): Promise<InvokeToolResult> {
+ const { callId, definition, observer } = input;
+ const signal = input.signal ?? new AbortController().signal;
+
+ if (definition.approval !== undefined) {
+ let status: ApprovalStatus;
+ try {
+ status = await resolveApprovalPolicy(definition.approval)({
+ ...buildCallbackContext(),
+ abortSignal: signal,
+ approvedTools: new Set<string>(),
+ callId,
+ toolInput: input.input,
+ toolName: definition.name,
+ });
+ } catch (error) {
+ observer.failedWith(error);
+ return failedFromError(error, definition.name, "approval policy failed");
+ }
+ const decision = decideApproval(status);
+ if (decision.kind === "denied") return denied(decision.reason);
+ if (decision.kind === "user-approval") return { status: "approval-required" };
+ }
+
+ const executeOptions: ToolExecuteOptions = {
+ abortSignal: signal,
+ messages: [],
+ toolCallId: callId,
+ };
+ // `execute` and output serialization are one step, as in a conversation's wrapped execute.
+ await observer.executing(input.input);
+ let output: unknown;
+ let json: unknown;
+ let returned = false;
+ // Started after the start event's handlers, and read once when execute settles.
+ const startedAt = performance.now();
+ const elapsed = () => performance.now() - startedAt;
+ let durationMs: number;
+ try {
+ output = await definition.execute!(input.input, executeOptions);
+ if (isAsyncIterable(output)) output = await lastIterated(output);
+ returned = true;
+ if (!isAuthorizationSignal(output)) {
+ json = normalizeToolJsonOutput({
+ boundary: "execute",
+ output,
+ toolCallId: callId,
+ toolName: definition.name,
+ });
+ }
+ durationMs = elapsed();
+ } catch (error) {
+ await observer.executed({ durationMs: elapsed(), error, type: "error" });
+ observer.failedWith(error);
+ if (returned) {
+ return failedFromError(error, definition.name, "tool output could not be serialized");
+ }
+ if (isConnectionAuthorizationFailedError(error)) {
+ return failed(toErrorMessage(error));
+ }
+ return failedFromError(error, definition.name, "tool execution failed");
+ }
+ if (isAuthorizationSignal(output)) {
+ await observer.executed({
+ durationMs,
+ output: modelFacingAuthorizationOutput(output),
+ type: "result",
+ });
+ return {
+ connections: output.challenges.map((challenge) => challenge.name),
+ status: "authorization-required",
+ };
+ }
+ await observer.executed({ durationMs, output: json, type: "result" });
+
+ try {
+ return {
+ modelOutput: (await toolCallModelOutput(definition, json, callId)) as ToolModelOutput,
+ output: json,
+ status: "completed",
+ };
+ } catch (error) {
+ observer.failedWith(error);
+ return failedFromError(error, definition.name, "tool output could not be serialized");
+ }
+}
+
+function decideApproval(
+ status: ApprovalStatus,
+):
+ | { readonly kind: "run" }
+ | { readonly kind: "user-approval" }
+ | { readonly kind: "denied"; readonly reason?: string } {
+ if (status === true || status === "user-approval") return { kind: "user-approval" };
+ if (status === "denied") return { kind: "denied" };
+ if (typeof status === "object" && status !== null) {
+ if (status.type === "user-approval") return { kind: "user-approval" };
+ if (status.type === "denied") return { kind: "denied", reason: status.reason };
+ }
+ return { kind: "run" };
+}
+
+async function lastIterated(iterable: AsyncIterable<unknown>): Promise<unknown> {
+ let last: unknown;
+ for await (const value of iterable) last = value;
+ return last;
+}
+
+function denied(reason: string | undefined): InvokeToolResult {
+ return reason === undefined ? { status: "denied" } : { reason, status: "denied" };
+}
+
+function failed(message: string): InvokeToolResult {
+ return { message, status: "failed" };
+}
+
+/**
+ * Logs the error under a fresh id and returns that id with a generic message:
+ * an unexpected error's text can carry paths, hosts, or secrets.
+ */
+function failedFromError(error: unknown, toolName: string, what: string): InvokeToolResult {
+ // Off every span: the tool span records the failure itself, under its content decision.
+ const errorId = otelContext.with(trace.deleteSpan(otelContext.active()), () =>
+ logError(log, `invokeTool ${what}`, error, { toolName }),
+ );
+ return {
+ errorId,
+ message: `Tool "${toolName}" failed: ${what}. The error is logged with id ${errorId}.`,
+ status: "failed",
+ };
+}
diff --git a/packages/eve/src/execution/sandbox/active-handles.ts b/packages/eve/src/execution/sandbox/active-handles.ts
index b14b7f09d..fda41f7d1 100644
--- a/packages/eve/src/execution/sandbox/active-handles.ts
+++ b/packages/eve/src/execution/sandbox/active-handles.ts
@@ -39,6 +39,16 @@ export function trackActiveSandboxHandle(input: {
);
}
+/** Drops a handle from shutdown tracking, unless a newer handle replaced it. */
+export function untrackActiveSandboxHandle(input: {
+ readonly providerName: string;
+ readonly handle: ShutdownCapableSandboxHandle;
+ readonly sessionId: string;
+}): void {
+ const key = createActiveSandboxHandleKey(input.providerName, input.sessionId);
+ if (activeSandboxHandles.get(key) === input.handle) activeSandboxHandles.delete(key);
+}
+
/**
* Stops every tracked sandbox by invoking its runtime-shutdown hook in
* parallel, then clears the registry. Failures are logged and never
diff --git a/packages/eve/src/execution/sandbox/ensure.ts b/packages/eve/src/execution/sandbox/ensure.ts
index bf2adadcd..8395d71d6 100644
--- a/packages/eve/src/execution/sandbox/ensure.ts
+++ b/packages/eve/src/execution/sandbox/ensure.ts
@@ -5,7 +5,10 @@ import {
buildCallbackContext,
withRuntimeSandboxLifecycle,
} from "#context/build-callback-context.js";
-import { trackActiveSandboxHandle } from "#execution/sandbox/active-handles.js";
+import {
+ trackActiveSandboxHandle,
+ untrackActiveSandboxHandle,
+} from "#execution/sandbox/active-handles.js";
import { createSandboxProviderHost } from "#execution/sandbox/provider-host.js";
import { resolveSandboxCacheDirectory } from "#internal/application/paths.js";
import {
@@ -324,7 +327,11 @@ export async function ensureSandboxAccess(input: EnsureSandboxAccessInput): Prom
if (input.ownsSandbox === false)
throw new Error("Only the owning session can delete this sandbox.");
const current = await requireHandle();
+ const providerName = opened?.providerName;
await current.onSessionDelete(deleteOptions);
+ if (providerName !== undefined) {
+ untrackActiveSandboxHandle({ handle: current, providerName, sessionId: input.sessionId });
+ }
opened = undefined;
opening = undefined;
persisted = null;
diff --git a/packages/eve/src/harness/tool-call-io.ts b/packages/eve/src/harness/tool-call-io.ts
new file mode 100644
index 000000000..939febc45
--- /dev/null
+++ b/packages/eve/src/harness/tool-call-io.ts
@@ -0,0 +1,82 @@
+import { asSchema } from "ai";
+
+import {
+ authorizationPendingModelText,
+ isAuthorizationPendingModelOutput,
+} from "#harness/authorization.js";
+import { resolveToolCallInputObject } from "#harness/coordination.js";
+import type { HarnessToolDefinition } from "#harness/execute-tool.js";
+import { normalizeToolModelOutput, type ToolModelOutputValue } from "#harness/tool-model-output.js";
+import { toErrorMessage } from "#shared/errors.js";
+import type { JsonObject } from "#shared/json.js";
+import { toModelSchema } from "#tools/schema.js";
+
+/** The result of checking one tool call's input the way a model-issued call is checked. */
+export type ToolCallInputCheck =
+ | { readonly kind: "valid"; readonly value: JsonObject }
+ | { readonly kind: "invalid"; readonly message: string }
+ | { readonly kind: "threw"; readonly error: unknown };
+
+/**
+ * Checks a tool call's input the way a conversation does: no input (or an
+ * empty string) is `{}`, anything else that is not a JSON object is
+ * rejected, and the rest must satisfy the schema the model was given.
+ */
+export async function checkToolCallInput(
+ definition: Pick<HarnessToolDefinition, "inputSchema" | "name">,
+ input: unknown,
+ callId: string,
+): Promise<ToolCallInputCheck> {
+ let value: JsonObject;
+ try {
+ value = resolveToolCallInputObject(input, { callId, toolName: definition.name });
+ } catch (error) {
+ return {
+ kind: "invalid",
+ message: `Invalid input for tool "${definition.name}": ${toErrorMessage(error)}`,
+ };
+ }
+ let result: Awaited<ReturnType<NonNullable<ReturnType<typeof asSchema>["validate"]>>>;
+ try {
+ // The schema the model sees; normalizing a malformed one throws like a validator.
+ const schema = asSchema(toModelSchema(definition.inputSchema, "input"));
+ if (schema.validate === undefined) return { kind: "valid", value };
+ result = await schema.validate(value);
+ } catch (error) {
+ // A validator that throws failed itself; its message is not a diagnostic of the input.
+ return { error, kind: "threw" };
+ }
+ return result.success
+ ? { kind: "valid", value: result.value as JsonObject }
+ : {
+ kind: "invalid",
+ message: `Invalid input for tool "${definition.name}": ${toErrorMessage(result.error)}`,
+ };
+}
+
+/**
+ * What the model sees for a tool's output: pending sign-in text, the
+ * author's `toModelOutput`, or the output as text or JSON.
+ */
+export async function toolCallModelOutput(
+ definition: Pick<HarnessToolDefinition, "name" | "toModelOutput">,
+ output: unknown,
+ toolCallId: string | undefined,
+): Promise<ToolModelOutputValue> {
+ if (isAuthorizationPendingModelOutput(output)) {
+ return { type: "text", value: authorizationPendingModelText(output.connections) };
+ }
+ if (definition.toModelOutput !== undefined) {
+ return normalizeToolModelOutput({
+ output: await definition.toModelOutput(output),
+ toolCallId,
+ toolName: definition.name,
+ });
+ }
+ if (typeof output === "string") return { type: "text", value: output };
+ return normalizeToolModelOutput({
+ output: { type: "json", value: output ?? null },
+ toolCallId,
+ toolName: definition.name,
+ });
+}
diff --git a/packages/eve/src/harness/tool-model-output.ts b/packages/eve/src/harness/tool-model-output.ts
index c7bd3dc2f..1a073d744 100644
--- a/packages/eve/src/harness/tool-model-output.ts
+++ b/packages/eve/src/harness/tool-model-output.ts
@@ -12,7 +12,7 @@ import { withToolOutputSerializationError } from "#harness/tool-output-serializa
* `json` values are proven JSON-serializable and `content` arrays are
* mutable so the value is assignable to the SDK's `ToolResultOutput`.
*/
-type ToolModelOutputValue =
+export type ToolModelOutputValue =
| { readonly type: "json"; readonly value: JSONValue }
| { readonly type: "text"; readonly value: string }
| { readonly type: "content"; readonly value: ToolModelOutputPart[] };
diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.ts
index dab009d26..9d5a01471 100644
--- a/packages/eve/src/harness/tools.ts
+++ b/packages/eve/src/harness/tools.ts
@@ -8,16 +8,12 @@ import { resolveWebSearchBackend, resolveWebSearchProviderTool } from "#harness/
import type { HarnessToolMap } from "#harness/types.js";
import { buildCallbackContext } from "#context/build-callback-context.js";
import { loadContext } from "#context/container.js";
-import {
- authorizationPendingModelText,
- isAuthorizationPendingModelOutput,
- isAuthorizationSignal,
- modelFacingAuthorizationOutput,
-} from "#harness/authorization.js";
+import { isAuthorizationSignal, modelFacingAuthorizationOutput } from "#harness/authorization.js";
import { stashToolInterrupt } from "#harness/tool-interrupts.js";
import { isApprovedToolCall, markApprovalRecheck } from "#harness/approval-recheck.js";
import { toModelSchema } from "#tools/schema.js";
-import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";
+import { normalizeToolJsonOutput } from "#harness/tool-model-output.js";
+import { toolCallModelOutput } from "#harness/tool-call-io.js";
import type { ToolExecuteOptions } from "#tools/definition.js";
import { isAsyncIterable } from "#shared/async-iterable.js";
@@ -64,54 +60,17 @@ export function buildToolSet(input: {
inputSchema: toModelSchema(definition.inputSchema, "input"),
strict: false,
outputSchema: toModelSchema(definition.outputSchema, "output"),
- ...(definition.execute !== undefined
+ ...(definition.execute !== undefined || authorToModelOutput !== undefined
? {
- toModelOutput: async ({
+ toModelOutput: ({
output,
toolCallId,
}: {
readonly output: unknown;
readonly toolCallId?: string;
- }) => {
- if (isAuthorizationPendingModelOutput(output)) {
- return {
- type: "text" as const,
- value: authorizationPendingModelText(output.connections),
- };
- }
- if (authorToModelOutput !== undefined) {
- return normalizeToolModelOutput({
- output: await authorToModelOutput(output),
- toolCallId,
- toolName: definition.name,
- });
- }
- if (typeof output === "string") {
- return { type: "text" as const, value: output };
- }
- return normalizeToolModelOutput({
- output: { type: "json" as const, value: output ?? null },
- toolCallId,
- toolName: definition.name,
- });
- },
+ }) => toolCallModelOutput(definition, output, toolCallId),
}
- : authorToModelOutput !== undefined
- ? {
- toModelOutput: async ({
- output,
- toolCallId,
- }: {
- readonly output: unknown;
- readonly toolCallId?: string;
- }) =>
- normalizeToolModelOutput({
- output: await authorToModelOutput(output),
- toolCallId,
- toolName: definition.name,
- }),
- }
- : {}),
+ : {}),
});
tools[definition.name] = aiTool;
if (definition.approval !== undefined) {
diff --git a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
index d7d44c44a..c49a16760 100644
--- a/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
+++ b/packages/eve/src/internal/nitro/routes/channel-dispatch.ts
@@ -28,6 +28,7 @@ import {
} from "#internal/nitro/routes/runtime-artifacts.js";
import { traceChannelRequest } from "#internal/nitro/routes/channel-request-instrumentation.js";
import { resolveNitroChannelRuntimeBundle } from "#internal/nitro/routes/runtime-stack.js";
+import { createRouteInvokeTool } from "#internal/nitro/routes/route-invoke-tool.js";
import { readVercelProjectLink } from "#internal/vercel/project-link.js";
import { withVercelOidcProjectResolver } from "#channel/auth/vercel-oidc-project.js";
import { withLocalDevRequestScope } from "#runtime/local-dev-capability.js";
@@ -277,6 +278,12 @@ async function buildRouteArgs(
attachSession,
...channelOperations,
...createAgentDescriptionRouteArgs(() => resolveNitroCompiledArtifactsSource(config)),
+ invokeTool: createRouteInvokeTool({
+ agentName: bundle.agentName,
+ config,
+ origin: { adapter, agentName: bundle.agentName, channelName },
+ requestUrl: event.req.url,
+ }),
params,
requestIp,
to,
diff --git a/packages/eve/src/internal/nitro/routes/route-invoke-tool.ts b/packages/eve/src/internal/nitro/routes/route-invoke-tool.ts
new file mode 100644
index 000000000..6c7f426d8
--- /dev/null
+++ b/packages/eve/src/internal/nitro/routes/route-invoke-tool.ts
@@ -0,0 +1,68 @@
+import type { InvokeToolFn } from "#channel/invoke-tool.js";
+import { invokeTool, type InvokeToolRuntime } from "#execution/invoke-tool.js";
+import { createNodeHarnessTools } from "#execution/node-step.js";
+import { resolveWorkflowCallbackBaseUrl } from "#execution/workflow-callback-url.js";
+import {
+ type NitroArtifactsConfig,
+ resolveNitroCompiledArtifactsSource,
+} from "#internal/nitro/routes/runtime-artifacts.js";
+import type { RuntimeCompiledArtifactsSource } from "#runtime/compiled-artifacts-source.js";
+import { loadCompiledManifest } from "#runtime/loaders/manifest.js";
+import { getCompiledRuntimeAgentBundle } from "#runtime/sessions/compiled-agent-cache.js";
+import type { InvokeToolTraceOrigin } from "#tracing/invoke-tool-span.js";
+
+/**
+ * Builds the route's `invokeTool`. The agent's static tools and sandbox load on
+ * the first call, so routes that never invoke a tool pay nothing.
+ */
+export function createRouteInvokeTool(input: {
+ /** The agent's name, on every call's span and in its trace policy input. */
+ readonly agentName: string;
+ readonly config: NitroArtifactsConfig;
+ /** The channel this route belongs to; trace policy classifies calls by it. */
+ readonly origin?: InvokeToolTraceOrigin;
+ readonly requestUrl: string;
+}): InvokeToolFn {
+ let runtime: Promise<LoadedInvokeToolRuntime> | undefined;
+ return async (name, toolInput, options) => {
+ runtime ??= loadInvokeToolRuntime({
+ callbackBaseUrl: resolveWorkflowCallbackBaseUrl(new URL(input.requestUrl).origin),
+ compiledArtifactsSource: resolveNitroCompiledArtifactsSource(input.config),
+ }).catch((error: unknown) => {
+ runtime = undefined;
+ throw error;
+ });
+ const loaded = await runtime;
+ return await invokeTool(
+ { ...loaded, agentName: input.agentName, origin: input.origin },
+ name,
+ toolInput,
+ options,
+ );
+ };
+}
+
+/** The part of `InvokeToolRuntime` that comes from the compiled agent. */
+export type LoadedInvokeToolRuntime = Omit<InvokeToolRuntime, "agentName" | "origin">;
+
+/** Loads the root agent's static tools and sandbox. Dynamic resolvers are not run. */
+export async function loadInvokeToolRuntime(input: {
+ readonly callbackBaseUrl: string;
+ readonly compiledArtifactsSource: RuntimeCompiledArtifactsSource;
+}): Promise<LoadedInvokeToolRuntime> {
+ const { compiledArtifactsSource } = input;
+ const [bundle, manifest] = await Promise.all([
+ getCompiledRuntimeAgentBundle({ compiledArtifactsSource }),
+ loadCompiledManifest({ compiledArtifactsSource }),
+ ]);
+ const node = bundle.graph.root;
+ return {
+ bundle,
+ callbackBaseUrl: input.callbackBaseUrl,
+ compiledArtifactsSource,
+ manifest,
+ nodeId: node.nodeId,
+ sandboxRegistry: node.sandboxRegistry,
+ tools: createNodeHarnessTools({ node }),
+ };
+}
diff --git a/packages/eve/src/internal/testing/channel-conformance/harness.ts b/packages/eve/src/internal/testing/channel-conformance/harness.ts
index e8ee2be55..6bb9b5914 100644
--- a/packages/eve/src/internal/testing/channel-conformance/harness.ts
+++ b/packages/eve/src/internal/testing/channel-conformance/harness.ts
@@ -649,6 +649,7 @@ async function converse(
},
attachSession,
describe: unsupported("describe"),
+ invokeTool: unsupported("invokeTool"),
params,
requestIp: null,
to: unsupported("to"),
diff --git a/packages/eve/src/internal/testing/mocks/mock-route-args.ts b/packages/eve/src/internal/testing/mocks/mock-route-args.ts
index 3498acddd..6992edb1b 100644
--- a/packages/eve/src/internal/testing/mocks/mock-route-args.ts
+++ b/packages/eve/src/internal/testing/mocks/mock-route-args.ts
@@ -1,10 +1,13 @@
import type { RouteHandlerArgs } from "#channel/routes.js";
/** The agent route args, for tests whose routes never call them. */
-export function mockAgentRouteArgs(): Pick<RouteHandlerArgs, "describe"> {
+export function mockAgentRouteArgs(): Pick<RouteHandlerArgs, "describe" | "invokeTool"> {
return {
describe: async () => {
throw new Error("describe() is unavailable in this test.");
},
+ invokeTool: async () => {
+ throw new Error("invokeTool() is unavailable in this test.");
+ },
};
}
diff --git a/packages/eve/src/public/channels/index.ts b/packages/eve/src/public/channels/index.ts
index 5bedf3a48..b41a79a85 100644
--- a/packages/eve/src/public/channels/index.ts
+++ b/packages/eve/src/public/channels/index.ts
@@ -44,6 +44,9 @@ export {
type RouteHandlerArgs,
type AgentDescription,
type AgentToolDescription,
+ type InvokeToolFn,
+ type InvokeToolOptions,
+ type InvokeToolResult,
type HttpRouteDefinition,
type WebSocketMessage,
type WebSocketPeer,
diff --git a/packages/eve/src/public/definitions/channel.ts b/packages/eve/src/public/definitions/channel.ts
index e3ba5e31d..05e81f58f 100644
--- a/packages/eve/src/public/definitions/channel.ts
+++ b/packages/eve/src/public/definitions/channel.ts
@@ -58,6 +58,7 @@ export type {
};
export type { ChannelCors, ChannelCorsOptions } from "#channel/cors.js";
export type { AgentDescription, AgentToolDescription } from "#channel/agent-description.js";
+export type { InvokeToolFn, InvokeToolOptions, InvokeToolResult } from "#channel/invoke-tool.js";
export { DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, WS } from "#channel/routes.js";
export type {
AttachSessionFn,
diff --git a/packages/eve/src/tracing/agent-span-contract.ts b/packages/eve/src/tracing/agent-span-contract.ts
index ab7defec1..d517fae49 100644
--- a/packages/eve/src/tracing/agent-span-contract.ts
+++ b/packages/eve/src/tracing/agent-span-contract.ts
@@ -33,6 +33,18 @@ interface AgentSpanRecord {
readonly attributes: Readonly<Record<string, unknown>>;
}
+/** Marks the `execute_tool` span of a tool call made outside any conversation. */
+export const DIRECT_TOOL_CALL_ATTRIBUTE = "eve.tool.invocation";
+export const DIRECT_TOOL_CALL_VALUE = "direct";
+
+/**
+ * A direct tool call has no turn, so its own span is what starts and ends
+ * its claim on the trace, the way an activation span does for a turn.
+ */
+export function isDirectToolCallSpan(span: Pick<AgentSpanRecord, "attributes">): boolean {
+ return span.attributes[DIRECT_TOOL_CALL_ATTRIBUTE] === DIRECT_TOOL_CALL_VALUE;
+}
+
export function isAgentActivationSpan(span: AgentSpanRecord): boolean {
return (
span.name === "agent.turn" ||
diff --git a/packages/eve/src/tracing/agent-trace-span-processor.ts b/packages/eve/src/tracing/agent-trace-span-processor.ts
index acd50272c..4642f93c7 100644
--- a/packages/eve/src/tracing/agent-trace-span-processor.ts
+++ b/packages/eve/src/tracing/agent-trace-span-processor.ts
@@ -1,5 +1,5 @@
import type { SpanProcessor } from "#compiled/@vercel/otel/index.js";
-import { isAgentActivationSpan } from "#tracing/agent-span-contract.js";
+import { isAgentActivationSpan, isDirectToolCallSpan } from "#tracing/agent-span-contract.js";
const REMEMBERED_TRACE_LIMIT = 2048;
@@ -7,7 +7,7 @@ interface SpanLike {
readonly name?: string;
readonly attributes: Readonly<Record<string, unknown>>;
readonly instrumentationScope?: { readonly name?: string };
- readonly spanContext: () => { readonly traceId: string };
+ readonly spanContext: () => { readonly spanId?: string; readonly traceId: string };
}
/** Routes spans from agent-owned traces to provider-neutral child processors. */
@@ -16,6 +16,11 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
readonly #ownedTraceIds = new Set<string>();
readonly #completedTraceIds = new Set<string>();
readonly #rememberedTraceIds = new Set<string>();
+ /**
+ * Open direct tool calls per trace they claimed. Several calls can share
+ * one caller trace, so the trace completes when the last one ends.
+ */
+ readonly #directCalls = new Map<string, Set<string>>();
readonly #traceOwnership = new Map<
string,
{ readonly conversationId: string; readonly ownerRunId?: string }
@@ -30,6 +35,7 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
onStart(span: unknown, parentContext: unknown): void {
if (!isSpanLike(span)) return;
+ if (isDirectToolCallSpan(span)) this.#startDirectCall(span);
const conversationId = span.attributes["gen_ai.conversation.id"];
const runId = span.attributes["agent.run.id"];
if (typeof conversationId === "string") {
@@ -64,6 +70,7 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
) {
this.#completedTraceIds.add(traceId);
}
+ if (isDirectToolCallSpan(span)) this.#endDirectCall(span);
}
/** Trace IDs protected by an unfinished activation or pending final writes. */
@@ -96,6 +103,7 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
this.#ownedTraceIds.delete(traceId);
this.#completedTraceIds.delete(traceId);
this.#traceOwnership.delete(traceId);
+ this.#directCalls.delete(traceId);
}
return released;
}
@@ -104,6 +112,44 @@ export class AgentTraceSpanProcessor implements SpanProcessor {
await Promise.all(this.#children.map((child) => child.shutdown()));
}
+ /**
+ * Claims the trace for a direct call. A trace a conversation already owns
+ * stays the conversation's to release; otherwise the call owns it, even
+ * when an earlier call on the same caller trace already released it.
+ */
+ #startDirectCall(span: SpanLike): void {
+ const { spanId, traceId } = span.spanContext();
+ if (spanId === undefined) return;
+ const open = this.#directCalls.get(traceId);
+ if (open !== undefined) {
+ open.add(spanId);
+ this.#completedTraceIds.delete(traceId);
+ return;
+ }
+ if (this.#ownedTraceIds.has(traceId) && !this.#completedTraceIds.has(traceId)) return;
+ const conversationId = span.attributes["gen_ai.conversation.id"];
+ const runId = span.attributes["agent.run.id"];
+ if (typeof conversationId !== "string") return;
+ this.#completedTraceIds.delete(traceId);
+ this.#rememberedTraceIds.delete(traceId);
+ this.#ownedTraceIds.add(traceId);
+ this.#traceOwnership.set(traceId, {
+ conversationId,
+ ownerRunId: typeof runId === "string" ? runId : undefined,
+ });
+ this.#directCalls.set(traceId, new Set([spanId]));
+ }
+
+ /** The last open direct call on a trace completes it, like an activation. */
+ #endDirectCall(span: SpanLike): void {
+ const { spanId, traceId } = span.spanContext();
+ const open = this.#directCalls.get(traceId);
+ if (spanId === undefined || open === undefined || !open.delete(spanId)) return;
+ if (open.size > 0) return;
+ this.#directCalls.delete(traceId);
+ this.#completedTraceIds.add(traceId);
+ }
+
#accepts(span: SpanLike): boolean {
return (
span.instrumentationScope?.name !== "workflow" &&
diff --git a/packages/eve/src/tracing/invoke-tool-span.ts b/packages/eve/src/tracing/invoke-tool-span.ts
new file mode 100644
index 000000000..ee805e676
--- /dev/null
+++ b/packages/eve/src/tracing/invoke-tool-span.ts
@@ -0,0 +1,314 @@
+import {
+ context as otelContext,
+ SpanKind,
+ trace,
+ type Attributes,
+ type Context,
+ type Span,
+} from "#compiled/@opentelemetry/api/index.js";
+
+import type { InvokeToolResult } from "#channel/invoke-tool.js";
+import type { SessionAuthContext } from "#channel/types.js";
+import type { ChannelAdapter } from "#channel/adapter.js";
+import { buildConversationContext } from "#channel/conversation-context.js";
+import {
+ toolCallIdempotencyKey,
+ type InstrumentationAttemptScope,
+ type InstrumentationHooks,
+} from "#instrumentation/lifecycle.js";
+import { getInstrumentationRuntime } from "#instrumentation/runtime-global.js";
+import { resolveInstrumentationEnvironment } from "#internal/application/dev-environment.js";
+import { createLogger, formatError } from "#internal/logging.js";
+import { applyLiveDeliveryAudienceCeiling } from "#shared/forwarded-trace-policy.js";
+import { resolveTracePolicy } from "#shared/trace-policy.js";
+import { agentTraceIdentityAttributes } from "#tracing/agent-otel-attributes.js";
+import { contentAttribute } from "#tracing/agent-otel-content.js";
+import { recordAgentSpanError } from "#tracing/agent-span-error.js";
+import {
+ DIRECT_TOOL_CALL_ATTRIBUTE,
+ DIRECT_TOOL_CALL_VALUE,
+} from "#tracing/agent-span-contract.js";
+import { agentSpanNamingAttributes } from "#tracing/agent-span-naming.js";
+import { markAgentTraceContext } from "#tracing/agent-trace-context.js";
+import { withAgentToolSpanContext } from "#tracing/agent-tool-span-context.js";
+import { withChannelAudience } from "#tracing/channel-audience-context.js";
+import { withErrorContent } from "#tracing/error-content-context.js";
+import { suppressTracing } from "#tracing/suppress-tracing.js";
+
+const log = createLogger("invoke-tool");
+
+/** Where a direct tool call came from, so trace policy can classify it like a conversation. */
+export interface InvokeToolTraceOrigin {
+ readonly adapter: ChannelAdapter<any>;
+ readonly agentName: string;
+ readonly channelName: string;
+}
+
+/**
+ * Runs one direct tool call the way a conversation runs a model-issued one,
+ * minus the turn around it.
+ *
+ * Instrumentation providers get the same `tool.call.started` and
+ * `tool.call.completed` events, and the `execute_tool` span carries the same
+ * attributes. Content follows the same decision: the OpenTelemetry
+ * declaration's content setting, the trace policy, and the channel audience
+ * ceiling. Arguments, the result, and error text are recorded only when that
+ * decision allows them; otherwise a failure is a generic error. Error content
+ * is switched off until the span exists, so a trace policy that throws, or a
+ * call whose span is dropped, never writes error text to a parent span. A
+ * throwing policy is logged as a warning, which never touches a span.
+ *
+ * The span is marked as a direct call so trace processors treat it as the
+ * call's activation: it claims the trace when it starts and completes it
+ * when it ends. The call flushes the runtime afterwards so that completion
+ * is released even on a deployment that only serves direct calls.
+ */
+export async function withInvokeToolSpan(
+ input: {
+ /** The agent's name, on the span whether or not the call has a channel origin. */
+ readonly agentName: string;
+ readonly auth: SessionAuthContext;
+ readonly callId: string;
+ readonly origin: InvokeToolTraceOrigin | undefined;
+ readonly sessionId: string;
+ readonly toolName: string;
+ },
+ run: (observer: InvokeToolObserver) => Promise<InvokeToolResult>,
+): Promise<InvokeToolResult> {
+ const base = withErrorContent(otelContext.active(), false);
+ return await otelContext.with(base, () => traced(input, base, run));
+}
+
+/**
+ * What the call reports while it runs, so providers and the span see the
+ * same steps a model-issued call goes through.
+ */
+export interface InvokeToolObserver {
+ /** The tool's `execute` is about to run with its checked input, the input the span records. */
+ executing(input: unknown): Promise<void>;
+ /**
+ * `execute` settled with this output, or threw this error, after running
+ * for `durationMs`: measured from just before `execute` to its settlement,
+ * so provider handlers are not counted, as in the AI SDK.
+ */
+ executed(
+ outcome: (
+ | { readonly type: "result"; readonly output: unknown }
+ | { readonly type: "error"; readonly error: unknown }
+ ) & { readonly durationMs: number },
+ ): Promise<void>;
+ /** The error behind a `failed` result, recorded on the span when outputs are. */
+ failedWith(error: unknown): void;
+}
+
+async function traced(
+ input: Parameters<typeof withInvokeToolSpan>[0],
+ base: Context,
+ run: (observer: InvokeToolObserver) => Promise<InvokeToolResult>,
+): Promise<InvokeToolResult> {
+ const runtime = getInstrumentationRuntime();
+ if (runtime === undefined) return await run(silentObserver);
+
+ const conversation = buildConversationContext(
+ {
+ adapter: input.origin?.adapter ?? { kind: "channel" },
+ auth: input.auth,
+ channelName: input.origin?.channelName,
+ },
+ resolveInstrumentationEnvironment(),
+ );
+ const hooks =
+ runtime.hooks.forTrace?.({ agentName: input.agentName, ...conversation }) ?? runtime.hooks;
+ const scope: InstrumentationAttemptScope = {
+ attemptId: input.callId,
+ attemptIndex: 0,
+ channelAudience: conversation.audience,
+ functionId: input.agentName,
+ rootSessionId: input.sessionId,
+ sessionId: input.sessionId,
+ stepIndex: 0,
+ traceSessionId: input.sessionId,
+ // No turn exists; the call stands in for one, as its session context does.
+ turnId: input.callId,
+ };
+ const events = toolCallEvents(hooks, scope, input);
+
+ const settings = runtime.otelSettings;
+ // No declared OpenTelemetry: eve emits no agent spans anywhere, so none here either.
+ if (settings === undefined) return await run(events.observer(undefined));
+
+ const decision = resolveTracePolicy(
+ settings.tracePolicy,
+ { agentName: input.agentName, ...conversation },
+ (error) =>
+ log.warn("tracePolicy threw; dropping the tool call's trace", {
+ error: formatError(error),
+ }),
+ );
+ if (decision.action === "drop") {
+ return await otelContext.with(suppressTracing(base), () => run(events.observer(undefined)));
+ }
+ const content = applyLiveDeliveryAudienceCeiling(
+ {
+ action: "record",
+ recordInputs: settings.recordInputs && decision.recordInputs,
+ recordOutputs: settings.recordOutputs && decision.recordOutputs,
+ },
+ conversation.audience,
+ undefined,
+ conversation.environment,
+ );
+ const recordInputs = content.action === "record" && content.recordInputs;
+ const recordOutputs = content.action === "record" && content.recordOutputs;
+
+ const spanName = `execute_tool ${input.toolName}`;
+ const parent = withChannelAudience(base, conversation.audience);
+ const attributes: Attributes = {
+ "gen_ai.agent.name": input.agentName,
+ "gen_ai.operation.name": "execute_tool",
+ "gen_ai.tool.call.id": input.callId,
+ "gen_ai.tool.name": input.toolName,
+ "gen_ai.tool.type": "function",
+ [DIRECT_TOOL_CALL_ATTRIBUTE]: DIRECT_TOOL_CALL_VALUE,
+ ...agentSpanNamingAttributes(spanName, "execute_tool"),
+ ...agentTraceIdentityAttributes({
+ rootSessionId: input.sessionId,
+ sessionId: input.sessionId,
+ traceSessionId: input.sessionId,
+ }),
+ };
+ if (input.origin !== undefined) {
+ attributes["eve.channel.kind"] = conversation.channel.kind;
+ attributes["eve.channel.name"] = input.origin.channelName;
+ }
+ const span = trace
+ .getTracer("eve.agent")
+ .startSpan(spanName, { attributes, kind: SpanKind.INTERNAL }, parent);
+ // As on a conversation's tool span: error text inside the call follows the output decision.
+ const active = markAgentTraceContext(
+ withAgentToolSpanContext(withErrorContent(trace.setSpan(parent, span), recordOutputs), {
+ recordInputs,
+ recordOutputs,
+ recordError: (error, errorType) =>
+ recordAgentSpanError(span, recordOutputs ? error : undefined, errorType),
+ setAttributes: (attributes) => setDefined(span, attributes),
+ }),
+ );
+
+ let failure: { readonly error: unknown } | undefined;
+ const observer = events.observer({
+ failedWith: (error) => {
+ failure = { error };
+ },
+ recordInputs,
+ span,
+ });
+ try {
+ const result = await otelContext.with(active, () => run(observer));
+ span.setAttribute("eve.tool.outcome", result.status);
+ if (result.status === "completed" && recordOutputs) {
+ const output = contentAttribute(result.output);
+ if (output !== undefined) span.setAttribute("gen_ai.tool.call.result", output);
+ }
+ if (result.status === "invalid-input") {
+ // A model-issued call with invalid input never runs, so it has no span to compare to.
+ recordAgentSpanError(span, undefined, result.status);
+ } else if (result.status === "failed") {
+ // The conversation's rule: the error itself when outputs are recorded, else a generic one.
+ recordAgentSpanError(
+ span,
+ recordOutputs ? failure?.error : undefined,
+ failure === undefined ? result.status : undefined,
+ );
+ }
+ return result;
+ } catch (error) {
+ recordAgentSpanError(span, recordOutputs ? error : undefined);
+ throw error;
+ } finally {
+ span.end();
+ await runtime.forceFlush().catch((error: unknown) => {
+ log.warn("flushing a tool call's trace failed", { error: formatError(error) });
+ });
+ }
+}
+
+const silentObserver: InvokeToolObserver = {
+ executed: async () => {},
+ executing: async () => {},
+ failedWith: () => {},
+};
+
+/**
+ * The `tool.call.*` events a model-issued call publishes, in the same shapes
+ * (`instrumentation/ai-sdk-hook-bridge.ts`): started before `execute`, and
+ * completed with its result or error after. Content is projected the same way.
+ */
+function toolCallEvents(
+ hooks: InstrumentationHooks,
+ scope: InstrumentationAttemptScope,
+ input: { readonly callId: string; readonly toolName: string },
+) {
+ const capturesInputs = hooks.capturesInputs ?? hooks.capturesContent;
+ const capturesOutputs = hooks.capturesOutputs ?? hooks.capturesContent;
+ const idempotencyKey = toolCallIdempotencyKey(scope, input.callId, 0);
+ return {
+ observer(
+ spanState:
+ | {
+ readonly failedWith: (error: unknown) => void;
+ readonly recordInputs: boolean;
+ readonly span: Span;
+ }
+ | undefined,
+ ): InvokeToolObserver {
+ return {
+ async executing(toolInput) {
+ // The checked input, as a conversation's span records it; rejected input never gets here.
+ if (spanState?.recordInputs) {
+ const args = contentAttribute(toolInput);
+ if (args !== undefined) spanState.span.setAttribute("gen_ai.tool.call.arguments", args);
+ }
+ await hooks.publish(
+ Object.freeze({
+ callId: input.callId,
+ idempotencyKey,
+ input: capturesInputs ? toolInput : undefined,
+ scope,
+ toolName: input.toolName,
+ type: "tool.call.started",
+ }),
+ );
+ },
+ async executed(outcome) {
+ spanState?.span.setAttribute("gen_ai.execute_tool.duration", outcome.durationMs / 1000);
+ const output =
+ outcome.type === "result"
+ ? capturesOutputs
+ ? { output: outcome.output, type: "result" as const }
+ : { type: "result" as const }
+ : capturesOutputs
+ ? { error: outcome.error, type: "error" as const }
+ : { type: "error" as const };
+ await hooks.publish(
+ Object.freeze({
+ idempotencyKey,
+ output: Object.freeze(output),
+ scope,
+ type: "tool.call.completed",
+ }),
+ );
+ },
+ failedWith(error) {
+ spanState?.failedWith(error);
+ },
+ };
+ },
+ };
+}
+
+function setDefined(span: Span, attributes: Attributes): void {
+ for (const [name, value] of Object.entries(attributes)) {
+ if (value !== undefined) span.setAttribute(name, value);
+ }
+}