| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565 |
- import { describe, expect, it } from "vitest";
- import {
- createRootTraceContext,
- createSessionId,
- createToolCallId,
- createTurnId,
- } from "@zcode/contracts";
- import { createInMemoryHookRunner } from "../src/hooks/index.js";
- import { createManualPermissionBroker } from "../src/permission/broker.js";
- import { PermissionService, defaultPermissionConfig } from "../src/permission/service.js";
- import { createToolExecutor } from "../src/tool/executor.js";
- import { createToolRegistry } from "../src/tool/registry.js";
- import type { ToolEntry, ToolExecutionContext, ToolHandler } from "../src/tool/types.js";
- describe("tool execution input normalization", () => {
- it("safe-parses stringified JSON before tool execution when adapter input is still a string", async () => {
- const sessionId = createSessionId("tool-input-string");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- let capturedInput: unknown;
- registry.register(
- createToolEntry({
- name: "StringInputTool",
- runtimeInputSchema: objectRuntimeSchema((value) =>
- typeof value.value === "string" ? { value: value.value } : undefined,
- ),
- handler: async (input) => {
- capturedInput = input;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("string-input"),
- input: '{"value":"from-string"}',
- name: "StringInputTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(capturedInput).toEqual({ value: "from-string" });
- });
- it("applies runtime schema defaults before hooks and handlers", async () => {
- const sessionId = createSessionId("tool-input-defaults");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- let hookSawInput: unknown;
- let handlerSawInput: unknown;
- registry.register(
- createToolEntry({
- name: "DefaultingTool",
- runtimeInputSchema: objectRuntimeSchema((value) => ({
- flag: typeof value.flag === "boolean" ? value.flag : false,
- })),
- handler: async (input) => {
- handlerSawInput = input;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- flag: { type: "boolean" },
- },
- additionalProperties: false,
- },
- }),
- );
- const hookRunner = createInMemoryHookRunner({
- hooks: [
- {
- event: "PreToolUse",
- matcher: "DefaultingTool",
- callback: async (input) => {
- hookSawInput = input.toolInput;
- return undefined;
- },
- },
- ],
- });
- const executor = createToolExecutor({
- emitEvent: async () => {},
- hookRunner,
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("defaulting-input"),
- input: {},
- name: "DefaultingTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(hookSawInput).toEqual({ flag: false });
- expect(handlerSawInput).toEqual({ flag: false });
- });
- it("returns exact initial validation content for an adapter-normalized empty object", async () => {
- const sessionId = createSessionId("tool-input-malformed");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- let handlerRan = false;
- registry.register(
- createToolEntry({
- name: "AskUserQuestion",
- runtimeInputSchema: objectRuntimeSchema((value) =>
- Array.isArray(value.questions) ? { questions: value.questions } : undefined,
- ),
- handler: async () => {
- handlerRan = true;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- questions: { type: "array" },
- },
- required: ["questions"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("malformed-input"),
- input: {},
- name: "AskUserQuestion",
- },
- { traceContext },
- );
- expect(result.success).toBe(false);
- expect(result).toMatchObject({
- toolCallId: createToolCallId("malformed-input"),
- toolName: "AskUserQuestion",
- });
- expect(result.error?.message).toBe("Tool input failed inputSchema validation");
- expect(result.modelContent).toBe(
- [
- "<tool_use_error>InputValidationError: AskUserQuestion failed due to the following issue:",
- "The required parameter `questions` is missing</tool_use_error>",
- ].join("\n"),
- );
- expect(handlerRan).toBe(false);
- });
- it("uses the canonical tool name in initial validation content", async () => {
- const sessionId = createSessionId("tool-input-alias-validation");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- registry.register(
- createToolEntry({
- aliases: ["validation_alias"],
- name: "CanonicalValidationTool",
- runtimeInputSchema: objectRuntimeSchema((value) =>
- typeof value.value === "string" ? { value: value.value } : undefined,
- ),
- handler: async () => "ok",
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("alias-validation"),
- input: {},
- name: "validation_alias",
- },
- { traceContext },
- );
- expect(result.success).toBe(false);
- expect(result.toolName).toBe("CanonicalValidationTool");
- expect(result.modelContent).toContain(
- "InputValidationError: CanonicalValidationTool failed due to the following issue:",
- );
- });
- it("does not turn a runtime-only parser issue into a new initial rejection", async () => {
- const sessionId = createSessionId("tool-input-runtime-only-issue");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- let handlerSawInput: unknown;
- registry.register(
- createToolEntry({
- name: "RuntimeOnlyValidationTool",
- runtimeInputSchema: {
- safeParse: () => ({
- success: false,
- error: {
- issues: [{ code: "custom", message: "runtime-only issue", path: ["value"] }],
- },
- }),
- },
- handler: async (input) => {
- handlerSawInput = input;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const input = { value: "accepted-by-json-schema" };
- const result = await executor.execute(
- {
- id: createToolCallId("runtime-only-issue"),
- input,
- name: "RuntimeOnlyValidationTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(handlerSawInput).toEqual(input);
- });
- it("re-normalizes hook-updated stringified input before permission and handler execution", async () => {
- const sessionId = createSessionId("tool-input-hook-update");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- let handlerSawInput: unknown;
- registry.register(
- createToolEntry({
- name: "HookUpdatedInputTool",
- runtimeInputSchema: objectRuntimeSchema((value) =>
- typeof value.value === "string" ? { value: value.value } : undefined,
- ),
- handler: async (input) => {
- handlerSawInput = input;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const hookRunner = createInMemoryHookRunner({
- hooks: [
- {
- event: "PreToolUse",
- matcher: "HookUpdatedInputTool",
- callback: async () => ({
- hookSpecificOutput: {
- hookEventName: "PreToolUse",
- updatedInput: '{"value":"from-hook"}',
- },
- }),
- },
- ],
- });
- const executor = createToolExecutor({
- emitEvent: async () => {},
- hookRunner,
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("hook-updated-input"),
- input: { value: "initial" },
- name: "HookUpdatedInputTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(handlerSawInput).toEqual({ value: "from-hook" });
- });
- it("re-normalizes broker-modified stringified input before handler execution", async () => {
- const sessionId = createSessionId("tool-input-broker-update");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- const permissionBroker = createManualPermissionBroker({
- onRequest: (request) => {
- permissionBroker.resolvePermission(request.requestId, {
- decision: "modify",
- modifiedInput: '{"value":"from-broker"}',
- });
- },
- });
- let handlerSawInput: unknown;
- registry.register(
- createToolEntry({
- name: "BrokerUpdatedInputTool",
- needsApproval: true,
- runtimeInputSchema: objectRuntimeSchema((value) =>
- typeof value.value === "string" ? { value: value.value } : undefined,
- ),
- handler: async (input) => {
- handlerSawInput = input;
- return "ok";
- },
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionBroker,
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("broker-updated-input"),
- input: { value: "initial" },
- name: "BrokerUpdatedInputTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(true);
- expect(handlerSawInput).toEqual({ value: "from-broker" });
- });
- it("does not apply initial validation content to broker-modified input", async () => {
- const sessionId = createSessionId("tool-input-broker-invalid");
- const turnId = createTurnId("tool-turn");
- const traceContext = createRootTraceContext({ sessionId, turnId });
- const registry = createToolRegistry();
- const permissionBroker = createManualPermissionBroker({
- onRequest: (request) => {
- permissionBroker.resolvePermission(request.requestId, {
- decision: "modify",
- modifiedInput: {},
- });
- },
- });
- registry.register(
- createToolEntry({
- name: "BrokerInvalidInputTool",
- needsApproval: true,
- runtimeInputSchema: objectRuntimeSchema((value) =>
- typeof value.value === "string" ? { value: value.value } : undefined,
- ),
- handler: async () => "should-not-run",
- inputSchema: {
- type: "object",
- properties: {
- value: { type: "string" },
- },
- required: ["value"],
- additionalProperties: false,
- },
- }),
- );
- const executor = createToolExecutor({
- emitEvent: async () => {},
- permissionBroker,
- permissionService: new PermissionService(defaultPermissionConfig),
- registry,
- sessionId,
- turnId,
- traceContext,
- });
- const result = await executor.execute(
- {
- id: createToolCallId("broker-invalid-input"),
- input: { value: "initial" },
- name: "BrokerInvalidInputTool",
- },
- { traceContext },
- );
- expect(result.success).toBe(false);
- expect(result.error?.message).toBe("Tool input failed inputSchema validation");
- expect(result.modelContent).toBeUndefined();
- });
- });
- function createToolEntry(options: {
- aliases?: readonly string[];
- name: string;
- handler: ToolHandler;
- inputSchema: ToolEntry["inputSchema"];
- needsApproval?: boolean;
- runtimeInputSchema: unknown;
- }): ToolEntry {
- const needsApproval = options.needsApproval ?? false;
- return {
- aliases: options.aliases,
- capability: `${options.name} test capability`,
- metadata: {
- concurrentSafe: true,
- destructive: false,
- name: options.name,
- needsApproval,
- readOnly: true,
- riskLevel: needsApproval ? "medium" : "low",
- sideEffectScope: "none",
- timeoutMs: 30000,
- },
- handler: async (input: unknown, context: ToolExecutionContext) =>
- options.handler(input, context),
- inputSchema: options.inputSchema,
- outputSchema: {
- type: "string",
- },
- permission: {
- permission: "test",
- reason: "test tool",
- riskLevel: needsApproval ? "medium" : "low",
- sideEffectScope: "none",
- needsApproval,
- patternSources: ["none"],
- denyPriority: "beforeAsk",
- },
- resultBudget: {
- maxInlineBytes: 100_000,
- maxModelBytes: 100_000,
- strategy: "truncate",
- },
- runtimeInputSchema: options.runtimeInputSchema,
- timeout: {
- defaultMs: 30000,
- maxMs: 30000,
- allowCallOverride: false,
- },
- cancellation: {
- supported: true,
- cleanup: "none",
- userVisibleMessage: "Test tool was cancelled",
- },
- trace: {
- required: true,
- propagateToAdapters: true,
- recordInput: "summary",
- recordOutput: "summary",
- },
- };
- }
- function objectRuntimeSchema<T extends Record<string, unknown>>(
- normalize: (value: Record<string, unknown>) => T | undefined,
- ): { safeParse: (value: unknown) => { success: true; data: T } | { success: false } } {
- return {
- safeParse(value) {
- if (!value || typeof value !== "object" || Array.isArray(value)) {
- return { success: false };
- }
- const normalized = normalize(value as Record<string, unknown>);
- if (!normalized) {
- return { success: false };
- }
- return {
- success: true,
- data: normalized,
- };
- },
- };
- }
|