@copilotkit/runtime 2.0.0-rc.35 → 2.0.0-rc.37

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +9 -2
  2. package/dist/agent/{url-download.cjs → ai-sdk/url-download.cjs} +19 -75
  3. package/dist/agent/ai-sdk/url-download.cjs.map +1 -0
  4. package/dist/agent/{url-download.d.cts → ai-sdk/url-download.d.cts} +11 -8
  5. package/dist/agent/ai-sdk/url-download.d.cts.map +1 -0
  6. package/dist/agent/{url-download.d.mts → ai-sdk/url-download.d.mts} +11 -8
  7. package/dist/agent/ai-sdk/url-download.d.mts.map +1 -0
  8. package/dist/agent/{url-download.mjs → ai-sdk/url-download.mjs} +20 -74
  9. package/dist/agent/ai-sdk/url-download.mjs.map +1 -0
  10. package/dist/agent/ai-sdk.cjs +425 -0
  11. package/dist/agent/ai-sdk.cjs.map +1 -0
  12. package/dist/agent/ai-sdk.d.cts +119 -0
  13. package/dist/agent/ai-sdk.d.cts.map +1 -0
  14. package/dist/agent/ai-sdk.d.mts +119 -0
  15. package/dist/agent/ai-sdk.d.mts.map +1 -0
  16. package/dist/agent/ai-sdk.mjs +419 -0
  17. package/dist/agent/ai-sdk.mjs.map +1 -0
  18. package/dist/agent/classic-tools.cjs +185 -0
  19. package/dist/agent/classic-tools.cjs.map +1 -0
  20. package/dist/agent/classic-tools.mjs +183 -0
  21. package/dist/agent/classic-tools.mjs.map +1 -0
  22. package/dist/agent/converters/aisdk.cjs +0 -3
  23. package/dist/agent/converters/aisdk.mjs +1 -1
  24. package/dist/agent/converters/tanstack.cjs +200 -27
  25. package/dist/agent/converters/tanstack.cjs.map +1 -1
  26. package/dist/agent/converters/tanstack.d.cts +90 -6
  27. package/dist/agent/converters/tanstack.d.cts.map +1 -1
  28. package/dist/agent/converters/tanstack.d.mts +90 -6
  29. package/dist/agent/converters/tanstack.d.mts.map +1 -1
  30. package/dist/agent/converters/tanstack.mjs +200 -27
  31. package/dist/agent/converters/tanstack.mjs.map +1 -1
  32. package/dist/agent/learned-skills.cjs +15 -16
  33. package/dist/agent/learned-skills.cjs.map +1 -1
  34. package/dist/agent/learned-skills.d.cts +9 -3
  35. package/dist/agent/learned-skills.d.cts.map +1 -1
  36. package/dist/agent/learned-skills.d.mts +9 -3
  37. package/dist/agent/learned-skills.d.mts.map +1 -1
  38. package/dist/agent/learned-skills.mjs +15 -16
  39. package/dist/agent/learned-skills.mjs.map +1 -1
  40. package/dist/agent/model.cjs +42 -0
  41. package/dist/agent/model.cjs.map +1 -0
  42. package/dist/agent/model.d.cts +19 -0
  43. package/dist/agent/model.d.cts.map +1 -0
  44. package/dist/agent/model.d.mts +19 -0
  45. package/dist/agent/model.d.mts.map +1 -0
  46. package/dist/agent/model.mjs +41 -0
  47. package/dist/agent/model.mjs.map +1 -0
  48. package/dist/agent.cjs +558 -0
  49. package/dist/agent.cjs.map +1 -0
  50. package/dist/agent.d.cts +455 -0
  51. package/dist/agent.d.cts.map +1 -0
  52. package/dist/agent.d.mts +455 -0
  53. package/dist/agent.d.mts.map +1 -0
  54. package/dist/agent.mjs +551 -0
  55. package/dist/agent.mjs.map +1 -0
  56. package/dist/index.cjs +0 -17
  57. package/dist/index.d.cts +5 -10
  58. package/dist/index.d.mts +5 -10
  59. package/dist/index.mjs +1 -5
  60. package/dist/internal/learned-skills.d.cts +1 -1
  61. package/dist/internal/learned-skills.d.mts +1 -1
  62. package/dist/runtime/core/channel-manager.d.cts +1 -1
  63. package/dist/runtime/core/channel-manager.d.mts +1 -1
  64. package/dist/runtime/core/debug-event-bus.d.cts +1 -1
  65. package/dist/runtime/core/learning.d.cts +1 -1
  66. package/dist/runtime/core/package-info.cjs +1 -1
  67. package/dist/runtime/core/package-info.mjs +1 -1
  68. package/dist/runtime/core/runtime.d.cts +3 -3
  69. package/dist/runtime/core/runtime.d.mts +2 -2
  70. package/dist/runtime/generative-ui/surface-writer.d.cts +1 -1
  71. package/dist/runtime/index.d.cts +4 -6
  72. package/dist/runtime/index.d.mts +4 -6
  73. package/dist/runtime/intelligence-platform/client.d.cts +1 -1
  74. package/dist/runtime/intelligence-platform/client.d.mts +1 -1
  75. package/dist/runtime/intelligence-platform/skill-registry/index.d.cts +1 -1
  76. package/dist/runtime/intelligence-platform/skill-registry/index.d.mts +1 -1
  77. package/package.json +32 -11
  78. package/dist/agent/converters/index.d.mts +0 -2
  79. package/dist/agent/index.cjs +0 -1329
  80. package/dist/agent/index.cjs.map +0 -1
  81. package/dist/agent/index.d.cts +0 -459
  82. package/dist/agent/index.d.cts.map +0 -1
  83. package/dist/agent/index.d.mts +0 -460
  84. package/dist/agent/index.d.mts.map +0 -1
  85. package/dist/agent/index.mjs +0 -1321
  86. package/dist/agent/index.mjs.map +0 -1
  87. package/dist/agent/mcp-tool-names.cjs +0 -82
  88. package/dist/agent/mcp-tool-names.cjs.map +0 -1
  89. package/dist/agent/mcp-tool-names.mjs +0 -80
  90. package/dist/agent/mcp-tool-names.mjs.map +0 -1
  91. package/dist/agent/url-download.cjs.map +0 -1
  92. package/dist/agent/url-download.d.cts.map +0 -1
  93. package/dist/agent/url-download.d.mts.map +0 -1
  94. package/dist/agent/url-download.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-sdk.mjs","names":["tool","createVercelAISDKTool","aiJsonSchema"],"sources":["../../src/agent/ai-sdk/index.ts"],"sourcesContent":["/**\n * `@copilotkit/runtime/agent/ai-sdk`: helpers for `type: \"aisdk\"` factories.\n *\n * This is the only runtime entry that imports `ai` at module scope. An app\n * that imports it uses the AI SDK, so `ai` must be installed.\n */\nimport { RENDER_A2UI_TOOL } from \"@ag-ui/a2ui-middleware\";\nimport type {\n ContentPart,\n Message,\n RunAgentInput,\n ToolMessage,\n} from \"@ag-ui/client\";\nimport { Validator } from \"@cfworker/json-schema\";\nimport { safeParseToolArgs, schemaToJsonSchema } from \"@copilotkit/shared\";\nimport type { StandardSchemaV1 } from \"@copilotkit/shared\";\nimport type { AnyTool } from \"@tanstack/ai\";\nimport type {\n AssistantModelMessage,\n FilePart,\n ImagePart,\n ModelMessage,\n SystemModelMessage,\n TextPart,\n ToolCallPart,\n ToolModelMessage,\n ToolResultPart,\n ToolSet,\n UserModelMessage,\n} from \"ai\";\nimport { jsonSchema as aiJsonSchema, tool as createVercelAISDKTool } from \"ai\";\nimport { z } from \"zod\";\nimport type { ToolDefinition } from \"../index\";\n\nexport { createSafeUrlDownload } from \"./url-download\";\nexport type {\n CreateSafeUrlDownloadOptions,\n SafeUrlDownloadOptions,\n} from \"./url-download\";\n\n/**\n * A tool result or user part can name a provider file handle (`file` source).\n * It is neither bytes nor a URL, and the AI SDK cannot send it to the\n * provider, so the part is dropped with a warning.\n */\nfunction warnDroppedFileSource(what: string) {\n console.warn(\n `[CopilotKit] Dropping a ${what} that references a provider file handle: it is not a URL or inline data, so it cannot be sent to the model here.`,\n );\n}\n\n/**\n * The AI SDK output for an AG-UI tool message.\n *\n * A text-only result is one text output. A URL part becomes its URL as text.\n * A result with inline media is a content list: the text entry first, when\n * there is any, then each media part with its bytes and media type. A\n * media-only result is media alone. A result whose parts were all dropped is\n * the empty string, because AG-UI 1.0 requires every call to be answered.\n */\nfunction toolResultOutput(\n content: ToolMessage[\"content\"],\n): ToolResultPart[\"output\"] {\n if (typeof content === \"string\") return { type: \"text\", value: content };\n const segments: string[] = [];\n const media: Array<{ type: \"media\"; data: string; mediaType: string }> = [];\n let open = false; // whether the last segment is text still being appended to\n for (const part of content) {\n if (part.type === \"text\") {\n if (open) segments[segments.length - 1] += part.text;\n else segments.push(part.text);\n open = true;\n } else if (part.source.type === \"file\") {\n warnDroppedFileSource(`${part.type} part in a tool result`);\n } else if (part.source.type === \"url\") {\n segments.push(part.source.value);\n open = false;\n } else {\n media.push({\n type: \"media\",\n data: part.source.value,\n mediaType: part.source.mimeType,\n });\n open = false;\n }\n }\n const text = segments.join(\"\\n\");\n if (media.length === 0) return { type: \"text\", value: text };\n return {\n type: \"content\",\n value: [\n ...(text.length > 0 ? [{ type: \"text\" as const, text }] : []),\n ...media,\n ],\n };\n}\n\ntype LegacyBinaryInputContent = {\n type: \"binary\";\n mimeType?: string;\n data?: string;\n url?: string;\n};\n\n/** A URL from the request, or `null` (logged) when it does not parse. */\nfunction parseContentUrl(value: string, what: string) {\n try {\n return new URL(value);\n } catch {\n console.error(\n `[CopilotKit] convertUserMessageContent: invalid URL \"${value}\" in ${what} part, skipping`,\n );\n return null;\n }\n}\n\n/**\n * Converts AG-UI user message content to AI SDK user content: plain strings,\n * modality parts (image, audio, video, document), and the legacy `binary`\n * part.\n */\nfunction convertUserMessageContent(\n content: string | Array<ContentPart | LegacyBinaryInputContent>,\n): string | Array<TextPart | ImagePart | FilePart> {\n if (!content) return \"\";\n if (typeof content === \"string\") return content;\n\n const parts: Array<TextPart | ImagePart | FilePart> = [];\n\n for (const part of content) {\n // The request body is not validated, so a part can be anything.\n if (!part || typeof part !== \"object\" || !(\"type\" in part)) continue;\n\n switch (part.type) {\n case \"text\": {\n if (part.text) parts.push({ type: \"text\", text: part.text });\n break;\n }\n\n case \"image\": {\n const { source } = part;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"image\",\n image: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"file\") {\n warnDroppedFileSource(\"image part\");\n } else {\n const url = parseContentUrl(source.value, \"image\");\n if (url) {\n parts.push({\n type: \"image\",\n image: url,\n mediaType: source.mimeType,\n });\n }\n }\n break;\n }\n\n case \"audio\":\n case \"video\":\n case \"document\": {\n const { source } = part;\n if (!source) break;\n if (source.type === \"data\") {\n parts.push({\n type: \"file\",\n data: source.value,\n mediaType: source.mimeType,\n });\n } else if (source.type === \"file\") {\n warnDroppedFileSource(`${part.type} part`);\n } else {\n const url = parseContentUrl(source.value, part.type);\n if (url) {\n parts.push({\n type: \"file\",\n data: url,\n mediaType: source.mimeType ?? \"application/octet-stream\",\n });\n }\n }\n break;\n }\n\n case \"binary\": {\n const mimeType = part.mimeType ?? \"application/octet-stream\";\n const isImage = mimeType.startsWith(\"image/\");\n const data = part.data\n ? part.data\n : part.url\n ? parseContentUrl(part.url, \"binary\")\n : null;\n if (!data) break;\n parts.push(\n isImage\n ? { type: \"image\", image: data, mediaType: mimeType }\n : { type: \"file\", data, mediaType: mimeType },\n );\n break;\n }\n\n default: {\n const unknownPart: { type: string } = part;\n console.error(\n `[CopilotKit] convertUserMessageContent: unrecognized content part type \"${unknownPart.type}\", skipping`,\n );\n break;\n }\n }\n }\n\n return parts.length > 0 ? parts : \"\";\n}\n\n/**\n * Options for {@link convertMessagesToVercelAISDKMessages}.\n */\nexport interface MessageConversionOptions {\n /** Send AG-UI `system` messages to the model as system messages. */\n forwardSystemMessages?: boolean;\n /** Send AG-UI `developer` messages to the model as system messages. */\n forwardDeveloperMessages?: boolean;\n}\n\n/**\n * Converts AG-UI messages to AI SDK `ModelMessage`s, for `streamText` calls in\n * a `type: \"aisdk\"` factory.\n *\n * System and developer messages are dropped unless the matching option is on.\n * Tool results keep their text and inline media.\n *\n * @param messages - The run's AG-UI messages, usually `ctx.input.messages`.\n * @param options - Which system and developer messages to forward.\n *\n * ```ts\n * streamText({ model, messages: convertMessagesToVercelAISDKMessages(ctx.input.messages) })\n * ```\n */\nexport function convertMessagesToVercelAISDKMessages(\n messages: Message[],\n options: MessageConversionOptions = {},\n) {\n const result: ModelMessage[] = [];\n\n for (const message of messages) {\n if (message.role === \"system\" && options.forwardSystemMessages) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (\n message.role === \"developer\" &&\n options.forwardDeveloperMessages\n ) {\n const systemMsg: SystemModelMessage = {\n role: \"system\",\n content: message.content ?? \"\",\n };\n result.push(systemMsg);\n } else if (message.role === \"assistant\") {\n const parts: Array<TextPart | ToolCallPart> = message.content\n ? [{ type: \"text\", text: message.content }]\n : [];\n\n const toolCalls = message.toolCalls ?? [];\n for (const toolCall of toolCalls) {\n parts.push({\n type: \"tool-call\",\n toolCallId: toolCall.id,\n toolName: toolCall.function.name,\n input: safeParseToolArgs(toolCall.function.arguments),\n ...(toolCall.encryptedValue\n ? {\n providerOptions: {\n google: { thoughtSignature: toolCall.encryptedValue },\n },\n }\n : {}),\n });\n }\n\n const assistantMsg: AssistantModelMessage = {\n role: \"assistant\",\n content: parts,\n };\n result.push(assistantMsg);\n } else if (message.role === \"user\") {\n const userMsg: UserModelMessage = {\n role: \"user\",\n content: convertUserMessageContent(message.content),\n };\n result.push(userMsg);\n } else if (message.role === \"tool\") {\n // The tool name comes from the assistant message that made the call.\n const toolName =\n messages\n .flatMap((msg) =>\n msg.role === \"assistant\" ? (msg.toolCalls ?? []) : [],\n )\n .find((toolCall) => toolCall.id === message.toolCallId)?.function\n .name ?? \"unknown\";\n\n const toolMsg: ToolModelMessage = {\n role: \"tool\",\n content: [\n {\n type: \"tool-result\",\n toolCallId: message.toolCallId,\n toolName,\n output: toolResultOutput(message.content),\n },\n ],\n };\n result.push(toolMsg);\n }\n }\n\n return result;\n}\n\n/**\n * The JSON Schema subset that {@link convertJsonSchemaToZodSchema} reads.\n */\ninterface JsonSchema {\n type?:\n | \"object\"\n | \"string\"\n | \"number\"\n | \"integer\"\n | \"boolean\"\n | \"array\"\n | \"null\";\n description?: string;\n properties?: Record<string, JsonSchema>;\n required?: string[];\n items?: JsonSchema;\n enum?: string[];\n // Union combinators. A frontend tool authored with `z.discriminatedUnion`\n // (or any `z.union`) serializes to a node carrying `anyOf` / `oneOf` and\n // usually NO top-level `type`.\n anyOf?: JsonSchema[];\n oneOf?: JsonSchema[];\n}\n\n/**\n * Converts a JSON Schema to a Zod schema, for `type: \"aisdk\"` factories that\n * need a Zod schema for an AG-UI tool.\n *\n * @param jsonSchema - The schema: objects, strings (with `enum`), numbers,\n * integers, booleans, arrays, `null`, and `anyOf` / `oneOf` unions.\n * @param required - When false, the result is `.optional()`.\n * @throws Error for an array without `items` or a `type` it does not know.\n */\nexport function convertJsonSchemaToZodSchema(\n jsonSchema: JsonSchema,\n required: boolean,\n): z.ZodSchema {\n // Zod 4 emits an empty `description` into JSON Schema; Zod 3's converters\n // dropped it. Only attach a description the JSON Schema actually had.\n const describe = <T extends z.ZodType>(schema: T): T =>\n jsonSchema.description ? schema.describe(jsonSchema.description) : schema;\n\n if (jsonSchema.type === \"null\") {\n const schema = describe(z.null());\n return required ? schema : schema.optional();\n }\n\n // Handle `anyOf` / `oneOf` unions (e.g. `z.discriminatedUnion` or `z.union`\n // on a frontend tool) as `z.union`. These nodes usually carry no top-level\n // `type`, so they MUST be handled before the empty-schema guard below.\n // Otherwise the union collapses to an empty object (`z.object({})`), the\n // reconstructed tool schema loses the union-typed field entirely, and the\n // model can never emit it. This is especially load-bearing for a union\n // nested inside array `items`, which OpenAI otherwise silently drops.\n const unionVariants = jsonSchema.anyOf ?? jsonSchema.oneOf;\n if (Array.isArray(unionVariants) && unionVariants.length > 0) {\n // A single-variant union is just that variant.\n if (unionVariants.length === 1) {\n return convertJsonSchemaToZodSchema(unionVariants[0], required);\n }\n const variantSchemas = unionVariants.map((variant) =>\n convertJsonSchemaToZodSchema(variant, true),\n );\n const schema = describe(\n z.union(variantSchemas as [z.ZodSchema, z.ZodSchema, ...z.ZodSchema[]]),\n );\n return required ? schema : schema.optional();\n }\n\n // Handle empty schemas {} (no input required) - treat as empty object\n if (!jsonSchema.type) {\n return required ? z.object({}) : z.object({}).optional();\n }\n if (jsonSchema.type === \"object\") {\n const spec: { [key: string]: z.ZodSchema } = {};\n\n if (!jsonSchema.properties || !Object.keys(jsonSchema.properties).length) {\n return !required ? z.object(spec).optional() : z.object(spec);\n }\n\n const requiredKeys = new Set(jsonSchema.required ?? []);\n for (const [key, value] of Object.entries(jsonSchema.properties)) {\n spec[key] = convertJsonSchemaToZodSchema(value, requiredKeys.has(key));\n }\n const schema = describe(z.object(spec));\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"string\") {\n if (jsonSchema.enum && jsonSchema.enum.length > 0) {\n const schema = describe(z.enum(jsonSchema.enum as [string, ...string[]]));\n return required ? schema : schema.optional();\n }\n const schema = describe(z.string());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"number\" || jsonSchema.type === \"integer\") {\n const schema = describe(z.number());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"boolean\") {\n const schema = describe(z.boolean());\n return required ? schema : schema.optional();\n } else if (jsonSchema.type === \"array\") {\n if (!jsonSchema.items) {\n throw new Error(\"Array type must have items property\");\n }\n const itemSchema = convertJsonSchemaToZodSchema(jsonSchema.items, true);\n const schema = describe(z.array(itemSchema));\n return required ? schema : schema.optional();\n }\n console.error(\"Invalid JSON schema:\", JSON.stringify(jsonSchema, null, 2));\n throw new Error(\"Invalid JSON schema\");\n}\n\nconst JSON_SCHEMA_TYPES = [\n \"object\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"array\",\n];\n\nfunction isJsonSchema(obj: unknown): obj is JsonSchema {\n if (typeof obj !== \"object\" || obj === null) return false;\n // Empty objects {} are valid JSON schemas (no input required)\n if (Object.keys(obj).length === 0) return true;\n return (\n \"type\" in obj &&\n typeof obj.type === \"string\" &&\n JSON_SCHEMA_TYPES.includes(obj.type)\n );\n}\n\n/**\n * Converts AG-UI tools (the run's frontend tools, `ctx.input.tools`) to an AI\n * SDK `ToolSet`, for `streamText` calls in a `type: \"aisdk\"` factory.\n *\n * The tools have no `execute`, so the AI SDK leaves their calls to the\n * client. Their JSON Schema goes to the model unchanged, and the arguments\n * are validated against it.\n *\n * @param tools - AG-UI tools whose `parameters` are JSON Schema objects.\n * @throws Error when a tool's `parameters` is not a JSON Schema object.\n *\n * ```ts\n * streamText({ model, tools: convertToolsToVercelAITools(ctx.input.tools) })\n * ```\n */\nexport function convertToolsToVercelAITools(tools: RunAgentInput[\"tools\"]) {\n const result: ToolSet = {};\n\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n const validator = new Validator(tool.parameters, \"7\");\n result[tool.name] = createVercelAISDKTool({\n description: tool.description,\n // AG-UI already supplies JSON Schema. A Zod round trip loses open object\n // fields (including A2UI components), references, and other constraints.\n inputSchema: aiJsonSchema(tool.parameters, {\n validate: (value) => {\n const validation = validator.validate(value);\n return validation.valid\n ? { success: true, value }\n : {\n success: false,\n error: new Error(`Invalid arguments for tool ${tool.name}`),\n };\n },\n }),\n // A2UI components require open objects. Other tools keep the provider's\n // existing strictness default instead of opting every tool out.\n ...(tool.name === RENDER_A2UI_TOOL.name ? { strict: false } : {}),\n });\n }\n\n return result;\n}\n\n/** Whether a TanStack `inputSchema` is a Standard Schema (Zod, Valibot, ArkType). */\nfunction isStandardSchema(\n schema: NonNullable<AnyTool[\"inputSchema\"]>,\n): schema is StandardSchemaV1 {\n return \"~standard\" in schema;\n}\n\n/**\n * The AI SDK input schema for a TanStack tool. No schema means no arguments.\n * A Standard Schema also validates the input, so `execute` gets the parsed\n * output (for example with Zod defaults applied), as in `chat()`.\n */\nfunction toolInputSchema(name: string, schema: AnyTool[\"inputSchema\"]) {\n if (!schema) return aiJsonSchema({ type: \"object\", properties: {} });\n if (!isStandardSchema(schema)) return aiJsonSchema(schema);\n return aiJsonSchema(schemaToJsonSchema(schema), {\n validate: async (value) => {\n const parsed = await schema[\"~standard\"].validate(value);\n if (\"value\" in parsed) return { success: true, value: parsed.value };\n const details = parsed.issues.map((issue) => issue.message).join(\"; \");\n return {\n success: false,\n error: new Error(`Invalid arguments for tool ${name}: ${details}`),\n };\n },\n });\n}\n\n/**\n * Converts TanStack AI tools to an AI SDK `ToolSet`, for `streamText` calls in\n * a `type: \"aisdk\"` factory.\n *\n * - A tool with `execute` keeps it. The AI SDK runs it with the parsed input.\n * - A tool without `execute` stays client-side: the AI SDK leaves its calls\n * to the client.\n * - `inputSchema` can be JSON Schema or a Standard Schema such as Zod.\n *\n * A typical use is the learned-skill tools of the run:\n *\n * ```ts\n * import { streamText } from \"ai\";\n * import { toAISDKTools } from \"@copilotkit/runtime/agent/ai-sdk\";\n *\n * factory: (ctx) =>\n * streamText({\n * model,\n * system: ctx.learnedSkills.catalog,\n * messages,\n * tools: toAISDKTools(ctx.learnedSkills.tools),\n * }),\n * ```\n *\n * @param tools - TanStack server or client tools, as plain objects or from\n * `toolDefinition()`.\n * @throws Error when a Standard Schema cannot describe itself as JSON Schema.\n */\nexport function toAISDKTools(tools: readonly AnyTool[]) {\n const result: ToolSet = {};\n\n for (const tanstackTool of tools) {\n const { execute } = tanstackTool;\n result[tanstackTool.name] = createVercelAISDKTool({\n description: tanstackTool.description,\n inputSchema: toolInputSchema(tanstackTool.name, tanstackTool.inputSchema),\n ...(execute ? { execute: (input: unknown) => execute(input) } : {}),\n ...(tanstackTool.needsApproval ? { needsApproval: true } : {}),\n });\n }\n\n return result;\n}\n\n/**\n * Converts tools made with `defineTool()` to an AI SDK `ToolSet`, for\n * `streamText` calls in a `type: \"aisdk\"` factory.\n *\n * Each tool offers its JSON Schema to the model. Its `execute` validates the\n * arguments with the tool's parameters schema and runs your `execute` with the\n * parsed output. A tool without `execute` (an interrupt tool) stays\n * client-side.\n *\n * @param tools - Tools from `defineTool()`.\n *\n * ```ts\n * streamText({ model, tools: convertToolDefinitionsToVercelAITools([weatherTool]) })\n * ```\n */\nexport function convertToolDefinitionsToVercelAITools(\n tools: readonly ToolDefinition[],\n) {\n return toAISDKTools(tools);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA6CA,SAAS,sBAAsB,MAAc;AAC3C,SAAQ,KACN,2BAA2B,KAAK,kHACjC;;;;;;;;;;;AAYH,SAAS,iBACP,SAC0B;AAC1B,KAAI,OAAO,YAAY,SAAU,QAAO;EAAE,MAAM;EAAQ,OAAO;EAAS;CACxE,MAAM,WAAqB,EAAE;CAC7B,MAAM,QAAmE,EAAE;CAC3E,IAAI,OAAO;AACX,MAAK,MAAM,QAAQ,QACjB,KAAI,KAAK,SAAS,QAAQ;AACxB,MAAI,KAAM,UAAS,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-tools.ts
5
+ const JSON_SCHEMA_TYPES = new Set([
6
+ "object",
7
+ "string",
8
+ "number",
9
+ "integer",
10
+ "boolean",
11
+ "array"
12
+ ]);
13
+ /**
14
+ * Whether a frontend tool's parameters are a JSON Schema: an empty object
15
+ * (the tool takes no input), or an object whose `type` is a JSON Schema type
16
+ * name.
17
+ */
18
+ function isJsonSchema(value) {
19
+ if (!require_usage.isRecord(value)) return false;
20
+ if (Object.keys(value).length === 0) return true;
21
+ return typeof value.type === "string" && JSON_SCHEMA_TYPES.has(value.type);
22
+ }
23
+ /**
24
+ * Checks that every frontend (AG-UI) tool's parameters are a JSON Schema, so
25
+ * the classic agent fails the run before the model call instead of sending
26
+ * an invalid schema to the provider.
27
+ *
28
+ * @param tools - The run input's frontend tools.
29
+ * @throws Error `Invalid JSON schema for tool <name>` for the first tool whose
30
+ * parameters are not a JSON Schema.
31
+ */
32
+ function assertFrontendToolSchemas(tools) {
33
+ for (const tool of tools) if (!isJsonSchema(tool.parameters)) throw new Error(`Invalid JSON schema for tool ${tool.name}`);
34
+ }
35
+ /**
36
+ * The tools that let the model change the application state. Their results
37
+ * become STATE_SNAPSHOT and STATE_DELTA events in `convertTanStackStream`.
38
+ */
39
+ const STATE_TOOLS = [{
40
+ __toolSide: "server",
41
+ name: "AGUISendStateSnapshot",
42
+ description: "Replace the entire application state with a new snapshot",
43
+ inputSchema: {
44
+ type: "object",
45
+ properties: { snapshot: { description: "The complete new state object" } },
46
+ required: ["snapshot"],
47
+ additionalProperties: false
48
+ },
49
+ execute: ({ snapshot }) => Promise.resolve({
50
+ success: true,
51
+ snapshot
52
+ })
53
+ }, {
54
+ __toolSide: "server",
55
+ name: "AGUISendStateDelta",
56
+ description: "Apply incremental updates to application state using JSON Patch operations",
57
+ inputSchema: {
58
+ type: "object",
59
+ properties: { delta: {
60
+ type: "array",
61
+ items: {
62
+ type: "object",
63
+ properties: {
64
+ op: {
65
+ type: "string",
66
+ enum: [
67
+ "add",
68
+ "replace",
69
+ "remove"
70
+ ],
71
+ description: "The operation to perform"
72
+ },
73
+ path: {
74
+ type: "string",
75
+ description: "JSON Pointer path (e.g., '/foo/bar')"
76
+ },
77
+ value: { description: "The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'." }
78
+ },
79
+ required: ["op", "path"],
80
+ additionalProperties: false
81
+ },
82
+ description: "Array of JSON Patch operations"
83
+ } },
84
+ required: ["delta"],
85
+ additionalProperties: false
86
+ },
87
+ execute: ({ delta }) => Promise.resolve({
88
+ success: true,
89
+ delta
90
+ })
91
+ }];
92
+ /**
93
+ * The text of a TanStack AI tool error result. `chat()` sends a failed tool
94
+ * call's result as `{"error": "<message>"}`.
95
+ */
96
+ function toolErrorText(content) {
97
+ if (typeof content !== "string") return require_aisdk.formatToolError(content);
98
+ try {
99
+ const parsed = JSON.parse(content);
100
+ if (require_usage.isRecord(parsed) && typeof parsed.error === "string") return parsed.error;
101
+ } catch {}
102
+ return content;
103
+ }
104
+ function isToolErrorResult(chunk) {
105
+ const metadata = require_usage.isRecord(chunk.metadata) ? chunk.metadata : {};
106
+ return (require_usage.isRecord(metadata.tanstack) ? metadata.tanstack : {}).state === "output-error";
107
+ }
108
+ /**
109
+ * Reads the interrupt settings that `defineTool()` puts in
110
+ * `metadata.copilotkit`. A tool without `interrupt: true` there has none.
111
+ */
112
+ function toolInterrupt(tool) {
113
+ const settings = tool.metadata?.copilotkit;
114
+ if (!require_usage.isRecord(settings) || settings.interrupt !== true) return void 0;
115
+ const { interruptReason, interruptMessage } = settings;
116
+ const interrupt = { reason: typeof interruptReason === "string" ? interruptReason : "tool_call" };
117
+ if (typeof interruptMessage === "string" && interruptMessage) interrupt.message = interruptMessage;
118
+ return interrupt;
119
+ }
120
+ /**
121
+ * Applies the classic tool rules to a TanStack AI `chat()` stream, before
122
+ * `convertTanStackStream` turns it into AG-UI events.
123
+ *
124
+ * - A call to an interrupt tool (`interrupt: true` in the tool's
125
+ * `metadata.copilotkit`, as `defineTool()` sets it) adds one `Interrupt` to
126
+ * `pendingInterrupts` when the call ends, keyed by the tool call id. A
127
+ * result for that call is dropped: the human supplies it on the resume run.
128
+ * - A failed tool call's result reads `Error: <message>`, for every tool
129
+ * (config, MCP, learned skills, and arguments that fail the schema).
130
+ *
131
+ * @param stream - The `chat()` stream.
132
+ * @param tools - The classic config's tools.
133
+ * @param pendingInterrupts - Filled with the interrupts of this run.
134
+ */
135
+ async function* withClassicToolRules(stream, tools, pendingInterrupts) {
136
+ const interruptTools = /* @__PURE__ */ new Map();
137
+ for (const tool of tools) {
138
+ const interrupt = toolInterrupt(tool);
139
+ if (interrupt) interruptTools.set(tool.name, interrupt);
140
+ }
141
+ const interruptByCallId = /* @__PURE__ */ new Map();
142
+ const interruptedCallIds = /* @__PURE__ */ new Set();
143
+ for await (const chunk of stream) {
144
+ if (!require_usage.isRecord(chunk) || typeof chunk.toolCallId !== "string") {
145
+ yield chunk;
146
+ continue;
147
+ }
148
+ const toolCallId = chunk.toolCallId;
149
+ switch (chunk.type) {
150
+ case "TOOL_CALL_START": {
151
+ const interrupt = typeof chunk.toolCallName === "string" ? interruptTools.get(chunk.toolCallName) : void 0;
152
+ if (interrupt) interruptByCallId.set(toolCallId, interrupt);
153
+ break;
154
+ }
155
+ case "TOOL_CALL_END": {
156
+ const interrupt = interruptByCallId.get(toolCallId);
157
+ if (!interrupt || interruptedCallIds.has(toolCallId)) break;
158
+ interruptedCallIds.add(toolCallId);
159
+ pendingInterrupts.push({
160
+ id: toolCallId,
161
+ toolCallId,
162
+ ...interrupt
163
+ });
164
+ break;
165
+ }
166
+ case "TOOL_CALL_RESULT":
167
+ if (interruptByCallId.has(toolCallId)) continue;
168
+ if (isToolErrorResult(chunk)) {
169
+ yield {
170
+ ...chunk,
171
+ content: `Error: ${toolErrorText(chunk.content)}`
172
+ };
173
+ continue;
174
+ }
175
+ break;
176
+ }
177
+ yield chunk;
178
+ }
179
+ }
180
+
181
+ //#endregion
182
+ exports.STATE_TOOLS = STATE_TOOLS;
183
+ exports.assertFrontendToolSchemas = assertFrontendToolSchemas;
184
+ exports.withClassicToolRules = withClassicToolRules;
185
+ //# sourceMappingURL=classic-tools.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classic-tools.cjs","names":["isRecord","formatToolError"],"sources":["../../src/agent/classic-tools.ts"],"sourcesContent":["import type { Interrupt, RunAgentInput } from \"@ag-ui/client\";\nimport type { AnyServerTool, AnyTool } from \"@tanstack/ai\";\nimport { formatToolError } from \"./converters/aisdk\";\nimport { isRecord } from \"./converters/usage\";\n\nconst JSON_SCHEMA_TYPES = new Set([\n \"object\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"array\",\n]);\n\n/**\n * Whether a frontend tool's parameters are a JSON Schema: an empty object\n * (the tool takes no input), or an object whose `type` is a JSON Schema type\n * name.\n */\nfunction isJsonSchema(value: unknown) {\n if (!isRecord(value)) return false;\n if (Object.keys(value).length === 0) return true;\n return typeof value.type === \"string\" && JSON_SCHEMA_TYPES.has(value.type);\n}\n\n/**\n * Checks that every frontend (AG-UI) tool's parameters are a JSON Schema, so\n * the classic agent fails the run before the model call instead of sending\n * an invalid schema to the provider.\n *\n * @param tools - The run input's frontend tools.\n * @throws Error `Invalid JSON schema for tool <name>` for the first tool whose\n * parameters are not a JSON Schema.\n */\nexport function assertFrontendToolSchemas(tools: RunAgentInput[\"tools\"]) {\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n }\n}\n\n/**\n * The tools that let the model change the application state. Their results\n * become STATE_SNAPSHOT and STATE_DELTA events in `convertTanStackStream`.\n */\nexport const STATE_TOOLS: readonly AnyServerTool[] = [\n {\n __toolSide: \"server\",\n name: \"AGUISendStateSnapshot\",\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: {\n type: \"object\",\n properties: {\n snapshot: { description: \"The complete new state object\" },\n },\n required: [\"snapshot\"],\n additionalProperties: false,\n },\n execute: ({ snapshot }: { snapshot?: unknown }) =>\n Promise.resolve({ success: true, snapshot }),\n },\n {\n __toolSide: \"server\",\n name: \"AGUISendStateDelta\",\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: {\n type: \"object\",\n properties: {\n delta: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: {\n type: \"string\",\n enum: [\"add\", \"replace\", \"remove\"],\n description: \"The operation to perform\",\n },\n path: {\n type: \"string\",\n description: \"JSON Pointer path (e.g., '/foo/bar')\",\n },\n value: {\n description:\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n },\n },\n required: [\"op\", \"path\"],\n additionalProperties: false,\n },\n description: \"Array of JSON Patch operations\",\n },\n },\n required: [\"delta\"],\n additionalProperties: false,\n },\n execute: ({\n delta,\n }: {\n delta: {\n op: \"add\" | \"replace\" | \"remove\";\n path: string;\n value?: unknown;\n }[];\n }) => Promise.resolve({ success: true, delta }),\n },\n];\n\n/**\n * The text of a TanStack AI tool error result. `chat()` sends a failed tool\n * call's result as `{\"error\": \"<message>\"}`.\n */\nfunction toolErrorText(content: unknown) {\n if (typeof content !== \"string\") return formatToolError(content);\n try {\n const parsed: unknown = JSON.parse(content);\n if (isRecord(parsed) && typeof parsed.error === \"string\") {\n return parsed.error;\n }\n } catch {\n // Not JSON: the content is the error text.\n }\n return content;\n}\n\nfunction isToolErrorResult(chunk: Record<string, unknown>) {\n const metadata = isRecord(chunk.metadata) ? chunk.metadata : {};\n const tanstack = isRecord(metadata.tanstack) ? metadata.tanstack : {};\n return tanstack.state === \"output-error\";\n}\n\n/** The `Interrupt` fields that a call to an interrupt tool raises. */\ntype ToolInterrupt = { reason: string; message?: string };\n\n/**\n * Reads the interrupt settings that `defineTool()` puts in\n * `metadata.copilotkit`. A tool without `interrupt: true` there has none.\n */\nfunction toolInterrupt(tool: Pick<AnyTool, \"metadata\">) {\n const settings = tool.metadata?.copilotkit;\n if (!isRecord(settings) || settings.interrupt !== true) return undefined;\n const { interruptReason, interruptMessage } = settings;\n const interrupt: ToolInterrupt = {\n reason: typeof interruptReason === \"string\" ? interruptReason : \"tool_call\",\n };\n if (typeof interruptMessage === \"string\" && interruptMessage) {\n interrupt.message = interruptMessage;\n }\n return interrupt;\n}\n\n/**\n * Applies the classic tool rules to a TanStack AI `chat()` stream, before\n * `convertTanStackStream` turns it into AG-UI events.\n *\n * - A call to an interrupt tool (`interrupt: true` in the tool's\n * `metadata.copilotkit`, as `defineTool()` sets it) adds one `Interrupt` to\n * `pendingInterrupts` when the call ends, keyed by the tool call id. A\n * result for that call is dropped: the human supplies it on the resume run.\n * - A failed tool call's result reads `Error: <message>`, for every tool\n * (config, MCP, learned skills, and arguments that fail the schema).\n *\n * @param stream - The `chat()` stream.\n * @param tools - The classic config's tools.\n * @param pendingInterrupts - Filled with the interrupts of this run.\n */\nexport async function* withClassicToolRules(\n stream: AsyncIterable<unknown>,\n tools: readonly Pick<AnyTool, \"name\" | \"metadata\">[],\n pendingInterrupts: Interrupt[],\n) {\n const interruptTools = new Map<string, ToolInterrupt>();\n for (const tool of tools) {\n const interrupt = toolInterrupt(tool);\n if (interrupt) interruptTools.set(tool.name, interrupt);\n }\n const interruptByCallId = new Map<string, ToolInterrupt>();\n const interruptedCallIds = new Set<string>();\n\n for await (const chunk of stream) {\n if (!isRecord(chunk) || typeof chunk.toolCallId !== \"string\") {\n yield chunk;\n continue;\n }\n const toolCallId = chunk.toolCallId;\n\n switch (chunk.type) {\n case \"TOOL_CALL_START\": {\n const interrupt =\n typeof chunk.toolCallName === \"string\"\n ? interruptTools.get(chunk.toolCallName)\n : undefined;\n if (interrupt) interruptByCallId.set(toolCallId, interrupt);\n break;\n }\n case \"TOOL_CALL_END\": {\n const interrupt = interruptByCallId.get(toolCallId);\n if (!interrupt || interruptedCallIds.has(toolCallId)) break;\n interruptedCallIds.add(toolCallId);\n pendingInterrupts.push({ id: toolCallId, toolCallId, ...interrupt });\n break;\n }\n case \"TOOL_CALL_RESULT\": {\n if (interruptByCallId.has(toolCallId)) continue;\n if (isToolErrorResult(chunk)) {\n yield { ...chunk, content: `Error: ${toolErrorText(chunk.content)}` };\n continue;\n }\n break;\n }\n }\n yield chunk;\n }\n}\n"],"mappings":";;;;AAKA,MAAM,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAS,aAAa,OAAgB;AACpC,KAAI,CAACA,uBAAS,MAAM,CAAE,QAAO;AAC7B,KAAI,OAAO,KAAK,MAAM,CAAC,WAAW,EAAG,QAAO;AAC5C,QAAO,OAAO,MAAM,SAAS,YAAY,kBAAkB,IAAI,MAAM,KAAK;;;;;;;;;;;AAY5E,SAAgB,0BAA0B,OAA+B;AACvE,MAAK,MAAM,QAAQ,MACjB,KAAI,CAAC,aAAa,KAAK,WAAW,CAChC,OAAM,IAAI,MAAM,gCAAgC,KAAK,OAAO;;;;;;AASlE,MAAa,cAAwC,CACnD;CACE,YAAY;CACZ,MAAM;CACN,aAAa;CACb,aAAa;EACX,MAAM;EACN,YAAY,EACV,UAAU,EAAE,aAAa,iCAAiC,EAC3D;EACD,UAAU,CAAC,WAAW;EACtB,sBAAsB;EACvB;CACD,UAAU,EAAE,eACV,QAAQ,QAAQ;EAAE,SAAS;EAAM;EAAU,CAAC;CAC/C,EACD;CACE,YAAY;CACZ,MAAM;CACN,aACE;CACF,aAAa;EACX,MAAM;EACN,YAAY,EACV,OAAO;GACL,MAAM;GACN,OAAO;IACL,MAAM;IACN,YAAY;KACV,IAAI;MACF,MAAM;MACN,MAAM;OAAC;OAAO;OAAW;OAAS;MAClC,aAAa;MACd;KACD,MAAM;MACJ,MAAM;MACN,aAAa;MACd;KACD,OAAO,EACL,aACE,wFACH;KACF;IACD,UAAU,CAAC,MAAM,OAAO;IACxB,sBAAsB;IACvB;GACD,aAAa;GACd,EACF;EACD,UAAU,CAAC,QAAQ;EACnB,sBAAsB;EACvB;CACD,UAAU,EACR,YAOI,QAAQ,QAAQ;EAAE,SAAS;EAAM;E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QAAI,UAAW,mBAAkB,IAAI,YAAY,UAAU;AAC3D;;GAEF,KAAK,iBAAiB;IACpB,MAAM,YAAY,kBAAkB,IAAI,WAAW;AACnD,QAAI,CAAC,aAAa,mBAAmB,IAAI,WAAW,CAAE;AACtD,uBAAmB,IAAI,WAAW;AAClC,sBAAkB,KAAK;KAAE,IAAI;KAAY;KAAY,GAAG;KAAW,CAAC;AACpE;;GAEF,KAAK;AACH,QAAI,kBAAkB,IAAI,WAAW,CAAE;AACvC,QAAI,kBAAkB,MAAM,EAAE;AAC5B,WAAM;MAAE,GAAG;MAAO,SAAS,UAAU,cAAc,MAAM,QAAQ;MAAI;AACrE;;AAEF;;AAGJ,QAAM"}
@@ -0,0 +1,183 @@
1
+ import { isRecord } from "./converters/usage.mjs";
2
+ import { formatToolError } from "./converters/aisdk.mjs";
3
+
4
+ //#region src/agent/classic-tools.ts
5
+ const JSON_SCHEMA_TYPES = new Set([
6
+ "object",
7
+ "string",
8
+ "number",
9
+ "integer",
10
+ "boolean",
11
+ "array"
12
+ ]);
13
+ /**
14
+ * Whether a frontend tool's parameters are a JSON Schema: an empty object
15
+ * (the tool takes no input), or an object whose `type` is a JSON Schema type
16
+ * name.
17
+ */
18
+ function isJsonSchema(value) {
19
+ if (!isRecord(value)) return false;
20
+ if (Object.keys(value).length === 0) return true;
21
+ return typeof value.type === "string" && JSON_SCHEMA_TYPES.has(value.type);
22
+ }
23
+ /**
24
+ * Checks that every frontend (AG-UI) tool's parameters are a JSON Schema, so
25
+ * the classic agent fails the run before the model call instead of sending
26
+ * an invalid schema to the provider.
27
+ *
28
+ * @param tools - The run input's frontend tools.
29
+ * @throws Error `Invalid JSON schema for tool <name>` for the first tool whose
30
+ * parameters are not a JSON Schema.
31
+ */
32
+ function assertFrontendToolSchemas(tools) {
33
+ for (const tool of tools) if (!isJsonSchema(tool.parameters)) throw new Error(`Invalid JSON schema for tool ${tool.name}`);
34
+ }
35
+ /**
36
+ * The tools that let the model change the application state. Their results
37
+ * become STATE_SNAPSHOT and STATE_DELTA events in `convertTanStackStream`.
38
+ */
39
+ const STATE_TOOLS = [{
40
+ __toolSide: "server",
41
+ name: "AGUISendStateSnapshot",
42
+ description: "Replace the entire application state with a new snapshot",
43
+ inputSchema: {
44
+ type: "object",
45
+ properties: { snapshot: { description: "The complete new state object" } },
46
+ required: ["snapshot"],
47
+ additionalProperties: false
48
+ },
49
+ execute: ({ snapshot }) => Promise.resolve({
50
+ success: true,
51
+ snapshot
52
+ })
53
+ }, {
54
+ __toolSide: "server",
55
+ name: "AGUISendStateDelta",
56
+ description: "Apply incremental updates to application state using JSON Patch operations",
57
+ inputSchema: {
58
+ type: "object",
59
+ properties: { delta: {
60
+ type: "array",
61
+ items: {
62
+ type: "object",
63
+ properties: {
64
+ op: {
65
+ type: "string",
66
+ enum: [
67
+ "add",
68
+ "replace",
69
+ "remove"
70
+ ],
71
+ description: "The operation to perform"
72
+ },
73
+ path: {
74
+ type: "string",
75
+ description: "JSON Pointer path (e.g., '/foo/bar')"
76
+ },
77
+ value: { description: "The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'." }
78
+ },
79
+ required: ["op", "path"],
80
+ additionalProperties: false
81
+ },
82
+ description: "Array of JSON Patch operations"
83
+ } },
84
+ required: ["delta"],
85
+ additionalProperties: false
86
+ },
87
+ execute: ({ delta }) => Promise.resolve({
88
+ success: true,
89
+ delta
90
+ })
91
+ }];
92
+ /**
93
+ * The text of a TanStack AI tool error result. `chat()` sends a failed tool
94
+ * call's result as `{"error": "<message>"}`.
95
+ */
96
+ function toolErrorText(content) {
97
+ if (typeof content !== "string") return formatToolError(content);
98
+ try {
99
+ const parsed = JSON.parse(content);
100
+ if (isRecord(parsed) && typeof parsed.error === "string") return parsed.error;
101
+ } catch {}
102
+ return content;
103
+ }
104
+ function isToolErrorResult(chunk) {
105
+ const metadata = isRecord(chunk.metadata) ? chunk.metadata : {};
106
+ return (isRecord(metadata.tanstack) ? metadata.tanstack : {}).state === "output-error";
107
+ }
108
+ /**
109
+ * Reads the interrupt settings that `defineTool()` puts in
110
+ * `metadata.copilotkit`. A tool without `interrupt: true` there has none.
111
+ */
112
+ function toolInterrupt(tool) {
113
+ const settings = tool.metadata?.copilotkit;
114
+ if (!isRecord(settings) || settings.interrupt !== true) return void 0;
115
+ const { interruptReason, interruptMessage } = settings;
116
+ const interrupt = { reason: typeof interruptReason === "string" ? interruptReason : "tool_call" };
117
+ if (typeof interruptMessage === "string" && interruptMessage) interrupt.message = interruptMessage;
118
+ return interrupt;
119
+ }
120
+ /**
121
+ * Applies the classic tool rules to a TanStack AI `chat()` stream, before
122
+ * `convertTanStackStream` turns it into AG-UI events.
123
+ *
124
+ * - A call to an interrupt tool (`interrupt: true` in the tool's
125
+ * `metadata.copilotkit`, as `defineTool()` sets it) adds one `Interrupt` to
126
+ * `pendingInterrupts` when the call ends, keyed by the tool call id. A
127
+ * result for that call is dropped: the human supplies it on the resume run.
128
+ * - A failed tool call's result reads `Error: <message>`, for every tool
129
+ * (config, MCP, learned skills, and arguments that fail the schema).
130
+ *
131
+ * @param stream - The `chat()` stream.
132
+ * @param tools - The classic config's tools.
133
+ * @param pendingInterrupts - Filled with the interrupts of this run.
134
+ */
135
+ async function* withClassicToolRules(stream, tools, pendingInterrupts) {
136
+ const interruptTools = /* @__PURE__ */ new Map();
137
+ for (const tool of tools) {
138
+ const interrupt = toolInterrupt(tool);
139
+ if (interrupt) interruptTools.set(tool.name, interrupt);
140
+ }
141
+ const interruptByCallId = /* @__PURE__ */ new Map();
142
+ const interruptedCallIds = /* @__PURE__ */ new Set();
143
+ for await (const chunk of stream) {
144
+ if (!isRecord(chunk) || typeof chunk.toolCallId !== "string") {
145
+ yield chunk;
146
+ continue;
147
+ }
148
+ const toolCallId = chunk.toolCallId;
149
+ switch (chunk.type) {
150
+ case "TOOL_CALL_START": {
151
+ const interrupt = typeof chunk.toolCallName === "string" ? interruptTools.get(chunk.toolCallName) : void 0;
152
+ if (interrupt) interruptByCallId.set(toolCallId, interrupt);
153
+ break;
154
+ }
155
+ case "TOOL_CALL_END": {
156
+ const interrupt = interruptByCallId.get(toolCallId);
157
+ if (!interrupt || interruptedCallIds.has(toolCallId)) break;
158
+ interruptedCallIds.add(toolCallId);
159
+ pendingInterrupts.push({
160
+ id: toolCallId,
161
+ toolCallId,
162
+ ...interrupt
163
+ });
164
+ break;
165
+ }
166
+ case "TOOL_CALL_RESULT":
167
+ if (interruptByCallId.has(toolCallId)) continue;
168
+ if (isToolErrorResult(chunk)) {
169
+ yield {
170
+ ...chunk,
171
+ content: `Error: ${toolErrorText(chunk.content)}`
172
+ };
173
+ continue;
174
+ }
175
+ break;
176
+ }
177
+ yield chunk;
178
+ }
179
+ }
180
+
181
+ //#endregion
182
+ export { STATE_TOOLS, assertFrontendToolSchemas, withClassicToolRules };
183
+ //# sourceMappingURL=classic-tools.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"classic-tools.mjs","names":[],"sources":["../../src/agent/classic-tools.ts"],"sourcesContent":["import type { Interrupt, RunAgentInput } from \"@ag-ui/client\";\nimport type { AnyServerTool, AnyTool } from \"@tanstack/ai\";\nimport { formatToolError } from \"./converters/aisdk\";\nimport { isRecord } from \"./converters/usage\";\n\nconst JSON_SCHEMA_TYPES = new Set([\n \"object\",\n \"string\",\n \"number\",\n \"integer\",\n \"boolean\",\n \"array\",\n]);\n\n/**\n * Whether a frontend tool's parameters are a JSON Schema: an empty object\n * (the tool takes no input), or an object whose `type` is a JSON Schema type\n * name.\n */\nfunction isJsonSchema(value: unknown) {\n if (!isRecord(value)) return false;\n if (Object.keys(value).length === 0) return true;\n return typeof value.type === \"string\" && JSON_SCHEMA_TYPES.has(value.type);\n}\n\n/**\n * Checks that every frontend (AG-UI) tool's parameters are a JSON Schema, so\n * the classic agent fails the run before the model call instead of sending\n * an invalid schema to the provider.\n *\n * @param tools - The run input's frontend tools.\n * @throws Error `Invalid JSON schema for tool <name>` for the first tool whose\n * parameters are not a JSON Schema.\n */\nexport function assertFrontendToolSchemas(tools: RunAgentInput[\"tools\"]) {\n for (const tool of tools) {\n if (!isJsonSchema(tool.parameters)) {\n throw new Error(`Invalid JSON schema for tool ${tool.name}`);\n }\n }\n}\n\n/**\n * The tools that let the model change the application state. Their results\n * become STATE_SNAPSHOT and STATE_DELTA events in `convertTanStackStream`.\n */\nexport const STATE_TOOLS: readonly AnyServerTool[] = [\n {\n __toolSide: \"server\",\n name: \"AGUISendStateSnapshot\",\n description: \"Replace the entire application state with a new snapshot\",\n inputSchema: {\n type: \"object\",\n properties: {\n snapshot: { description: \"The complete new state object\" },\n },\n required: [\"snapshot\"],\n additionalProperties: false,\n },\n execute: ({ snapshot }: { snapshot?: unknown }) =>\n Promise.resolve({ success: true, snapshot }),\n },\n {\n __toolSide: \"server\",\n name: \"AGUISendStateDelta\",\n description:\n \"Apply incremental updates to application state using JSON Patch operations\",\n inputSchema: {\n type: \"object\",\n properties: {\n delta: {\n type: \"array\",\n items: {\n type: \"object\",\n properties: {\n op: {\n type: \"string\",\n enum: [\"add\", \"replace\", \"remove\"],\n description: \"The operation to perform\",\n },\n path: {\n type: \"string\",\n description: \"JSON Pointer path (e.g., '/foo/bar')\",\n },\n value: {\n description:\n \"The value to set. Required for 'add' and 'replace' operations, ignored for 'remove'.\",\n },\n },\n required: [\"op\", \"path\"],\n additionalProperties: false,\n },\n description: \"Array of JSON Patch operations\",\n },\n },\n required: [\"delta\"],\n additionalProperties: false,\n },\n execute: ({\n delta,\n }: {\n delta: {\n op: \"add\" | \"replace\" | \"remove\";\n path: string;\n value?: unknown;\n }[];\n }) => Promise.resolve({ success: true, delta }),\n },\n];\n\n/**\n * The text of a TanStack AI tool error result. `chat()` sends a failed tool\n * call's result as `{\"error\": \"<message>\"}`.\n */\nfunction toolErrorText(content: unknown) {\n if (typeof content !== \"string\") return formatToolError(content);\n try {\n const parsed: unknown = JSON.parse(content);\n if (isRecord(parsed) && typeof parsed.error === \"string\") {\n return parsed.error;\n }\n } catch {\n // Not JSON: the content is the error text.\n }\n return content;\n}\n\nfunction isToolErrorResult(chunk: Record<string, unknown>) {\n const metadata = isRecord(chunk.metadata) ? chunk.metadata : {};\n const tanstack = isRecord(metadata.tanstack) ? metadata.tanstack : {};\n return tanstack.state === \"output-error\";\n}\n\n/** The `Interrupt` fields that a call to an interrupt tool raises. */\ntype ToolInterrupt = { reason: string; message?: string };\n\n/**\n * Reads the interrupt settings that `defineTool()` puts in\n * `metadata.copilotkit`. A tool without `interrupt: true` there has none.\n */\nfunction toolInterrupt(tool: Pick<AnyTool, \"metadata\">) {\n const settings = tool.metadata?.copilotkit;\n if (!isRecord(settings) || settings.interrupt !== true) return undefined;\n const { interruptReason, interruptMessage } = settings;\n const interrupt: ToolInterrupt = {\n reason: typeof interruptReason === \"string\" ? interruptReason : \"tool_call\",\n };\n if (typeof interruptMessage === \"string\" && interruptMessage) {\n interrupt.message = interruptMessage;\n }\n return interrupt;\n}\n\n/**\n * Applies the classic tool rules to a TanStack AI `chat()` stream, before\n * `convertTanStackStream` turns it into AG-UI events.\n *\n * - A call to an interrupt tool (`interrupt: true` in the tool's\n * `metadata.copilotkit`, as `defineTool()` sets it) adds one `Interrupt` to\n * `pendingInterrupts` when the call ends, keyed by the tool call id. A\n * result for that call is dropped: the human supplies it on the resume run.\n * - A failed tool call's result reads `Error: <message>`, for every tool\n * (config, MCP, learned skills, and arguments that fail the schema).\n *\n * @param stream - The `chat()` stream.\n * @param tools - The classic config's tools.\n * @param pendingInterrupts - Filled with the interrupts of this run.\n */\nexport async function* withClassicToolRules(\n stream: AsyncIterable<unknown>,\n tools: readonly Pick<AnyTool, \"name\" | \"metadata\">[],\n pendingInterrupts: Interrupt[],\n) {\n const interruptTools = new Map<string, ToolInterrupt>();\n for (const tool of tools) {\n const interrupt = toolInterrupt(tool);\n if (interrupt) interruptTools.set(tool.name, interrupt);\n }\n const interruptByCallId = new Map<string, ToolInterrupt>();\n const interruptedCallIds = new Set<string>();\n\n for await (const chunk of stream) {\n if (!isRecord(chunk) || typeof chunk.toolCallId !== \"string\") {\n yield chunk;\n continue;\n }\n const toolCallId = chunk.toolCallId;\n\n switch (chunk.type) {\n case \"TOOL_CALL_START\": {\n const interrupt =\n typeof chunk.toolCallName === \"string\"\n ? interruptTools.get(chunk.toolCallName)\n : undefined;\n if (interrupt) interruptByCallId.set(toolCallId, interrupt);\n break;\n }\n case \"TOOL_CALL_END\": {\n const interrupt = interruptByCallId.get(toolCallId);\n if (!interrupt || interruptedCallIds.has(toolCallId)) break;\n interruptedCallIds.add(toolCallId);\n pendingInterrupts.push({ id: toolCallId, toolCallId, ...interrupt });\n break;\n }\n case \"TOOL_CALL_RESULT\": {\n if (interruptByCallId.has(toolCallId)) continue;\n if (isToolErrorResult(chunk)) {\n yield { ...chunk, content: `Error: ${toolErrorText(chunk.content)}` };\n continue;\n }\n break;\n }\n }\n yield chunk;\n }\n}\n"],"mappings":";;;;AAKA,MAAM,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;;;;;;AAOF,SAAS,aAAa,OAAgB;AACpC,KAAI,CAAC,SAAS,MAAM,CAAE,QAAO;AAC7B,KAAI,OAAO,KAAK,MAAM,CAAC,WAAW,EAAG,QAAO;AAC5C,QAAO,OAAO,MAAM,SAAS,YAAY,kBAAkB,IAAI,MAAM,KAAK;;;;;;;;;;;AAY5E,SAAgB,0BAA0B,OAA+B;AACvE,MAAK,MAAM,QAAQ,MACjB,KAAI,CAAC,aAAa,KAAK,WAAW,CAChC,OAAM,IAAI,MAAM,gCAAgC,KAAK,OAAO;;;;;;AASlE,MAAa,cAAwC,CACnD;CACE,YAAY;CACZ,MAAM;CACN,aAAa;CACb,aAAa;EACX,MAAM;EACN,YAAY,EACV,UAAU,EAAE,aAAa,iCAAiC,EAC3D;EACD,UAAU,CAAC,WAAW;EACtB,sBAAsB;EACvB;CACD,UAAU,EAAE,eACV,QAAQ,QAAQ;EAAE,SAAS;EAAM;EAAU,CAAC;CAC/C,EACD;CACE,YAAY;C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ACxB,MAAM,YAAY,cAAc,KAAK;AACrC,MAAI,UAAW,gBAAe,IAAI,KAAK,MAAM,UAAU;;CAEzD,MAAM,oCAAoB,IAAI,KAA4B;CAC1D,MAAM,qCAAqB,IAAI,KAAa;AAE5C,YAAW,MAAM,SAAS,QAAQ;AAChC,MAAI,CAAC,SAAS,MAAM,IAAI,OAAO,MAAM,eAAe,UAAU;AAC5D,SAAM;AACN;;EAEF,MAAM,aAAa,MAAM;AAEzB,UAAQ,MAAM,MAAd;GACE,KAAK,mBAAmB;IACtB,MAAM,YACJ,OAAO,MAAM,iBAAiB,WAC1B,eAAe,IAAI,MAAM,aAAa,GACtC;AACN,QAAI,UAAW,mBAAkB,IAAI,YAAY,UAAU;AAC3D;;GAEF,KAAK,iBAAiB;IACpB,MAAM,YAAY,kBAAkB,IAAI,WAAW;AACnD,QAAI,CAAC,aAAa,mBAAmB,IAAI,WAAW,CAAE;AACtD,uBAAmB,IAAI,WAAW;AAClC,sBAAkB,KAAK;KAAE,IAAI;KAAY;KAAY,GAAG;KAAW,CAAC;AACpE;;GAEF,KAAK;AACH,QAAI,kBAAkB,IAAI,WAAW,CAAE;AACvC,QAAI,kBAAkB,MAAM,EAAE;AAC5B,WAAM;MAAE,GAAG;MAAO,SAAS,UAAU,cAAc,MAAM,QAAQ;MAAI;AACrE;;AAEF;;AAGJ,QAAM"}
@@ -365,7 +365,4 @@ async function* convertAISDKStream(fullStream, abortSignal, pendingInterrupts, i
365
365
  //#endregion
366
366
  exports.convertAISDKStream = convertAISDKStream;
367
367
  exports.formatToolError = formatToolError;
368
- exports.getAISDKRunFinishedDetails = getAISDKRunFinishedDetails;
369
- exports.resolveStreamPartMessageId = resolveStreamPartMessageId;
370
- exports.toolCallThoughtSignatureEvent = toolCallThoughtSignatureEvent;
371
368
  //# sourceMappingURL=aisdk.cjs.map
@@ -363,5 +363,5 @@ async function* convertAISDKStream(fullStream, abortSignal, pendingInterrupts, i
363
363
  }
364
364
 
365
365
  //#endregion
366
- export { convertAISDKStream, formatToolError, getAISDKRunFinishedDetails, resolveStreamPartMessageId, toolCallThoughtSignatureEvent };
366
+ export { convertAISDKStream, formatToolError };
367
367
  //# sourceMappingURL=aisdk.mjs.map