The Open Framework for Building Agents
fix(eve): zod boundary - JSON Schema tools and one private vendored copy (#3696)
Andrew Barba92505dd79492
diff --git a/.changeset/json-schema-tool-boundary.md b/.changeset/json-schema-tool-boundary.mdnew file mode 100644index 000000000..55a835bf2--- /dev/null+++ b/.changeset/json-schema-tool-boundary.md@@ -0,0 +1,7 @@+---+"eve": patch+---++Fix `Cannot read properties of undefined (reading 'push')` failures in turns with MCP tools such as Notion, and with the file-memory tools, when an app installs a different Zod version than eve bundles. Tool schemas now reach the AI SDK only as JSON Schema, MCP and other JSON Schema tools are advertised exactly as published and validated with a standard JSON Schema validator, and the `*_INPUT_SCHEMA` and `*_OUTPUT_SCHEMA` constants from `eve/tools/*` are JSON Schema-backed Standard Schemas instead of Zod objects.++eve now ships a single private copy of Zod instead of bundling several. `eve/client` no longer exports `AgentInfoResultSchema`, `HealthResultSchema`, `inputOptionSchema`, `inputRequestKindSchema`, `inputRequestSchema`, or `inputResponseSchema`, and `eve/self-modification` no longer exports `selfModificationConfigSchema`; use the exported types together with `isInputRequest`, `isInputResponse`, and `parseInputResponse`.diff --git a/docs/connections/overview.mdx b/docs/connections/overview.mdxindex 9dad0e774..6f22a42d4 100644--- a/docs/connections/overview.mdx+++ b/docs/connections/overview.mdx@@ -10,7 +10,7 @@ Connections live under `agent/connections/`. A static connection's runtime name## MCP connections-Use an MCP connection when the external service already exposes an MCP server. The server publishes its tools and schemas, and eve makes the matched tools callable by the model.+Use an MCP connection when the external service already exposes an MCP server. The server publishes its tools and schemas, and eve makes the matched tools callable by the model. Each tool's JSON Schema reaches the model as published, minus any arguments you supply with `toolCall.providedArguments`, and eve checks the model's arguments against it before it calls the server.Read [MCP connections](/docs/connections/mcp) for `defineMcpClientConnection`, transport requirements, and MCP tool filters.diff --git a/docs/tools/overview.mdx b/docs/tools/overview.mdxindex 982777147..e1770750a 100644--- a/docs/tools/overview.mdx+++ b/docs/tools/overview.mdx@@ -32,6 +32,13 @@ A tool definition needs:When a tool returns structured data, add an optional `outputSchema`. With Zod or Standard Schema it also types the `execute` return.+eve validates the model's input against `inputSchema` before `execute` runs:++- A Zod or Standard Schema validates with its own library, so tools work with whichever Zod version your app installs.+- A plain JSON Schema object reaches the model as written, without its `$schema` keyword. eve validates input against it with JSON Schema 2020-12 rules, which also cover draft-07 keywords, then fills omitted properties from their `default` values.+- eve treats `format` as an annotation and does not reject input for it.+- When eve cannot evaluate a JSON Schema locally, for example because of an unknown `type` name or a `$ref` it cannot resolve, the model still receives the schema and eve passes the input to `execute` unvalidated.+### Hide a tool from delegated agentsSet `availableInSubagents: false` when a tool should be callable only in a top-level root session:diff --git a/packages/eve/package.json b/packages/eve/package.jsonindex e927f1103..30436492e 100644--- a/packages/eve/package.json+++ b/packages/eve/package.json@@ -515,6 +515,7 @@"@ai-sdk/otel": "catalog:","@ai-sdk/provider": "catalog:","@ai-sdk/provider-utils": "catalog:",+ "@cfworker/json-schema": "4.1.1","@chat-adapter/slack": "4.41.0","@chat-adapter/state-memory": "4.41.0","@chat-adapter/twilio": "4.41.0",diff --git a/packages/eve/scripts/build-rolldown.mjs b/packages/eve/scripts/build-rolldown.mjsindex c9fd2d674..0bf4d5b75 100644--- a/packages/eve/scripts/build-rolldown.mjs+++ b/packages/eve/scripts/build-rolldown.mjs@@ -18,6 +18,7 @@ import { isBuiltin } from "node:module";import { join, parse, relative } from "node:path";import { buildWithNitroRolldown } from "./nitro-rolldown.mjs";+import vendoredZod from "./vendor-compiled/zod.mjs";import { createVendoredDependencyWarningFilter } from "./vendor-warning-log.mjs";/**@@ -207,6 +208,35 @@ function isExternalPackageSpecifier(source) {return false;}+const VENDORED_ZOD_IMPORTS = new Map(+ Object.entries(vendoredZod.sharedSpecifiers).map(([specifier, outputPath]) => [+ specifier,+ `#compiled/zod/${outputPath}.js`,+ ]),+);++/**+ * eve ships one Zod. Every Zod import that reaches the build, from eve's+ * sources or a bundled dependency, resolves to the vendored copy instead of+ * copying Zod's sources into `dist/src/node_modules`.+ */+function createVendoredZodPlugin() {+ return {+ name: "eve:vendored-zod",+ resolveId(source, importer) {+ if (source !== "zod" && !source.startsWith("zod/")) return null;+ const id = VENDORED_ZOD_IMPORTS.get(source);+ if (id === undefined) {+ throw new Error(+ `${importer ?? "eve"} imports "${source}", which eve's vendored Zod does not export. ` ++ `Add it to sharedSpecifiers in scripts/vendor-compiled/zod.mjs.`,+ );+ }+ return { id, external: true };+ },+ };+}+async function collectSourceFiles(directory, relativeRoot = "") {const entries = await readdir(directory, { withFileTypes: true });const sourceFiles = [];@@ -263,6 +293,7 @@ await buildWithNitroRolldown({external: isExternalPackageSpecifier,platform: "node",plugins: [+ createVendoredZodPlugin(),createStripUnusedRolldownRuntimeImportPlugin(),createDynamicToolTransformPlugin(),createWorkflowMetadataTransformPlugin(),diff --git a/packages/eve/scripts/vendor-compiled/@cfworker/json-schema.mjs b/packages/eve/scripts/vendor-compiled/@cfworker/json-schema.mjsnew file mode 100644index 000000000..5473dc0f8--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/@cfworker/json-schema.mjs@@ -0,0 +1,14 @@+import { loadDeclaration } from "../_shared.mjs";++/**+ * JSON Schema validator for tool schemas that arrive as plain JSON Schema+ * (MCP, OpenAPI, serialized output schemas, and eve's own framework tools).+ * It interprets schemas without code generation, so it runs anywhere eve does.+ */+export default {+ packageName: "@cfworker/json-schema",+ compiledPath: "@cfworker/json-schema",+ bundling: "standalone",+ platform: "neutral",+ declaration: await loadDeclaration("@cfworker/json-schema.d.ts"),+};diff --git a/packages/eve/scripts/vendor-compiled/@vercel/sdk.mjs b/packages/eve/scripts/vendor-compiled/@vercel/sdk.mjsnew file mode 100644index 000000000..cb5fd5b63--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/@vercel/sdk.mjs@@ -0,0 +1,25 @@+import { fileURLToPath } from "node:url";++import { loadDeclaration } from "../_shared.mjs";++/**+ * Vendor config for the slice of `@vercel/sdk` the dev TUI uses: the+ * trusted-sources model helpers re-exported by `entries/@vercel/sdk.mjs`.+ * The SDK's models import `zod/v3`, which resolves to eve's vendored Zod.+ */+const wrapperEntry = fileURLToPath(+ new URL("./entries/@vercel/sdk.mjs", new URL("../", import.meta.url)),+);++export default {+ packageName: "@vercel/sdk",+ compiledPath: "@vercel/sdk",+ bundling: "standalone",+ entries: [+ {+ input: wrapperEntry,+ outputPath: "index",+ declaration: await loadDeclaration("@vercel/sdk.d.ts"),+ },+ ],+};diff --git a/packages/eve/scripts/vendor-compiled/_shared.mjs b/packages/eve/scripts/vendor-compiled/_shared.mjsindex 57c8ecb9f..aa289c7bc 100644--- a/packages/eve/scripts/vendor-compiled/_shared.mjs+++ b/packages/eve/scripts/vendor-compiled/_shared.mjs@@ -34,14 +34,17 @@* banner?: string, // standalone bundle prelude* chunkGroup?: string, // default "node"* typeOnly?: boolean, // skips JS bundling entirely+ * sharedSpecifiers?: Record<string, string>, // specifier → entry outputPath other bundles import instead of bundling their own copy+ * privateCopies?: string[], // shared packages this bundle may still bundle privately (a different major)* fingerprintFiles?: string[], // package-relative files included in the stamp* }* ```*/import { createHash } from "node:crypto";+import { realpathSync } from "node:fs";import { copyFile, mkdir, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";import { createRequire } from "node:module";-import { dirname, join, parse, posix, relative } from "node:path";+import { dirname, isAbsolute, join, parse, posix, relative } from "node:path";import { fileURLToPath } from "node:url";import { buildWithNitroRolldown } from "../nitro-rolldown.mjs";@@ -663,7 +666,13 @@ function getDefaultResolve() {return { mainFields: ["module", "main"] };}-async function bundleStandaloneModule({ destinationRoot, module, packageInfo, packageRoot }) {+async function bundleStandaloneModule({+ destinationRoot,+ module,+ packageInfo,+ packageRoot,+ sharedSpecifiers,+}) {const warningFilter = createVendoredDependencyWarningFilter();const entries = getModuleEntries(module, packageInfo);const platform = getModulePlatform(module);@@ -680,7 +689,7 @@ async function bundleStandaloneModule({ destinationRoot, module, packageInfo, paexternal: module.external ?? [],moduleTypes: module.loader ?? {},platform,- plugins: module.plugins ?? [],+ plugins: [...(module.plugins ?? []), createSharedSpecifierPlugin(sharedSpecifiers, [module])],resolve: module.resolve ?? getDefaultResolve(),treeshake: true,output: {@@ -702,6 +711,7 @@ async function bundleModuleGroup({preparedModules,packageRoot,compiledRoot,+ sharedSpecifiers,}) {const warningFilter = createVendoredDependencyWarningFilter();const entrypoints = Object.fromEntries(@@ -724,7 +734,13 @@ async function bundleModuleGroup({{},...preparedModules.map(({ module }) => module.loader ?? {}),);- const plugins = preparedModules.flatMap(({ module }) => module.plugins ?? []);+ const plugins = [+ ...preparedModules.flatMap(({ module }) => module.plugins ?? []),+ createSharedSpecifierPlugin(+ sharedSpecifiers,+ preparedModules.map(({ module }) => module),+ ),+ ];await buildWithNitroRolldown({cwd: packageRoot,@@ -759,6 +775,7 @@ async function bundleModules({ modules, packageRoot, compiledRoot }) {await rm(join(compiledRoot, "_chunks"), { recursive: true, force: true });+ const sharedSpecifiers = collectSharedSpecifiers(preparedModules);const standalone = preparedModules.filter(({ module }) => module.bundling === "standalone");const shared = preparedModules.filter(({ module }) => module.bundling !== "standalone");const groups = Map.groupBy(@@ -766,7 +783,9 @@ async function bundleModules({ modules, packageRoot, compiledRoot }) {({ module }) => `${module.chunkGroup ?? "node"}\0${getModulePlatform(module)}`,);- await Promise.all(standalone.map((entry) => bundleStandaloneModule({ ...entry, packageRoot })));+ await Promise.all(+ standalone.map((entry) => bundleStandaloneModule({ ...entry, packageRoot, sharedSpecifiers })),+ );await Promise.all([...groups].map(([groupKey, groupModules]) => {@@ -777,6 +796,7 @@ async function bundleModules({ modules, packageRoot, compiledRoot }) {preparedModules: groupModules,packageRoot,compiledRoot,+ sharedSpecifiers,});}),);@@ -799,6 +819,105 @@ async function bundleModules({ modules, packageRoot, compiledRoot }) {}}+/**+ * A vendored package that declares `sharedSpecifiers` ships exactly once.+ * Every other vendored bundle imports those specifiers from the owner's+ * `#compiled/*` entries instead of bundling its own copy. eve's imports map+ * resolves them within the same tree (`.generated` under `eve-source`,+ * `dist` otherwise), just like eve's own `#compiled/*` imports.+ *+ * Zod needs this: its schema objects only work with the copy that built+ * them, so eve must not carry several copies that could exchange schemas.+ */+function collectSharedSpecifiers(preparedModules) {+ const shared = new Map();+ for (const { module, packageInfo } of preparedModules) {+ for (const [specifier, outputPath] of Object.entries(module.sharedSpecifiers ?? {})) {+ shared.set(specifier, {+ importSpecifier: `#compiled/${module.compiledPath}/${outputPath}.js`,+ module,+ packageRoot: realpathSync(packageInfo.packageRoot),+ });+ }+ }+ return shared;+}++const SHARED_FACADE_PREFIX = "\0eve-shared-facade:";++function createSharedSpecifierPlugin(sharedSpecifiers, bundledModules) {+ const owners = new Map(+ [...sharedSpecifiers.values()].map((entry) => [entry.module.packageName, entry]),+ );+ const privateCopies = new Set(bundledModules.flatMap((module) => module.privateCopies ?? []));+ return {+ name: "eve:shared-vendored-modules",+ async resolveId(source, importer, options) {+ if (importer?.startsWith(SHARED_FACADE_PREFIX)) return { id: source, external: true };+ const owner = owners.get(packageNameOf(source));+ // Modules bundled together already share one copy through chunking.+ if (+ owner === undefined ||+ bundledModules.includes(owner.module) ||+ privateCopies.has(owner.module.packageName)+ ) {+ return null;+ }++ const resolved = await this.resolve(source, importer, { ...options, skipSelf: true });+ if (resolved === null || resolved.external) return null;+ if (!isInsideDirectory(resolved.id, owner.packageRoot)) {+ throw new Error(+ `Vendor: ${importer ?? "a vendored module"} resolves "${source}" to ${resolved.id}, a ` ++ `different install than the vendored "${owner.module.packageName}" at ` ++ `${owner.packageRoot}. eve ships a single copy of "${owner.module.packageName}"; align ` ++ `the dependency on one version (for example with a pnpm override). Only a different ` ++ `major whose objects never reach the shared copy may be listed in the vendored ` ++ `module's privateCopies.`,+ );+ }++ const target = sharedSpecifiers.get(source);+ if (target === undefined) {+ throw new Error(+ `Vendor: ${importer ?? "a vendored module"} imports "${source}", which the vendored ` ++ `"${owner.module.packageName}" module does not share. Add "${source}" to its ` ++ `sharedSpecifiers so eve keeps a single copy of "${owner.module.packageName}".`,+ );+ }+ // A CommonJS `require()` of an external stays a runtime `require()`+ // that app bundlers cannot follow, so route it through an ESM facade+ // that keeps a static import.+ if (options.kind === "require-call")+ return `${SHARED_FACADE_PREFIX}${target.importSpecifier}`;+ return { id: target.importSpecifier, external: true };+ },+ load(id) {+ if (!id.startsWith(SHARED_FACADE_PREFIX)) return null;+ return `export * from ${JSON.stringify(id.slice(SHARED_FACADE_PREFIX.length))};`;+ },+ };+}++function packageNameOf(specifier) {+ if (specifier.startsWith(".") || specifier.startsWith("/") || specifier.includes(":")) {+ return undefined;+ }+ const segments = specifier.split("/");+ return specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];+}++function isInsideDirectory(file, directory) {+ let resolvedFile;+ try {+ resolvedFile = realpathSync(file);+ } catch {+ return false;+ }+ const offset = relative(directory, resolvedFile);+ return offset !== "" && !offset.startsWith("..") && !isAbsolute(offset);+}+async function writeTypeOnlyModule({ module, compiledRoot, packageRoot }) {const { destinationRoot, packageInfo } = await prepareCompiledModule({module,diff --git a/packages/eve/scripts/vendor-compiled/declarations/@cfworker/json-schema.d.ts b/packages/eve/scripts/vendor-compiled/declarations/@cfworker/json-schema.d.tsnew file mode 100644index 000000000..6d9946314--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/declarations/@cfworker/json-schema.d.ts@@ -0,0 +1,18 @@+export type SchemaDraft = "4" | "7" | "2019-09" | "2020-12";++export interface OutputUnit {+ readonly error: string;+ readonly instanceLocation: string;+ readonly keyword: string;+ readonly keywordLocation: string;+}++export interface ValidationResult {+ readonly errors: readonly OutputUnit[];+ readonly valid: boolean;+}++export declare class Validator {+ constructor(schema: object | boolean, draft?: SchemaDraft, shortCircuit?: boolean);+ validate(instance: unknown): ValidationResult;+}diff --git a/packages/eve/scripts/vendor-compiled/declarations/@vercel/sdk.d.ts b/packages/eve/scripts/vendor-compiled/declarations/@vercel/sdk.d.tsnew file mode 100644index 000000000..3157c37ce--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/declarations/@vercel/sdk.d.ts@@ -0,0 +1,41 @@+// Minimal declaration for the vendored slice of `@vercel/sdk`: the project+// trusted-sources model helpers. Mirrors upstream's `UpdateProject*` shapes+// for the fields eve reads; widen it if a caller needs more of the policy.++/** System environment slugs (`production`, `preview`) and/or custom environment slugs. */+export type UpdateProjectEnvironmentSet =+ | { slugs: string[]; preset?: "all-custom" | undefined }+ | { slugs?: string[] | undefined; preset: "all-custom" };++export type UpdateProjectCustomAllow = {+ from: UpdateProjectEnvironmentSet;+ to: UpdateProjectEnvironmentSet;+};++export type UpdateProjectTrustedSources = {+ projects?:+ | {+ [projectId: string]: {+ label?: string | undefined;+ customAllow?: UpdateProjectCustomAllow[] | undefined;+ };+ }+ | undefined;+ oidcProviders?:+ | {+ [provider: string]: Array<{+ to: UpdateProjectEnvironmentSet;+ label?: string | undefined;+ claims: { [claim: string]: string[] };+ }>;+ }+ | undefined;+};++export declare function updateProjectTrustedSourcesFromJSON(+ jsonString: string,+):+ | { ok: true; value: UpdateProjectTrustedSources; error?: never }+ | { ok: false; value?: never; error: Error };++export declare function trustedSourcesToJSON(trustedSources: UpdateProjectTrustedSources): string;diff --git a/packages/eve/scripts/vendor-compiled/entries/@vercel/sdk.mjs b/packages/eve/scripts/vendor-compiled/entries/@vercel/sdk.mjsnew file mode 100644index 000000000..03b55509e--- /dev/null+++ b/packages/eve/scripts/vendor-compiled/entries/@vercel/sdk.mjs@@ -0,0 +1,6 @@+// Thin ESM re-export of the `@vercel/sdk` model helpers the dev TUI uses to+// read and patch a project's trusted-sources policy. Vendoring this slice+// instead of importing `@vercel/sdk` directly keeps the SDK and its Zod out+// of eve's dist tree: the bundle imports eve's single vendored Zod.+export { updateProjectTrustedSourcesFromJSON } from "@vercel/sdk/models/updateprojectblock.js";+export { trustedSourcesToJSON } from "@vercel/sdk/models/updateprojectprojectsbranchmatcher.js";diff --git a/packages/eve/scripts/vendor-compiled/entries/zod.mjs b/packages/eve/scripts/vendor-compiled/entries/zod.mjsdeleted file mode 100644index 12c6c7f6c..000000000--- a/packages/eve/scripts/vendor-compiled/entries/zod.mjs+++ /dev/null@@ -1,7 +0,0 @@-import "zod/compile";--import * as z from "zod";--export * from "zod";-export { z };-export default z;diff --git a/packages/eve/scripts/vendor-compiled/index.mjs b/packages/eve/scripts/vendor-compiled/index.mjsindex 52d1b059d..5a27c3f9a 100644--- a/packages/eve/scripts/vendor-compiled/index.mjs+++ b/packages/eve/scripts/vendor-compiled/index.mjs@@ -12,6 +12,7 @@ import openai from "./@ai-sdk/openai.mjs";import otel from "./@ai-sdk/otel.mjs";import provider from "./@ai-sdk/provider.mjs";import providerUtils from "./@ai-sdk/provider-utils.mjs";+import cfworkerJsonSchema from "./@cfworker/json-schema.mjs";import chatAdapterSlack from "./@chat-adapter/slack.mjs";import chatAdapterStateMemory from "./@chat-adapter/state-memory.mjs";@@ -29,6 +30,7 @@ import vercelDetectAgent from "./@vercel/detect-agent.mjs";import vercelOidc from "./@vercel/oidc.mjs";import vercelOtel from "./@vercel/otel.mjs";import vercelSandbox from "./@vercel/sandbox.mjs";+import vercelSdk from "./@vercel/sdk.mjs";import workflowCore from "./@workflow/core.mjs";import workflowErrors from "./@workflow/errors.mjs";import workflowSerde from "./@workflow/serde.mjs";@@ -58,6 +60,7 @@ import zodValidationError from "./zod-validation-error.mjs";export const MODULES = [acpSdk,anthropic,+ cfworkerJsonSchema,codeMode,chat,chatAdapterSlack,@@ -96,6 +99,7 @@ export const MODULES = [vercelOidc,vercelOtel,vercelSandbox,+ vercelSdk,workflowCore,workflowErrors,workflowSerde,diff --git a/packages/eve/scripts/vendor-compiled/shadcn-registry.mjs b/packages/eve/scripts/vendor-compiled/shadcn-registry.mjsindex d52e2aec5..425464660 100644--- a/packages/eve/scripts/vendor-compiled/shadcn-registry.mjs+++ b/packages/eve/scripts/vendor-compiled/shadcn-registry.mjs@@ -43,6 +43,9 @@ export default {},],bundling: "standalone",+ // shadcn requires Zod 3, a separate major whose schemas stay inside the+ // registry CLI and never meet eve's shared Zod 4.+ privateCopies: ["zod"],plugins: [json5ShimPlugin],banner: `/* oxlint-disable */import { fileURLToPath as __eveFileURLToPath } from "node:url";diff --git a/packages/eve/scripts/vendor-compiled/zod.mjs b/packages/eve/scripts/vendor-compiled/zod.mjsindex f8910e9e1..a8553e4b5 100644--- a/packages/eve/scripts/vendor-compiled/zod.mjs+++ b/packages/eve/scripts/vendor-compiled/zod.mjs@@ -1,19 +1,23 @@-import { fileURLToPath } from "node:url";-import { loadDeclaration } from "./_shared.mjs";-const declaration = await loadDeclaration("zod.d.ts");-+/**+ * eve ships exactly one Zod. Other vendored bundles and eve's own build+ * (`build-rolldown.mjs`) import these entries instead of bundling their own+ * copy, because Zod schema objects only work with the copy that built them.+ *+ * Keep this a plain re-export: Zod shares configuration through `globalThis`+ * across every copy in a process, so a side-effect import such as+ * `zod/compile` would also rewrite the app's own schemas.+ */export default {packageName: "zod",compiledPath: "zod",chunkGroup: "client",entries: [- {- declaration,- input: fileURLToPath(new URL("./entries/zod.mjs", import.meta.url)),- outputPath: "index",- },+ { declaration: await loadDeclaration("zod.d.ts"), input: "zod", outputPath: "index" },+ { input: "zod/v4/core", outputPath: "v4/core" },+ { input: "zod/v3", outputPath: "v3" },],platform: "neutral",+ sharedSpecifiers: { zod: "index", "zod/v3": "v3", "zod/v4": "index", "zod/v4/core": "v4/core" },};diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.tsindex 009d506fb..d53c25b40 100644--- a/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources-policy.ts@@ -1,7 +1,7 @@import type {UpdateProjectCustomAllow,UpdateProjectTrustedSources,-} from "@vercel/sdk/models/updateprojectblock.js";+} from "#compiled/@vercel/sdk/index.js";export type TrustedSourceEnvironmentRule = UpdateProjectCustomAllow;diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.tsindex 1bdc3f2db..a776473cb 100644--- a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.test.ts@@ -2,7 +2,7 @@ import { createFakePrompter } from "#internal/testing/fake-prompter.js";import { resolveTestVercelTarget } from "#internal/testing/verified-vercel-target.js";import type { VercelCaptureResult } from "#setup/primitives/index.js";import type { Prompter, PrompterValue, SingleSelectOptions } from "#setup/prompter.js";-import { trustedSourcesToJSON } from "@vercel/sdk/models/updateprojectprojectsbranchmatcher.js";+import { trustedSourcesToJSON } from "#compiled/@vercel/sdk/index.js";import { describe, expect, it } from "vitest";import { vi } from "vitest";diff --git a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.tsindex a1845f839..174ba65a9 100644--- a/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts+++ b/packages/eve/src/cli/dev/tui/vercel-trusted-sources.ts@@ -1,13 +1,13 @@import {updateProjectTrustedSourcesFromJSON,type UpdateProjectTrustedSources,-} from "@vercel/sdk/models/updateprojectblock.js";-import { trustedSourcesToJSON } from "@vercel/sdk/models/updateprojectprojectsbranchmatcher.js";+ trustedSourcesToJSON,+} from "#compiled/@vercel/sdk/index.js";import { captureVercel } from "#setup/primitives/index.js";import type { Prompter } from "#setup/prompter.js";import { normalizeVercelApiResult } from "#setup/vercel-api-failure.js";import type { VerifiedVercelTarget } from "#setup/vercel-deployment.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import {planTrustedSourceAccess,diff --git a/packages/eve/src/cli/invoke/result.ts b/packages/eve/src/cli/invoke/result.tsindex 3b31d87f2..752187d25 100644--- a/packages/eve/src/cli/invoke/result.ts+++ b/packages/eve/src/cli/invoke/result.ts@@ -1,5 +1,5 @@import { z } from "#compiled/zod/index.js";-import { inputOptionSchema, inputRequestSchema, type InputRequest } from "#client/index.js";+import { inputOptionSchema, inputRequestSchema, type InputRequest } from "#shared/input.js";import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";const sessionCursorSchema = zdiff --git a/packages/eve/src/cli/telemetry/preference.ts b/packages/eve/src/cli/telemetry/preference.tsindex fb06d5bdb..07f373bc9 100644--- a/packages/eve/src/cli/telemetry/preference.ts+++ b/packages/eve/src/cli/telemetry/preference.ts@@ -7,7 +7,7 @@ import {} from "#cli/telemetry/identity.js";import { dirname, isAbsolute, join } from "node:path";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";const EVE_TELEMETRY_NOTICE_VERSION = 1;diff --git a/packages/eve/src/client/index.ts b/packages/eve/src/client/index.tsindex b9f360d1d..eb6cd5999 100644--- a/packages/eve/src/client/index.ts+++ b/packages/eve/src/client/index.ts@@ -5,9 +5,7 @@export { EveAgentStore } from "#client/eve-agent-store.js";export { Client } from "#client/client.js";export { AgentInfoResponseError } from "#client/agent-info-error.js";-export { AgentInfoResultSchema } from "#client/agent-info-schema.js";export { HealthResponseError } from "#client/health-response-error.js";-export { HealthResultSchema } from "#client/health-schema.js";export { ClientError } from "#client/client-error.js";export { defaultMessageReducer } from "#client/message-reducer.js";export { createDataUrlFilePart, createTextWithFileContent } from "#client/file-parts.js";@@ -146,10 +144,6 @@ export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/messagexport type { InputOption, InputRequest, InputRequestKind, InputResponse } from "#shared/input.js";export {- inputOptionSchema,- inputRequestKindSchema,- inputRequestSchema,- inputResponseSchema,isInputRequest,isInputResponse,parseInputResponse,diff --git a/packages/eve/src/execution/tools/agent-router.ts b/packages/eve/src/execution/tools/agent-router.tsindex c9e8fb203..ce720e134 100644--- a/packages/eve/src/execution/tools/agent-router.ts+++ b/packages/eve/src/execution/tools/agent-router.ts@@ -1,5 +1,5 @@-import { z } from "#compiled/zod/index.js";import type { JsonObject } from "#shared/json.js";+import { defineJsonSchema } from "#tools/schema.js";export { executeAgentRouterTool } from "#execution/tools/agent-router-workflow.js";@@ -11,13 +11,20 @@ export interface AgentRouterInput {readonly outputSchema?: JsonObject;}-export const AGENT_ROUTER_INPUT_SCHEMA: z.ZodType<AgentRouterInput> = z.strictObject({- message: z.string().min(1).describe("The complete task to send to the selected agent."),- outputSchema: (- z- .looseObject({})- .describe(+export const AGENT_ROUTER_INPUT_SCHEMA = defineJsonSchema<AgentRouterInput>({+ type: "object",+ properties: {+ message: {+ type: "string",+ minLength: 1,+ description: "The complete task to send to the selected agent.",+ },+ outputSchema: {+ type: "object",+ description:"Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The selected agent must match a provided schema, and that structured output becomes the tool result.",- ) as z.ZodType<JsonObject>- ).optional(),+ },+ },+ required: ["message"],+ additionalProperties: false,});diff --git a/packages/eve/src/execution/tools/ask-question.ts b/packages/eve/src/execution/tools/ask-question.tsindex cd68965b3..765b5d175 100644--- a/packages/eve/src/execution/tools/ask-question.ts+++ b/packages/eve/src/execution/tools/ask-question.ts@@ -1,4 +1,4 @@-import { z } from "#compiled/zod/index.js";+import { defineJsonSchema } from "#tools/schema.js";export { executeAskQuestionTool } from "#execution/tools/ask-question-workflow.js";@@ -14,42 +14,89 @@ export const ASK_QUESTION_TOOL_DESCRIPTION = ['- If the status is "unavailable", no one can answer in this session; continue with your best judgment and state the assumption you made.',].join("\n");-const ASK_QUESTION_OPTION_SCHEMA = z.strictObject({- description: z- .string()- .min(1)- .max(200)- .describe("One short sentence on the impact or tradeoff of choosing this option."),- label: z.string().min(1).max(80).describe("User-facing label, 1-5 words."),-});+export interface AskQuestionInput {+ options?: { description: string; label: string }[];+ question: string;+}-export const ASK_QUESTION_INPUT_SCHEMA = z.strictObject({- options: z- .array(ASK_QUESTION_OPTION_SCHEMA)- .min(2)- .max(3)- .refine((options) => new Set(options.map((option) => option.label)).size === options.length, {- message: "Option labels must be unique.",- })- .describe(- 'Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.',- )- .optional(),- question: z- .string()- .min(1)- .max(2000)- .describe("The question to show the user, with the context needed to answer it."),-});+export type AskQuestionOutput =+ | { answer: string; status: "answered" }+ | { status: "dismissed" }+ | { status: "unavailable" };-export const ASK_QUESTION_OUTPUT_SCHEMA = z.discriminatedUnion("status", [- z.strictObject({- answer: z.string().describe("The chosen option's label, or the user's own words."),- status: z.literal("answered"),- }),- z.strictObject({ status: z.literal("dismissed") }),- z.strictObject({ status: z.literal("unavailable") }),-]);+export const ASK_QUESTION_INPUT_SCHEMA = defineJsonSchema<AskQuestionInput>(+ {+ type: "object",+ properties: {+ options: {+ type: "array",+ minItems: 2,+ maxItems: 3,+ items: {+ type: "object",+ properties: {+ description: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ description: "One short sentence on the impact or tradeoff of choosing this option.",+ },+ label: {+ type: "string",+ minLength: 1,+ maxLength: 80,+ description: "User-facing label, 1-5 words.",+ },+ },+ required: ["description", "label"],+ additionalProperties: false,+ },+ description:+ 'Two or three mutually exclusive choices, recommended option first. Omit for an open-ended question. Never include an "Other" option.',+ },+ question: {+ type: "string",+ minLength: 1,+ maxLength: 2000,+ description: "The question to show the user, with the context needed to answer it.",+ },+ },+ required: ["question"],+ additionalProperties: false,+ },+ // Labels double as option ids, so duplicates would make answers ambiguous.+ (input) =>+ input.options !== undefined &&+ new Set(input.options.map((option) => option.label)).size !== input.options.length+ ? "Option labels must be unique."+ : undefined,+);-export type AskQuestionInput = z.infer<typeof ASK_QUESTION_INPUT_SCHEMA>;-export type AskQuestionOutput = z.infer<typeof ASK_QUESTION_OUTPUT_SCHEMA>;+export const ASK_QUESTION_OUTPUT_SCHEMA = defineJsonSchema<AskQuestionOutput>({+ oneOf: [+ {+ type: "object",+ properties: {+ answer: {+ type: "string",+ description: "The chosen option's label, or the user's own words.",+ },+ status: { type: "string", const: "answered" },+ },+ required: ["answer", "status"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: { status: { type: "string", const: "dismissed" } },+ required: ["status"],+ additionalProperties: false,+ },+ {+ type: "object",+ properties: { status: { type: "string", const: "unavailable" } },+ required: ["status"],+ additionalProperties: false,+ },+ ],+});diff --git a/packages/eve/src/execution/tools/connection-search.test.ts b/packages/eve/src/execution/tools/connection-search.test.tsindex 62b37c329..7b57e6bf1 100644--- a/packages/eve/src/execution/tools/connection-search.test.ts+++ b/packages/eve/src/execution/tools/connection-search.test.ts@@ -75,7 +75,6 @@ function registry(input: {connect: async () => {},executeTool: async () => {},getToolMetadata: input.loadTools[name]!,- getTools: async () => ({}),}),getConnectionApproval: () => undefined,getConnectionNames: () => input.connections.map((item) => item.connectionName),diff --git a/packages/eve/src/execution/tools/connection-search.ts b/packages/eve/src/execution/tools/connection-search.tsindex a7353d61a..ba410a584 100644--- a/packages/eve/src/execution/tools/connection-search.ts+++ b/packages/eve/src/execution/tools/connection-search.ts@@ -1,5 +1,3 @@-import { z } from "#compiled/zod/index.js";-import { loadContext } from "#context/container.js";import { ContextKey } from "#context/key.js";import {@@ -21,6 +19,7 @@ import {} from "#approval/definition.js";import type { JsonObject } from "#shared/json.js";import { stampDurableDynamicToolCallbacks } from "#tools/durable-callbacks.js";+import { defineJsonSchema } from "#tools/schema.js";import { resolveConnectionAuthorization } from "#runtime/connections/resolve-authorization.js";import {createAuthorizationExecution,@@ -39,33 +38,43 @@ import { ConnectionRegistryKey } from "#context/providers/connection-key.js";const logger = createLogger("framework.connection-search-dynamic");-const CONNECTION_SEARCH_INPUT_SCHEMA = z.strictObject({- connection: z- .string()- .describe("Optional: limit search to a specific connection name.")- .optional(),- keywords: z- .string()- .describe(- "Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.",- ),- limit: z.number().describe("Max results to return. Default 10.").optional(),+const CONNECTION_SEARCH_INPUT_SCHEMA = defineJsonSchema<ConnectionSearchInput>({+ type: "object",+ properties: {+ connection: {+ type: "string",+ description: "Optional: limit search to a specific connection name.",+ },+ keywords: {+ type: "string",+ description:+ "Search keywords and expanded aliases. Distill intent into keywords; avoid stop words like 'a', 'the', 'in'.",+ },+ limit: { type: "number", description: "Max results to return. Default 10." },+ },+ required: ["keywords"],+ additionalProperties: false,});-const connectionSchema = z.looseObject({});-const CONNECTION_SEARCH_RESULT_ITEM_SCHEMA = z.strictObject({- connection: z.string(),- description: z.string(),- error: z.string().optional(),- inputSchema: connectionSchema.optional(),- needsAuthorization: z.boolean().optional(),- outputSchema: connectionSchema.optional(),- qualifiedName: z.string().optional(),- tool: z.string().optional(),+const CONNECTION_SEARCH_OUTPUT_SCHEMA = defineJsonSchema<ConnectionSearchResultItem[]>({+ type: "array",+ items: {+ type: "object",+ properties: {+ connection: { type: "string" },+ description: { type: "string" },+ error: { type: "string" },+ inputSchema: { type: "object" },+ needsAuthorization: { type: "boolean" },+ outputSchema: { type: "object" },+ qualifiedName: { type: "string" },+ tool: { type: "string" },+ },+ required: ["connection", "description"],+ additionalProperties: false,+ },});-const CONNECTION_SEARCH_OUTPUT_SCHEMA = z.array(CONNECTION_SEARCH_RESULT_ITEM_SCHEMA);-/*** Durable context key for connection search results. Written by* `executeConnectionSearch` so the resolver can find discovered tools withoutdiff --git a/packages/eve/src/execution/tools/load-skill.ts b/packages/eve/src/execution/tools/load-skill.tsindex 7bca1d98e..5f3a325ae 100644--- a/packages/eve/src/execution/tools/load-skill.ts+++ b/packages/eve/src/execution/tools/load-skill.ts@@ -1,4 +1,4 @@-import { z } from "#compiled/zod/index.js";+import { defineJsonSchema } from "#tools/schema.js";import { loadContext } from "#context/container.js";import { DynamicSkillManifestKey } from "#context/keys.js";@@ -9,7 +9,9 @@ import { stripSkillFrontmatter } from "#shared/skill-package.js";/*** Typed input accepted by {@link executeLoadSkillTool}.*/-type LoadSkillInput = z.infer<typeof SKILL_INPUT_SCHEMA>;+interface LoadSkillInput {+ skill: string;+}/*** Executes the `load_skill` tool.@@ -54,10 +56,15 @@ function formatSkillNotFoundError(skill: string, availableSkills: readonly strin// Tool definition// ----------------------------------------------------------------------------export const SKILL_INPUT_SCHEMA = z.strictObject({- skill: z.string().describe("Available skill name or id."),+export const SKILL_INPUT_SCHEMA = defineJsonSchema<LoadSkillInput>({+ type: "object",+ properties: {+ skill: { type: "string", description: "Available skill name or id." },+ },+ required: ["skill"],+ additionalProperties: false,});-export const SKILL_OUTPUT_SCHEMA = z.string();+export const SKILL_OUTPUT_SCHEMA = defineJsonSchema<string>({ type: "string" });export async function executeLoadSkill(input: unknown): Promise<unknown> {return await executeLoadSkillTool(input as LoadSkillInput);diff --git a/packages/eve/src/execution/tools/sleep.ts b/packages/eve/src/execution/tools/sleep.tsindex c7ebeac08..4763bfaa7 100644--- a/packages/eve/src/execution/tools/sleep.ts+++ b/packages/eve/src/execution/tools/sleep.ts@@ -1,4 +1,4 @@-import { z } from "#compiled/zod/index.js";+import { defineJsonSchema } from "#tools/schema.js";export { executeSleepTool } from "#execution/tools/sleep-workflow.js";@@ -7,13 +7,33 @@ const MAX_SLEEP_SECONDS = Math.floor(Number.MAX_SAFE_INTEGER / 1_000);export const SLEEP_TOOL_DESCRIPTION ="Wait for a specified amount of time before continuing. Use this when a process or condition needs time to change before it is useful to check its progress or status again.";-export const SLEEP_INPUT_SCHEMA = z.strictObject({- seconds: z.number().positive().max(MAX_SLEEP_SECONDS).describe("How long to wait, in seconds."),-});+export interface SleepToolInput {+ seconds: number;+}++export interface SleepToolOutput {+ waitedSeconds: number;+}-export const SLEEP_OUTPUT_SCHEMA = z.strictObject({- waitedSeconds: z.number().positive(),+export const SLEEP_INPUT_SCHEMA = defineJsonSchema<SleepToolInput>({+ type: "object",+ properties: {+ seconds: {+ type: "number",+ exclusiveMinimum: 0,+ maximum: MAX_SLEEP_SECONDS,+ description: "How long to wait, in seconds.",+ },+ },+ required: ["seconds"],+ additionalProperties: false,});-export type SleepToolInput = z.infer<typeof SLEEP_INPUT_SCHEMA>;-export type SleepToolOutput = z.infer<typeof SLEEP_OUTPUT_SCHEMA>;+export const SLEEP_OUTPUT_SCHEMA = defineJsonSchema<SleepToolOutput>({+ type: "object",+ properties: {+ waitedSeconds: { type: "number", exclusiveMinimum: 0 },+ },+ required: ["waitedSeconds"],+ additionalProperties: false,+});diff --git a/packages/eve/src/harness/final-output.ts b/packages/eve/src/harness/final-output.tsindex d8cb02ddc..8a5660020 100644--- a/packages/eve/src/harness/final-output.ts+++ b/packages/eve/src/harness/final-output.ts@@ -1,6 +1,6 @@import type { Tool } from "ai";-import { toInputSchema } from "#tools/schema.js";+import { defineJsonSchema, toModelSchema } from "#tools/schema.js";import type { JsonObject } from "#shared/json.js";/**@@ -20,10 +20,10 @@ const FINAL_OUTPUT_TOOL_DESCRIPTION =* to the schema during generation, exactly like every other eve tool input.*/export function buildFinalOutputTool(schema: JsonObject): Tool {- const runtimeSchema = toInputSchema(schema);+ const modelSchema = toModelSchema(defineJsonSchema(schema), "input");return {description: FINAL_OUTPUT_TOOL_DESCRIPTION,- inputSchema: runtimeSchema,- outputSchema: runtimeSchema,+ inputSchema: modelSchema,+ outputSchema: modelSchema,};}diff --git a/packages/eve/src/harness/input-extraction.ts b/packages/eve/src/harness/input-extraction.tsindex b92278f6f..af959b52c 100644--- a/packages/eve/src/harness/input-extraction.ts+++ b/packages/eve/src/harness/input-extraction.ts@@ -1,5 +1,5 @@import type { ContentPart, ModelMessage, ToolSet } from "ai";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import type { InputRequest } from "#shared/input.js";import { createRuntimeToolCallActionFromToolCall } from "#harness/tool-call-action.js";diff --git a/packages/eve/src/harness/tool-loop.ts b/packages/eve/src/harness/tool-loop.tsindex 8f404a943..02ddd92c7 100644--- a/packages/eve/src/harness/tool-loop.ts+++ b/packages/eve/src/harness/tool-loop.ts@@ -224,6 +224,7 @@ import {buildToolSetWithProviderTools,} from "#harness/tools.js";import { buildFinalOutputTool, FINAL_OUTPUT_TOOL_NAME } from "#harness/final-output.js";+import { toModelSchema } from "#tools/schema.js";import type { RuntimeModelReference } from "#runtime/agent/bootstrap.js";import type { RunMode } from "#shared/run-mode.js";import { createHistoryViewPreparer, type HistoryViewProjector } from "#shared/history-view.js";@@ -1429,6 +1430,12 @@ export function createToolLoopHarness(config: ToolLoopHarnessConfig): StepFn {const effectiveTools = marker ? applyLastToolCacheBreakpoint(modelTools, marker) : modelTools;for (const tool of Object.values(effectiveTools)) {+ // Whatever produced this tool, the AI SDK must only receive its own+ // schema type; see toModelSchema.+ tool.inputSchema = toModelSchema(tool.inputSchema, "input");+ if (tool.outputSchema !== undefined) {+ tool.outputSchema = toModelSchema(tool.outputSchema, "output");+ }const execute = tool.execute;if (execute !== undefined)tool.execute = (...args) => {diff --git a/packages/eve/src/harness/tools.test.ts b/packages/eve/src/harness/tools.test.tsindex 0045c0153..05720f5ca 100644--- a/packages/eve/src/harness/tools.test.ts+++ b/packages/eve/src/harness/tools.test.ts@@ -1,5 +1,6 @@-import { type JSONSchema7, jsonSchema } from "ai";+import { asSchema, type JSONSchema7, jsonSchema } from "ai";import { describe, expect, it } from "vitest";+import { z } from "zod";import { ContextContainer, contextStorage } from "#context/container.js";import { SessionKey, type Session } from "#context/keys.js";@@ -24,6 +25,8 @@ import { createToolExecuteWithAuth } from "#execution/tool-auth.js";import type { ApprovalContext } from "#approval/definition.js";import type { ToolContext } from "#tools/definition.js";import type { ToolExecuteOptions } from "#tools/definition.js";+import { BASH_INPUT_SCHEMA, BASH_OUTPUT_SCHEMA } from "#tools/provided/bash.js";+import { toInputSchema, UNSPECIFIED_INPUT_SCHEMA } from "#tools/schema.js";function getJsonSchema(tool: unknown): unknown {return (tool as { inputSchema: { jsonSchema: unknown } }).inputSchema.jsonSchema;@@ -385,6 +388,70 @@ describe("buildToolSet", () => {expect(getOutputJsonSchema(result.summarize)).toEqual(outputSchema);});+ it("hands the AI SDK only its own schema type, whatever produced the tool schema", async () => {+ // The AI SDK converts and parses Zod-vendored schemas with the app's own+ // Zod copy. Handing it anything but its own `Schema` lets a mismatched+ // copy crash mid-stream, so every source is lowered first.+ const remote = {+ anyOf: [{ required: ["page_id"] }, { required: ["title"] }],+ patternProperties: { "^x-": { type: "string" } },+ properties: {+ page_id: { format: "uuid", type: "string" },+ target: {+ allOf: [+ { properties: { id: { type: "string" } }, type: "object" },+ { properties: { kind: { enum: ["page", "database"] } }, type: "object" },+ ],+ },+ title: { type: "string" },+ },+ type: "object",+ };+ const sources: Record<string, HarnessToolDefinition["inputSchema"]> = {+ authored_zod: z+ .object({ id: z.string() })+ .and(z.object({ tags: z.record(z.string(), z.string()) })),+ framework: BASH_INPUT_SCHEMA,+ native: jsonSchema({ type: "object" }),+ remote: toInputSchema(remote),+ unspecified: UNSPECIFIED_INPUT_SCHEMA,+ };+ const tools: HarnessToolMap = new Map(+ Object.entries(sources).map(([name, inputSchema]) => [+ name,+ {+ description: name,+ execute: async (input: unknown) => input,+ inputSchema,+ name,+ outputSchema: name === "framework" ? BASH_OUTPUT_SCHEMA : undefined,+ },+ ]),+ );++ const result = buildToolSet({ tools });++ for (const tool of Object.values(result)) {+ for (const schema of [tool.inputSchema, tool.outputSchema]) {+ if (schema === undefined) continue;+ expect(Reflect.get(schema, Symbol.for("vercel.ai.schema"))).toBe(true);+ expect(asSchema(schema)).toBe(schema);+ expect("~standard" in schema).toBe(false);+ expect("_zod" in schema).toBe(false);+ }+ }+ expect(getJsonSchema(result.remote)).toEqual(remote);+ await expect(+ asSchema(result.remote!.inputSchema).validate?.({+ page_id: "1f2e3d4c5b6a79881f2e3d4c5b6a7988",+ target: { id: "db-1", kind: "database" },+ }),+ ).resolves.toMatchObject({ success: true });+ await expect(asSchema(result.remote!.inputSchema).validate?.({})).resolves.toMatchObject({+ success: false,+ });+ });+it("supports client-side tools without server executors", () => {const schema = {properties: { prompt: { type: "string" } },diff --git a/packages/eve/src/harness/tools.ts b/packages/eve/src/harness/tools.tsindex adbcc7dac..67a0e953b 100644--- a/packages/eve/src/harness/tools.ts+++ b/packages/eve/src/harness/tools.ts@@ -15,6 +15,7 @@ import {modelFacingAuthorizationOutput,} from "#harness/authorization.js";import { stashToolInterrupt } from "#harness/tool-interrupts.js";+import { toModelSchema } from "#tools/schema.js";import { normalizeToolJsonOutput, normalizeToolModelOutput } from "#harness/tool-model-output.js";import type { ToolExecuteOptions } from "#tools/definition.js";import { isAsyncIterable } from "#shared/async-iterable.js";@@ -74,7 +75,7 @@ export function buildToolSet(input: {const aiTool = tool({description: definition.description,execute: wrapToolExecute(definition, backgroundBatch),- inputSchema: definition.inputSchema,+ inputSchema: toModelSchema(definition.inputSchema, "input"),...(definition.execution === "background"? {onInputAvailable: ({@@ -95,7 +96,7 @@ export function buildToolSet(input: {},}: {}),- outputSchema: definition.outputSchema,+ outputSchema: toModelSchema(definition.outputSchema, "output"),...(definition.execute !== undefined? {toModelOutput: async ({diff --git a/packages/eve/src/public/memory/file/provider.test.ts b/packages/eve/src/public/memory/file/provider.test.tsindex ce7f11f1e..2a2ed926e 100644--- a/packages/eve/src/public/memory/file/provider.test.ts+++ b/packages/eve/src/public/memory/file/provider.test.ts@@ -9,6 +9,7 @@ import type {MemoryToolsContext,MemoryTurnStartedContext,} from "#public/memory/index.js";+import type { ToolSchema } from "#tools/schema.js";interface TestTool<TInput> {execute(input: TInput, context: never): unknown;@@ -341,6 +342,39 @@ describe("fileMemory", () => {});});+describe("fileMemory tool schemas", () => {+ // Tool schemas reach the app's AI SDK, which would run a Zod schema through+ // the app's own Zod copy, so these must be plain JSON Schema.+ it("advertises plain JSON Schema and validates input against it", async () => {+ const tools = await fileMemory({ backend: inMemory() }).tools?.(toolsContext());+ const save = tools?.save_memory?.inputSchema as ToolSchema<{ text: string }>;+ const remove = tools?.remove_memory?.inputSchema as ToolSchema<{ index: number }>;++ expect(save).not.toHaveProperty("_zod");+ expect(remove).not.toHaveProperty("_zod");+ expect(save["~standard"].jsonSchema.input({ target: "draft-2020-12" })).toEqual({+ type: "object",+ properties: { text: { type: "string", minLength: 1 } },+ required: ["text"],+ additionalProperties: false,+ });+ expect(remove["~standard"].jsonSchema.input({ target: "draft-2020-12" })).toEqual({+ type: "object",+ properties: { index: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER } },+ required: ["index"],+ additionalProperties: false,+ });++ expect(await save["~standard"].validate({ text: "Likes tea." })).toEqual({+ value: { text: "Likes tea." },+ });+ expect(await save["~standard"].validate({ text: "" })).toHaveProperty("issues");+ expect(await remove["~standard"].validate({ index: 3 })).toEqual({ value: { index: 3 } });+ expect(await remove["~standard"].validate({ index: 1.5 })).toHaveProperty("issues");+ expect(await remove["~standard"].validate({ index: -1 })).toHaveProperty("issues");+ });+});+async function resolveTools(provider: MemoryProvider) {const tools = await provider.tools?.(toolsContext());const saveMemory = tools?.save_memory;diff --git a/packages/eve/src/public/memory/file/provider.ts b/packages/eve/src/public/memory/file/provider.tsindex aaf740441..450be51f4 100644--- a/packages/eve/src/public/memory/file/provider.ts+++ b/packages/eve/src/public/memory/file/provider.ts@@ -1,6 +1,5 @@-import { z } from "#compiled/zod/index.js";-import { defineTool } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";import {MemoryDocumentConflictError,type MemoryDocument,@@ -66,6 +65,24 @@ export function fileMemory(options: FileMemoryOptions = {}): MemoryProvider {});}+const REMOVE_MEMORY_INPUT_SCHEMA = defineJsonSchema<{ index: number }>({+ type: "object",+ properties: {+ index: { type: "integer", minimum: 0, maximum: Number.MAX_SAFE_INTEGER },+ },+ required: ["index"],+ additionalProperties: false,+});++const SAVE_MEMORY_INPUT_SCHEMA = defineJsonSchema<{ text: string }>({+ type: "object",+ properties: {+ text: { type: "string", minLength: 1 },+ },+ required: ["text"],+ additionalProperties: false,+});+function createFileMemoryTools(input: {readonly backend: MemoryDocumentBackend;readonly key: string;@@ -84,9 +101,7 @@ function createFileMemoryTools(input: {signal: toolContext.abortSignal,});},- inputSchema: z.object({- index: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),- }),+ inputSchema: REMOVE_MEMORY_INPUT_SCHEMA,}),save_memory: defineTool({description:@@ -101,9 +116,7 @@ function createFileMemoryTools(input: {text: toolInput.text,});},- inputSchema: z.object({- text: z.string().min(1),- }),+ inputSchema: SAVE_MEMORY_INPUT_SCHEMA,}),};}diff --git a/packages/eve/src/runtime/connections/mcp-client.ts b/packages/eve/src/runtime/connections/mcp-client.tsindex 8ecb362ed..48fadbb7f 100644--- a/packages/eve/src/runtime/connections/mcp-client.ts+++ b/packages/eve/src/runtime/connections/mcp-client.ts@@ -104,16 +104,6 @@ export class McpConnectionClient implements ConnectionClient {return cache.metadata;}- /**- * Returns the AI SDK `ToolSet` produced by `@ai-sdk/mcp`'s- * `toolsFromDefinitions()`. Each entry is a full SDK `Tool` with- * `inputSchema`, `description`, and `execute` already set.- */- async getTools(): Promise<ToolSet> {- const cache = await this.#ensureTools();- return cache.tools;- }-/*** Executes a named tool through the AI SDK's tool executor, which* handles the JSON-RPC `tools/call` internally.diff --git a/packages/eve/src/runtime/connections/openapi-client.test.ts b/packages/eve/src/runtime/connections/openapi-client.test.tsindex 400f5fb64..d38eb9289 100644--- a/packages/eve/src/runtime/connections/openapi-client.test.ts+++ b/packages/eve/src/runtime/connections/openapi-client.test.ts@@ -798,7 +798,7 @@ describe("OpenApiConnectionClient", () => {expect(properties.untyped).toEqual({ default: "false", example: "false" });});- it("keeps operations whose input schemas cannot be locally validated", async () => {+ it("keeps operations whose input schemas cannot be validated locally", async () => {const spec: Record<string, unknown> = {openapi: "3.0.3",info: { title: "T", version: "1" },@@ -822,14 +822,12 @@ describe("OpenApiConnectionClient", () => {};const client = new OpenApiConnectionClient(makeConnection({ spec }));- // Schemas outside the local validation subset degrade to passthrough- // validation instead of dropping the operation — the API validates.+ // Schemas the local validator cannot evaluate stay advertised and pass+ // values through instead of dropping the operation — the API validates.await expect(client.getToolMetadata()).resolves.toMatchObject([{ name: "getValid" },- { name: "getInvalid" },+ { name: "getInvalid", inputSchema: { properties: { state: { enum: "not-an-array" } } } },]);- await expect(client.getTools()).resolves.toHaveProperty("getValid");- await expect(client.getTools()).resolves.toHaveProperty("getInvalid");});it("parses a YAML spec fetched from a URL", async () => {diff --git a/packages/eve/src/runtime/connections/openapi-client.ts b/packages/eve/src/runtime/connections/openapi-client.tsindex 453acf053..4c1b05c83 100644--- a/packages/eve/src/runtime/connections/openapi-client.ts+++ b/packages/eve/src/runtime/connections/openapi-client.ts@@ -1,5 +1,3 @@-import { tool, type ToolSet } from "ai";-import { createLogger } from "#internal/logging.js";import type { ResolvedConnectionDefinition } from "#runtime/types.js";import { passesToolFilter, resolveHeaders } from "#runtime/connections/mcp-client.js";@@ -30,7 +28,7 @@ import type {ConnectionToolMetadata,} from "#shared/connection-types.js";import { isObject } from "#shared/guards.js";-import { toInputSchema, type ToolSchema } from "#tools/schema.js";+import { parseJsonObject, type JsonObject } from "#shared/json.js";import { isLoopbackHostname } from "#shared/network-address.js";const log = createLogger("runtime.connections.openapi-client");@@ -38,7 +36,6 @@ const log = createLogger("runtime.connections.openapi-client");interface OpenApiToolCache {readonly metadata: readonly ConnectionToolMetadata[];readonly operations: ReadonlyMap<string, OpenApiOperation>;- readonly tools: ToolSet;readonly baseUrl: string;}@@ -103,11 +100,6 @@ export class OpenApiConnectionClient implements ConnectionClient {return cache.metadata;}- async getTools(): Promise<ToolSet> {- const cache = await this.#ensureTools();- return cache.tools;- }-async executeTool(toolName: string,args: unknown,@@ -161,17 +153,14 @@ export class OpenApiConnectionClient implements ConnectionClient {const metadata: ConnectionToolMetadata[] = [];const operationMap = new Map<string, OpenApiOperation>();- const tools: ToolSet = {};const providedArgumentNames = Object.keys(this.#connection.toolCall?.providedArguments ?? {});for (const operation of selected) {- const projectedInputSchema = omitProvidedArgumentsFromSchema(- operation.inputSchema,- providedArgumentNames,- );- let inputSchema: ToolSchema;+ let inputSchema: JsonObject;try {- inputSchema = toInputSchema(projectedInputSchema);+ inputSchema = parseJsonObject(+ omitProvidedArgumentsFromSchema(operation.inputSchema, providedArgumentNames),+ );} catch (error) {log.warn("omitting OpenAPI operation with an invalid input schema", {connectionName: this.#connection.connectionName,@@ -183,22 +172,13 @@ export class OpenApiConnectionClient implements ConnectionClient {operationMap.set(operation.toolName, operation);metadata.push({- description: operation.description,- inputSchema: projectedInputSchema,- name: operation.toolName,- });- tools[operation.toolName] = tool({description: operation.description,inputSchema,- execute: async (input: unknown, toolOptions) =>- this.#request(operation, baseUrl, isObject(input) ? input : {}, {- abortSignal: toolOptions?.abortSignal,- callId: toolOptions.toolCallId,- }),+ name: operation.toolName,});}- return { metadata, operations: operationMap, tools, baseUrl };+ return { metadata, operations: operationMap, baseUrl };}/**diff --git a/packages/eve/src/self-modification/config.ts b/packages/eve/src/self-modification/config.tsindex 2794f7cb0..f5336676e 100644--- a/packages/eve/src/self-modification/config.ts+++ b/packages/eve/src/self-modification/config.ts@@ -1,4 +1,5 @@import type { SessionAuthContext } from "#channel/types.js";+import type { AgentReasoningDefinition, AgentStaticModelDefinition } from "#public/index.js";import { assertGitRef, assertRepositoryPart } from "./identifiers.js";@@ -60,6 +61,12 @@ export interface SelfModificationConfig {};}+/** Values accepted by the self-modification extension mount. */+export interface SelfModificationExtensionConfig extends SelfModificationConfig {+ readonly model?: AgentStaticModelDefinition;+ readonly reasoning?: AgentReasoningDefinition;+}+export interface ResolvedSelfModificationConfig {readonly localEnabled: boolean;readonly deployed?: ResolvedDeployedSelfModificationConfig;diff --git a/packages/eve/src/self-modification/extension/config-schema.ts b/packages/eve/src/self-modification/extension/config-schema.tsnew file mode 100644index 000000000..a17083967--- /dev/null+++ b/packages/eve/src/self-modification/extension/config-schema.ts@@ -0,0 +1,35 @@+import { z } from "#compiled/zod/index.js";+import { isAgentReasoningDefinition, isRuntimeLanguageModel } from "#internal/runtime-model.js";+import type { AgentReasoningDefinition, AgentStaticModelDefinition } from "#public/index.js";+import type { GitHubCredentialProvider, SelfModificationAuthorization } from "../config.js";++export const selfModificationConfigSchema = z.object({+ model: z+ .custom<AgentStaticModelDefinition>(+ (value) => typeof value === "string" || isRuntimeLanguageModel(value),+ )+ .optional(),+ reasoning: z.custom<AgentReasoningDefinition>(isAgentReasoningDefinition).optional(),+ local: z.object({ enabled: z.boolean().optional() }).optional(),+ deployed: z+ .object({+ credentials: z+ .union([+ z.object({ pat: z.literal(true) }),+ z.custom<GitHubCredentialProvider>(+ (value) =>+ typeof value === "object" &&+ value !== null &&+ "resolve" in value &&+ typeof value.resolve === "function",+ ),+ ])+ .optional(),+ source: z.object({+ git: z.object({ directory: z.string(), repository: z.string() }),+ }),+ target: z.object({ branch: z.string() }),+ authorize: z.custom<SelfModificationAuthorization>((value) => typeof value === "function"),+ })+ .optional(),+});diff --git a/packages/eve/src/self-modification/extension/extension.test.ts b/packages/eve/src/self-modification/extension/extension.test.tsindex 87a1f1623..5b96e8a9c 100644--- a/packages/eve/src/self-modification/extension/extension.test.ts+++ b/packages/eve/src/self-modification/extension/extension.test.ts@@ -1,7 +1,7 @@import { MockLanguageModelV3 } from "ai/test";import { describe, expect, it } from "vitest";-import { selfModificationConfigSchema } from "./extension.js";+import { selfModificationConfigSchema } from "./config-schema.js";class StatefulCredentialProvider {private readonly token: string;diff --git a/packages/eve/src/self-modification/extension/extension.ts b/packages/eve/src/self-modification/extension/extension.tsindex 29270272d..11099fcd2 100644--- a/packages/eve/src/self-modification/extension/extension.ts+++ b/packages/eve/src/self-modification/extension/extension.ts@@ -1,40 +1,12 @@import { defineExtension } from "eve/extension";-import { z } from "zod";-import { isAgentReasoningDefinition, isRuntimeLanguageModel } from "#internal/runtime-model.js";-import type { AgentReasoningDefinition, AgentStaticModelDefinition } from "#public/index.js";-import type { GitHubCredentialProvider, SelfModificationAuthorization } from "../config.js";+import type { StandardSchemaV1 } from "#compiled/@standard-schema/spec/index.js";+import type { SelfModificationExtensionConfig } from "../config.js";+import { selfModificationConfigSchema } from "./config-schema.js";-export const selfModificationConfigSchema = z.object({- model: z- .custom<AgentStaticModelDefinition>(- (value) => typeof value === "string" || isRuntimeLanguageModel(value),- )- .optional(),- reasoning: z.custom<AgentReasoningDefinition>(isAgentReasoningDefinition).optional(),- local: z.object({ enabled: z.boolean().optional() }).optional(),- deployed: z- .object({- credentials: z- .union([- z.object({ pat: z.literal(true) }),- z.custom<GitHubCredentialProvider>(- (value) =>- typeof value === "object" &&- value !== null &&- "resolve" in value &&- typeof value.resolve === "function",- ),- ])- .optional(),- source: z.object({- git: z.object({ directory: z.string(), repository: z.string() }),- }),- target: z.object({ branch: z.string() }),- authorize: z.custom<SelfModificationAuthorization>((value) => typeof value === "function"),- })- .optional(),-});+// Typed as a Standard Schema so the public declaration names eve's own+// config type instead of Zod's.+const config: StandardSchemaV1<SelfModificationExtensionConfig> = selfModificationConfigSchema;/** Extension mount configured with the same policy as the agent and sandbox. */-export default defineExtension({ config: selfModificationConfigSchema });+export default defineExtension({ config });diff --git a/packages/eve/src/services/dev-client/request-headers.ts b/packages/eve/src/services/dev-client/request-headers.tsindex 41781cea8..c94e9867c 100644--- a/packages/eve/src/services/dev-client/request-headers.ts+++ b/packages/eve/src/services/dev-client/request-headers.ts@@ -1,7 +1,7 @@import { getVercelOidcToken } from "#compiled/@vercel/oidc/index.js";import { readVercelProjectLink } from "#internal/vercel/project-link.js";import { toErrorMessage } from "#shared/errors.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";const VercelOidcClaimsSchema = z.object({owner_id: z.string().min(1),diff --git a/packages/eve/src/setup/integrations/discord/api.ts b/packages/eve/src/setup/integrations/discord/api.tsindex 5133c3687..6cf481aa1 100644--- a/packages/eve/src/setup/integrations/discord/api.ts+++ b/packages/eve/src/setup/integrations/discord/api.ts@@ -1,4 +1,4 @@-import { z } from "zod";+import { z } from "#compiled/zod/index.js";const DISCORD_API_BASE_URL = "https://discord.com/api/v10";diff --git a/packages/eve/src/setup/integrations/discord/connect.ts b/packages/eve/src/setup/integrations/discord/connect.tsindex 1723ffc54..d09d13c1c 100644--- a/packages/eve/src/setup/integrations/discord/connect.ts+++ b/packages/eve/src/setup/integrations/discord/connect.ts@@ -2,7 +2,7 @@ import { createPromptCommandOutput, withPhase, type ChannelSetupLog } from "#setimport { replaceConnectTrigger } from "#setup/connect-provisioning.js";import type { VercelProjectReference } from "#setup/project-resolution.js";import { runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const DISCORD_TRIGGER_PATH = "/eve/v1/discord";diff --git a/packages/eve/src/setup/integrations/github/connect.ts b/packages/eve/src/setup/integrations/github/connect.tsindex 03be247e0..95b6edc91 100644--- a/packages/eve/src/setup/integrations/github/connect.ts+++ b/packages/eve/src/setup/integrations/github/connect.ts@@ -2,7 +2,7 @@ import { createPromptCommandOutput, withPhase, type ChannelSetupLog } from "#setimport { replaceConnectTrigger } from "#setup/connect-provisioning.js";import type { VercelProjectReference } from "#setup/project-resolution.js";import { runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const GITHUB_TRIGGER_PATH = "/eve/v1/github";diff --git a/packages/eve/src/setup/integrations/linear/connect.ts b/packages/eve/src/setup/integrations/linear/connect.tsindex aedd514b4..8d732fdbc 100644--- a/packages/eve/src/setup/integrations/linear/connect.ts+++ b/packages/eve/src/setup/integrations/linear/connect.ts@@ -2,7 +2,7 @@ import { createPromptCommandOutput, withPhase, type ChannelSetupLog } from "#setimport { replaceConnectTrigger } from "#setup/connect-provisioning.js";import type { VercelProjectReference } from "#setup/project-resolution.js";import { runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const LINEAR_TRIGGER_PATH = "/eve/v1/linear";const LINEAR_AGENT_SESSION_TRIGGER_EVENT = "AgentSessionEvent";diff --git a/packages/eve/src/setup/integrations/linq/connect.ts b/packages/eve/src/setup/integrations/linq/connect.tsindex d05b8a0ef..88f5dd8e1 100644--- a/packages/eve/src/setup/integrations/linq/connect.ts+++ b/packages/eve/src/setup/integrations/linq/connect.ts@@ -8,7 +8,7 @@ import {runVercelCaptureStdout,type RunVercelCaptureResult,} from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const LINQ_TRIGGER_PATH = "/eve/v1/linq";export const LINQ_TRIGGER_EVENTS = ["message.received", "reaction.added", "reaction.removed"];diff --git a/packages/eve/src/setup/integrations/photon/connect.ts b/packages/eve/src/setup/integrations/photon/connect.tsindex 7ae673d1d..5400c3a7f 100644--- a/packages/eve/src/setup/integrations/photon/connect.ts+++ b/packages/eve/src/setup/integrations/photon/connect.ts@@ -7,7 +7,7 @@ import {runVercelCaptureStdout,type RunVercelCaptureResult,} from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const PHOTON_CONNECT_SERVICE = "photon";export const PHOTON_CONNECTOR_TYPE = "photon";diff --git a/packages/eve/src/setup/integrations/teams/connect.ts b/packages/eve/src/setup/integrations/teams/connect.tsindex dfaf14232..1828bf49c 100644--- a/packages/eve/src/setup/integrations/teams/connect.ts+++ b/packages/eve/src/setup/integrations/teams/connect.ts@@ -1,7 +1,7 @@import { createPromptCommandOutput, withPhase, type ChannelSetupLog } from "#setup/cli/index.js";import type { VercelProjectReference } from "#setup/project-resolution.js";import { runVercel, runVercelCaptureStdout } from "#setup/primitives/run-vercel.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";export const TEAMS_TRIGGER_PATH = "/eve/v1/teams";diff --git a/packages/eve/src/setup/project-resolution.ts b/packages/eve/src/setup/project-resolution.tsindex 8a3c34041..f693e0bbd 100644--- a/packages/eve/src/setup/project-resolution.ts+++ b/packages/eve/src/setup/project-resolution.ts@@ -1,6 +1,6 @@import { stat } from "node:fs/promises";import { join } from "node:path";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import {readVercelProjectLink,diff --git a/packages/eve/src/setup/slack-connect.ts b/packages/eve/src/setup/slack-connect.tsindex 07feb0fb8..fa3bca20f 100644--- a/packages/eve/src/setup/slack-connect.ts+++ b/packages/eve/src/setup/slack-connect.ts@@ -6,7 +6,7 @@* focused on flow and these stay trivially testable.*/-import { z } from "zod";+import { z } from "#compiled/zod/index.js";interface VercelConnectListClient {uid?: unknown;diff --git a/packages/eve/src/setup/vercel-api-failure.ts b/packages/eve/src/setup/vercel-api-failure.tsindex e2deed664..5a4f76bb7 100644--- a/packages/eve/src/setup/vercel-api-failure.ts+++ b/packages/eve/src/setup/vercel-api-failure.ts@@ -1,5 +1,5 @@import type { VercelCaptureFailure, VercelCaptureResult } from "#setup/primitives/index.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";const VercelApiErrorSchema = z.object({error: zdiff --git a/packages/eve/src/setup/vercel-deployment.ts b/packages/eve/src/setup/vercel-deployment.tsindex fc9210169..e5acb8a1d 100644--- a/packages/eve/src/setup/vercel-deployment.ts+++ b/packages/eve/src/setup/vercel-deployment.ts@@ -1,6 +1,6 @@import { captureVercel, type VercelCaptureFailure } from "#setup/primitives/index.js";import type { VercelProjectReference } from "#setup/project-resolution.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import {isForbiddenApiFailure,diff --git a/packages/eve/src/setup/vercel-project-api.ts b/packages/eve/src/setup/vercel-project-api.tsindex c341cbcfd..4ceff5566 100644--- a/packages/eve/src/setup/vercel-project-api.ts+++ b/packages/eve/src/setup/vercel-project-api.ts@@ -1,6 +1,6 @@import { HumanActionRequiredError } from "#setup/human-action.js";import { captureVercel, type VercelCaptureFailure } from "#setup/primitives/index.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import { isForbiddenApiFailure } from "./vercel-api-failure.js";import type { VercelProjectOperationOptions } from "./project-resolution.js";diff --git a/packages/eve/src/setup/vercel-project-framework.ts b/packages/eve/src/setup/vercel-project-framework.tsindex 77a4a2ff8..a0fd26a53 100644--- a/packages/eve/src/setup/vercel-project-framework.ts+++ b/packages/eve/src/setup/vercel-project-framework.ts@@ -3,7 +3,7 @@ import { captureVercel } from "#setup/primitives/index.js";import type { Dirent } from "node:fs";import * as fs from "node:fs/promises";import { extname, join } from "node:path";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import { readProjectLink } from "./project-resolution.js";import type { Prompter } from "./prompter.js";diff --git a/packages/eve/src/setup/vercel-project.ts b/packages/eve/src/setup/vercel-project.tsindex 67eb4afaf..c79173c3e 100644--- a/packages/eve/src/setup/vercel-project.ts+++ b/packages/eve/src/setup/vercel-project.ts@@ -2,7 +2,7 @@ import { createPromptCommandOutput, whimsyFor } from "#setup/cli/index.js";import { HumanActionRequiredError } from "#setup/human-action.js";import { captureVercel, runVercel, type VercelCaptureFailure } from "#setup/primitives/index.js";import pc from "#compiled/picocolors/index.js";-import { z } from "zod";+import { z } from "#compiled/zod/index.js";import {assertNoLegacyProjectLinkDirectory,diff --git a/packages/eve/src/shared/connection-types.ts b/packages/eve/src/shared/connection-types.tsindex 67dd5f89e..bd6d2c41a 100644--- a/packages/eve/src/shared/connection-types.ts+++ b/packages/eve/src/shared/connection-types.ts@@ -6,8 +6,6 @@* protocol-specific implementation such as MCP.*/-import type { ToolSet } from "ai";-import type { ConnectionAuthorizationChallenge } from "#connections/errors.js";import type { SessionContext } from "#context/session-context.js";import type { JsonValue } from "#shared/json.js";@@ -469,5 +467,4 @@ export interface ConnectionClient {options: ConnectionToolExecuteOptions,): Promise<unknown>;getToolMetadata(): Promise<readonly ConnectionToolMetadata[]>;- getTools(): Promise<ToolSet>;}diff --git a/packages/eve/src/tasks/json.test.ts b/packages/eve/src/tasks/json.test.tsindex c8570283f..ec36a1cf5 100644--- a/packages/eve/src/tasks/json.test.ts+++ b/packages/eve/src/tasks/json.test.ts@@ -43,7 +43,7 @@ describe("taskCancel.outputSchema", () => {it("preserves the broad task-control output contract", () => {expect(taskCancel.outputSchema).toBe(TASK_VIEWS_OUTPUT_SCHEMA);expect(- TASK_VIEWS_OUTPUT_SCHEMA.parse({+ TASK_VIEWS_OUTPUT_SCHEMA["~standard"].validate({tasks: [{inputRequests: [{ prompt: "Choose" }],@@ -54,6 +54,6 @@ describe("taskCancel.outputSchema", () => {},],}),- ).toMatchObject({ tasks: [{ status: "working", taskId: "task-1" }] });+ ).toMatchObject({ value: { tasks: [{ status: "working", taskId: "task-1" }] } });});});diff --git a/packages/eve/src/tasks/json.ts b/packages/eve/src/tasks/json.tsindex 0c36b2291..86ae7fcd8 100644--- a/packages/eve/src/tasks/json.ts+++ b/packages/eve/src/tasks/json.ts@@ -1,9 +1,47 @@-import type { z } from "#compiled/zod/index.js";+import { z } from "#compiled/zod/index.js";import type { JsonValue } from "#shared/json.js";-import { TASK_VIEW_JSON_SCHEMA } from "#tools/framework/task-contract.js";+import { jsonValueSchema } from "#shared/json-schemas.js";import type { TaskView } from "#tasks/types.js";+const taskMetadataJsonSchema = z.object({+ agentId: z.string().optional(),+ kind: z.string(),+ mode: z.enum(["local", "remote"]).optional(),+ name: z.string(),+});++const taskOutputJsonSchema = z.object({+ data: jsonValueSchema,+ type: z.enum(["result", "error"]),+});++const taskViewJsonBaseShape = {+ metadata: taskMetadataJsonSchema,+ taskId: z.string(),+};++/** Strict model-visible task projection. */+const TASK_VIEW_JSON_SCHEMA = z.discriminatedUnion("status", [+ z.object({ ...taskViewJsonBaseShape, status: z.literal("working") }),+ z.object({+ ...taskViewJsonBaseShape,+ inputRequests: z.array(jsonValueSchema).readonly(),+ status: z.literal("input_required"),+ }),+ z.object({+ ...taskViewJsonBaseShape,+ lastOutput: taskOutputJsonSchema.extend({ type: z.literal("result") }),+ status: z.literal("completed"),+ }),+ z.object({+ ...taskViewJsonBaseShape,+ lastOutput: taskOutputJsonSchema.extend({ type: z.literal("error") }),+ status: z.literal("failed"),+ }),+ z.object({ ...taskViewJsonBaseShape, status: z.literal("cancelled") }),+]);+/*** Model-visible task view, inferred from {@link TASK_VIEW_JSON_SCHEMA}.*diff --git a/packages/eve/src/tools/framework/agent-contract.ts b/packages/eve/src/tools/framework/agent-contract.tsindex e07957f3f..2cbed24ed 100644--- a/packages/eve/src/tools/framework/agent-contract.ts+++ b/packages/eve/src/tools/framework/agent-contract.ts@@ -1,4 +1,5 @@-import { z } from "#compiled/zod/index.js";+import type { JsonObject } from "#shared/json.js";+import { defineJsonSchema } from "#tools/schema.js";export const AGENT_TOOL_NAME = "agent";@@ -9,23 +10,31 @@ export const AGENT_TOOL_DESCRIPTION = ["A new child has fresh history and state but reuses your tools and sandbox, so include essential context in `message` and give parallel writers non-overlapping scopes.",].join(" ");-export const SUBAGENT_TOOL_INPUT_SCHEMA = z.strictObject({- agentId: z- .string()- .nullable()- .describe(- "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",- )- .optional(),- message: z- .string()- .describe(- "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",- ),- outputSchema: z- .looseObject({})- .describe(- "Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The subagent must match a provided schema, and that structured output becomes the tool result.",- )- .optional(),+export interface SubagentToolInput {+ agentId?: string | null;+ message: string;+ outputSchema?: JsonObject;+}++export const SUBAGENT_TOOL_INPUT_SCHEMA = defineJsonSchema<SubagentToolInput>({+ type: "object",+ properties: {+ agentId: {+ type: ["string", "null"],+ description:+ "The id of an existing agent from the <agents> list or a task receipt. A message to a busy agent steers it: its previous task is cancelled and the updated work runs in the same child session. Omit this field (or pass null or an empty string) to start a new agent.",+ },+ message: {+ type: "string",+ description:+ "The message to send to the subagent. Provide all context the subagent needs to complete the task; the subagent does not see the parent's history.",+ },+ outputSchema: {+ type: "object",+ description:+ "Only provide a non-empty JSON Schema when the caller explicitly requests structured output; otherwise omit this field. The subagent must match a provided schema, and that structured output becomes the tool result.",+ },+ },+ required: ["message"],+ additionalProperties: false,});diff --git a/packages/eve/src/tools/framework/agent.ts b/packages/eve/src/tools/framework/agent.tsindex 23fd58f30..73b8d6657 100644--- a/packages/eve/src/tools/framework/agent.ts+++ b/packages/eve/src/tools/framework/agent.ts@@ -1,10 +1,12 @@-import type { z } from "#compiled/zod/index.js";import { stampToolDefinition } from "#tools/definition.js";import {AGENT_TOOL_DESCRIPTION,SUBAGENT_TOOL_INPUT_SCHEMA,} from "#tools/framework/agent-contract.js";-import { SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA } from "#tools/framework/task-contract.js";+import {+ SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,+ type SubagentTaskReceipt,+} from "#tools/framework/task-contract.js";import { attachToolBehavior } from "#tools/behavior.js";export const agent = attachToolBehavior(@@ -14,7 +16,7 @@ export const agent = attachToolBehavior(execution: "background",inputSchema: SUBAGENT_TOOL_INPUT_SCHEMA,outputSchema: SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA,- execute(): z.infer<typeof SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA> {+ execute(): SubagentTaskReceipt {throw new Error('The framework "agent" tool was executed directly. It must be resolved through the runtime tool registry, which dispatches it to the shared subagent workflow.',);diff --git a/packages/eve/src/tools/framework/task-contract.ts b/packages/eve/src/tools/framework/task-contract.tsindex d6972320e..bb096c805 100644--- a/packages/eve/src/tools/framework/task-contract.ts+++ b/packages/eve/src/tools/framework/task-contract.ts@@ -1,81 +1,81 @@-import { z } from "#compiled/zod/index.js";-import { jsonValueSchema } from "#shared/json-schemas.js";+import { defineJsonSchema } from "#tools/schema.js";export const TASK_CANCEL_TOOL_NAME = "task_cancel";/** Framework task-control tool names lowered by the runtime. */export const TASK_TOOL_NAMES: ReadonlySet<string> = new Set([TASK_CANCEL_TOOL_NAME]);-const TASK_IDS_SCHEMA = z- .array(z.string().min(1))- .min(1)- .describe("Task ids from earlier subagent task receipts.");--export const TASK_CANCEL_INPUT_SCHEMA = z.strictObject({ taskIds: TASK_IDS_SCHEMA });--const taskMetadataJsonSchema = z.object({- agentId: z.string().optional(),- kind: z.string(),- mode: z.enum(["local", "remote"]).optional(),- name: z.string(),+export const TASK_CANCEL_INPUT_SCHEMA = defineJsonSchema<{ taskIds: string[] }>({+ type: "object",+ properties: {+ taskIds: {+ type: "array",+ minItems: 1,+ items: { type: "string", minLength: 1 },+ description: "Task ids from earlier subagent task receipts.",+ },+ },+ required: ["taskIds"],+ additionalProperties: false,});-const taskOutputJsonSchema = z.object({- data: jsonValueSchema,- type: z.enum(["result", "error"]),+/**+ * Broad schema advertised by task-control tool outputs. Objects stay open so+ * task metadata can grow without breaking consumers of the output contract.+ */+export const TASK_VIEWS_OUTPUT_SCHEMA = defineJsonSchema({+ type: "object",+ properties: {+ tasks: {+ type: "array",+ items: {+ type: "object",+ properties: {+ inputRequests: { type: "array", items: {} },+ lastOutput: {+ type: "object",+ properties: {+ data: {},+ type: { type: "string", enum: ["result", "error"] },+ },+ required: ["data", "type"],+ },+ metadata: {+ type: "object",+ properties: {+ agentId: { type: "string" },+ kind: { type: "string" },+ mode: { type: "string", enum: ["local", "remote"] },+ name: { type: "string" },+ },+ required: ["kind", "name"],+ },+ status: {+ type: "string",+ enum: ["working", "input_required", "completed", "failed", "cancelled"],+ },+ taskId: { type: "string" },+ },+ required: ["metadata", "status", "taskId"],+ },+ },+ },+ required: ["tasks"],});-const taskViewJsonBaseShape = {- metadata: taskMetadataJsonSchema,- taskId: z.string(),-};--/** Strict model-visible task projection. */-export const TASK_VIEW_JSON_SCHEMA = z.discriminatedUnion("status", [- z.object({ ...taskViewJsonBaseShape, status: z.literal("working") }),- z.object({- ...taskViewJsonBaseShape,- inputRequests: z.array(jsonValueSchema).readonly(),- status: z.literal("input_required"),- }),- z.object({- ...taskViewJsonBaseShape,- lastOutput: taskOutputJsonSchema.extend({ type: z.literal("result") }),- status: z.literal("completed"),- }),- z.object({- ...taskViewJsonBaseShape,- lastOutput: taskOutputJsonSchema.extend({ type: z.literal("error") }),- status: z.literal("failed"),- }),- z.object({ ...taskViewJsonBaseShape, status: z.literal("cancelled") }),-]);--/** Broad schema advertised by task-control tool outputs. */-export const TASK_VIEW_OUTPUT_SCHEMA = z.object({- inputRequests: z.array(z.unknown()).optional(),- lastOutput: z- .object({- data: z.unknown(),- type: z.enum(["result", "error"]),- })- .optional(),- metadata: z.object({- agentId: z.string().optional(),- kind: z.string(),- mode: z.enum(["local", "remote"]).optional(),- name: z.string(),- }),- status: z.enum(["working", "input_required", "completed", "failed", "cancelled"]),- taskId: z.string(),-});--export const TASK_VIEWS_OUTPUT_SCHEMA = z.object({- tasks: z.array(TASK_VIEW_OUTPUT_SCHEMA),-});+export interface SubagentTaskReceipt {+ agentId: string;+ status: "working";+ taskId: string;+}-export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = z.strictObject({- agentId: z.string(),- status: z.literal("working"),- taskId: z.string(),+export const SUBAGENT_TASK_RECEIPT_OUTPUT_SCHEMA = defineJsonSchema<SubagentTaskReceipt>({+ type: "object",+ properties: {+ agentId: { type: "string" },+ status: { type: "string", const: "working" },+ taskId: { type: "string" },+ },+ required: ["agentId", "status", "taskId"],+ additionalProperties: false,});diff --git a/packages/eve/src/tools/provided/agent-router.test.ts b/packages/eve/src/tools/provided/agent-router.test.tsindex c22f6c546..d1bc5e665 100644--- a/packages/eve/src/tools/provided/agent-router.test.ts+++ b/packages/eve/src/tools/provided/agent-router.test.ts@@ -29,8 +29,8 @@ describe("agentRouter", () => {properties: { outputSchema: { type: "object" } },});expect(JSON.stringify(serialized)).not.toContain('"propertyNames"');- expect(() =>- AGENT_ROUTER_INPUT_SCHEMA.parse({+ expect(+ AGENT_ROUTER_INPUT_SCHEMA["~standard"].validate({message: "Return a structured result",outputSchema: {$defs: { answer: { type: "string" } },@@ -38,7 +38,7 @@ describe("agentRouter", () => {type: "object",},}),- ).not.toThrow();+ ).not.toHaveProperty("issues");});it("routes through all workflow agent descriptions", async () => {diff --git a/packages/eve/src/tools/provided/ask-question.test.ts b/packages/eve/src/tools/provided/ask-question.test.tsindex 667e11d9f..9568f1b86 100644--- a/packages/eve/src/tools/provided/ask-question.test.ts+++ b/packages/eve/src/tools/provided/ask-question.test.ts@@ -11,6 +11,12 @@ import {import { askQuestion } from "#tools/provided/ask-question.js";import { isWorkflowToolDefinition } from "#tools/workflow-definition.js";+function accepts(value: unknown): boolean {+ const result = ASK_QUESTION_INPUT_SCHEMA["~standard"].validate(value);+ if (result instanceof Promise) throw new Error("Expected synchronous validation.");+ return result.issues === undefined;+}+const colorQuestion = {options: [{ description: "Warm and bold.", label: "Red (Recommended)" },@@ -34,36 +40,32 @@ describe("askQuestion", () => {});it("accepts one question with at most three label and description options", () => {- expect(ASK_QUESTION_INPUT_SCHEMA.safeParse(colorQuestion).success).toBe(true);- expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({ question: "What should we call it?" }).success,- ).toBe(true);+ expect(accepts(colorQuestion)).toBe(true);+ expect(accepts({ question: "What should we call it?" })).toBe(true);expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({+ accepts({options: [colorQuestion.options[0]],question: "Only one choice?",- }).success,+ }),).toBe(false);expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({+ accepts({options: [...colorQuestion.options, ...colorQuestion.options],question: "Too many choices?",- }).success,+ }),).toBe(false);expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({+ accepts({options: colorQuestion.options.map((option, index) => ({ ...option, id: `${index}` })),question: colorQuestion.question,- }).success,- ).toBe(false);- expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({ ...colorQuestion, questions: [colorQuestion] }).success,+ }),).toBe(false);+ expect(accepts({ ...colorQuestion, questions: [colorQuestion] })).toBe(false);expect(- ASK_QUESTION_INPUT_SCHEMA.safeParse({+ accepts({options: [colorQuestion.options[1], colorQuestion.options[1]],question: "Blue or blue?",- }).success,+ }),).toBe(false);});});diff --git a/packages/eve/src/tools/provided/bash.ts b/packages/eve/src/tools/provided/bash.tsindex 2de339173..bf6fe9ce8 100644--- a/packages/eve/src/tools/provided/bash.ts+++ b/packages/eve/src/tools/provided/bash.ts@@ -1,29 +1,46 @@-import { z } from "#compiled/zod/index.js";-import { executeBashOnSandbox, type BashInput } from "#execution/sandbox/bash.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface BashToolInput {+ command: string;+}++export interface BashToolOutput {+ exitCode: number;+ stderr: string;+ stdout: string;+ truncated: boolean;+}/*** Input schema for the provided `bash` tool.*/-export const BASH_INPUT_SCHEMA = z.strictObject({- command: z.string().describe("The shell command to execute."),+export const BASH_INPUT_SCHEMA = defineJsonSchema<BashToolInput>({+ type: "object",+ properties: {+ command: { type: "string", description: "The shell command to execute." },+ },+ required: ["command"],+ additionalProperties: false,});/*** Output schema for the provided `bash` tool.*/-export const BASH_OUTPUT_SCHEMA = z.strictObject({- exitCode: z.number(),- stderr: z.string(),- stdout: z.string(),- truncated: z.boolean(),+export const BASH_OUTPUT_SCHEMA = defineJsonSchema<BashToolOutput>({+ type: "object",+ properties: {+ exitCode: { type: "number" },+ stderr: { type: "string" },+ stdout: { type: "string" },+ truncated: { type: "boolean" },+ },+ required: ["exitCode", "stderr", "stdout", "truncated"],+ additionalProperties: false,});-export type BashToolInput = z.infer<typeof BASH_INPUT_SCHEMA>;-export type BashToolOutput = z.infer<typeof BASH_OUTPUT_SCHEMA>;-/*** Framework-owned executors stay statically imported so hosted server bundles* can trace and rewrite them into deployable output chunks.diff --git a/packages/eve/src/tools/provided/glob.ts b/packages/eve/src/tools/provided/glob.tsindex 5af588e69..6faaac663 100644--- a/packages/eve/src/tools/provided/glob.ts+++ b/packages/eve/src/tools/provided/glob.ts@@ -1,45 +1,63 @@-import { z } from "#compiled/zod/index.js";-import { type GlobInput, executeGlobOnSandbox } from "#execution/sandbox/glob-tool.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface GlobToolInput {+ limit?: number;+ path?: string;+ pattern: string;+}++export interface GlobToolOutput {+ content: string;+ count: number;+ path: string;+ truncated: boolean;+}/*** Input schema for the provided `glob` tool.*/-export const GLOB_INPUT_SCHEMA = z.strictObject({- limit: z- .number()- .int()- .min(1)- .max(1000)- .describe("Maximum number of results to return. Defaults to 100.")- .optional(),- path: z- .string()- .describe(- "The directory to search in. Defaults to /workspace. " ++export const GLOB_INPUT_SCHEMA = defineJsonSchema<GlobToolInput>({+ type: "object",+ properties: {+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 1000,+ description: "Maximum number of results to return. Defaults to 100.",+ },+ path: {+ type: "string",+ description:+ "The directory to search in. Defaults to /workspace. " +"Must be an absolute path or begin with $HOME/. Omit to use the default.",- )- .optional(),- pattern: z- .string()- .describe('The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.js").'),+ },+ pattern: {+ type: "string",+ description: 'The glob pattern to match files against (e.g. "**/*.ts", "src/**/*.js").',+ },+ },+ required: ["pattern"],+ additionalProperties: false,});/*** Output schema for the provided `glob` tool.*/-export const GLOB_OUTPUT_SCHEMA = z.strictObject({- content: z.string(),- count: z.number().int(),- path: z.string(),- truncated: z.boolean(),+export const GLOB_OUTPUT_SCHEMA = defineJsonSchema<GlobToolOutput>({+ type: "object",+ properties: {+ content: { type: "string" },+ count: { type: "integer" },+ path: { type: "string" },+ truncated: { type: "boolean" },+ },+ required: ["content", "count", "path", "truncated"],+ additionalProperties: false,});-export type GlobToolInput = z.infer<typeof GLOB_INPUT_SCHEMA>;-export type GlobToolOutput = z.infer<typeof GLOB_OUTPUT_SCHEMA>;-/*** Framework-owned executor that delegates to the default sandbox.*/diff --git a/packages/eve/src/tools/provided/grep.ts b/packages/eve/src/tools/provided/grep.tsindex e2193d555..708b15484 100644--- a/packages/eve/src/tools/provided/grep.ts+++ b/packages/eve/src/tools/provided/grep.ts@@ -1,66 +1,87 @@-import { z } from "#compiled/zod/index.js";-import { type GrepInput, executeGrepOnSandbox } from "#execution/sandbox/grep-tool.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface GrepToolInput {+ context?: number;+ glob?: string;+ ignoreCase?: boolean;+ limit?: number;+ literal?: boolean;+ path?: string;+ pattern: string;+}++export interface GrepToolOutput {+ content: string;+ matchCount: number;+ path: string;+ truncated: boolean;+}/*** Input schema for the provided `grep` tool.*/-export const GREP_INPUT_SCHEMA = z.strictObject({- context: z- .number()- .int()- .min(0)- .describe(- "Number of surrounding context lines to include before and after each match. Defaults to 0.",- )- .optional(),- glob: z.string().describe('Filter files by glob pattern (e.g. "*.ts", "*.{ts,tsx}").').optional(),- ignoreCase: z- .boolean()- .describe("Perform case-insensitive search. Defaults to false.")- .optional(),- limit: z- .number()- .int()- .min(1)- .max(1000)- .describe("Maximum number of matches to return per file. Defaults to 100.")- .optional(),- literal: z- .boolean()- .describe(- "Treat the pattern as a literal string instead of a regular expression. Defaults to false.",- )- .optional(),- path: z- .string()- .describe(- "The directory or file to search in. Defaults to /workspace. " ++export const GREP_INPUT_SCHEMA = defineJsonSchema<GrepToolInput>({+ type: "object",+ properties: {+ context: {+ type: "integer",+ minimum: 0,+ description:+ "Number of surrounding context lines to include before and after each match. Defaults to 0.",+ },+ glob: {+ type: "string",+ description: 'Filter files by glob pattern (e.g. "*.ts", "*.{ts,tsx}").',+ },+ ignoreCase: {+ type: "boolean",+ description: "Perform case-insensitive search. Defaults to false.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 1000,+ description: "Maximum number of matches to return per file. Defaults to 100.",+ },+ literal: {+ type: "boolean",+ description:+ "Treat the pattern as a literal string instead of a regular expression. Defaults to false.",+ },+ path: {+ type: "string",+ description:+ "The directory or file to search in. Defaults to /workspace. " +"Must be an absolute path or begin with $HOME/. Omit to use the default.",- )- .optional(),- pattern: z- .string()- .describe(- 'The regex pattern to search for in file contents (e.g. "log.*Error", "function\\s+\\w+").',- ),+ },+ pattern: {+ type: "string",+ description:+ 'The regex pattern to search for in file contents (e.g. "log.*Error", "function\\s+\\w+").',+ },+ },+ required: ["pattern"],+ additionalProperties: false,});/*** Output schema for the provided `grep` tool.*/-export const GREP_OUTPUT_SCHEMA = z.strictObject({- content: z.string(),- matchCount: z.number().int(),- path: z.string(),- truncated: z.boolean(),+export const GREP_OUTPUT_SCHEMA = defineJsonSchema<GrepToolOutput>({+ type: "object",+ properties: {+ content: { type: "string" },+ matchCount: { type: "integer" },+ path: { type: "string" },+ truncated: { type: "boolean" },+ },+ required: ["content", "matchCount", "path", "truncated"],+ additionalProperties: false,});-export type GrepToolInput = z.infer<typeof GREP_INPUT_SCHEMA>;-export type GrepToolOutput = z.infer<typeof GREP_OUTPUT_SCHEMA>;-/*** Framework-owned executor that delegates to the default sandbox.*/diff --git a/packages/eve/src/tools/provided/read-file.ts b/packages/eve/src/tools/provided/read-file.tsindex 00f956e73..c12769eaf 100644--- a/packages/eve/src/tools/provided/read-file.ts+++ b/packages/eve/src/tools/provided/read-file.ts@@ -1,44 +1,63 @@-import { z } from "#compiled/zod/index.js";-import { type ReadFileInput, executeReadFileOnSandbox } from "#execution/sandbox/read-file.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface ReadFileToolInput {+ filePath: string;+ limit?: number;+ offset?: number;+}++export interface ReadFileToolOutput {+ content: string;+ nextOffset?: number;+ path: string;+ totalLines: number;+ truncated: boolean;+}/*** Input schema for the provided `read_file` tool.*/-export const READ_FILE_INPUT_SCHEMA = z.strictObject({- filePath: z- .string()- .describe("The absolute path to the file to read. A leading $HOME is supported."),- limit: z- .number()- .int()- .min(1)- .describe("Maximum number of lines to return. Defaults to 2000.")- .optional(),- offset: z- .number()- .int()- .min(1)- .describe("1-based line number to start from. Defaults to 1.")- .optional(),+export const READ_FILE_INPUT_SCHEMA = defineJsonSchema<ReadFileToolInput>({+ type: "object",+ properties: {+ filePath: {+ type: "string",+ description: "The absolute path to the file to read. A leading $HOME is supported.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ description: "Maximum number of lines to return. Defaults to 2000.",+ },+ offset: {+ type: "integer",+ minimum: 1,+ description: "1-based line number to start from. Defaults to 1.",+ },+ },+ required: ["filePath"],+ additionalProperties: false,});/*** Output schema for the provided `read_file` tool.*/-export const READ_FILE_OUTPUT_SCHEMA = z.strictObject({- content: z.string(),- nextOffset: z.number().int().min(1).optional(),- path: z.string(),- totalLines: z.number().int().min(0),- truncated: z.boolean(),+export const READ_FILE_OUTPUT_SCHEMA = defineJsonSchema<ReadFileToolOutput>({+ type: "object",+ properties: {+ content: { type: "string" },+ nextOffset: { type: "integer", minimum: 1 },+ path: { type: "string" },+ totalLines: { type: "integer", minimum: 0 },+ truncated: { type: "boolean" },+ },+ required: ["content", "path", "totalLines", "truncated"],+ additionalProperties: false,});-export type ReadFileToolInput = z.infer<typeof READ_FILE_INPUT_SCHEMA>;-export type ReadFileToolOutput = z.infer<typeof READ_FILE_OUTPUT_SCHEMA>;-/*** Framework-owned executor that delegates to the default sandbox.*/diff --git a/packages/eve/src/tools/provided/web-fetch.ts b/packages/eve/src/tools/provided/web-fetch.tsindex dd08d7196..7c8b70b70 100644--- a/packages/eve/src/tools/provided/web-fetch.ts+++ b/packages/eve/src/tools/provided/web-fetch.ts@@ -1,29 +1,54 @@-import { z } from "#compiled/zod/index.js";-import { type WebFetchInput, executeWebFetchTool } from "#execution/web-fetch/execute.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";-export const WEB_FETCH_INPUT_SCHEMA = z.strictObject({- format: z- .enum(["markdown", "text", "html"])- .describe(- 'The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".',- )- .optional(),- timeout: z.number().describe("Optional timeout in seconds. Defaults to 30, max 120.").optional(),- url: z.string().describe("The fully-formed URL to fetch content from. Must start with https://."),-});+export interface WebFetchToolInput {+ format?: "markdown" | "text" | "html";+ timeout?: number;+ url: string;+}++export interface WebFetchToolOutput {+ content: string;+ contentType: string;+ truncated: boolean;+ url: string;+}-export const WEB_FETCH_OUTPUT_SCHEMA = z.strictObject({- content: z.string(),- contentType: z.string(),- truncated: z.boolean(),- url: z.string(),+export const WEB_FETCH_INPUT_SCHEMA = defineJsonSchema<WebFetchToolInput>({+ type: "object",+ properties: {+ format: {+ type: "string",+ enum: ["markdown", "text", "html"],+ description:+ 'The format to return the content in (text, markdown, or html). HTML responses are automatically converted to the requested format. Defaults to "markdown".',+ },+ timeout: {+ type: "number",+ description: "Optional timeout in seconds. Defaults to 30, max 120.",+ },+ url: {+ type: "string",+ description: "The fully-formed URL to fetch content from. Must start with https://.",+ },+ },+ required: ["url"],+ additionalProperties: false,});-export type WebFetchToolInput = z.infer<typeof WEB_FETCH_INPUT_SCHEMA>;-export type WebFetchToolOutput = z.infer<typeof WEB_FETCH_OUTPUT_SCHEMA>;+export const WEB_FETCH_OUTPUT_SCHEMA = defineJsonSchema<WebFetchToolOutput>({+ type: "object",+ properties: {+ content: { type: "string" },+ contentType: { type: "string" },+ truncated: { type: "boolean" },+ url: { type: "string" },+ },+ required: ["content", "contentType", "truncated", "url"],+ additionalProperties: false,+});export const webFetch: ToolDefinition<WebFetchToolInput, WebFetchToolOutput> = defineTool({label: { start: (input) => toolLabel("Fetch", input.url) },diff --git a/packages/eve/src/tools/provided/workflow.ts b/packages/eve/src/tools/provided/workflow.tsindex 2d42497fa..8b1e6845c 100644--- a/packages/eve/src/tools/provided/workflow.ts+++ b/packages/eve/src/tools/provided/workflow.ts@@ -1,5 +1,3 @@-import { z } from "#compiled/zod/index.js";-import {DEFAULT_WORKFLOW_PROGRAM_MAX_SUBAGENTS,parseWorkflowProgramOptions,@@ -11,6 +9,7 @@ import {type BlockingWorkflowToolDefinition,} from "#tools/workflow-definition.js";import { attachWorkflowProgramOptions } from "#tools/workflow-program-input.js";+import { defineJsonSchema } from "#tools/schema.js";export interface WorkflowToolOptions {/** Maximum child-agent calls per program, from 1 to 128. Defaults to 100. */@@ -26,12 +25,16 @@ export type WorkflowTool = BlockingWorkflowToolDefinition<WorkflowToolInput, Jsoconst workflowProgramAgentContract ="Call ctx.agent(name, { message: string, agentId?: string, outputSchema?: object }). It resolves directly to the child's JSON-serializable output; when outputSchema is provided, the output matches that schema. It does not return an agent metadata wrapper. Use an agentId from the conversation's <agents> block to continue that child. The owning agent resolves the target and applies its existing availability and authorization checks.";-const workflowInputSchema = z.strictObject({- js: z- .string()- .describe(- `JavaScript statements executed inside an async function. Supply only the body, without a surrounding function declaration or arrow function. ${workflowProgramAgentContract} Return one JSON-serializable value.`,- ),+const workflowInputSchema = defineJsonSchema<WorkflowToolInput>({+ type: "object",+ properties: {+ js: {+ type: "string",+ description: `JavaScript statements executed inside an async function. Supply only the body, without a surrounding function declaration or arrow function. ${workflowProgramAgentContract} Return one JSON-serializable value.`,+ },+ },+ required: ["js"],+ additionalProperties: false,});/** Defines a model-facing workflow tool backed by isolated runtime JavaScript. */diff --git a/packages/eve/src/tools/provided/write-file.ts b/packages/eve/src/tools/provided/write-file.tsindex 146b69e0f..6b6880b71 100644--- a/packages/eve/src/tools/provided/write-file.ts+++ b/packages/eve/src/tools/provided/write-file.ts@@ -1,30 +1,47 @@-import { z } from "#compiled/zod/index.js";-import { type WriteFileInput, executeWriteFileOnSandbox } from "#execution/sandbox/write-file.js";import { toolLabel } from "#tools/tool-label.js";import { defineTool, type ToolDefinition } from "#tools/definition.js";+import { defineJsonSchema } from "#tools/schema.js";++export interface WriteFileToolInput {+ content: string;+ filePath: string;+}++export interface WriteFileToolOutput {+ existed: boolean;+ path: string;+}/*** Input schema for the provided `write_file` tool.*/-export const WRITE_FILE_INPUT_SCHEMA = z.strictObject({- content: z.string().describe("Complete replacement file contents."),- filePath: z- .string()- .describe("The absolute path to the file to write. A leading $HOME is supported."),+export const WRITE_FILE_INPUT_SCHEMA = defineJsonSchema<WriteFileToolInput>({+ type: "object",+ properties: {+ content: { type: "string", description: "Complete replacement file contents." },+ filePath: {+ type: "string",+ description: "The absolute path to the file to write. A leading $HOME is supported.",+ },+ },+ required: ["content", "filePath"],+ additionalProperties: false,});/*** Output schema for the provided `write_file` tool.*/-export const WRITE_FILE_OUTPUT_SCHEMA = z.strictObject({- existed: z.boolean(),- path: z.string(),+export const WRITE_FILE_OUTPUT_SCHEMA = defineJsonSchema<WriteFileToolOutput>({+ type: "object",+ properties: {+ existed: { type: "boolean" },+ path: { type: "string" },+ },+ required: ["existed", "path"],+ additionalProperties: false,});-export type WriteFileToolInput = z.infer<typeof WRITE_FILE_INPUT_SCHEMA>;-export type WriteFileToolOutput = z.infer<typeof WRITE_FILE_OUTPUT_SCHEMA>;-/*** Framework-owned executor that delegates to the default sandbox.*/diff --git a/packages/eve/src/tools/schema.test.ts b/packages/eve/src/tools/schema.test.tsindex dbfaf6705..f158ae7a1 100644--- a/packages/eve/src/tools/schema.test.ts+++ b/packages/eve/src/tools/schema.test.ts@@ -1,126 +1,472 @@-import { asSchema } from "ai";-import { describe, expect, it } from "vitest";+import { asSchema, jsonSchema, TypeValidationError } from "ai";+import { afterEach, describe, expect, it, vi } from "vitest";import { z } from "zod";import { z as z3 } from "zod/v3";import {UNSPECIFIED_INPUT_SCHEMA,+ defineJsonSchema,isToolSchema,serializeInputSchema,serializeOutputSchema,toInputSchema,+ toModelSchema,toOutputSchema,} from "#tools/schema.js";-describe("ToolSchema", () => {- it("rehydrates and validates serialized JSON Schema", async () => {- const schema = toInputSchema({+const AI_SDK_SCHEMA = Symbol.for("vercel.ai.schema");++function validate(schema: object, value: unknown) {+ const result = (schema as ReturnType<typeof defineJsonSchema>)["~standard"].validate(value);+ if (result instanceof Promise) throw new Error("Expected synchronous validation.");+ return result;+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe("defineJsonSchema", () => {+ it("validates values against the JSON Schema", () => {+ const schema = defineJsonSchema({additionalProperties: false,- properties: {- prompt: { type: "string" },- },+ properties: { prompt: { type: "string" } },required: ["prompt"],type: "object",});- const validate = asSchema(schema).validate;- await expect(validate?.({})).resolves.toMatchObject({ success: false });- await expect(validate?.({ prompt: 42 })).resolves.toMatchObject({ success: false });- await expect(validate?.({ extra: true, prompt: "Choose." })).resolves.toMatchObject({- success: false,+ expect(validate(schema, {})).toEqual({+ issues: [{ message: 'Instance does not have required property "prompt".' }],});- await expect(validate?.({ prompt: "Choose." })).resolves.toEqual({- success: true,- value: { prompt: "Choose." },+ expect(validate(schema, { prompt: 42 })).toEqual({+ issues: [+ { message: 'Instance type "number" is invalid. Expected "string".', path: ["prompt"] },+ ],});+ expect(validate(schema, { extra: true, prompt: "Choose." })).toHaveProperty("issues");+ expect(validate(schema, { prompt: "Choose." })).toEqual({ value: { prompt: "Choose." } });});- it("preserves JSON Schema constraints", async () => {- const schema = toInputSchema({- items: { type: "string" },- maxItems: 1,- type: "array",- });+ it("advertises the source schema verbatim through fresh copies", () => {+ const source = {+ anyOf: [{ required: ["page_id"] }, { required: ["data_source_id"] }],+ properties: {+ data_source_id: { type: "string" },+ page_id: { format: "uuid", type: "string" },+ },+ type: "object",+ };+ const schema = defineJsonSchema(source);+ const emitted = serializeInputSchema(schema) as Record<string, unknown>;++ expect(emitted).toEqual(source);+ expect(emitted).not.toBe(source);+ (emitted as { type: string }).type = "mutated";+ expect(serializeOutputSchema(schema)).toEqual(source);+ });- await expect(asSchema(schema).validate?.(["one", "too many"])).resolves.toMatchObject({- success: false,+ it("enforces composition keywords that tool servers commonly emit", () => {+ const schema = defineJsonSchema({+ properties: {+ pages: {+ items: {+ anyOf: [{ required: ["page_id"] }, { required: ["title"] }],+ properties: { page_id: { type: "string" }, title: { type: "string" } },+ type: "object",+ },+ type: "array",+ },+ properties: {+ additionalProperties: { type: ["string", "number", "null"] },+ type: "object",+ },+ target: {+ allOf: [+ { properties: { id: { type: "string" } }, required: ["id"], type: "object" },+ { properties: { kind: { enum: ["page", "database"] } }, type: "object" },+ ],+ },+ variant: {+ oneOf: [+ { properties: { mode: { const: "a" } }, required: ["mode"], type: "object" },+ { properties: { mode: { const: "b" } }, required: ["mode"], type: "object" },+ ],+ },+ },+ patternProperties: { "^x-": { type: "string" } },+ type: "object",});++ expect(+ validate(schema, {+ pages: [{ page_id: "1f2e3d4c5b6a79881f2e3d4c5b6a7988" }, { title: "Notes" }],+ properties: { Owner: "Bob", Points: 3, Status: null },+ target: { id: "db-1", kind: "database" },+ variant: { mode: "b" },+ "x-trace": "abc",+ }),+ ).toHaveProperty("value");+ expect(validate(schema, { pages: [{}] })).toHaveProperty("issues");+ expect(validate(schema, { properties: { Owner: {} } })).toHaveProperty("issues");+ expect(validate(schema, { target: { kind: "page" } })).toHaveProperty("issues");+ expect(validate(schema, { variant: { mode: "c" } })).toHaveProperty("issues");+ expect(validate(schema, { "x-trace": 1 })).toHaveProperty("issues");});- it("rehydrates draft 2020-12 $defs references with real validation", async () => {- const schema = toInputSchema({+ it("resolves $defs, definitions, and inline JSON Pointer references", () => {+ const schema = defineJsonSchema({$defs: { item: { type: "string" } },- properties: { item: { $ref: "#/$defs/item" } },- required: ["item"],+ definitions: { count: { type: "integer" } },+ properties: {+ count: { $ref: "#/definitions/count" },+ item: { $ref: "#/$defs/item" },+ same: { $ref: "#/properties/item" },+ },type: "object",});- const validate = asSchema(schema).validate;- await expect(validate?.({ item: 42 })).resolves.toMatchObject({ success: false });- await expect(validate?.({ item: "ok" })).resolves.toMatchObject({ success: true });+ expect(validate(schema, { count: 1, item: "ok", same: "ok" })).toHaveProperty("value");+ expect(validate(schema, { item: 42 })).toHaveProperty("issues");+ expect(validate(schema, { count: 1.5 })).toHaveProperty("issues");+ expect(validate(schema, { same: 42 })).toHaveProperty("issues");});- it("degrades schemas outside zod's conversion subset to validation-free passthrough", async () => {- // Valid JSON Schema with an inline JSON Pointer $ref that zod's converter- // rejects (it only resolves #, #/definitions/*, and #/$defs/*).+ it("treats format as an annotation", () => {+ const schema = defineJsonSchema({+ properties: { page_id: { format: "uuid", type: "string" } },+ type: "object",+ });++ expect(validate(schema, { page_id: "1f2e3d4c5b6a79881f2e3d4c5b6a7988" })).toHaveProperty(+ "value",+ );+ expect(serializeInputSchema(schema)).toEqual({+ properties: { page_id: { format: "uuid", type: "string" } },+ type: "object",+ });+ });++ // Every schema-bearing keyword @cfworker/json-schema evaluates. The probe+ // accepts "x" only when `format` is stripped and rejects "long" only when the+ // validator reaches it, so a keyword the preparation walk skips fails here.+ const PROBE = { format: "uuid", maxLength: 3 };+ it.each([+ ["additionalItems", { additionalItems: PROBE, items: [true] }, (v: string) => [0, v]],+ ["additionalProperties", { additionalProperties: PROBE }, (v: string) => ({ a: v })],+ ["allOf", { allOf: [PROBE] }, (v: string) => v],+ ["anyOf", { anyOf: [PROBE] }, (v: string) => v],+ ["contains", { contains: PROBE }, (v: string) => [v]],+ ["$defs", { $defs: { id: PROBE }, $ref: "#/$defs/id" }, (v: string) => v],+ ["definitions", { $ref: "#/definitions/id", definitions: { id: PROBE } }, (v: string) => v],+ [+ "dependencies",+ { dependencies: { a: { properties: { b: PROBE } } } },+ (v: string) => ({ a: 1, b: v }),+ ],+ [+ "dependentSchemas",+ { dependentSchemas: { a: { properties: { b: PROBE } } } },+ (v: string) => ({ a: 1, b: v }),+ ],+ ["else", { else: PROBE, if: false }, (v: string) => v],+ // eslint-disable-next-line unicorn/no-thenable -- `then` is a JSON Schema keyword here+ ["if", { else: false, if: PROBE, then: true }, (v: string) => v],+ ["items", { items: PROBE }, (v: string) => [v]],+ ["items (tuple)", { items: [PROBE] }, (v: string) => [v]],+ ["not", { not: { not: PROBE } }, (v: string) => v],+ ["oneOf", { oneOf: [PROBE] }, (v: string) => v],+ ["patternProperties", { patternProperties: { "^a": PROBE } }, (v: string) => ({ a: v })],+ ["prefixItems", { prefixItems: [PROBE] }, (v: string) => [v]],+ ["properties", { properties: { a: PROBE } }, (v: string) => ({ a: v })],+ ["propertyNames", { propertyNames: PROBE }, (v: string) => ({ [v]: 1 })],+ // eslint-disable-next-line unicorn/no-thenable -- `then` is a JSON Schema keyword here+ ["then", { if: true, then: PROBE }, (v: string) => v],+ ["unevaluatedItems", { unevaluatedItems: PROBE }, (v: string) => [v]],+ ["unevaluatedProperties", { unevaluatedProperties: PROBE }, (v: string) => ({ a: v })],+ ])("treats format as an annotation under %s", (_keyword, source, instance) => {+ const schema = defineJsonSchema(source);++ expect(validate(schema, instance("x"))).toHaveProperty("value");+ expect(validate(schema, instance("long"))).toHaveProperty("issues");+ });++ it("reads draft-04 boolean exclusive bounds", () => {const source = {properties: {- filters: {- anyOf: [- { properties: { source: { type: "string" } }, type: "object" },- {- properties: {- source: { $ref: "#/properties/filters/anyOf/0/properties/source" },- },- type: "object",- },- ],+ percent: {+ exclusiveMaximum: true,+ exclusiveMinimum: true,+ maximum: 100,+ minimum: 0,+ type: "number",},+ ratio: { exclusiveMaximum: false, maximum: 1, type: "number" },},type: "object",};- const schema = toInputSchema(source);+ const schema = defineJsonSchema(source);- expect(isToolSchema(schema)).toBe(true);- // The source JSON Schema is advertised verbatim.+ expect(validate(schema, { percent: 50, ratio: 1 })).toHaveProperty("value");+ expect(validate(schema, { percent: 100 })).toHaveProperty("issues");+ expect(validate(schema, { percent: 0 })).toHaveProperty("issues");+ expect(validate(schema, { ratio: 1.5 })).toHaveProperty("issues");expect(serializeInputSchema(schema)).toEqual(source);- // Validation accepts any input — the tool's executor validates instead.- await expect(asSchema(schema).validate?.({ filters: { source: 42 } })).resolves.toEqual({- success: true,- value: { filters: { source: 42 } },+ });++ it("reports unrecognized keys and every failure at once", () => {+ const schema = defineJsonSchema({+ $defs: { count: { type: "integer" } },+ additionalProperties: false,+ properties: {+ command: { type: "string" },+ count: { $ref: "#/$defs/count" },+ options: {+ additionalProperties: false,+ properties: { depth: { type: "integer" } },+ type: "object",+ },+ },+ required: ["command"],+ type: "object",+ });++ expect(validate(schema, { command: "ls", cwd: "/" })).toEqual({+ issues: [{ message: 'Unrecognized key: "cwd"' }],+ });+ expect(validate(schema, { command: 1, count: "2", cwd: "/" })).toEqual({+ issues: [+ { message: 'Instance type "number" is invalid. Expected "string".', path: ["command"] },+ { message: 'Instance type "string" is invalid. Expected "integer".', path: ["count"] },+ { message: 'Unrecognized key: "cwd"' },+ ],+ });+ expect(validate(schema, { command: "ls", options: { color: true, depth: "deep" } })).toEqual({+ issues: [+ {+ message: 'Instance type "string" is invalid. Expected "integer".',+ path: ["options", "depth"],+ },+ { message: 'Unrecognized key: "color"', path: ["options"] },+ ],});});- it("emits fresh copies from a passthrough schema so consumers cannot mutate the source", () => {- const source = { properties: { x: { $ref: "#/properties/y" } }, type: "object" };- const schema = toInputSchema(source);+ it("enforces draft-07 property-list dependencies", () => {+ const schema = defineJsonSchema({ dependencies: { card: ["billing_address"] } });- // asSchema's standardSchema path mutates the emitted JSON Schema in place.- const emitted = asSchema(schema).jsonSchema as { additionalProperties?: boolean };+ expect(validate(schema, { billing_address: "1 Main St", card: "4242" })).toHaveProperty(+ "value",+ );+ expect(validate(schema, { card: "4242" })).toHaveProperty("issues");+ });- expect(emitted.additionalProperties).toBe(false);- expect(source).toEqual({ properties: { x: { $ref: "#/properties/y" } }, type: "object" });- expect(serializeInputSchema(schema)).toEqual(source);+ it("fills omitted properties with their defaults after validation", () => {+ const schema = defineJsonSchema({+ $defs: { depth: { default: 2, type: "integer" } },+ properties: {+ filter: { properties: { depth: { $ref: "#/$defs/depth" } }, type: "object" },+ limit: { default: 10, type: "integer" },+ // A default its own schema rejects is still used (Pydantic's `x: str = None`).+ query: { default: null, type: "string" },+ rows: {+ items: { properties: { n: { default: 1, type: "integer" } }, type: "object" },+ type: "array",+ },+ tags: { default: ["a"], type: "array" },+ variant: { anyOf: [{ properties: { mode: { default: "a" } }, type: "object" }] },+ },+ type: "object",+ });+ const input = { filter: {}, rows: [{}, { n: 5 }], variant: {} };++ expect(validate(schema, input)).toEqual({+ value: {+ filter: { depth: 2 },+ limit: 10,+ query: null,+ rows: [{ n: 1 }, { n: 5 }],+ tags: ["a"],+ variant: {},+ },+ });+ expect(input).toEqual({ filter: {}, rows: [{}, { n: 5 }], variant: {} });+ expect(validate(schema, { limit: 3, query: "open" })).toEqual({+ value: { limit: 3, query: "open", tags: ["a"] },+ });+ expect(validate(schema, { limit: "3" })).toHaveProperty("issues");++ const first = validate(schema, {}) as { value: { tags: string[] } };+ first.value.tags.push("b");+ expect(validate(schema, {})).toHaveProperty("value.tags", ["a"]);});- it("degrades malformed serialized schemas instead of failing the boundary", () => {- expect(isToolSchema(toInputSchema({ type: "not-a-json-schema-type" }))).toBe(true);+ it("reports only the deepest failure of each chain with its path", () => {+ const schema = defineJsonSchema({+ properties: {+ pages: {+ items: { properties: { "a/b": { type: "string" } }, type: "object" },+ type: "array",+ },+ },+ type: "object",+ });++ expect(validate(schema, { pages: [{ "a/b": 1 }] })).toEqual({+ issues: [+ {+ message: 'Instance type "number" is invalid. Expected "string".',+ path: ["pages", "0", "a/b"],+ },+ ],+ });});- it("preserves a live validated schema", () => {- const schema = z.object({ prompt: z.string() });+ it.each([+ ["an unknown type name", { properties: { value: { type: "any" } }, type: "object" }],+ ["a non-array enum", { properties: { state: { enum: "open" } }, type: "object" }],+ ["an invalid pattern", { properties: { id: { pattern: "(?i)abc", type: "string" } } }],+ ["an invalid pattern property", { patternProperties: { "(?i)x": { type: "string" } } }],+ [+ "an invalid pattern under dependencies",+ { dependencies: { a: { properties: { id: { pattern: "(?i)abc" } } } } },+ ],+ ["a non-array required", { required: "id", type: "object" }],+ ["an unresolvable reference", { properties: { a: { $ref: "https://example.com/a.json" } } }],+ ])("advertises %s but passes values through unvalidated", (_label, source) => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const schema = defineJsonSchema(source);- expect(toInputSchema(schema)).toBe(schema);- expect(toOutputSchema(schema)).toBe(schema);+ expect(serializeInputSchema(schema)).toEqual(source);+ expect(validate(schema, { a: 1, id: 1, state: 1, value: 1, x: 1 })).toEqual({+ value: { a: 1, id: 1, state: 1, value: 1, x: 1 },+ });+ expect(validate(schema, { a: 2 })).toEqual({ value: { a: 2 } });+ expect(warn).toHaveBeenCalledOnce();+ });++ it("runs the extra check only after the JSON Schema accepts a value", () => {+ const check = vi.fn((value: { readonly labels: readonly string[] }) =>+ new Set(value.labels).size === value.labels.length ? undefined : "Labels must be unique.",+ );+ const schema = defineJsonSchema(+ { properties: { labels: { items: { type: "string" }, type: "array" } }, type: "object" },+ check,+ );++ expect(validate(schema, { labels: ["a", "b"] })).toEqual({ value: { labels: ["a", "b"] } });+ expect(validate(schema, { labels: ["a", "a"] })).toEqual({+ issues: [{ message: "Labels must be unique." }],+ });+ expect(validate(schema, { labels: [1] })).toHaveProperty("issues");+ expect(check).toHaveBeenCalledTimes(2);});- it("rehydrates one validator per serialized source object", () => {+ it("does not mutate the source while validating", () => {const source = {- properties: { prompt: { type: "string" } },+ properties: { id: { format: "uuid", type: "string" } },type: "object",};+ const snapshot = structuredClone(source);+ const schema = defineJsonSchema(source);++ validate(schema, { id: "x" });++ expect(source).toEqual(snapshot);+ expect(Object.getOwnPropertyNames(source)).toEqual(Object.getOwnPropertyNames(snapshot));+ });+});- expect(toInputSchema(source)).toBe(toInputSchema(source));+describe("toModelSchema", () => {+ it("lowers Standard Schemas onto AI SDK schemas the AI SDK uses as-is", async () => {+ const sources = [+ defineJsonSchema({ properties: { city: { type: "string" } }, type: "object" }),+ z.strictObject({ city: z.string() }),+ ];++ for (const source of sources) {+ const modelSchema = toModelSchema(source, "input") as object;++ expect(Reflect.get(modelSchema, AI_SDK_SCHEMA)).toBe(true);+ expect("~standard" in modelSchema).toBe(false);+ expect("_zod" in modelSchema).toBe(false);+ expect(asSchema(modelSchema as Parameters<typeof asSchema>[0])).toBe(modelSchema);+ await expect(asSchema(modelSchema as never).validate?.({ city: "Paris" })).resolves.toEqual({+ success: true,+ value: { city: "Paris" },+ });+ }+ });++ it("emits library schemas as the AI SDK would and plain JSON Schema as written", async () => {+ const zodSchema = z.object({ city: z.string(), units: z.object({ system: z.string() }) });+ const jsonSource = { properties: { city: { type: "string" } }, type: "object" };+ const { $schema: _version, ...aiSdkJsonSchema } = await asSchema(zodSchema).jsonSchema;++ expect(await asSchema(toModelSchema(zodSchema, "input")).jsonSchema).toEqual(aiSdkJsonSchema);+ expect(aiSdkJsonSchema).toMatchObject({+ additionalProperties: false,+ properties: { units: { additionalProperties: false } },+ });+ expect(await asSchema(toModelSchema(defineJsonSchema(jsonSource), "input")).jsonSchema).toEqual(+ jsonSource,+ );+ });++ it("emits the requested direction of a transforming schema", async () => {+ const schema = z.strictObject({+ count: z+ .string()+ .transform((value) => Number.parseInt(value, 10))+ .pipe(z.number().int()),+ });++ expect(await asSchema(toModelSchema(schema, "output")).jsonSchema).toMatchObject({+ properties: { count: expect.objectContaining({ type: "integer" }) },+ });+ await expect(+ asSchema(toModelSchema(schema, "input")).validate?.({ count: "7" }),+ ).resolves.toEqual({ success: true, value: { count: 7 } });+ });++ it("reports validation failures as AI SDK type validation errors with the issues", async () => {+ const schema = toModelSchema(+ defineJsonSchema({ properties: { city: { type: "string" } }, type: "object" }),+ "input",+ );++ const result = await asSchema(schema).validate?.({ city: 1 });++ expect(result).toMatchObject({ success: false });+ const error = (result as { readonly error: unknown }).error;+ expect(TypeValidationError.isInstance(error)).toBe(true);+ expect((error as TypeValidationError).cause).toEqual([+ { message: 'Instance type "number" is invalid. Expected "string".', path: ["city"] },+ ]);+ });++ it("passes AI SDK-native and absent schemas through", () => {+ const native = jsonSchema({ type: "object" });+ const lazy = () => native;++ expect(toModelSchema(native, "input")).toBe(native);+ expect(toModelSchema(lazy, "input")).toBe(lazy);+ expect(toModelSchema(undefined, "output")).toBeUndefined();+ });+});++describe("tool schema conversion", () => {+ it("resolves plain JSON Schema into a validating schema", () => {+ const schema = toInputSchema({ items: { type: "string" }, maxItems: 1, type: "array" });++ expect(isToolSchema(schema)).toBe(true);+ expect(validate(schema, ["one", "too many"])).toHaveProperty("issues");+ });++ it("preserves a live validated schema", () => {+ const schema = z.object({ prompt: z.string() });++ expect(toInputSchema(schema)).toBe(schema);+ expect(toOutputSchema(schema)).toBe(schema);});it("passes null and undefined through every conversion", () => {@@ -143,7 +489,7 @@ describe("ToolSchema", () => {});});- it("serializes and rehydrates a Zod 3 input schema", async () => {+ it("serializes and validates a Zod 3 input schema", async () => {const source = z3.object({ city: z3.string() });expect(serializeInputSchema(source)).toEqual({@@ -153,9 +499,11 @@ describe("ToolSchema", () => {type: "object",});- const validate = asSchema(toInputSchema(source)).validate;- await expect(validate?.({ city: "San Francisco" })).resolves.toMatchObject({ success: true });- await expect(validate?.({ city: 42 })).resolves.toMatchObject({ success: false });+ const modelSchema = asSchema(toModelSchema(toInputSchema(source), "input"));+ await expect(modelSchema.validate?.({ city: "San Francisco" })).resolves.toMatchObject({+ success: true,+ });+ await expect(modelSchema.validate?.({ city: 42 })).resolves.toMatchObject({ success: false });});it("rejects a Zod 3 output schema with an actionable error", () => {@@ -210,10 +558,10 @@ describe("ToolSchema", () => {expect(isToolSchema(null)).toBe(false);});- it("accepts any input via UNSPECIFIED_INPUT_SCHEMA", async () => {- const validate = asSchema(UNSPECIFIED_INPUT_SCHEMA).validate;-- await expect(validate?.({})).resolves.toMatchObject({ success: true });- await expect(validate?.({ extra: true })).resolves.toMatchObject({ success: true });+ it("accepts any input via UNSPECIFIED_INPUT_SCHEMA", () => {+ expect(validate(UNSPECIFIED_INPUT_SCHEMA, {})).toEqual({ value: {} });+ expect(validate(UNSPECIFIED_INPUT_SCHEMA, { extra: true })).toEqual({+ value: { extra: true },+ });});});diff --git a/packages/eve/src/tools/schema.ts b/packages/eve/src/tools/schema.tsindex 8dc3f9a15..e92648aa6 100644--- a/packages/eve/src/tools/schema.ts+++ b/packages/eve/src/tools/schema.ts@@ -1,18 +1,27 @@-import { asSchema } from "ai";+import {+ asSchema,+ jsonSchema,+ TypeValidationError,+ type FlexibleSchema,+ type JSONSchema7,+ type Schema,+} from "ai";+import { Validator, type OutputUnit } from "#compiled/@cfworker/json-schema/index.js";import type {StandardJSONSchemaV1,StandardSchemaV1,} from "#compiled/@standard-schema/spec/index.js";-import { z } from "#compiled/zod/index.js";import { toErrorMessage } from "#shared/errors.js";+import { isObject } from "#shared/guards.js";import { parseJsonObject, type JsonObject } from "#shared/json.js";/*** eve-owned schema contract for tool input and output schemas: a Standard- * Schema validator that can also emit JSON Schema. Zod implements both- * constituent protocols without exposing Zod through runtime-owned types.+ * Schema validator that can also emit JSON Schema. Author schemas (Zod,+ * Valibot, ArkType) implement it directly; plain JSON Schema data is lowered+ * onto it by {@link defineJsonSchema}.*/export type ToolSchema<Input = unknown, Output = Input> = StandardSchemaV1<Input, Output> &StandardJSONSchemaV1<Input, Output>;@@ -32,18 +41,10 @@ type SchemaResult<TSource, TResult> = TSource extends null | undefined ? TSourceconst JSON_SCHEMA_TARGET: StandardJSONSchemaV1.Target = "draft-07";-// Keyed on source identity so replayed durable schemas rehydrate once.-const rehydratedSchemas: Record<SchemaDirection, WeakMap<object, ToolSchema>> = {- input: new WeakMap(),- output: new WeakMap(),-};-/*** Resolves a source into a live input {@link ToolSchema}. Live schemas pass- * through unchanged; serialized JSON Schemas are rehydrated into vendored Zod- * validators. Serialized schemas outside Zod's conversion subset degrade to a- * validation-free schema that still advertises the source JSON Schema. `null`- * and `undefined` pass through untouched.+ * through unchanged; plain JSON Schema data becomes a {@link defineJsonSchema}+ * schema. `null` and `undefined` pass through untouched.*/export function toInputSchema<T extends ToolSchemaSource | null | undefined>(source: T,@@ -53,10 +54,8 @@ export function toInputSchema<T extends ToolSchemaSource | null | undefined>(/*** Resolves a source into a live output {@link ToolSchema}. Live schemas pass- * through unchanged; serialized JSON Schemas are rehydrated into vendored Zod- * validators. Serialized schemas outside Zod's conversion subset degrade to a- * validation-free schema that still advertises the source JSON Schema. `null`- * and `undefined` pass through untouched.+ * through unchanged; plain JSON Schema data becomes a {@link defineJsonSchema}+ * schema. `null` and `undefined` pass through untouched.*/export function toOutputSchema<T extends ToolSchemaSource | null | undefined>(source: T,@@ -104,78 +103,134 @@ export function isToolSchema(value: unknown): value is ToolSchema {);}+/**+ * Builds a {@link ToolSchema} from plain JSON Schema data. The schema is+ * advertised exactly as given, and values are validated against it with a+ * JSON Schema 2020-12 validator that also accepts draft-07 constructs.+ *+ * `format` is treated as an annotation, as JSON Schema 2020-12 specifies by+ * default. A valid value's omitted properties receive their `default` values.+ * A schema the validator cannot evaluate faithfully (unknown `type`+ * names, invalid `pattern` expressions, unresolvable `$ref`s) is still+ * advertised, but its values pass through unvalidated; the tool's executor,+ * such as a remote MCP server, remains the authority for its own contract.+ *+ * `check` runs after the JSON Schema accepts a value and reports a message+ * for constraints JSON Schema cannot express.+ */+export function defineJsonSchema<T = unknown>(+ schema: JsonObject,+ check?: (value: T) => string | undefined,+): ToolSchema<T> {+ const emit = (): Record<string, unknown> => structuredClone(schema) as Record<string, unknown>;+ const toolSchema = {+ "~standard": {+ version: 1,+ vendor: "eve",+ validate: createJsonSchemaValidator(+ schema,+ check as ((value: unknown) => string | undefined) | undefined,+ ),+ jsonSchema: { input: emit, output: emit },+ },+ } as ToolSchema<T>;+ plainJsonSchemas.add(toolSchema);+ return toolSchema;+}++/** Schemas built by {@link defineJsonSchema}, which reach the model exactly as written. */+const plainJsonSchemas = new WeakSet<object>();+/*** Permissive schema lowered onto model-visible tools whose definitions* declare no input schema. Accepts any input — an absent schema declares no* contract, so rejecting stray properties would only force needless retries.*/-export const UNSPECIFIED_INPUT_SCHEMA: ToolSchema = z.fromJSONSchema({}) as ToolSchema;+export const UNSPECIFIED_INPUT_SCHEMA: ToolSchema = defineJsonSchema({});-function toSchema(- source: ToolSchemaSource | null | undefined,+/**+ * Lowers a harness tool schema onto the AI SDK boundary.+ *+ * Every Standard Schema is wrapped in an AI SDK `jsonSchema()` schema whose+ * JSON Schema and validation both come from the schema's own library. The+ * AI SDK treats an existing `Schema` as final, so it never reaches for the+ * app's `zod` copy to convert or parse a schema built by another copy — a+ * mismatch that crashes JSON Schema conversion across Zod minor versions.+ * AI SDK-native schemas (already wrapped, or lazy) pass through.+ *+ * Library schemas get the object closing the AI SDK applies to them itself;+ * plain JSON Schema from {@link defineJsonSchema} is advertised as written.+ */+export function toModelSchema(schema: FlexibleSchema, direction: SchemaDirection): FlexibleSchema;+export function toModelSchema(+ schema: FlexibleSchema | undefined,direction: SchemaDirection,-): ToolSchema | null | undefined {- if (source === null || source === undefined) return source;- if (isToolSchema(source)) return source;-- const cache = rehydratedSchemas[direction];- let resolved = cache.get(source);- if (resolved === undefined) {- resolved = rehydrateJsonSchema(toJsonObject(source, direction));- cache.set(source, resolved);+): FlexibleSchema | undefined;+export function toModelSchema(+ schema: FlexibleSchema | undefined,+ direction: SchemaDirection,+): FlexibleSchema | undefined {+ if (schema === undefined || typeof schema === "function" || !("~standard" in schema)) {+ return schema;}- return resolved;+ const source = schema as StandardSchemaV1;+ const verbatim = plainJsonSchemas.has(source);+ return jsonSchema(+ () => {+ const json = serializeSchema(source, direction);+ return (verbatim ? json : closeObjectSchemas(json)) as JSONSchema7;+ },+ {+ validate: async (value) => {+ const result = await source["~standard"].validate(value);+ return result.issues === undefined+ ? { success: true, value: result.value }+ : { success: false, error: new TypeValidationError({ value, cause: result.issues }) };+ },+ },+ ) satisfies Schema;}-type FromJsonSchemaSource = Parameters<typeof z.fromJSONSchema>[0];--function rehydrateJsonSchema(jsonSchema: JsonObject): ToolSchema {- // The first rehydration target must match JSON_SCHEMA_TARGET: serialized- // schemas strip `$schema`, so zod would otherwise assume draft-2020-12.- try {- return z.fromJSONSchema(jsonSchema as FromJsonSchemaSource, {- defaultTarget: "draft-7",- }) as ToolSchema;- } catch {- // Retry below with the dialect raw remote schemas actually use.+/**+ * Mirrors the AI SDK's `addAdditionalPropertiesToJsonSchema`: every object+ * schema without a subschema for extra keys gets `additionalProperties: false`.+ * Returns a copy; library emitters may cache the schemas they return.+ */+function closeObjectSchemas(schema: unknown): unknown {+ if (!isObject(schema)) return schema;+ const node: Record<string, unknown> = { ...schema };+ const { type } = node;+ if (type === "object" || (Array.isArray(type) && type.includes("object"))) {+ node.additionalProperties = isObject(node.additionalProperties)+ ? closeObjectSchemas(node.additionalProperties)+ : false;+ if (isObject(node.properties)) node.properties = mapValues(node.properties, closeObjectSchemas);}-- // MCP declares tool schemas as JSON Schema 2020-12, where `$defs` replaces- // draft-07 `definitions`, so raw remote schemas get a second pass here.- try {- return z.fromJSONSchema(jsonSchema as FromJsonSchemaSource, {- defaultTarget: "draft-2020-12",- }) as ToolSchema;- } catch (error) {- // Valid JSON Schema can exceed zod's conversion subset (inline JSON- // Pointer $refs, conditionals, unevaluated* keywords). Advertise the- // schema unchanged without local validation — the tool's executor (e.g.- // the remote MCP server) still validates input — rather than letting one- // incompatible tool schema fail the whole turn.- console.warn(- "[eve] Tool schema uses JSON Schema features outside local validation support; " +- `passing input through unvalidated: ${toErrorMessage(error)}`,- );- return toPassthroughSchema(jsonSchema);+ if (Array.isArray(node.items)) node.items = node.items.map(closeObjectSchemas);+ else if (isObject(node.items)) node.items = closeObjectSchemas(node.items);+ for (const keyword of ["allOf", "anyOf", "oneOf"] as const) {+ const list = node[keyword];+ if (Array.isArray(list)) node[keyword] = list.map(closeObjectSchemas);}+ if (isObject(node.definitions))+ node.definitions = mapValues(node.definitions, closeObjectSchemas);+ return node;}-/**- * Validation-free {@link ToolSchema} that advertises the source JSON Schema- * verbatim and accepts any input. Emission returns a fresh copy per call so- * consumers that mutate emitted schemas cannot corrupt durable sources.- */-function toPassthroughSchema(jsonSchema: JsonObject): ToolSchema {- const emit = (): Record<string, unknown> =>- structuredClone(jsonSchema) as Record<string, unknown>;- return {- "~standard": {- version: 1,- vendor: "eve",- validate: (value: unknown) => ({ value }),- jsonSchema: { input: emit, output: emit },- },- };+function mapValues(+ record: Record<string, unknown>,+ map: (value: unknown) => unknown,+): Record<string, unknown> {+ return Object.fromEntries(Object.entries(record).map(([key, value]) => [key, map(value)]));+}++function toSchema(+ source: ToolSchemaSource | null | undefined,+ direction: SchemaDirection,+): ToolSchema | null | undefined {+ if (source === null || source === undefined) return source;+ if (isToolSchema(source)) return source;+ return defineJsonSchema(toJsonObject(source, direction));}function serializeSchema(@@ -202,6 +257,8 @@ function toJsonObject(source: ToolSchemaSource, direction: SchemaDirection): Jsoconst vendor = typeof standard?.vendor === "string" ? standard.vendor : "unknown";if (standard !== undefined && typeof emit !== "function" && vendor === "zod") {if (direction === "input") {+ // Zod 3 and early Zod 4 releases predate Standard JSON Schema. The schema+ // comes from the author's own Zod, which the author's AI SDK also uses.const schema = asSchema(source as Parameters<typeof asSchema>[0]);const { $schema: _schemaVersion, ...canonical } = parseJsonObject(schema.jsonSchema);return canonical;@@ -238,3 +295,337 @@ function getStandardSchemaProperties(value: unknown): Record<string, unknown> |? (standard as Record<string, unknown>): undefined;}++// ---------------------------------------------------------------------------+// JSON Schema validation+// ---------------------------------------------------------------------------++type ValidateFn = (value: unknown) => StandardSchemaV1.Result<unknown>;++function createJsonSchemaValidator(+ schema: JsonObject,+ check: ((value: unknown) => string | undefined) | undefined,+): ValidateFn {+ // Built on first use: most advertised schemas never validate a value in a+ // given process, and building one walks the whole schema.+ let validator: Validator | null | undefined;+ let warned = false;+ const passThrough = (value: unknown, reason: string) => {+ if (!warned) {+ warned = true;+ console.warn(+ `[eve] Tool schema cannot validate values locally; passing them through unvalidated: ${reason}`,+ );+ }+ return { value };+ };++ return (value) => {+ if (validator === undefined) {+ const built = buildValidator(schema);+ if (typeof built === "string") {+ validator = null;+ return passThrough(value, built);+ }+ validator = built;+ }+ if (validator === null) return { value };++ let result;+ try {+ result = validator.validate(value);+ } catch (error) {+ if (value === undefined) return { issues: [{ message: "Expected a JSON value." }] };+ return passThrough(value, toErrorMessage(error));+ }+ if (!result.valid) return { issues: toIssues(result.errors) };++ const filled = applyDefaults(schema, schema, value);+ const message = check?.(filled);+ return message === undefined ? { value: filled } : { issues: [{ message }] };+ };+}++/**+ * Fills omitted object properties from their `default` values through+ * `properties`, array `items`, and local `$ref`s. It runs after validation, so+ * a default is used as declared even when its own schema rejects it, as with+ * Pydantic's `{ "type": "string", "default": null }` for `x: str = None`.+ * Branches of `allOf`, `anyOf`, and `oneOf` are skipped because which branch+ * governs a value is ambiguous. The input is not mutated.+ */+function applyDefaults(root: JsonObject, schema: unknown, value: unknown): unknown {+ let result = value;+ for (const node of followRefs(root, schema)) {+ const { items, properties } = node;+ if (isObject(result) && isObject(properties)) {+ result = fillProperties(root, properties, result);+ } else if (Array.isArray(result) && isObject(items)) {+ const list: unknown[] = result;+ const next = list.map((item) => applyDefaults(root, items, item));+ if (next.some((item, index) => item !== list[index])) result = next;+ }+ }+ return result;+}++function fillProperties(+ root: JsonObject,+ properties: Record<string, unknown>,+ value: Record<string, unknown>,+): Record<string, unknown> {+ let result = value;+ for (const [key, property] of Object.entries(properties)) {+ const current = Object.hasOwn(value, key) ? value[key] : undefined;+ const next =+ current === undefined ? findDefault(root, property) : applyDefaults(root, property, current);+ if (next === current) continue;+ if (result === value) result = { ...value };+ result[key] = next;+ }+ return result;+}++function findDefault(root: JsonObject, schema: unknown): unknown {+ for (const node of followRefs(root, schema)) {+ if ("default" in node) return structuredClone(node.default);+ }+ return undefined;+}++/** Yields a subschema, then each local `$ref` target it chains through. */+function* followRefs(root: JsonObject, schema: unknown): Generator<Record<string, unknown>> {+ const seen = new Set<object>();+ let node = schema;+ while (isObject(node) && !seen.has(node)) {+ seen.add(node);+ yield node;+ node = resolveLocalRef(root, node.$ref);+ }+}++function resolveLocalRef(root: JsonObject, ref: unknown): unknown {+ if (typeof ref !== "string" || (ref !== "#" && !ref.startsWith("#/"))) return undefined;+ let node: unknown = root;+ for (const segment of decodePointer(ref)) {+ if (typeof node !== "object" || node === null || !Object.hasOwn(node, segment)) {+ return undefined;+ }+ node = (node as Record<string, unknown>)[segment];+ }+ return node;+}++/** Returns a validator, or the reason the schema cannot be evaluated faithfully. */+function buildValidator(schema: JsonObject): Validator | string {+ try {+ // The validator annotates the schema objects it walks, so it gets a copy.+ const copy = structuredClone(schema) as Record<string, unknown>;+ const problem = prepareForValidation(copy);+ // Collect every failure, not just the first, so one retry can fix them all.+ return problem ?? new Validator(copy, "2020-12", false);+ } catch (error) {+ return toErrorMessage(error);+ }+}++const JSON_TYPES = new Set(["array", "boolean", "integer", "null", "number", "object", "string"]);+const EXCLUSIVE_BOUNDS = [+ ["exclusiveMinimum", "minimum"],+ ["exclusiveMaximum", "maximum"],+] as const;+const SUBSCHEMA_KEYWORDS = [+ "additionalItems",+ "additionalProperties",+ "contains",+ "else",+ "if",+ "not",+ "propertyNames",+ "then",+ "unevaluatedItems",+ "unevaluatedProperties",+] as const;+const SUBSCHEMA_LIST_KEYWORDS = ["allOf", "anyOf", "oneOf", "prefixItems"] as const;+const SUBSCHEMA_MAP_KEYWORDS = [+ "$defs",+ "definitions",+ "dependencies",+ "dependentSchemas",+ "patternProperties",+ "properties",+] as const;++/**+ * Walks every subschema of a private schema copy, removing `format` (an+ * annotation in JSON Schema 2020-12) and returning the first construct the+ * validator would misjudge instead of rejecting every value.+ */+function prepareForValidation(schema: unknown): string | undefined {+ if (typeof schema === "boolean") return undefined;+ if (typeof schema !== "object" || schema === null || Array.isArray(schema)) {+ return "a subschema is neither an object nor a boolean";+ }+ const node = schema as Record<string, unknown>;+ delete node.format;+ // Draft-04 and OpenAPI 3.0 write exclusive bounds as booleans beside `minimum`/`maximum`.+ for (const [flag, bound] of EXCLUSIVE_BOUNDS) {+ if (typeof node[flag] !== "boolean") continue;+ if (node[flag] && typeof node[bound] === "number") {+ node[flag] = node[bound];+ delete node[bound];+ } else {+ delete node[flag];+ }+ }++ const { enum: values, pattern, required, type } = node;+ if (type !== undefined && !(Array.isArray(type) ? type.every(isJsonType) : isJsonType(type))) {+ return `unsupported type ${JSON.stringify(type)}`;+ }+ if (values !== undefined && !Array.isArray(values)) return "`enum` is not an array";+ if (+ required !== undefined &&+ !(Array.isArray(required) && required.every((key) => typeof key === "string"))+ ) {+ return "`required` is not an array of strings";+ }+ if (pattern !== undefined && !isRegExpSource(pattern)) {+ return `invalid pattern ${JSON.stringify(pattern)}`;+ }++ for (const keyword of SUBSCHEMA_KEYWORDS) {+ if (keyword in node) {+ const problem = prepareForValidation(node[keyword]);+ if (problem !== undefined) return problem;+ }+ }+ const items = node.items;+ for (const subschema of Array.isArray(items) ? items : items === undefined ? [] : [items]) {+ const problem = prepareForValidation(subschema);+ if (problem !== undefined) return problem;+ }+ for (const keyword of SUBSCHEMA_LIST_KEYWORDS) {+ const list = node[keyword];+ if (list === undefined) continue;+ if (!Array.isArray(list)) return `\`${keyword}\` is not an array`;+ for (const subschema of list) {+ const problem = prepareForValidation(subschema);+ if (problem !== undefined) return problem;+ }+ }+ for (const keyword of SUBSCHEMA_MAP_KEYWORDS) {+ const map = node[keyword];+ if (map === undefined) continue;+ if (typeof map !== "object" || map === null || Array.isArray(map)) {+ return `\`${keyword}\` is not an object`;+ }+ for (const [key, subschema] of Object.entries(map)) {+ if (keyword === "patternProperties" && !isRegExpSource(key)) {+ return `invalid pattern ${JSON.stringify(key)}`;+ }+ // Draft-07 `dependencies` mixes subschemas with lists of required property names.+ if (keyword === "dependencies" && Array.isArray(subschema)) continue;+ const problem = prepareForValidation(subschema);+ if (problem !== undefined) return problem;+ }+ }+ return undefined;+}++function isJsonType(value: unknown): boolean {+ return typeof value === "string" && JSON_TYPES.has(value);+}++function isRegExpSource(value: unknown): boolean {+ if (typeof value !== "string") return false;+ try {+ new RegExp(value, "u");+ return true;+ } catch {+ return false;+ }+}++const CLOSED_OBJECT_KEYWORD = /\/(?:additional|unevaluated)Properties$/;++interface Failure {+ readonly keyword: string;+ readonly location: string;+ readonly message: string;+ /** Location of the closed object that rejected this key. */+ readonly object?: string;+}++/**+ * The validator reports each failure as a chain from the root to the failing+ * keyword. Only the deepest unit of each chain carries information the model+ * can act on; the rest restate its location, as a `$ref` unit does for the+ * failure it wraps.+ *+ * A closed object reports an extra key as a parent unit plus a bare "False+ * boolean schema." child, so that pair becomes one "Unrecognized key" issue.+ * Without short-circuiting, the validator also reports declared keys that+ * failed their own schema that way; those repeats are dropped.+ */+function toIssues(errors: readonly OutputUnit[]): StandardSchemaV1.Issue[] {+ const failures: Failure[] = [];+ for (let index = 0; index < errors.length; index++) {+ const unit = errors[index]!;+ const rejected = errors[index + 1];+ if (CLOSED_OBJECT_KEYWORD.test(unit.keywordLocation) && rejected?.keyword === "false") {+ const key = decodePointer(rejected.instanceLocation).at(-1);+ failures.push({+ keyword: "false",+ location: rejected.instanceLocation,+ message: `Unrecognized key: ${JSON.stringify(key)}`,+ object: unit.instanceLocation,+ });+ index++;+ } else {+ failures.push({+ keyword: unit.keyword,+ location: unit.instanceLocation,+ message: unit.error,+ });+ }+ }++ const relevant = failures.filter(+ (failure) =>+ failure.object === undefined ||+ !failures.some(+ (other) =>+ other.object === undefined &&+ (other.location === failure.location ||+ other.location.startsWith(`${failure.location}/`)),+ ),+ );+ return relevant+ .filter((failure, index) => {+ const next = relevant[index + 1];+ if (next === undefined) return true;+ if (next.location.startsWith(`${failure.location}/`)) return false;+ return !(failure.keyword === "$ref" && next.location === failure.location);+ })+ .map(({ location, message, object }) => {+ const path = decodePointer(object ?? location);+ return path.length === 0 ? { message } : { message, path };+ });+}++/** Decodes a `#/a/0/b` JSON Pointer fragment into its path segments. */+function decodePointer(location: string): string[] {+ return location+ .split("/")+ .slice(1)+ .map((segment) => {+ let decoded = segment;+ try {+ decoded = decodeURIComponent(segment);+ } catch {+ // Keep the raw segment; it still identifies the location.+ }+ return decoded.replaceAll("~1", "/").replaceAll("~0", "~");+ });+}diff --git a/packages/eve/test/runtime-subagent-registry.test.ts b/packages/eve/test/runtime-subagent-registry.test.tsindex 0dac92142..f49cd90bc 100644--- a/packages/eve/test/runtime-subagent-registry.test.ts+++ b/packages/eve/test/runtime-subagent-registry.test.ts@@ -29,11 +29,11 @@ const SUBAGENT_TOOL_INPUT_SCHEMA = {describe("createRuntimeSubagentRegistry", () => {it("accepts null as an omitted agentId", () => {expect(- subagentToolInputSchema.parse({+ subagentToolInputSchema["~standard"].validate({agentId: null,message: "Investigate this",}),- ).toEqual({ agentId: null, message: "Investigate this" });+ ).toEqual({ value: { agentId: null, message: "Investigate this" } });});it("lowers local subagent inputs into serializable model-visible tools with a uniform messaging schema", () => {diff --git a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.tsindex 9708b11fa..1a7245332 100644--- a/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts+++ b/packages/eve/test/scenarios/compiled-vendor-assets.scenario.test.ts@@ -67,20 +67,19 @@ function rewriteDeclarationImports(}describe("compiled vendor assets", () => {- it("lazily compiles schemas created by the vendored Zod runtime", async () => {+ it("leaves Zod's process-global configuration to the app", async () => {+ // Every Zod copy in a process shares `globalThis.__zod_globalConfig`, so a+ // vendored side effect there would rewrite the app's own schemas too.const zodUrl = pathToFileURL(join(COMPILED_VENDOR_ROOT, "zod", "index.js")).href;const { z } = await import(zodUrl);- const schema = z.object({- id: z.string(),- nested: z.array(z.object({ active: z.boolean(), count: z.number() })),- });+ const schema = z.object({ id: z.string() });+ expect(schema.parse({ id: "agent" })).toEqual({ id: "agent" });+ expect(+ (globalThis as { __zod_globalConfig?: { postProcessor?: unknown } }).__zod_globalConfig+ ?.postProcessor,+ ).toBeUndefined();expect(schema._zod.bag.validator).toBeUndefined();- expect(schema.parse({ id: "agent", nested: [{ active: true, count: 1 }] })).toEqual({- id: "agent",- nested: [{ active: true, count: 1 }],- });- expect(schema._zod.bag.validator).toBeTypeOf("function");});it("stamps the compiler versions that drive vendored output", async () => {diff --git a/packages/eve/test/scenarios/tool-schemas-app-zod.scenario.test.ts b/packages/eve/test/scenarios/tool-schemas-app-zod.scenario.test.tsnew file mode 100644index 000000000..4c0b06f93--- /dev/null+++ b/packages/eve/test/scenarios/tool-schemas-app-zod.scenario.test.ts@@ -0,0 +1,147 @@+import { realpathSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";++import { describe, expect, it } from "vitest";++import { Client } from "../../src/client/client.js";+import { useScenarioApp } from "../../src/internal/testing/scenario-app.js";+import { startEveDev } from "./dev-server-harness.js";++const scenarioApp = useScenarioApp();++// Shapes that tool servers commonly emit and that older JSON Schema to Zod+// bridges turned into intersections and records.+const REMOTE_INPUT_SCHEMA = {+ type: "object",+ properties: {+ pages: {+ type: "array",+ items: {+ type: "object",+ properties: { page_id: { type: "string", format: "uuid" }, title: { type: "string" } },+ anyOf: [{ required: ["page_id"] }, { required: ["title"] }],+ },+ },+ properties: { type: "object", additionalProperties: { type: ["string", "number", "null"] } },+ target: {+ allOf: [+ { type: "object", properties: { id: { type: "string" } }, required: ["id"] },+ { type: "object", properties: { kind: { enum: ["page", "database"] } } },+ ],+ },+ },+ patternProperties: { "^x-": { type: "string" } },+ required: ["target"],+};++const OUTPUT_SCHEMA = {+ type: "object",+ properties: {+ advertised: { type: "object" },+ results: { type: "array", items: { type: "object" } },+ },+ anyOf: [{ required: ["advertised"] }, { required: ["results"] }],+};++const VALID_REMOTE_INPUT = {+ pages: [{ page_id: "1f2e3d4c5b6a79881f2e3d4c5b6a7988" }, { title: "Weekly sync" }],+ properties: { Owner: "Bob", Points: 3 },+ target: { id: "db-1", kind: "database" },+ "x-trace": "alice",+};++describe("tool schemas in an app that pins its own Zod", () => {+ it("runs remote, authored, and structured-output schemas across Zod versions", async () => {+ const app = await scenarioApp({+ name: "tool-schemas-app-zod",+ installDependencies: true,+ // Older than the Zod eve bundles, and a version whose JSON Schema+ // conversion cannot process schemas built by eve's copy.+ dependencies: { zod: "4.4.3" },+ files: {+ "agent/instructions.md": "File the pages Alice asked for.\n",+ "agent/agent.ts": `import { defineAgent } from "eve";+import { mockModel } from "eve/evals";+export default defineAgent({+ model: mockModel(({ toolResults, tools }) => {+ if (toolResults.length === 0) {+ return { toolCalls: [+ { id: "remote-valid", name: "file_pages", input: ${JSON.stringify(VALID_REMOTE_INPUT)} },+ { id: "remote-invalid", name: "file_pages", input: { pages: [{}], target: {} } },+ { id: "authored", name: "tag_page", input: { id: "page-1", tags: { status: "done" } } },+ ] };+ }+ return { toolCalls: [{ id: "final", name: "final_output", input: {+ advertised: tools.find((tool) => tool.name === "file_pages")?.inputSchema,+ results: toolResults.map(({ id, isError, output }) => ({ id, isError, output })),+ } }] };+ }),+ modelContextWindowTokens: 32000,+});+`,+ "agent/tools/file-pages.ts": `import { defineDynamic, defineTool } from "eve/tools";+export default defineDynamic({+ events: {+ "session.started": () => ({+ file_pages: defineTool({+ description: "File pages into Alice's workspace.",+ inputSchema: ${JSON.stringify(REMOTE_INPUT_SCHEMA)},+ execute: (input) => ({ filed: input }),+ }),+ }),+ },+});+`,+ "agent/tools/tag_page.ts": `import { defineTool } from "eve/tools";+import { z } from "zod";+export default defineTool({+ description: "Tag one page.",+ inputSchema: z+ .object({ id: z.string() })+ .and(z.object({ tags: z.record(z.string(), z.string()) })),+ execute: (input) => ({ tagged: input }),+});+`,+ },+ });++ // The premise: the app's AI SDK converts schemas with the app's Zod.+ const requireFromAi = createRequire(+ realpathSync(join(app.appRoot, "node_modules", "ai", "package.json")),+ );+ const requireFromProviderUtils = createRequire(+ realpathSync(requireFromAi.resolve("@ai-sdk/provider-utils/package.json")),+ );+ expect(requireFromProviderUtils("zod/package.json")).toMatchObject({ version: "4.4.3" });++ const server = await startEveDev(app.appRoot, {+ env: { EVE_MOCK_AUTHORED_MODELS: "", NODE_ENV: "production" },+ });+ try {+ const client = new Client({ host: server.url });+ const { response } = await client.sessions.create({+ message: "Alice would like her pages filed and tagged.",+ outputSchema: OUTPUT_SCHEMA,+ });+ const result = await response.result();++ expect(result.events.some((event) => event.type === "turn.failed")).toBe(false);+ expect(server.stderr()).not.toContain("reading 'push'");+ expect(result.data).toEqual({+ advertised: REMOTE_INPUT_SCHEMA,+ results: [+ { id: "remote-valid", isError: false, output: { filed: VALID_REMOTE_INPUT } },+ { id: "remote-invalid", isError: true, output: expect.anything() },+ {+ id: "authored",+ isError: false,+ output: { tagged: { id: "page-1", tags: { status: "done" } } },+ },+ ],+ });+ } finally {+ await server.stop();+ }+ }, 360_000);+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex c478b9f21..dc0c5f0f4 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -252,6 +252,9 @@ catalogs:specifier: 4.5.4version: 4.5.4+overrides:+ '@vercel/cli-config>zod': 4.5.4+importers:.:@@ -1674,6 +1677,9 @@ importers:'@ai-sdk/provider-utils':specifier: 'catalog:'version: 5.0.43([email protected])+ '@cfworker/json-schema':+ specifier: 4.1.1+ version: 4.1.1'@chat-adapter/slack':specifier: 4.41.0version: 4.41.0([email protected]([email protected]))([email protected])([email protected]([email protected]))([email protected])([email protected])@@ -14927,9 +14933,6 @@ packages:resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}- resolution: {integrity: sha512-WPsqwxITS2tzx1bzhIKsEs19ABD5vmCVa4xBo2tq/SrV4RNZtfws1EnCWQXM6yh8bD08a1idvkB5MZSBiZsjwg==}-resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}@@ -20982,17 +20985,17 @@ snapshots:'@vercel/[email protected]':dependencies:xdg-app-paths: 5.5.1- zod: 4.1.11+ zod: 4.5.4'@vercel/[email protected]':dependencies:xdg-app-paths: 5.5.1- zod: 4.1.11+ zod: 4.5.4'@vercel/[email protected]':dependencies:xdg-app-paths: 5.5.1- zod: 4.1.11+ zod: 4.5.4'@vercel/[email protected]':dependencies:@@ -30545,8 +30548,6 @@ snapshots:- [email protected]: {}-diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex c33896bee..bea66726e 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -59,6 +59,12 @@ catalog:vitest: "4.1.10"zod: "4.5.4"+overrides:+ # eve ships one vendored Zod (packages/eve/scripts/vendor-compiled/zod.mjs).+ # @vercel/cli-config, which @vercel/oidc uses, pins its own Zod 4 release,+ # and the vendor build fails on a second copy.+ "@vercel/cli-config>zod": "catalog:"+minimumReleaseAge: 2880 # 2 daysminimumReleaseAgeExclude: