{"version":3,"sources":["../src/tools/validation.ts","../src/tools/tool.ts","../src/tools/toolchecks.ts"],"names":["standardSchemaToJSONSchema","unwrapZodType","isZodObject","getZodTypeName","isZodArray","toStandardSchema","RequestContext","resumeData"],"mappings":";;;;;;;AAaA,SAAS,YAAA,CACP,QACA,IAAA,EAC2D;AAC3D,EAAA,IAAI;AACF,IAAA,MAAM,MAAA,GAAS,MAAA,CAAO,WAAW,CAAA,CAAE,SAAS,IAAI,CAAA;AAChD,IAAA,IAAI,kBAAkB,OAAA,EAAS;AAC7B,MAAA,MAAM,IAAI,MAAM,yEAAyE,CAAA;AAAA,IAC3F;AACA,IAAA,OAAO,MAAA;AAAA,EACT,SAAS,GAAA,EAAK;AAGZ,IAAA,IAAI,eAAe,SAAA,IAAa,GAAA,CAAI,OAAA,CAAQ,QAAA,CAAS,qCAAqC,CAAA,EAAG;AAC3F,MAAA,MAAM,IAAI,KAAA;AAAA,QACR,CAAA,yNAAA,EAEgF,IAAI,OAAO,CAAA;AAAA,OAC7F;AAAA,IACF;AACA,IAAA,MAAM,GAAA;AAAA,EACR;AACF;AAiBO,SAAS,kBAAkB,KAAA,EAA0C;AAC1E,EAAA,OACE,KAAA,KAAU,IAAA,IACV,OAAO,KAAA,KAAU,QAAA,IACjB,WAAW,KAAA,IACX,KAAA,CAAM,KAAA,KAAU,IAAA,IAChB,kBAAA,IAAsB,KAAA;AAE1B;AAKA,SAAS,WAAW,OAAA,EAAqD;AACvE,EAAA,IAAI,OAAO,OAAA,KAAY,QAAA,IAAY,OAAA,KAAY,IAAA,IAAQ,SAAS,OAAA,EAAS;AACvE,IAAA,OAAO,MAAA,CAAO,QAAQ,GAAG,CAAA;AAAA,EAC3B;AACA,EAAA,OAAO,OAAO,OAAO,CAAA;AACvB;AAKA,SAAS,iBAAA,GAA2E;AAClF,EAAA,OAAO,EAAE,MAAA,EAAQ,EAAC,EAAG,MAAA,EAAQ,EAAC,EAAE;AAClC;AAQA,SAAS,qBAAwB,MAAA,EAAsE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tB;;;ACphBO,SAAS,aAAa,IAAA,EAAwB;AACnD,EAAA,OAAO,gBAAgB,IAAA,IAAS,OAAO,SAAS,QAAA,IAAY,IAAA,KAAS,QAAQ,kBAAA,IAAsB,IAAA;AACrG;AAOO,SAAS,aAAa,IAAA,EAA0C;AAKrE,EAAA,OAAO,CAAC,EACN,IAAA,IACA,CAAC,aAAa,IAAI,CAAA,KACjB,YAAA,IAAgB,IAAA,IAAS,aAAa,IAAA,IAAQ,OAAO,IAAA,CAAK,OAAA,KAAY,cAAc,aAAA,IAAiB,IAAA,CAAA,CAAA;AAE1G;AAoBO,SAAS,sBAAsB,IAAA,EAAqC;AACzE,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,IAAY,IAAA,KAAS,MAAM,OAAO,KAAA;AACtD,EAAA,MAAM,CAAA,GAAI,IAAA;AACV,EAAA,MAAM,cAAA,GAAiB,CAAA,CAAE,IAAA,KAAS,kBAAA,IAAsB,EAAE,IAAA,KAAS,UAAA;AACnE,EAAA,OAAO,cAAA,IAAkB,OAAO,CAAA,CAAE,EAAA,KAAO,QAAA;AAC3C;AAKO,IAAM,cAAA,GAAiB;AAMvB,SAAS,oBAAoB,UAAA,EAA4B;AAC9D,EAAA,OAAO,UAAA,CAAW,MAAM,GAAG,CAAA,CAAE,MAAM,CAAC,CAAA,CAAE,KAAK,GAAG,CAAA;AAChD","file":"chunk-7FEPHEDB.cjs","sourcesContent":["import type { RequestContext } from '../request-context';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, StandardSchemaIssue } from '../schema';\nimport { getZodTypeName, isZodArray, isZodObject, unwrapZodType } from '../utils/zod-utils';\n\n/**\n * Safely validates data against a Standard Schema.\n * Catches internal Zod errors (like undefined union options) and provides better error messages.\n *\n * @param schema The Standard Schema to validate against\n * @param data The data to validate\n * @returns The validation result or throws with a descriptive error\n */\nfunction safeValidate<T>(\n  schema: StandardSchemaWithJSON<T>,\n  data: unknown,\n): { value: T } | { issues: readonly StandardSchemaIssue[] } {\n  try {\n    const result = schema['~standard'].validate(data);\n    if (result instanceof Promise) {\n      throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n    }\n    return result as { value: T } | { issues: readonly StandardSchemaIssue[] };\n  } catch (err) {\n    // Catch Zod internal errors like \"Cannot read properties of undefined (reading 'run')\"\n    // This happens when a union schema has undefined options\n    if (err instanceof TypeError && err.message.includes('Cannot read properties of undefined')) {\n      throw new Error(\n        `Schema validation failed due to an invalid schema definition. ` +\n          `This often happens when a union schema (z.union or z.or) has undefined options. ` +\n          `Please check that all schema options are properly defined. Original error: ${err.message}`,\n      );\n    }\n    throw err;\n  }\n}\n\n/**\n * Formatted validation errors structure.\n * Contains `errors` array for messages at this level, and `fields` for nested field errors.\n */\nexport type FormattedValidationErrors<T = unknown> = {\n  errors: string[];\n  fields: T extends object ? { [K in keyof T]?: FormattedValidationErrors<T[K]> } : unknown;\n};\n\nexport interface ValidationError<T = unknown> {\n  error: true;\n  message: string;\n  validationErrors: FormattedValidationErrors<T>;\n}\n\nexport function isValidationError(value: unknown): value is ValidationError {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    'error' in value &&\n    value.error === true &&\n    'validationErrors' in value\n  );\n}\n\n/**\n * Extracts a string key from a path segment (handles both PropertyKey and PathSegment objects).\n */\nfunction getPathKey(segment: PropertyKey | { key: PropertyKey }): string {\n  if (typeof segment === 'object' && segment !== null && 'key' in segment) {\n    return String(segment.key);\n  }\n  return String(segment);\n}\n\n/**\n * Creates an empty FormattedValidationErrors object.\n */\nfunction createEmptyErrors(): { errors: string[]; fields: Record<string, unknown> } {\n  return { errors: [], fields: {} };\n}\n\n/**\n * Builds a formatted errors object from standard schema validation issues.\n *\n * @param issues Array of validation issues from standard schema validation\n * @returns Formatted errors object with nested structure based on paths\n */\nfunction buildFormattedErrors<T>(issues: readonly StandardSchemaIssue[]): FormattedValidationErrors<T> {\n  const result = createEmptyErrors();\n\n  for (const issue of issues) {\n    if (!issue.path || issue.path.length === 0) {\n      // Root-level error\n      result.errors.push(issue.message);\n    } else {\n      // Nested error - build path through fields\n      let current = result;\n      for (let i = 0; i < issue.path.length; i++) {\n        const key = getPathKey(issue.path[i]!);\n        if (i === issue.path.length - 1) {\n          // Last segment - add the error message\n          if (!current.fields[key]) {\n            current.fields[key] = createEmptyErrors();\n          }\n          (current.fields[key] as { errors: string[]; fields: Record<string, unknown> }).errors.push(issue.message);\n        } else {\n          // Intermediate segment - ensure object exists\n          if (!current.fields[key]) {\n            current.fields[key] = createEmptyErrors();\n          }\n          current = current.fields[key] as { errors: string[]; fields: Record<string, unknown> };\n        }\n      }\n    }\n  }\n\n  return result as FormattedValidationErrors<T>;\n}\n\n/**\n * Safely truncates data for error messages to avoid exposing sensitive information.\n * @param data The data to truncate\n * @param maxLength Maximum length of the truncated string (default: 200)\n * @returns Truncated string representation\n */\nfunction truncateForLogging(data: unknown, maxLength: number = 200): string {\n  try {\n    const stringified = JSON.stringify(data, null, 2);\n    if (stringified.length <= maxLength) {\n      return stringified;\n    }\n    return stringified.slice(0, maxLength) + '... (truncated)';\n  } catch {\n    return '[Unable to serialize data]';\n  }\n}\n\n/**\n * Validates raw suspend data against a schema.\n *\n * @param schema The schema to validate against\n * @param suspendData The raw suspend data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolSuspendData<T = unknown>(\n  schema: StandardSchemaWithJSON<T> | undefined,\n  suspendData: unknown,\n  toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n  // If no schema, or schema is not a Standard Schema, return suspend data as-is\n  if (!schema || !('~standard' in schema)) {\n    return { data: suspendData as T };\n  }\n\n  // Validate the input using standard schema interface\n  const validation = safeValidate(schema, suspendData);\n\n  if ('value' in validation) {\n    return { data: validation.value };\n  }\n\n  // Validation failed, return error\n  const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n  const error: ValidationError<T> = {\n    error: true,\n    message: `Tool suspension data validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(suspendData)}`,\n    validationErrors: buildFormattedErrors<T>(validation.issues),\n  };\n\n  return { error };\n}\n\n/**\n * Normalizes undefined/null input to an appropriate default value based on schema type.\n * This handles LLMs (Claude Sonnet 4.5, Gemini 2.4, etc.) that send undefined/null\n * instead of {} or [] when all parameters are optional.\n *\n * @param schema The Zod schema to check\n * @param input The input to normalize\n * @returns The normalized input (original value, {}, or [])\n */\nfunction normalizeNullishInput(schema: StandardSchemaWithJSON<any>, input: unknown): unknown {\n  if (typeof input !== 'undefined' && input !== null) {\n    return input;\n  }\n\n  const jsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n\n  // Check if schema is an array type (using typeName to avoid dual-package hazard)\n  if (jsonSchema.type === 'array') {\n    return [];\n  }\n\n  // Check if schema is an object type (using typeName to avoid dual-package hazard)\n  if (jsonSchema.type === 'object') {\n    return {};\n  }\n\n  // For other schema types, return the original input and let Zod validate\n  return input;\n}\n\n/**\n * Checks if a value is a plain object (created by {} or new Object()).\n * This excludes class instances, built-in objects like Date/Map/URL, etc.\n *\n * @param value The value to check\n * @returns true if the value is a plain object\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (value === null || typeof value !== 'object') {\n    return false;\n  }\n  const proto = Object.getPrototypeOf(value);\n  return proto === Object.prototype || proto === null;\n}\n\n/**\n * Recursively converts undefined values to null in an object.\n * This is needed for OpenAI compat layers which convert .optional() to .nullable()\n * for strict mode compliance. When fields are omitted (undefined), we convert them\n * to null so the schema validation passes, and the transform then converts null back\n * to undefined. (GitHub #11457)\n *\n * Only recurses into plain objects to preserve class instances and built-in objects\n * like Date, Map, URL, etc. (GitHub #11502)\n *\n * @param input The input to process\n * @returns The processed input with undefined values converted to null\n */\nfunction convertUndefinedToNull(input: unknown): unknown {\n  if (input === undefined) {\n    return null;\n  }\n\n  if (input === null || typeof input !== 'object') {\n    return input;\n  }\n\n  if (Array.isArray(input)) {\n    return input.map(convertUndefinedToNull);\n  }\n\n  // Only recurse into plain objects - preserve class instances, built-in objects\n  // (Date, Map, Set, URL, etc.) and any other non-plain objects\n  if (!isPlainObject(input)) {\n    return input;\n  }\n\n  // It's a plain object - recursively process all properties\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(input)) {\n    result[key] = convertUndefinedToNull(value);\n  }\n  return result;\n}\n\n/**\n * Recursively strips null/undefined values from object properties.\n * This handles LLMs (e.g. Gemini) that send null for .optional() fields,\n * where Zod expects undefined, not null. By stripping nullish values,\n * we let Zod treat them as \"not provided\" which matches .optional() semantics.\n * (GitHub #12362)\n *\n * @param input The input to process\n * @returns The processed input with null/undefined values stripped from objects\n */\nfunction stripNullishValues(input: unknown): unknown {\n  // Top-level null/undefined becomes undefined\n  if (input === null || input === undefined) {\n    return undefined;\n  }\n\n  if (typeof input !== 'object') {\n    return input;\n  }\n\n  if (Array.isArray(input)) {\n    // For arrays, recursively process elements but keep nulls in arrays\n    // (array elements with null may be intentional)\n    return input.map(item => (item === null ? null : stripNullishValues(item)));\n  }\n\n  // Only recurse into plain objects - preserve class instances, built-in objects\n  if (!isPlainObject(input)) {\n    return input;\n  }\n\n  // It's a plain object - recursively process all properties, omitting null/undefined values\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(input)) {\n    if (value === null || value === undefined) {\n      // Omit null/undefined values - equivalent to \"not provided\" for optional fields\n      continue;\n    }\n    result[key] = stripNullishValues(value);\n  }\n  return result;\n}\n\n/**\n * Strip null/undefined values only at specific paths that caused validation errors.\n * Preserves null for .nullable() fields that are valid.\n */\nfunction stripNullishValuesAtPaths(input: unknown, paths: Set<string>, currentPath = ''): unknown {\n  if (input === null || input === undefined) {\n    return paths.has(currentPath) ? undefined : input;\n  }\n\n  if (typeof input !== 'object') {\n    return input;\n  }\n\n  if (Array.isArray(input)) {\n    return input.map((item, i) =>\n      stripNullishValuesAtPaths(item, paths, currentPath ? `${currentPath}.${i}` : String(i)),\n    );\n  }\n\n  if (!isPlainObject(input)) {\n    return input;\n  }\n\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(input)) {\n    const fieldPath = currentPath ? `${currentPath}.${key}` : key;\n    if ((value === null || value === undefined) && paths.has(fieldPath)) {\n      // Only omit null/undefined for fields that caused validation errors\n      continue;\n    }\n    result[key] = stripNullishValuesAtPaths(value, paths, fieldPath);\n  }\n  return result;\n}\n\n/**\n * Gets the value at a path in a nested object, using the same path segment format\n * as Standard Schema validation issues.\n *\n * @param obj The object to traverse\n * @param pathSegments Array of path segments from a validation issue\n * @returns The value at the path, or a sentinel symbol if the path doesn't exist\n */\nconst PATH_NOT_FOUND = Symbol('PATH_NOT_FOUND');\nfunction getValueAtPath(obj: unknown, pathSegments: ReadonlyArray<PropertyKey | { key: PropertyKey }>): unknown {\n  let current: unknown = obj;\n  for (const segment of pathSegments) {\n    if (current === null || current === undefined || typeof current !== 'object') {\n      return PATH_NOT_FOUND;\n    }\n    const key =\n      typeof segment === 'object' && segment !== null && 'key' in segment ? String(segment.key) : String(segment);\n    current = (current as Record<string, unknown>)[key];\n  }\n  return current;\n}\n\n/**\n * Coerces stringified JSON values in object properties when the schema expects\n * an array or object but the LLM returned a JSON string.\n *\n * Some LLMs (e.g., GLM4.7) return stringified JSON for array/object parameters:\n *   { \"args\": \"[\\\"parse_excel.py\\\"]\" }\n * instead of:\n *   { \"args\": [\"parse_excel.py\"] }\n *\n * This function walks the top-level properties of a plain object and attempts\n * to JSON.parse string values when the schema expects a non-string type.\n * (GitHub #12757)\n *\n * @param schema The Zod schema to check field types against\n * @param input The input to process\n * @returns The input with stringified JSON values coerced, or the original input\n */\nfunction coerceStringifiedJsonValues(schema: StandardSchemaWithJSON<unknown>, input: unknown): unknown {\n  // Only process plain objects with object schemas\n  if (!isPlainObject(input)) {\n    return input;\n  }\n\n  const unwrapped = unwrapZodType(schema as any);\n  if (!isZodObject(unwrapped)) {\n    return input;\n  }\n\n  const shape = (unwrapped as any).shape;\n  if (!shape || typeof shape !== 'object') {\n    return input;\n  }\n\n  let changed = false;\n  const result: Record<string, unknown> = { ...input };\n\n  for (const [key, value] of Object.entries(input)) {\n    if (typeof value !== 'string') {\n      continue;\n    }\n\n    const fieldSchema = shape[key];\n    if (!fieldSchema) {\n      continue;\n    }\n\n    // Unwrap the field schema to find the base type\n    const baseFieldSchema = unwrapZodType(fieldSchema);\n\n    // Only attempt coercion if the schema expects a non-string type\n    // and the string looks like it could be JSON (starts with [ or {)\n    if (getZodTypeName(baseFieldSchema) === 'ZodString') {\n      continue;\n    }\n\n    const trimmed = value.trim();\n    if (\n      (isZodArray(baseFieldSchema) && trimmed.startsWith('[')) ||\n      (isZodObject(baseFieldSchema) && trimmed.startsWith('{'))\n    ) {\n      try {\n        const parsed = JSON.parse(value);\n        if (\n          (isZodArray(baseFieldSchema) && Array.isArray(parsed)) ||\n          (isZodObject(baseFieldSchema) && isPlainObject(parsed))\n        ) {\n          result[key] = parsed;\n          changed = true;\n        }\n      } catch {\n        // Not valid JSON, leave as-is\n      }\n    }\n  }\n\n  return changed ? result : input;\n}\n\n/**\n * Validates raw input data against a schema.\n *\n * @param schema The schema to validate against (or undefined to skip validation)\n * @param input The raw input data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolInput<T = unknown>(\n  schema: StandardSchemaWithJSON<T> | undefined,\n  input: unknown,\n  toolId?: string,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n  // If no schema, or schema is not a Standard Schema (e.g. plain JSON Schema from Vercel tools),\n  // return input as-is. Only validate when we have a proper Standard Schema with ~standard.validate.\n  if (!schema || !('~standard' in schema)) {\n    return { data: input as T };\n  }\n\n  // Validation pipeline:\n  //\n  // 1. normalizeNullishInput: Convert top-level null/undefined to {} or [] based on schema type.\n  //    Handles LLMs that send undefined instead of {} or [] for all-optional parameters.\n  //\n  // 2. convertUndefinedToNull: Convert undefined values to null in object properties.\n  //    Needed for OpenAI compat layers that convert .optional() to .nullable() for\n  //    strict mode compliance. The schema's transform converts null back to undefined.\n  //    (GitHub #11457)\n  //\n  // 3. First validation attempt with null values preserved. This handles .nullable()\n  //    schemas correctly (where null is a valid value).\n  //\n  // 4. If validation fails, retry with stringified JSON values coerced to their\n  //    proper types. Some LLMs (e.g. GLM4.7) return JSON arrays/objects as strings.\n  //    (GitHub #12757)\n  //\n  // 5. If validation still fails, retry with null values stripped from object properties.\n  //    This handles LLMs (e.g. Gemini) that send null for .optional() fields, where\n  //    Zod expects undefined, not null. (GitHub #12362)\n\n  // Step 1: Normalize top-level null/undefined to appropriate default\n  let normalizedInput = normalizeNullishInput(schema, input);\n\n  // Step 2: Convert undefined values to null recursively (GitHub #11457)\n  normalizedInput = convertUndefinedToNull(normalizedInput);\n\n  // Step 3: Validate the normalized input\n  const validation = safeValidate(schema, normalizedInput);\n\n  if ('value' in validation) {\n    return { data: validation.value };\n  }\n\n  // Step 4: Retry with stringified JSON values coerced (GitHub #12757)\n  // LLMs like GLM4.7 send stringified JSON for array/object parameters, e.g.\n  // { \"args\": \"[\\\"file.py\\\"]\" } instead of { \"args\": [\"file.py\"] }.\n  const coercedInput = coerceStringifiedJsonValues(schema, normalizedInput);\n  if (coercedInput !== normalizedInput) {\n    const coercedValidation = safeValidate(schema, coercedInput);\n    if ('value' in coercedValidation) {\n      return { data: coercedValidation.value };\n    }\n  }\n\n  // Step 5: Retry with null values stripped only for failing fields (GitHub #12362)\n  // LLMs like Gemini send null for optional fields, but Zod's .optional() only\n  // accepts undefined, not null. We only strip nulls for fields that caused\n  // validation errors, preserving null for .nullable() schemas that need it.\n  //\n  // We detect null-related failures by checking the actual value at the failing\n  // path rather than relying on error message string matching (GitHub #14476).\n  // This ensures we catch null values regardless of the validator's error message\n  // format (e.g., \"must be string\", \"must be object\", etc.).\n  const failingNullPaths = new Set(\n    validation.issues\n      .filter(issue => {\n        if (!issue.path || issue.path.length === 0) return false;\n        const value = getValueAtPath(normalizedInput, issue.path);\n        return value === null || value === undefined;\n      })\n      .map(issue => issue.path?.map(p => (typeof p === 'object' && 'key' in p ? String(p.key) : String(p))).join('.'))\n      .filter((p): p is string => !!p),\n  );\n  const strippedInput =\n    failingNullPaths.size > 0 ? stripNullishValuesAtPaths(input, failingNullPaths) : stripNullishValues(input);\n  const normalizedStripped = normalizeNullishInput(schema, strippedInput);\n  const retryValidation = safeValidate(schema, normalizedStripped);\n\n  if ('value' in retryValidation) {\n    return { data: retryValidation.value };\n  }\n\n  // Step 6: Retry with common prompt alias normalization (GitHub #14154)\n  // LLMs (especially Claude Sonnet via custom gateways) sometimes drift from\n  // using \"prompt\" to \"query\", \"message\", or \"input\" after repeated sub-agent\n  // tool calls in the same thread. Coerce these aliases to \"prompt\" and retry.\n  // Only applies when the schema actually declares a \"prompt\" field.\n  const promptJsonSchema = standardSchemaToJSONSchema(schema, { io: 'input' });\n  const schemaExpectsPrompt =\n    promptJsonSchema.type === 'object' &&\n    promptJsonSchema.properties != null &&\n    'prompt' in promptJsonSchema.properties;\n\n  if (\n    schemaExpectsPrompt &&\n    normalizedInput != null &&\n    typeof normalizedInput === 'object' &&\n    !Array.isArray(normalizedInput)\n  ) {\n    const obj = normalizedInput as Record<string, unknown>;\n    if (obj.prompt == null) {\n      const alias = [obj.query, obj.message, obj.input].find((v): v is string => typeof v === 'string');\n      if (alias !== undefined) {\n        const coercedPromptInput = { ...obj, prompt: alias };\n        const coercedPromptValidation = safeValidate(schema, coercedPromptInput);\n        if ('value' in coercedPromptValidation) {\n          return { data: coercedPromptValidation.value };\n        }\n      }\n    }\n  }\n\n  // All attempts failed - return the original (non-stripped) error since it's\n  // more informative about what the schema actually expects\n  const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n  const error: ValidationError<T> = {\n    error: true,\n    message: `Tool input validation failed${toolId ? ` for ${toolId}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided arguments: ${truncateForLogging(input)}`,\n    validationErrors: buildFormattedErrors<T>(validation.issues),\n  };\n\n  return { error };\n}\n\n/**\n * Validates tool output data against a schema.\n *\n * @param schema The schema to validate against\n * @param output The output data to validate\n * @param toolId Optional tool ID for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateToolOutput<T = unknown>(\n  schema: StandardSchemaWithJSON<T> | undefined,\n  output: unknown,\n  toolId?: string,\n  suspendCalled?: boolean,\n): { data: T; error?: undefined } | { data?: undefined; error: ValidationError<T> } {\n  // If no schema, not a Standard Schema, or suspend was called, return output as-is\n  if (!schema || !('~standard' in schema) || suspendCalled) {\n    return { data: output as T };\n  }\n\n  // Validate the output using standard schema interface\n  const validation = safeValidate(schema, output);\n\n  if ('value' in validation) {\n    return { data: validation.value };\n  }\n\n  // Validation failed, return error\n  const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n  const error: ValidationError<T> = {\n    error: true,\n    message: `Tool output validation failed${toolId ? ` for ${toolId}` : ''}. The tool returned invalid output:\\n${errorMessages}\\n\\nReturned output: ${truncateForLogging(output)}`,\n    validationErrors: buildFormattedErrors<T>(validation.issues),\n  };\n\n  return { error };\n}\n\n/**\n * Keys that are considered sensitive and should be redacted in error messages.\n */\nconst SENSITIVE_KEYS = ['password', 'secret', 'token', 'apiKey', 'api_key', 'auth', 'credential'];\n\n/**\n * Redacts sensitive keys from an object for safe logging.\n * @param obj The object to redact\n * @returns A new object with sensitive values replaced with '[REDACTED]'\n */\nfunction redactSensitiveKeys(obj: unknown): unknown {\n  if (obj === null || typeof obj !== 'object') {\n    return obj;\n  }\n\n  if (Array.isArray(obj)) {\n    return obj.map(redactSensitiveKeys);\n  }\n\n  const result: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(obj)) {\n    if (SENSITIVE_KEYS.some(sensitive => key.toLowerCase().includes(sensitive.toLowerCase()))) {\n      result[key] = '[REDACTED]';\n    } else if (typeof value === 'object' && value !== null) {\n      result[key] = redactSensitiveKeys(value);\n    } else {\n      result[key] = value;\n    }\n  }\n  return result;\n}\n\n/**\n * Validates request context data against a schema.\n * This is used to validate the request context before tool execution.\n *\n * @param schema The schema to validate against (PublicSchema which accepts Zod, JSONSchema, etc.)\n * @param requestContext The request context to validate\n * @param identifier Optional identifier (tool/step ID) for better error messages\n * @returns The validated data or a validation error\n */\nexport function validateRequestContext<T = any>(\n  schema: PublicSchema<T> | undefined,\n  requestContext: RequestContext | undefined,\n  identifier?: string,\n): { data: T | Record<string, any>; error?: ValidationError<T> } {\n  // If no schema, return request context values as-is\n  if (!schema) {\n    return { data: (requestContext?.all ?? {}) as T };\n  }\n\n  // Get the values from request context\n  const contextValues = requestContext?.all ?? {};\n\n  // Convert PublicSchema to StandardSchemaWithJSON for validation\n  const standardSchema = toStandardSchema(schema);\n\n  // Validate using standard schema interface\n  const validation = standardSchema['~standard'].validate(contextValues);\n\n  if (validation instanceof Promise) {\n    throw new Error('Your schema is async, which is not supported. Please use a sync schema.');\n  }\n\n  if ('value' in validation) {\n    return { data: validation.value };\n  }\n\n  // Validation failed, return error\n  const errorMessages = validation.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n  // Redact sensitive keys before including in error message\n  const redactedContext = redactSensitiveKeys(contextValues);\n\n  const error: ValidationError<T> = {\n    error: true,\n    message: `Request context validation failed${identifier ? ` for ${identifier}` : ''}. Please fix the following errors and try again:\\n${errorMessages}\\n\\nProvided request context: ${truncateForLogging(redactedContext)}`,\n    validationErrors: buildFormattedErrors<T>(validation.issues),\n  };\n\n  return { data: contextValues as T, error };\n}\n","import type { Mastra } from '../mastra';\nimport { RequestContext } from '../request-context';\nimport { toStandardSchema } from '../schema';\nimport type { PublicSchema, StandardSchemaWithJSON, InferPublicSchema } from '../schema';\nimport type { SuspendOptions } from '../workflows';\nimport type { McpMetadata, MCPToolProperties, ToolAction, ToolExecutionContext } from './types';\nimport { validateToolInput, validateToolOutput, validateToolSuspendData, validateRequestContext } from './validation';\n\n/**\n * Marker to identify Mastra tools even when `instanceof` fails.\n * This can happen in environments like Vite SSR where the same module\n * may be loaded multiple times, creating different class instances.\n * Uses Symbol.for() so the same symbol is shared across module copies.\n * Follows the naming convention: <org>.<product>.<category>.<className>\n */\nexport const MASTRA_TOOL_MARKER = Symbol.for('mastra.core.tool.Tool');\n\n/**\n * A type-safe tool that agents and workflows can call to perform specific actions.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n *\n * @example Basic tool with validation\n * ```typescript\n * const weatherTool = createTool({\n *   id: 'get-weather',\n *   description: 'Get weather for a location',\n *   inputSchema: z.object({\n *     location: z.string(),\n *     units: z.enum(['celsius', 'fahrenheit']).optional()\n *   }),\n *   execute: async (inputData) => {\n *     return await fetchWeather(inputData.location, inputData.units);\n *   }\n * });\n * ```\n *\n * @example Tool requiring approval\n * ```typescript\n * const deleteFileTool = createTool({\n *   id: 'delete-file',\n *   description: 'Delete a file',\n *   requireApproval: true,\n *   inputSchema: z.object({ filepath: z.string() }),\n *   execute: async (inputData) => {\n *     await fs.unlink(inputData.filepath);\n *     return { deleted: true };\n *   }\n * });\n * ```\n *\n * @example Tool with Mastra integration\n * ```typescript\n * const saveTool = createTool({\n *   id: 'save-data',\n *   description: 'Save data to storage',\n *   inputSchema: z.object({ key: z.string(), value: z.any() }),\n *   execute: async (inputData, context) => {\n *     const storage = context?.mastra?.getStorage();\n *     await storage?.set(inputData.key, inputData.value);\n *     return { saved: true };\n *   }\n * });\n * ```\n */\nexport class Tool<\n  TSchemaIn = unknown,\n  TSchemaOut = unknown,\n  TSuspendSchema = unknown,\n  TResumeSchema = unknown,\n  TContext extends ToolExecutionContext<TSuspendSchema, TResumeSchema, any> = ToolExecutionContext<\n    TSuspendSchema,\n    TResumeSchema\n  >,\n  TId extends string = string,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> implements ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext> {\n  /** Unique identifier for the tool */\n  id: TId;\n\n  /** Description of what the tool does */\n  description: string;\n\n  /** Schema for validating input parameters */\n  inputSchema?: StandardSchemaWithJSON<TSchemaIn>;\n\n  /** Schema for validating output structure */\n  outputSchema?: StandardSchemaWithJSON<TSchemaOut>;\n\n  /** Schema for suspend operation data */\n  suspendSchema?: StandardSchemaWithJSON<TSuspendSchema>;\n\n  /** Schema for resume operation data */\n  resumeSchema?: StandardSchemaWithJSON<TResumeSchema>;\n\n  /**\n   * Schema for validating request context values.\n   * When provided, the request context will be validated against this schema before tool execution.\n   */\n  requestContextSchema?: PublicSchema<TRequestContext>;\n\n  /**\n   * Tool execution function\n   * @param inputData - The raw, validated input data\n   * @param context - Optional execution context with metadata\n   * @returns Promise resolving to tool output or a ValidationError if input validation fails\n   */\n  execute?: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>['execute'];\n\n  /** Parent Mastra instance for accessing shared resources */\n  mastra?: Mastra;\n\n  /**\n   * Whether the tool requires explicit user approval before execution\n   * @example\n   * ```typescript\n   * // For destructive operations\n   * requireApproval: true\n   * ```\n   */\n  requireApproval?: boolean;\n\n  /**\n   * Enables strict tool input generation for providers that support it.\n   */\n  strict?: boolean;\n\n  /**\n   * Provider-specific options passed to the model when this tool is used.\n   * Keys are provider names (e.g., 'anthropic', 'openai'), values are provider-specific configs.\n   * @example\n   * ```typescript\n   * providerOptions: {\n   *   anthropic: {\n   *     cacheControl: { type: 'ephemeral' }\n   *   }\n   * }\n   * ```\n   */\n  providerOptions?: Record<string, Record<string, unknown>>;\n\n  /**\n   * Optional function to transform the tool's raw output before sending it to the model.\n   * The raw result is still available for application logic; only the model sees the transformed version.\n   */\n  toModelOutput?: (output: TSchemaOut) => unknown;\n\n  /**\n   * Optional MCP-specific properties including annotations and metadata.\n   * Only relevant when the tool is being used in an MCP context.\n   * @example\n   * ```typescript\n   * mcp: {\n   *   annotations: {\n   *     title: 'Weather Lookup',\n   *     readOnlyHint: true,\n   *     destructiveHint: false\n   *   },\n   *   _meta: {\n   *     version: '1.0.0',\n   *     author: 'team@example.com'\n   *   }\n   * }\n   * ```\n   */\n  mcp?: MCPToolProperties;\n\n  onInputStart?: ToolAction<\n    TSchemaIn,\n    TSchemaOut,\n    TSuspendSchema,\n    TResumeSchema,\n    TContext,\n    TId,\n    TRequestContext\n  >['onInputStart'];\n  onInputDelta?: ToolAction<\n    TSchemaIn,\n    TSchemaOut,\n    TSuspendSchema,\n    TResumeSchema,\n    TContext,\n    TId,\n    TRequestContext\n  >['onInputDelta'];\n  onInputAvailable?: ToolAction<\n    TSchemaIn,\n    TSchemaOut,\n    TSuspendSchema,\n    TResumeSchema,\n    TContext,\n    TId,\n    TRequestContext\n  >['onInputAvailable'];\n  onOutput?: ToolAction<\n    TSchemaIn,\n    TSchemaOut,\n    TSuspendSchema,\n    TResumeSchema,\n    TContext,\n    TId,\n    TRequestContext\n  >['onOutput'];\n\n  /**\n   * Examples of valid tool inputs passed through to the AI SDK.\n   */\n  inputExamples?: Array<{ input: Record<string, unknown> }>;\n\n  /**\n   * Metadata identifying this tool as originating from an MCP server.\n   * Set automatically by the MCP client when creating tools.\n   */\n  mcpMetadata?: McpMetadata;\n\n  /**\n   * Creates a new Tool instance with input validation wrapper.\n   *\n   * @param opts - Tool configuration and execute function\n   * @example\n   * ```typescript\n   * const tool = new Tool({\n   *   id: 'my-tool',\n   *   description: 'Does something useful',\n   *   inputSchema: z.object({ name: z.string() }),\n   *   execute: async (inputData) => ({ greeting: `Hello ${inputData.name}` })\n   * });\n   * ```\n   */\n  constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TSuspendSchema, TResumeSchema, TContext, TId, TRequestContext>) {\n    (this as any)[MASTRA_TOOL_MARKER] = true;\n    this.id = opts.id;\n    this.description = opts.description;\n    this.inputSchema = opts.inputSchema ? toStandardSchema(opts.inputSchema) : undefined;\n    this.outputSchema = opts.outputSchema ? toStandardSchema(opts.outputSchema) : undefined;\n    this.suspendSchema = opts.suspendSchema ? toStandardSchema(opts.suspendSchema) : undefined;\n    this.resumeSchema = opts.resumeSchema ? toStandardSchema(opts.resumeSchema) : undefined;\n    this.requestContextSchema = opts.requestContextSchema;\n    this.mastra = opts.mastra;\n    this.requireApproval = opts.requireApproval || false;\n    this.strict = opts.strict;\n    this.providerOptions = opts.providerOptions;\n    this.toModelOutput = opts.toModelOutput;\n    this.inputExamples = opts.inputExamples;\n    this.mcp = opts.mcp;\n    this.mcpMetadata = opts.mcpMetadata;\n    this.onInputStart = opts.onInputStart;\n    this.onInputDelta = opts.onInputDelta;\n    this.onInputAvailable = opts.onInputAvailable;\n    this.onOutput = opts.onOutput;\n\n    // Tools receive two parameters:\n    // 1. input - The raw, validated input data\n    // 2. context - Execution metadata (mastra, suspend, etc.)\n    if (opts.execute) {\n      const originalExecute = opts.execute;\n      this.execute = async (inputData: TSchemaIn, context?: any) => {\n        // Validate input if schema exists\n        const { data, error } = validateToolInput(this.inputSchema, inputData, this.id);\n        if (error) {\n          return error;\n        }\n\n        // Validate request context if schema exists\n        const { error: requestContextError } = validateRequestContext(\n          this.requestContextSchema,\n          context?.requestContext,\n          this.id,\n        );\n        if (requestContextError) {\n          return requestContextError as any;\n        }\n\n        let suspendData = null;\n\n        const baseContext = context\n          ? {\n              ...context,\n              ...(context.suspend\n                ? {\n                    suspend: (args: any, suspendOptions?: SuspendOptions) => {\n                      suspendData = args;\n                      return context.suspend?.(args, suspendOptions);\n                    },\n                  }\n                : {}),\n            }\n          : {};\n\n        // Organize context based on execution source\n        let organizedContext = baseContext;\n        if (!context) {\n          // No context provided - create a minimal context with requestContext\n          organizedContext = {\n            requestContext: new RequestContext(),\n            mastra: undefined,\n          };\n        } else {\n          // Check if this is agent execution (has toolCallId and messages)\n          const isAgentExecution = baseContext.toolCallId && baseContext.messages;\n\n          // Check if this is workflow execution (has workflow properties)\n          // Agent execution takes precedence - don't treat as workflow if it's an agent call\n          const isWorkflowExecution = !isAgentExecution && (baseContext.workflow || baseContext.workflowId);\n\n          if (isAgentExecution && !baseContext.agent) {\n            // Reorganize agent context - nest agent-specific properties under 'agent' key\n            const {\n              agentId,\n              toolCallId,\n              messages,\n              suspend,\n              resumeData,\n              threadId,\n              resourceId,\n              writableStream,\n              ...rest\n            } = baseContext;\n            organizedContext = {\n              ...rest,\n              agent: {\n                agentId: agentId || '',\n                toolCallId,\n                messages,\n                suspend,\n                resumeData,\n                threadId,\n                resourceId,\n                writableStream,\n              },\n              // Ensure requestContext is always present\n              requestContext: rest.requestContext || new RequestContext(),\n            };\n          } else if (isWorkflowExecution && !baseContext.workflow) {\n            // Reorganize workflow context - nest workflow-specific properties under 'workflow' key\n            const { workflowId, runId, state, setState, suspend, resumeData, ...rest } = baseContext;\n            organizedContext = {\n              ...rest,\n              workflow: {\n                workflowId,\n                runId,\n                state,\n                setState,\n                suspend,\n                resumeData,\n              },\n              // Ensure requestContext is always present\n              requestContext: rest.requestContext || new RequestContext(),\n            };\n          } else {\n            // Ensure requestContext is always present even for direct execution\n            organizedContext = {\n              ...baseContext,\n              agent: baseContext.agent\n                ? {\n                    ...baseContext.agent,\n                    agentId: baseContext.agent.agentId ?? '',\n                    suspend: (args: any, suspendOptions?: SuspendOptions) => {\n                      suspendData = args;\n                      return baseContext.agent?.suspend?.(args, suspendOptions);\n                    },\n                  }\n                : baseContext.agent,\n              workflow: baseContext.workflow\n                ? {\n                    ...baseContext.workflow,\n                    suspend: (args: any, suspendOptions?: SuspendOptions) => {\n                      suspendData = args;\n                      return baseContext.workflow?.suspend?.(args, suspendOptions);\n                    },\n                  }\n                : baseContext.workflow,\n              requestContext: baseContext.requestContext || new RequestContext(),\n            };\n          }\n        }\n\n        const resumeData =\n          organizedContext.agent?.resumeData ?? organizedContext.workflow?.resumeData ?? organizedContext?.resumeData;\n\n        if (resumeData) {\n          const resumeValidation = validateToolInput(this.resumeSchema, resumeData, this.id);\n          if (resumeValidation.error) {\n            return resumeValidation.error as any;\n          }\n        }\n\n        // Call the original execute with validated input and organized context\n        const output = await originalExecute(data as any, organizedContext);\n\n        if (suspendData) {\n          const suspendValidation = validateToolSuspendData(this.suspendSchema, suspendData, this.id);\n          if (suspendValidation.error) {\n            return suspendValidation.error as any;\n          }\n        }\n\n        const skiptOutputValidation = !!(typeof output === 'undefined' && suspendData);\n\n        // Validate output if schema exists\n        const outputValidation = validateToolOutput(this.outputSchema, output, this.id, skiptOutputValidation);\n\n        if (outputValidation.error) {\n          return outputValidation.error as any;\n        }\n\n        return outputValidation.data;\n      };\n    }\n  }\n}\n\n/**\n * Creates a type-safe tool with automatic input validation.\n *\n * @template TSchemaIn - Input schema type\n * @template TSchemaOut - Output schema type\n * @template TSuspendSchema - Suspend operation schema type\n * @template TResumeSchema - Resume operation schema type\n * @template TContext - Execution context type\n * @template TExecute - Execute function type\n *\n * @param opts - Tool configuration including schemas and execute function\n * @returns Type-safe Tool instance with conditional typing based on schemas\n *\n * @example Simple tool\n * ```typescript\n * const greetTool = createTool({\n *   id: 'greet',\n *   description: 'Say hello',\n *   execute: async () => ({ message: 'Hello!' })\n * });\n * ```\n *\n * @example Tool with input validation\n * ```typescript\n * const calculateTool = createTool({\n *   id: 'calculate',\n *   description: 'Perform calculations',\n *   inputSchema: z.object({\n *     operation: z.enum(['add', 'subtract']),\n *     a: z.number(),\n *     b: z.number()\n *   }),\n *   execute: async (inputData) => {\n *     const result = inputData.operation === 'add'\n *       ? inputData.a + inputData.b\n *       : inputData.a - inputData.b;\n *     return { result };\n *   }\n * });\n * ```\n *\n * @example Tool with output schema\n * ```typescript\n * const userTool = createTool({\n *   id: 'get-user',\n *   description: 'Get user data',\n *   inputSchema: z.object({ userId: z.string() }),\n *   outputSchema: z.object({\n *     id: z.string(),\n *     name: z.string(),\n *     email: z.string()\n *   }),\n *   execute: async (inputData) => {\n *     return await fetchUser(inputData.userId);\n *   }\n * });\n * ```\n *\n * @example Tool with external API\n * ```typescript\n * const weatherTool = createTool({\n *   id: 'weather',\n *   description: 'Get weather data',\n *   inputSchema: z.object({\n *     city: z.string(),\n *     units: z.enum(['metric', 'imperial']).default('metric')\n *   }),\n *   execute: async (inputData) => {\n *     const response = await fetch(\n *       `https://api.weather.com/v1/weather?q=${inputData.city}&units=${inputData.units}`\n *     );\n *     return response.json();\n *   }\n * });\n * ```\n */\ntype SchemaLike = PublicSchema<any> | undefined;\ntype InferSchema<T extends SchemaLike> = T extends PublicSchema<any> ? InferPublicSchema<T> : unknown;\n\ntype CreateToolOpts<\n  TId extends string,\n  TInputSchema extends SchemaLike,\n  TOutputSchema extends SchemaLike,\n  TSuspendSchema extends SchemaLike,\n  TResumeSchema extends SchemaLike,\n  TRequestContext,\n  TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n> = Omit<\n  ToolAction<\n    InferSchema<TInputSchema>,\n    InferSchema<TOutputSchema>,\n    InferSchema<TSuspendSchema>,\n    InferSchema<TResumeSchema>,\n    TContext,\n    TId,\n    TRequestContext\n  >,\n  'inputSchema' | 'outputSchema' | 'suspendSchema' | 'resumeSchema'\n> & {\n  inputSchema?: TInputSchema;\n  outputSchema?: TOutputSchema;\n  suspendSchema?: TSuspendSchema;\n  resumeSchema?: TResumeSchema;\n};\nexport function createTool<\n  TId extends string = string,\n  TInputSchema extends SchemaLike = undefined,\n  TOutputSchema extends SchemaLike = undefined,\n  TSuspendSchema extends SchemaLike = undefined,\n  TResumeSchema extends SchemaLike = undefined,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n  TContext extends ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext> =\n    ToolExecutionContext<InferSchema<TSuspendSchema>, InferSchema<TResumeSchema>, TRequestContext>,\n>(\n  opts: CreateToolOpts<TId, TInputSchema, TOutputSchema, TSuspendSchema, TResumeSchema, TRequestContext, TContext>,\n): Tool<\n  InferSchema<TInputSchema>,\n  InferSchema<TOutputSchema>,\n  InferSchema<TSuspendSchema>,\n  InferSchema<TResumeSchema>,\n  TContext,\n  TId,\n  TRequestContext\n> {\n  return new Tool(opts);\n}\n","import { Tool, MASTRA_TOOL_MARKER } from './tool';\nimport type { ToolToConvert } from './tool-builder/builder';\nimport type { VercelTool } from './types';\n\n/**\n * Checks if a tool is a Mastra Tool, using both instanceof and marker.\n * The marker fallback handles environments like Vite SSR where the same\n * module may be loaded multiple times, causing instanceof to fail.\n */\nexport function isMastraTool(tool: unknown): boolean {\n  return tool instanceof Tool || (typeof tool === 'object' && tool !== null && MASTRA_TOOL_MARKER in tool);\n}\n\n/**\n * Checks if a tool is a Vercel Tool (AI SDK tool)\n * @param tool - The tool to check\n * @returns True if the tool is a Vercel Tool, false otherwise\n */\nexport function isVercelTool(tool?: ToolToConvert): tool is VercelTool {\n  // Checks if this tool is not an instance of Mastra's Tool class\n  // AI SDK tools must have an execute function and either:\n  // - 'parameters' (v4) or 'inputSchema' (v5/v6)\n  // This prevents plain objects with inputSchema (like client tools) from being treated as VercelTools\n  return !!(\n    tool &&\n    !isMastraTool(tool) &&\n    ('parameters' in tool || ('execute' in tool && typeof tool.execute === 'function' && 'inputSchema' in tool))\n  );\n}\n\ntype ProviderTool = {\n  type: 'provider-defined' | 'provider';\n  id: string;\n  args?: Record<string, unknown>;\n  inputSchema?: unknown;\n  outputSchema?: unknown;\n  requestContextSchema?: unknown;\n};\n\n/**\n * Checks if a tool is a provider-defined tool from the AI SDK.\n * Provider tools (like google.tools.googleSearch(), openai.tools.webSearch()) have:\n * - type: \"provider-defined\" (AI SDK v5) or \"provider\" (AI SDK v6)\n * - id: in format 'provider.tool_name' (e.g., 'google.google_search')\n *\n * These tools have a lazy `inputSchema` function that returns an AI SDK Schema\n * (not a Zod schema), so they require special handling during serialization.\n */\nexport function isProviderDefinedTool(tool: unknown): tool is ProviderTool {\n  if (typeof tool !== 'object' || tool === null) return false;\n  const t = tool as Record<string, unknown>;\n  const isProviderType = t.type === 'provider-defined' || t.type === 'provider';\n  return isProviderType && typeof t.id === 'string';\n}\n\n/**\n * Alias for callers that prefer the shorter provider-tool terminology.\n */\nexport const isProviderTool = isProviderDefinedTool;\n\n/**\n * Extracts the model-facing tool name from a provider tool id.\n * e.g. 'openai.web_search' -> 'web_search'\n */\nexport function getProviderToolName(providerId: string): string {\n  return providerId.split('.').slice(1).join('.');\n}\n"]}