From 1ddc253c6983d2ddb90cb85e3069a61518b8fe85 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Sat, 24 Oct 2026 12:35:15 +0200 Subject: [PATCH 01/19] feat: add initial project structure with Dockerfile, .gitignore, and utility functions --- actions/ai-action/.gitignore | 3 + actions/ai-action/Dockerfile | 13 + actions/ai-action/manifest.json | 10 + actions/ai-action/package-lock.json | 3954 +++++++++++++++++ actions/ai-action/package.json | 33 + .../agent/datatypes/Agent.request.datatype.ts | 15 + .../datatypes/Agent.response.datatype.ts | 15 + .../datatypes/Agent.transform.datatype.ts | 4 + .../Agent.create.runtimefunction.ts | 79 + .../Agent.invoke.runtimefunction.ts | 89 + .../agent/utils/Agent.asToolEntries.util.ts | 20 + .../agent/utils/Agent.buildFlowTools.util.ts | 24 + .../agent/utils/Agent.compileAgent.util.ts | 50 + .../src/agent/utils/Agent.runAgent.util.ts | 30 + .../src/agent/utils/Agent.toolServers.util.ts | 7 + .../chat/datatypes/Chat.choice.datatype.ts | 16 + .../datatypes/Chat.contentPart.datatype.ts | 11 + .../chat/datatypes/Chat.message.datatype.ts | 20 + .../chat/datatypes/Chat.request.datatype.ts | 15 + .../chat/datatypes/Chat.response.datatype.ts | 20 + .../src/chat/datatypes/Chat.role.datatype.ts | 11 + .../chat/datatypes/Chat.toolCall.datatype.ts | 18 + .../src/chat/datatypes/Chat.usage.datatype.ts | 15 + .../chat/utils/Chat.fromChatMessage.util.ts | 25 + .../src/chat/utils/Chat.reportedModel.util.ts | 8 + .../src/chat/utils/Chat.toChatContent.util.ts | 8 + .../src/chat/utils/Chat.toChatMessage.util.ts | 27 + .../chat/utils/Chat.toChatResponse.util.ts | 22 + .../chat/utils/Chat.toChatToolCalls.util.ts | 16 + .../src/chat/utils/Chat.toChatUsage.util.ts | 13 + .../chat/utils/Chat.toContentBlock.util.ts | 9 + .../chat/utils/Chat.toContentBlocks.util.ts | 9 + .../chat/utils/Chat.toConversation.util.ts | 10 + .../src/chat/utils/Chat.toImageBlock.util.ts | 12 + .../chat/utils/Chat.toToolCallBlock.util.ts | 22 + actions/ai-action/src/index.ts | 103 + .../src/mcp/datatypes/Mcp.server.datatype.ts | 23 + .../mcp/datatypes/Mcp.transport.datatype.ts | 11 + .../src/mcp/utils/Mcp.buildMcpTools.util.ts | 30 + .../src/mcp/utils/Mcp.discoverTools.util.ts | 16 + .../src/mcp/utils/Mcp.toConnection.util.ts | 37 + .../mcp/utils/Mcp.validateMcpServers.util.ts | 16 + .../Message.contentBlock.datatype.ts | 11 + .../src/message/datatypes/Message.datatype.ts | 25 + .../datatypes/Message.role.datatype.ts | 11 + .../datatypes/Message.toolStatus.datatype.ts | 11 + .../utils/Message.replaceMessages.util.ts | 11 + .../message/utils/Message.toAiMessage.util.ts | 14 + .../utils/Message.toFlowMessage.util.ts | 40 + .../utils/Message.toInvalidToolCalls.util.ts | 13 + .../utils/Message.toLangChainMessage.util.ts | 20 + .../utils/Message.toMessageFields.util.ts | 22 + .../message/utils/Message.toToolCalls.util.ts | 12 + .../utils/Message.toToolMessage.util.ts | 12 + .../Middleware.agentState.datatype.ts | 20 + .../datatypes/Middleware.hook.datatype.ts | 11 + .../Middleware.stateUpdate.datatype.ts | 16 + .../Middleware.transform.datatype.ts | 4 + ...Middleware.trimMessages.runtimefunction.ts | 88 + .../Middleware.buildFlowMiddlewares.util.ts | 16 + .../Middleware.createHookHandler.util.ts | 31 + .../utils/Middleware.toFlowState.util.ts | 31 + .../model/datatypes/Model.request.datatype.ts | 19 + .../datatypes/Model.response.datatype.ts | 14 + .../datatypes/Model.toolChoice.datatype.ts | 4 + .../datatypes/Model.toolSpec.datatype.ts | 15 + .../datatypes/Model.transform.datatype.ts | 4 + .../Model.openRouter.runtimefunction.ts | 119 + .../model/utils/Model.flowChatModel.util.ts | 72 + .../src/model/utils/Model.toToolSpec.util.ts | 15 + .../src/shared/utils/Shared.asList.util.ts | 10 + .../src/shared/utils/Shared.asSubFlow.util.ts | 10 + .../src/shared/utils/Shared.asText.util.ts | 9 + .../utils/Shared.connectToAquila.util.ts | 7 + .../shared/utils/Shared.describeError.util.ts | 3 + .../utils/Shared.emptyJsonSchema.util.ts | 3 + .../shared/utils/Shared.formatIssues.util.ts | 5 + .../shared/utils/Shared.hasEntries.util.ts | 3 + .../src/shared/utils/Shared.isSubFlow.util.ts | 5 + .../shared/utils/Shared.parseOrThrow.util.ts | 9 + .../shared/utils/Shared.requireText.util.ts | 6 + .../shared/utils/Shared.toInputSchema.util.ts | 12 + .../datatypes/WebSearch.hit.datatype.ts | 16 + .../datatypes/WebSearch.result.datatype.ts | 16 + .../WebSearch.search.runtimefunction.ts | 74 + .../WebSearch.parseSearchPayload.util.ts | 9 + .../utils/WebSearch.toSearchResult.util.ts | 28 + actions/ai-action/test/agent.test.ts | 279 ++ actions/ai-action/test/dataTypes.test.ts | 289 ++ actions/ai-action/test/functions.test.ts | 335 ++ actions/ai-action/tsconfig.json | 23 + actions/ai-action/vite.config.ts | 18 + 92 files changed, 6739 insertions(+) create mode 100644 actions/ai-action/.gitignore create mode 100644 actions/ai-action/Dockerfile create mode 100644 actions/ai-action/manifest.json create mode 100644 actions/ai-action/package-lock.json create mode 100644 actions/ai-action/package.json create mode 100644 actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts create mode 100644 actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts create mode 100644 actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts create mode 100644 actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts create mode 100644 actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts create mode 100644 actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts create mode 100644 actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts create mode 100644 actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts create mode 100644 actions/ai-action/src/agent/utils/Agent.runAgent.util.ts create mode 100644 actions/ai-action/src/agent/utils/Agent.toolServers.util.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts create mode 100644 actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toConversation.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts create mode 100644 actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts create mode 100644 actions/ai-action/src/index.ts create mode 100644 actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts create mode 100644 actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts create mode 100644 actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts create mode 100644 actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts create mode 100644 actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts create mode 100644 actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts create mode 100644 actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts create mode 100644 actions/ai-action/src/message/datatypes/Message.datatype.ts create mode 100644 actions/ai-action/src/message/datatypes/Message.role.datatype.ts create mode 100644 actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts create mode 100644 actions/ai-action/src/message/utils/Message.replaceMessages.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toAiMessage.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toMessageFields.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toToolCalls.util.ts create mode 100644 actions/ai-action/src/message/utils/Message.toToolMessage.util.ts create mode 100644 actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts create mode 100644 actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts create mode 100644 actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts create mode 100644 actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts create mode 100644 actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts create mode 100644 actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts create mode 100644 actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts create mode 100644 actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts create mode 100644 actions/ai-action/src/model/datatypes/Model.request.datatype.ts create mode 100644 actions/ai-action/src/model/datatypes/Model.response.datatype.ts create mode 100644 actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts create mode 100644 actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts create mode 100644 actions/ai-action/src/model/datatypes/Model.transform.datatype.ts create mode 100644 actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts create mode 100644 actions/ai-action/src/model/utils/Model.flowChatModel.util.ts create mode 100644 actions/ai-action/src/model/utils/Model.toToolSpec.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.asList.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.asText.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.describeError.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.requireText.util.ts create mode 100644 actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts create mode 100644 actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts create mode 100644 actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts create mode 100644 actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts create mode 100644 actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts create mode 100644 actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts create mode 100644 actions/ai-action/test/agent.test.ts create mode 100644 actions/ai-action/test/dataTypes.test.ts create mode 100644 actions/ai-action/test/functions.test.ts create mode 100644 actions/ai-action/tsconfig.json create mode 100644 actions/ai-action/vite.config.ts diff --git a/actions/ai-action/.gitignore b/actions/ai-action/.gitignore new file mode 100644 index 0000000..ddc3c2a --- /dev/null +++ b/actions/ai-action/.gitignore @@ -0,0 +1,3 @@ +.env +node_modules/ +dist/ diff --git a/actions/ai-action/Dockerfile b/actions/ai-action/Dockerfile new file mode 100644 index 0000000..8d9f6c7 --- /dev/null +++ b/actions/ai-action/Dockerfile @@ -0,0 +1,13 @@ +FROM node:24.10.0-alpine + +WORKDIR /app + +COPY package.json package-lock.json* ./ + +RUN npm ci + +COPY . . + +RUN npm run build + +CMD ["npm", "run", "start"] diff --git a/actions/ai-action/manifest.json b/actions/ai-action/manifest.json new file mode 100644 index 0000000..7701645 --- /dev/null +++ b/actions/ai-action/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "ai", + "identifier": "ai-action", + "description": "AI agent integration: build LangChain agents from a model, tools (flows and MCP servers), middleware and a system prompt.", + "deployment": { + "docker": { + "image": "ghcr.io/code0-tech/centaurus/ci-builds/ai-action" + } + } +} diff --git a/actions/ai-action/package-lock.json b/actions/ai-action/package-lock.json new file mode 100644 index 0000000..44c14c8 --- /dev/null +++ b/actions/ai-action/package-lock.json @@ -0,0 +1,3954 @@ +{ + "name": "@code0-tech/ai-action", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@code0-tech/ai-action", + "version": "1.0.0", + "dependencies": { + "@code0-tech/hercules": "^1.6.0", + "@langchain/anthropic": "^1.0.0", + "@langchain/core": "^1.0.0", + "@langchain/groq": "^1.0.0", + "@langchain/mcp-adapters": "^2.0.1", + "@langchain/mistralai": "^1.0.0", + "@langchain/ollama": "^1.0.0", + "@langchain/openai": "^1.6.2", + "@langchain/tavily": "^1.2.0", + "langchain": "^1.5.16" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.0.0", + "typescript": "^5.9.3", + "vite": "^8.0.3", + "vitest": "^4.1.10" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.122.0", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.122.0.tgz", + "integrity": "sha512-GGPNftt0caaz9MDlmNQGHX8855Ojaduyy5pm9Sm1h7HalCn0cWNb5/bweadJF+4yzbal+QL6ztBa09WAAOzLmQ==", + "license": "MIT", + "dependencies": { + "json-schema-to-ts": "^3.1.1", + "standardwebhooks": "^1.0.0" + }, + "bin": { + "anthropic-ai-sdk": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/@babel/runtime": { + "version": "7.29.10", + "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.10.tgz", + "integrity": "sha512-NpugTzbKgGrNe45Ui32cN8vCFFMxVtP/9rtfwv0nP5FRDAjvYBxJcLVpYA9mr1jxP6cnIT7x9LUzuDTbWYYNRA==", + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@cfworker/json-schema": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", + "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", + "license": "MIT" + }, + "node_modules/@clack/core": { + "version": "1.0.0-alpha.4", + "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.0.0-alpha.4.tgz", + "integrity": "sha512-VCtU+vjyKPMSakVrB9q1bOnXN7QW/w4+YQDQCOF59GrzydW+169i0fVx/qzRRXJgt8KGj/pZZ/JxXroFZIDByg==", + "license": "MIT", + "dependencies": { + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, + "node_modules/@clack/prompts": { + "version": "1.0.0-alpha.4", + "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.0.0-alpha.4.tgz", + "integrity": "sha512-KnmtDF2xQGoI5AlBme9akHtvCRV0RKAARUXHBQO2tMwnY8B08/4zPWigT7uLK25UPrMCEqnyQPkKRjNdhPbf8g==", + "license": "MIT", + "dependencies": { + "@clack/core": "1.0.0-alpha.4", + "picocolors": "^1.0.0", + "sisteransi": "^1.0.5" + } + }, + "node_modules/@code0-tech/hercules": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.6.0.tgz", + "integrity": "sha512-1Ed4RcLdjFuTLUHuYP5yu3nQpHQDiE8gg0d4ZYFt/gRbKfHTPhmwxZ/V/Rj0Y0BxLLooIdc8bNKa2UgDxK+aqw==", + "license": "ISC", + "bin": { + "hercules": "bin/hercules.js" + }, + "peerDependencies": { + "@code0-tech/tucana": "0.0.82", + "@grpc/grpc-js": "^1.14.3", + "@protobuf-ts/grpc-backend": "^2.11.1", + "@protobuf-ts/grpc-transport": "^2.11.1", + "@protobuf-ts/runtime": "^2.11.1", + "@protobuf-ts/runtime-rpc": "^2.11.1", + "reflect-metadata": "^0.2.2", + "ts-morph": "^28.0.0", + "ts-to-zod": "^5.1.0", + "zod": "^4.4.3", + "zod-to-ts": "^2.1.0" + } + }, + "node_modules/@code0-tech/tucana": { + "version": "0.0.82", + "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.82.tgz", + "integrity": "sha512-9ImPNeGV09BeLT0M8/F08DHDe10MO6UI/VfE7i2aEYtRsB9DS3jIAGrcMEV67RXdmAj5ZWTtvxWVGOkem0CljQ==", + "license": "MIT", + "peer": true + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz", + "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz", + "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz", + "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz", + "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz", + "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz", + "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz", + "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz", + "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz", + "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz", + "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz", + "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz", + "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz", + "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz", + "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz", + "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz", + "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz", + "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz", + "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz", + "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz", + "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz", + "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/openharmony-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz", + "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz", + "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz", + "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz", + "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz", + "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=18" + } + }, + "node_modules/@grpc/grpc-js": { + "version": "1.14.6", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.6.tgz", + "integrity": "sha512-SgC/B3/VZ8lTyOZ4Cwk6f1skWhmkNAaVfiX90qd5u1rRXGKk1//8FTUEN9GvOUq7rfWIqAYkA3CoyumYVpOS6g==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@grpc/proto-loader": "^0.8.0", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.1.tgz", + "integrity": "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==", + "license": "Apache-2.0", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.5.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@langchain/anthropic": { + "version": "1.5.12", + "resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.5.12.tgz", + "integrity": "sha512-tVvI94zAtG6isYxBzL7hlbxfbqjmvx/BqBWAov7v+bABKYz3fZHFI2Io1UI5UzU+h/5SuC1qXUV+JxnaqylJJw==", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "^0.122.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.2.14" + } + }, + "node_modules/@langchain/core": { + "version": "1.2.17", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.2.17.tgz", + "integrity": "sha512-aLQLSed6oLCMLtJHrINhnFmsu79G2UiDlRslbOx+TSN9NmU+WuDv1OtVxrLpYglhXNy53elSduMVk3XBPG9ulw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@cfworker/json-schema": "^4.0.2", + "@standard-schema/spec": "^1.1.0", + "js-tiktoken": "^1.0.12", + "langsmith": ">=0.5.0 <1.0.0", + "mustache": "^4.2.0", + "p-queue": "^6.6.2", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@langchain/groq": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@langchain/groq/-/groq-1.3.1.tgz", + "integrity": "sha512-ImxfGBis4FEHpZdeT6dot6V6l09uBLYm/1BHQ6x3XEQmJFF7aKwbOeSOV5h/h5IeRx+2gaInR+LfyYoqT8satQ==", + "license": "MIT", + "dependencies": { + "groq-sdk": "^1.2.1" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.1.30" + } + }, + "node_modules/@langchain/langgraph": { + "version": "1.4.21", + "resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-1.4.21.tgz", + "integrity": "sha512-0LRyRw594IO98etnnBCM6nhckVjWGNnObpdaQij1e+u+GsUwGvn9P4/P42UAJG56WFF72A9n93WwCOW7Mq9yug==", + "license": "MIT", + "peer": true, + "dependencies": { + "@langchain/langgraph-checkpoint": "^1.1.6", + "@langchain/langgraph-sdk": "~1.12.3", + "@langchain/protocol": "^0.0.19", + "@standard-schema/spec": "1.1.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": "^1.1.48", + "zod": "^3.25.32 || ^4.2.0" + } + }, + "node_modules/@langchain/langgraph-checkpoint": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-checkpoint/-/langgraph-checkpoint-1.1.6.tgz", + "integrity": "sha512-CpDMGTY4Y6qzoGewMoL8MS9Ej35vyrrchbRpKCtUDWnHhrf4lbHp7wnu9dsHaavB3Z+M6aVRl+9GNQbIJVV1dg==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@langchain/core": "^1.1.48" + } + }, + "node_modules/@langchain/langgraph-sdk": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.12.3.tgz", + "integrity": "sha512-o5Qd1pepsJKHmHGIcWhOlZe2fvlPs2AEkVOxqzbL3R8IiMBPH2gNG8/kwK36czEnagiJtu4RUn02mKbGRwd5dQ==", + "license": "MIT", + "dependencies": { + "@langchain/protocol": "^0.0.19", + "@types/json-schema": "^7.0.15", + "p-queue": "^9.0.1", + "p-retry": "^7.1.1" + }, + "peerDependencies": { + "@langchain/core": "^1.1.48", + "react": "^18 || ^19", + "react-dom": "^18 || ^19" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "node_modules/@langchain/langgraph-sdk/node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/@langchain/langgraph-sdk/node_modules/p-queue": { + "version": "9.3.3", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.3.tgz", + "integrity": "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^5.0.4", + "p-timeout": "^7.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@langchain/langgraph-sdk/node_modules/p-timeout": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-7.0.2.tgz", + "integrity": "sha512-prbX4Z3YszrFNgH+MW5Zoeq3baXrMtP/MQnFeET90UB/GtGcGDQ5Usg9OCy6ETjTTntOw1SL2z9fMPUppN3Guw==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@langchain/mcp-adapters": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/@langchain/mcp-adapters/-/mcp-adapters-2.0.1.tgz", + "integrity": "sha512-dYijIiyN5JdufWX1I8cGrhKnmtSzl50cKLPuH9196xpsEJBz9TO+Z/ZM9pcHNyKM7+OZJDJvwB+DS7cAVhyheA==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/client": "^2.2.0", + "@modelcontextprotocol/core": "^2.2.0", + "zod": "^4.4.3" + }, + "engines": { + "node": ">=20.10.0" + }, + "peerDependencies": { + "@langchain/core": "^1.2.6", + "@langchain/langgraph": "^1.4.18" + }, + "peerDependenciesMeta": { + "@langchain/core": { + "optional": false + }, + "@langchain/langgraph": { + "optional": false + } + } + }, + "node_modules/@langchain/mistralai": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@langchain/mistralai/-/mistralai-1.2.0.tgz", + "integrity": "sha512-SRtCSDIBzcQc6ZK5qa1V2ZhqSdZomXOt4VzBWXkD//IYYhbMJHhbrlYuCIuHktwpF/1ME5a7Euyk+BujN9hkTA==", + "license": "MIT", + "dependencies": { + "@mistralai/mistralai": "2.2.1" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.0.0" + } + }, + "node_modules/@langchain/ollama": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/@langchain/ollama/-/ollama-1.3.0.tgz", + "integrity": "sha512-uzLkZVTXN0SI5zAoJbJzL4y/QN7gbmJ1txBgFfqJ5M0Qf+Yu2Zu8q98L3jIrfM+akWMaNmRU4R4APhcfQmeIsw==", + "license": "MIT", + "dependencies": { + "ollama": "^0.6.3" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.0.0" + } + }, + "node_modules/@langchain/openai": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-1.6.2.tgz", + "integrity": "sha512-KaXc3zjdM2/E24FdBlsk5NTT2Dyxh46vzCS2by78ehN6G5zdx+4OfVnPvyLl8r2tv2TqQCHpEhImVXgnAZaOvg==", + "license": "MIT", + "dependencies": { + "js-tiktoken": "^1.0.12", + "openai": "^7.10.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "@langchain/core": "^1.2.14" + } + }, + "node_modules/@langchain/protocol": { + "version": "0.0.19", + "resolved": "https://registry.npmjs.org/@langchain/protocol/-/protocol-0.0.19.tgz", + "integrity": "sha512-9hKcRrH7cBX6gfutdfXPoft1OCchHe4FEpALoDJMl5Qu+n/YG5ynZmyu8+8cxORlPwHBoKTxggvXz+76M1yX1Q==", + "license": "MIT" + }, + "node_modules/@langchain/tavily": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@langchain/tavily/-/tavily-1.2.0.tgz", + "integrity": "sha512-aPLPgtw8+b/Rnr3H+X8H8z98T/Y7JuCE4B5eqRDHoEWgZvMDUFF7divqwQqCTMq2deQttlVrm5bN5JbKaAR7/w==", + "license": "MIT", + "dependencies": { + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.0.0" + } + }, + "node_modules/@mistralai/mistralai": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/@mistralai/mistralai/-/mistralai-2.2.1.tgz", + "integrity": "sha512-uKU8CZmL2RzYKmplsU01hii4p3pe4HqJefpWNRWXm1Tcm0Sm4xXfwSLIy4k7ZCPlbETCGcp69E7hZs+WOJ5itQ==", + "license": "Apache-2.0", + "dependencies": { + "ws": "^8.18.0", + "zod": "^3.25.0 || ^4.0.0", + "zod-to-json-schema": "^3.25.0" + } + }, + "node_modules/@modelcontextprotocol/client": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz", + "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==", + "license": "Apache-2.0", + "dependencies": { + "@modelcontextprotocol/core": "2.3.1", + "cross-spawn": "^7.0.5", + "eventsource": "^3.0.2", + "eventsource-parser": "^3.0.8", + "jose": "^6.1.3", + "pkce-challenge": "^5.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz", + "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==", + "license": "Apache-2.0", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@oclif/core": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@oclif/core/-/core-4.14.0.tgz", + "integrity": "sha512-QCJIZoVJxV7jywgVAUlsQwl3dr3Sa21kfi5z9KrYolbexWJUtFSEtMoNiBWojD05mYycLnB50gp/VxlGdaOCRA==", + "license": "MIT", + "dependencies": { + "ansi-escapes": "^4.3.2", + "ansis": "^3.17.0", + "clean-stack": "^3.0.1", + "cli-spinners": "^2.9.2", + "debug": "^4.4.3", + "ejs": "^6", + "get-package-type": "^0.1.0", + "indent-string": "^4.0.0", + "lilconfig": "^3.1.3", + "minimatch": "^10.2.5", + "semver": "^7.8.1", + "string-width": "^4.2.3", + "supports-color": "^8", + "tinyglobby": "^0.2.17", + "widest-line": "^3.1.0", + "wordwrap": "^1.0.0", + "wrap-ansi": "^7.0.0", + "wsl-utils": "^0.4.0" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.153.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.153.0.tgz", + "integrity": "sha512-jSNrRIyvPVLL5E1z/tS5zLAprosGz/FuI1PWwEOz59j3E4TTTzSpqKb/RDGqJhhW0QHYISGXxq582wGx6T11Tw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@protobuf-ts/grpc-backend": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/grpc-backend/-/grpc-backend-2.11.1.tgz", + "integrity": "sha512-llAkJ03SlR/+p70YBTMOAQqdkXWghsTWwlPuGXC+Hj99hDQq6fa2CoVePPqbcn7A7/aLBcPG/9Ag3yqlltldxw==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@protobuf-ts/runtime": "^2.11.1", + "@protobuf-ts/runtime-rpc": "^2.11.1" + }, + "peerDependencies": { + "@grpc/grpc-js": "^1.8.22" + } + }, + "node_modules/@protobuf-ts/grpc-transport": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/grpc-transport/-/grpc-transport-2.11.1.tgz", + "integrity": "sha512-l6wrcFffY+tuNnuyrNCkRM8hDIsAZVLA8Mn7PKdVyYxITosYh60qW663p9kL6TWXYuDCL3oxH8ih3vLKTDyhtg==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@protobuf-ts/runtime": "^2.11.1", + "@protobuf-ts/runtime-rpc": "^2.11.1" + }, + "peerDependencies": { + "@grpc/grpc-js": "^1.6.0" + } + }, + "node_modules/@protobuf-ts/runtime": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/runtime/-/runtime-2.11.1.tgz", + "integrity": "sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ==", + "license": "(Apache-2.0 AND BSD-3-Clause)", + "peer": true + }, + "node_modules/@protobuf-ts/runtime-rpc": { + "version": "2.11.1", + "resolved": "https://registry.npmjs.org/@protobuf-ts/runtime-rpc/-/runtime-rpc-2.11.1.tgz", + "integrity": "sha512-4CqqUmNA+/uMz00+d3CYKgElXO9VrEbucjnBFEjqI4GuDrEQ32MaI3q+9qPBvIGOlL4PmHXrzM32vBPWRhQKWQ==", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "@protobuf-ts/runtime": "^2.11.1" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz", + "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz", + "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz", + "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==", + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", + "license": "BSD-3-Clause" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", + "license": "BSD-3-Clause" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.13.tgz", + "integrity": "sha512-Vu/NICrgdRvUOeaJZIyB2FP63s6fO/4ud5l8dXmxDx9yDyn+mN0y+gsvsVviSli+T361Aqo0h46EuMoobrwawA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.13.tgz", + "integrity": "sha512-6LEoIrGy5vvCd2boNnv2soPSUZj/PRvhp8R/t9KlX+mIZxThIE/ZqxrGXxmuNX0FuvQFvLdZr7S4HrYpYBVhEQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.13.tgz", + "integrity": "sha512-CaJSRzlQ6Q+zkDMVA9OkVxBjVoPRCDEE3v0FSJ9kIQBgRjFApA3Si4ijhbNVUji7ZJt+PfO0e46qy4nPInHUPA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.13.tgz", + "integrity": "sha512-e4r340I5hxSzJkD3YJBxgzq/rJ3wwxwdLLb2FPt1Zpyem20nrQPT11DDEEkazwxaHumH8wpglsp/Ozgj/wT6mw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.13.tgz", + "integrity": "sha512-hoBWDZ4/K/mJKVMbsgUd1jfpA2DiOrJ54mpegObU9TBHBBrtX4FLIXJJQRDPZ/2Dn91GvPob+Z2hwKJzf4E5SQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.13.tgz", + "integrity": "sha512-oF9fZu3vTWnTiVAkDFxU9PJLt1nh20K9RRpuHsR7ZnE2L7XookBbDBVLojCVSLGbvtSlxeUNnjAj6DbNsKyzbg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.13.tgz", + "integrity": "sha512-DTpb/+jMiqWMPgphn4ksW1zW+XLJ6dJJ9FMvnIk9I291LhCctMPhMYJrP5t9p6C9qa3KXadDdUEZHBaPh3kNxQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.13.tgz", + "integrity": "sha512-xU+Kvv9N2A3SY35zFh1FWWNjxbadE/BKeqnkXe7vScU4GZsw757BlVmDLITZEq8DPpk6m7uoDYkK7P+x/uU5Ow==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.13.tgz", + "integrity": "sha512-XMk/hnhh25oQ756Lclb1Q11h4ll0xC0Esa5w4Vzp+mAE2S3AGJgeM0SonrIgY8fHhjarb6hcoTuwoFG0VVP2ig==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.13.tgz", + "integrity": "sha512-U1BoTHYmlywE2n3HUWjzZ+8EQsKr+OwpxYuDWaubx42tUL8QSL7nOqRz/NVHanibbFP3M1Rxuprz/wNcbMKjqw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.13.tgz", + "integrity": "sha512-J4cm80Pc6wEwV5AZ42o62sIQgDk+Y7R2s646jIwuvO+4V46QB58N4vVuMPWCBaNgursXLpmUWJV//WQAkPvHBQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.13.tgz", + "integrity": "sha512-W0euZS40U4V6JkmEnVCIX9mcsL6cbXQ4X8c2w+MMOIjFg68TXUW+u3RT+2e1t1pv9mg/EP3pDtK3POXdQ7Rxyw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.13.tgz", + "integrity": "sha512-do/AF/4n9MRshia3a5aXoy8xM2c6mgfT6D7H/dY6my5z+hfCIR4ab7mk4IRj++nsEQpKy39kd0DQnDq+r692tw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.13.tgz", + "integrity": "sha512-6FtUf2cJZobutJdxnGYX8z0vtbgqU0b2v8vfBhkXb9wp2MppMFtkunE+IaOntyi01rkIQoPW2GHABtfzsC0BRQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.13.tgz", + "integrity": "sha512-UKhFaZTeTcbKrb3iU82m17jVcPEAoqDkCN5MBqgPyZSwp/cQmib21crTS0DdH7T1B7wZRWEI89YQAOJMet5yhg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@stablelib/base64": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@stablelib/base64/-/base64-1.0.1.tgz", + "integrity": "sha512-1bnPQqSxSuc3Ii6MhBysoWCg58j97aUjuCSZrGSmDxNqtytIi0k8utUenAwTZN4V5mXXYGsVUI9zeBqy+jBOSQ==", + "license": "MIT" + }, + "node_modules/@standard-schema/spec": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", + "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", + "license": "MIT" + }, + "node_modules/@ts-morph/common": { + "version": "0.29.0", + "resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.29.0.tgz", + "integrity": "sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg==", + "license": "MIT", + "dependencies": { + "minimatch": "^10.0.1", + "path-browserify": "^1.0.1", + "tinyglobby": "^0.2.14" + } + }, + "node_modules/@types/chai": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz", + "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/deep-eql": "*", + "assertion-error": "^2.0.1" + } + }, + "node_modules/@types/deep-eql": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz", + "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@typescript/vfs": { + "version": "1.6.5", + "resolved": "https://registry.npmjs.org/@typescript/vfs/-/vfs-1.6.5.tgz", + "integrity": "sha512-gobLHQLmvQGJInFk31NvgMd1uYzRXsd8qgnOssyLD055R2QPnw1ubRbBQ4+T+5qC7IQVuYXdvNDE2G7tMDVHgw==", + "license": "MIT", + "dependencies": { + "debug": "^4.4.3" + }, + "peerDependencies": { + "typescript": "*" + } + }, + "node_modules/@vitest/expect": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@standard-schema/spec": "^1.1.0", + "@types/chai": "^5.2.2", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "chai": "^6.2.2", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/mocker": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/spy": "4.1.11", + "estree-walker": "^3.0.3", + "magic-string": "^0.30.21" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "msw": "^2.4.9", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "msw": { + "optional": true + }, + "vite": { + "optional": true + } + } + }, + "node_modules/@vitest/pretty-format": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "dev": true, + "license": "MIT", + "dependencies": { + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/runner": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/utils": "4.1.11", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/snapshot": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", + "magic-string": "^0.30.21", + "pathe": "^2.0.3" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/spy": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/@vitest/utils": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "4.1.11", + "convert-source-map": "^2.0.0", + "tinyrainbow": "^3.1.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + } + }, + "node_modules/ansi-escapes": { + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", + "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.21.3" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.4.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz", + "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ansis": { + "version": "3.17.0", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-3.17.0.tgz", + "integrity": "sha512-0qWUglt9JEqLFr3w1I1pbrChn1grhaiAR2ocX1PP/flRmxgtwTzPFFFnfIlD6aMOLQZgSuCRlidD70lvx8yhzg==", + "license": "ISC", + "engines": { + "node": ">=14" + } + }, + "node_modules/assertion-error": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", + "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/base64-js": { + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", + "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/chai": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "license": "MIT", + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/clean-stack": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-3.0.1.tgz", + "integrity": "sha512-lR9wNiMRcVQjSB3a7xXGLuz4cr4wJuuXlaAEbRutGowQTmlp7R72/DOgN21e8jdwblMWl9UOJMJXarX94pzKdg==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "2.9.2", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", + "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.2.0.tgz", + "integrity": "sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==", + "license": "MIT", + "dependencies": { + "slice-ansi": "^8.0.0", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate/node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/code-block-writer": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/code-block-writer/-/code-block-writer-13.0.3.tgz", + "integrity": "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==", + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, + "node_modules/colorette": { + "version": "2.0.20", + "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", + "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/ejs": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-6.0.1.tgz", + "integrity": "sha512-UaaM14yby8U3k02ihS1Bmj5Kz2d7CCQM1scxpgs4Mhkq8F1wR2gl3+Ts4h5Ne4Mnt7M9m4Dw7jsuMr3+xO4vZA==", + "license": "Apache-2.0", + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.12.18" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.28.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz", + "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.28.2", + "@esbuild/android-arm": "0.28.2", + "@esbuild/android-arm64": "0.28.2", + "@esbuild/android-x64": "0.28.2", + "@esbuild/darwin-arm64": "0.28.2", + "@esbuild/darwin-x64": "0.28.2", + "@esbuild/freebsd-arm64": "0.28.2", + "@esbuild/freebsd-x64": "0.28.2", + "@esbuild/linux-arm": "0.28.2", + "@esbuild/linux-arm64": "0.28.2", + "@esbuild/linux-ia32": "0.28.2", + "@esbuild/linux-loong64": "0.28.2", + "@esbuild/linux-mips64el": "0.28.2", + "@esbuild/linux-ppc64": "0.28.2", + "@esbuild/linux-riscv64": "0.28.2", + "@esbuild/linux-s390x": "0.28.2", + "@esbuild/linux-x64": "0.28.2", + "@esbuild/netbsd-arm64": "0.28.2", + "@esbuild/netbsd-x64": "0.28.2", + "@esbuild/openbsd-arm64": "0.28.2", + "@esbuild/openbsd-x64": "0.28.2", + "@esbuild/openharmony-arm64": "0.28.2", + "@esbuild/sunos-x64": "0.28.2", + "@esbuild/win32-arm64": "0.28.2", + "@esbuild/win32-ia32": "0.28.2", + "@esbuild/win32-x64": "0.28.2" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/estree-walker": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", + "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.0" + } + }, + "node_modules/eventemitter3": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", + "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", + "license": "MIT" + }, + "node_modules/eventsource": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz", + "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==", + "license": "MIT", + "dependencies": { + "eventsource-parser": "^3.0.1" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/eventsource-parser": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz", + "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/expect-type": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/fast-sha256": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/fast-sha256/-/fast-sha256-1.3.0.tgz", + "integrity": "sha512-n11RGP/lrWEFI/bWdygLxhI+pVeo1ZYIVwvvPkW7azl/rOy+F3HYRZ2K5zeE9mmkhQppyv9sQFx0JM9UabnpPQ==", + "license": "Unlicense" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-package-type": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", + "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/groq-sdk": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/groq-sdk/-/groq-sdk-1.6.0.tgz", + "integrity": "sha512-ggMgo6n84aZdNObgkSbSxWrdAq4wABsViIRb5e4N15bMUtDLZVhqlgZOI7X4TeqdBMdaVUOuUdZxAZIp06u0vw==", + "license": "Apache-2.0", + "bin": { + "groq-sdk": "bin/cli" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/indent-string": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", + "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-docker": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "license": "MIT", + "bin": { + "is-docker": "cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "license": "MIT", + "dependencies": { + "is-docker": "^3.0.0" + }, + "bin": { + "is-inside-container": "cli.js" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-network-error": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.2.tgz", + "integrity": "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA==", + "license": "MIT", + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-wsl": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", + "integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==", + "license": "MIT", + "dependencies": { + "is-inside-container": "^1.0.0" + }, + "engines": { + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "license": "ISC" + }, + "node_modules/jose": { + "version": "6.2.12", + "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz", + "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/js-tiktoken": { + "version": "1.0.21", + "resolved": "https://registry.npmjs.org/js-tiktoken/-/js-tiktoken-1.0.21.tgz", + "integrity": "sha512-biOj/6M5qdgx5TKjDnFT1ymSpM5tbd3ylwDtrQvFQSu0Z7bBYko2dF+W/aUkXUPuk6IVpRxk/3Q2sHOzGlS36g==", + "license": "MIT", + "dependencies": { + "base64-js": "^1.5.1" + } + }, + "node_modules/json-schema-to-ts": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/json-schema-to-ts/-/json-schema-to-ts-3.1.1.tgz", + "integrity": "sha512-+DWg8jCJG2TEnpy7kOm/7/AxaYoaRbjVB4LFZLySZlWn8exGs3A4OLJR966cVvU26N7X9TWxl+Jsw7dzAqKT6g==", + "license": "MIT", + "dependencies": { + "@babel/runtime": "^7.18.3", + "ts-algebra": "^2.0.0" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/langchain": { + "version": "1.5.16", + "resolved": "https://registry.npmjs.org/langchain/-/langchain-1.5.16.tgz", + "integrity": "sha512-t5DvkNvySgkNAjWLJ5lIvg2R2WJJ/uF7hHtaSIwUEUUv/YzynzbtJLovwhIw0W1HdOnBbao6dkWOZthKjwBUPQ==", + "license": "MIT", + "dependencies": { + "@langchain/langgraph": "^1.4.18", + "@langchain/langgraph-checkpoint": "^1.1.5", + "langsmith": ">=0.5.0 <1.0.0", + "zod": "^3.25.76 || ^4" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@langchain/core": "^1.2.17" + } + }, + "node_modules/langsmith": { + "version": "0.10.10", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.10.10.tgz", + "integrity": "sha512-I83MmN/tqU662yHfv7DCMlJh8eFuRdY2Ri9rlvM61DGEsVdnVkOa0eyv9DpsstBM5dS877o5GDn+qHwZWfSgRg==", + "license": "MIT", + "dependencies": { + "p-queue": "6.6.2" + }, + "peerDependencies": { + "@opentelemetry/api": "*", + "@opentelemetry/exporter-trace-otlp-proto": "*", + "@opentelemetry/sdk-trace-base": "*", + "openai": "*", + "ws": ">=7" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@opentelemetry/exporter-trace-otlp-proto": { + "optional": true + }, + "@opentelemetry/sdk-trace-base": { + "optional": true + }, + "openai": { + "optional": true + }, + "ws": { + "optional": true + } + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lilconfig": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz", + "integrity": "sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==", + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/listr2": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/listr2/-/listr2-9.0.5.tgz", + "integrity": "sha512-ME4Fb83LgEgwNw96RKNvKV4VTLuXfoKudAmm2lP8Kk87KaMK0/Xrx/aAkMWmT8mDb+3MlFDspfbCs7adjRxA2g==", + "license": "MIT", + "dependencies": { + "cli-truncate": "^5.0.0", + "colorette": "^2.0.20", + "eventemitter3": "^5.0.1", + "log-update": "^6.1.0", + "rfdc": "^1.4.1", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=20.0.0" + } + }, + "node_modules/listr2/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/listr2/node_modules/eventemitter3": { + "version": "5.0.4", + "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/listr2/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/listr2/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", + "license": "MIT" + }, + "node_modules/log-update": { + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz", + "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==", + "license": "MIT", + "dependencies": { + "ansi-escapes": "^7.0.0", + "cli-cursor": "^5.0.0", + "slice-ansi": "^7.1.0", + "strip-ansi": "^7.1.0", + "wrap-ansi": "^9.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/log-update/node_modules/slice-ansi": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz", + "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/log-update/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-update/node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/mustache/-/mustache-4.2.0.tgz", + "integrity": "sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/ollama": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/ollama/-/ollama-0.6.4.tgz", + "integrity": "sha512-KzM6b5Sq0TgipeMTdImuELr/V4eNqrTf37PRzUTHCPPieFmboYw6qPn+pX7+lg0nSP1jsKwy4AFkiQFXhqHeZA==", + "license": "MIT", + "dependencies": { + "whatwg-fetch": "^3.6.20" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/openai": { + "version": "7.31.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-7.31.0.tgz", + "integrity": "sha512-ZGAzauuYb0DdB53qVbIR+X8rdmNtWgiElrrMthbZCVreLcIsQJBwzAIWUbpB2FkQu2Cj6OJ9zJR1EKMUYn4/SQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=22.0.0" + }, + "peerDependencies": { + "@aws-sdk/credential-provider-node": ">=3.972.0 <4", + "@smithy/hash-node": ">=4.3.0 <5", + "@smithy/signature-v4": ">=5.4.0 <6", + "undici": ">=5 <9", + "ws": "^8.21.0", + "zod": "^3.25 || ^4.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/credential-provider-node": { + "optional": true + }, + "@smithy/hash-node": { + "optional": true + }, + "@smithy/signature-v4": { + "optional": true + }, + "undici": { + "optional": true + }, + "ws": { + "optional": true + }, + "zod": { + "optional": true + } + } + }, + "node_modules/p-finally": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/p-finally/-/p-finally-1.0.0.tgz", + "integrity": "sha512-LICb2p9CB7FS+0eR1oqWnHhp0FljGLZCWBE9aix0Uye9W8LTQPwMTYVGWQWIw9RdQiDg4+epXQODwIYJtSJaow==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-6.6.2.tgz", + "integrity": "sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-retry": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-7.1.1.tgz", + "integrity": "sha512-J5ApzjyRkkf601HpEeykoiCvzHQjWxPAHhyjFcEUP2SWq0+35NKh8TLhpLw+Dkq5TZBFvUM6UigdE9hIVYTl5w==", + "license": "MIT", + "dependencies": { + "is-network-error": "^1.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/p-timeout/-/p-timeout-3.2.0.tgz", + "integrity": "sha512-rhIwUycgwwKcP9yTOOFK/AKsAopjjCakVqLHePO3CC6Mir1Z99xT+R63jZxAT5lFZLa2inS5h+ZS2GvR99/FBg==", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/path-browserify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-browserify/-/path-browserify-1.0.1.tgz", + "integrity": "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==", + "license": "MIT" + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pathe": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz", + "integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pkce-challenge": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz", + "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==", + "license": "MIT", + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/postcss": { + "version": "8.5.29", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", + "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.19", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/powershell-utils": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.1.0.tgz", + "integrity": "sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/protobufjs": { + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", + "hasInstallScript": true, + "license": "BSD-3-Clause", + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.5", + "@protobufjs/eventemitter": "^1.1.1", + "@protobufjs/fetch": "^1.1.1", + "@protobufjs/float": "^1.0.2", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.1", + "@types/node": ">=13.7.0", + "long": "^5.3.2" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "license": "MIT", + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/reflect-metadata": { + "version": "0.2.2", + "resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz", + "integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==", + "license": "Apache-2.0", + "peer": true + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/rfdc": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", + "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", + "license": "MIT" + }, + "node_modules/rolldown": { + "version": "1.2.13", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.13.tgz", + "integrity": "sha512-/5apOkwWxtACcQtZ5WlrAsKS4JwXVThQPJZ3RqIruRY9UG9M8e0VlXN068xum/JRKA4aIUoJ13ghe/kGCvidiQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.153.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.13", + "@rolldown/binding-android-arm64": "1.2.13", + "@rolldown/binding-darwin-arm64": "1.2.13", + "@rolldown/binding-darwin-x64": "1.2.13", + "@rolldown/binding-freebsd-x64": "1.2.13", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.13", + "@rolldown/binding-linux-arm64-gnu": "1.2.13", + "@rolldown/binding-linux-arm64-musl": "1.2.13", + "@rolldown/binding-linux-ppc64-gnu": "1.2.13", + "@rolldown/binding-linux-s390x-gnu": "1.2.13", + "@rolldown/binding-linux-x64-gnu": "1.2.13", + "@rolldown/binding-linux-x64-musl": "1.2.13", + "@rolldown/binding-openharmony-arm64": "1.2.13", + "@rolldown/binding-win32-arm64-msvc": "1.2.13", + "@rolldown/binding-win32-x64-msvc": "1.2.13" + } + }, + "node_modules/semver": { + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/siginfo": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", + "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", + "dev": true, + "license": "ISC" + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/sisteransi": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz", + "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==", + "license": "MIT" + }, + "node_modules/slash": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/slash/-/slash-5.1.0.tgz", + "integrity": "sha512-ZA6oR3T/pEyuqwMgAKT0/hAv8oAXckzbkmR0UkUosQ+Mc4RxGoJkRmwHgHufaenlyAgE1Mxgpdcrf75y6XcnDg==", + "license": "MIT", + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/slice-ansi": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-8.0.0.tgz", + "integrity": "sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stackback": { + "version": "0.0.2", + "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", + "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", + "dev": true, + "license": "MIT" + }, + "node_modules/standardwebhooks": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/standardwebhooks/-/standardwebhooks-1.1.1.tgz", + "integrity": "sha512-bCbX9ZEyFkWPsRz7Bl3NuQUJohmwGSev/yhr7vhaGPlc4AfIrspIRa6cPTBuI1ItmrTDJ4d/S2hCsfe4+vQGnQ==", + "license": "MIT", + "dependencies": { + "@stablelib/base64": "^1.0.0", + "fast-sha256": "^1.3.0" + } + }, + "node_modules/std-env": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", + "dev": true, + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/text-camel-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-camel-case/-/text-camel-case-1.2.11.tgz", + "integrity": "sha512-2ZsM/gOlB1tyza+8lGLvs6gtPuZ9qEYuKPa+gwo38m65wkY4k323SK4hT7ku8r5wIKyspUYIWSk1aB9/Jjxr7A==", + "license": "MIT", + "dependencies": { + "text-pascal-case": "^1.2.11" + } + }, + "node_modules/text-capital-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-capital-case/-/text-capital-case-1.2.11.tgz", + "integrity": "sha512-30A7B7+VUvevEmPE0xWK1Z2z0ncl/JTjSUBLfjpoXrkwuPpmNTVbjHShRTN3cX9GIuZn/P3jvR+TO9JiTZcl8A==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11", + "text-upper-case-first": "^1.2.11" + } + }, + "node_modules/text-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-case/-/text-case-1.2.11.tgz", + "integrity": "sha512-LbdWNQeuXWbfav+pxBxvaefkziffMYeSA53BHp52cgJa9rjiC0dkjum9AKrH8iQWoQJ4InGPSGexLeerGFaZ1Q==", + "license": "MIT", + "dependencies": { + "text-camel-case": "^1.2.11", + "text-capital-case": "^1.2.11", + "text-constant-case": "^1.2.11", + "text-dot-case": "^1.2.11", + "text-header-case": "^1.2.11", + "text-is-lower-case": "^1.2.11", + "text-is-upper-case": "^1.2.11", + "text-kebab-case": "^1.2.11", + "text-lower-case": "^1.2.11", + "text-lower-case-first": "^1.2.11", + "text-no-case": "^1.2.11", + "text-param-case": "^1.2.11", + "text-pascal-case": "^1.2.11", + "text-path-case": "^1.2.11", + "text-sentence-case": "^1.2.11", + "text-snake-case": "^1.2.11", + "text-swap-case": "^1.2.11", + "text-title-case": "^1.2.11", + "text-upper-case": "^1.2.11", + "text-upper-case-first": "^1.2.11" + } + }, + "node_modules/text-constant-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-constant-case/-/text-constant-case-1.2.11.tgz", + "integrity": "sha512-XnTBILsa7UpMWncUCchqIybZlg15FUcrlyNaWIJ8ybPy54qcoN513EXFswueyizuAgyJFXPCwwSFbSji6kw/Uw==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11", + "text-upper-case": "^1.2.11" + } + }, + "node_modules/text-dot-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-dot-case/-/text-dot-case-1.2.11.tgz", + "integrity": "sha512-7SLKiT45KZO0qad0+p+GvC0+F+6pZ851HJcTcBJiSF88HsK/e1qErlGLtVBT6hkTHIaAj48WfSyQr4lZRv1xJQ==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11" + } + }, + "node_modules/text-header-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-header-case/-/text-header-case-1.2.11.tgz", + "integrity": "sha512-7OBHd2g7X+aH6rXMC3cANFh6yvhXjXkyumw2NaRwJRIk343pP2e1SQCTCfowPDmmi8wkZVqz1fdWNq5LwvcBOQ==", + "license": "MIT", + "dependencies": { + "text-capital-case": "^1.2.11" + } + }, + "node_modules/text-is-lower-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-is-lower-case/-/text-is-lower-case-1.2.11.tgz", + "integrity": "sha512-dBqPAkNmX7eTM7ZbS3D/UBCQ5i9EXt5tujF2wIGGbZ1+aN8bY7Qda4mDpxgd6Hbzf/z10uQWRNzupl99wFQ8CQ==", + "license": "MIT" + }, + "node_modules/text-is-upper-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-is-upper-case/-/text-is-upper-case-1.2.11.tgz", + "integrity": "sha512-MZeUIYEYfKZ2FSeg0vnHCH4mHXLgGzes+iz2K+4BYnhnkEa2svKA1nNjQAqTUiVNHOPqPCuzmUr1LsyQZ73uyA==", + "license": "MIT" + }, + "node_modules/text-kebab-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-kebab-case/-/text-kebab-case-1.2.11.tgz", + "integrity": "sha512-RIg9iN6VwH+JrX9dFdm1nd1efPGR9LjNc0CiQz496sQETeKGkDEzxES/ZzxbkerrAL2DFEMGdLXckzDz1OEDBQ==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11" + } + }, + "node_modules/text-lower-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-lower-case/-/text-lower-case-1.2.11.tgz", + "integrity": "sha512-txTy6y0y8M23Lhf0mk8WcvXTqlf4OQ3AGnDsRB6o3uMNfIa0CJDol2s1PdKNa63rt5B2277zkZCCn6Xeq//big==", + "license": "MIT" + }, + "node_modules/text-lower-case-first": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-lower-case-first/-/text-lower-case-first-1.2.11.tgz", + "integrity": "sha512-QR483XLyuyIpq8tKu1ds3Q1jfsgfaa/p9rtoQKHe6Rv5ah9ic/SUzTGN0MQ7UIS9APADd8SUPn5TTh1Z2/ACyg==", + "license": "MIT" + }, + "node_modules/text-no-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-no-case/-/text-no-case-1.2.11.tgz", + "integrity": "sha512-wazS7FEq0Ct3aJzeE8MEMcSs0eW4+/X/fwdotv/rG66bLS+g1T0pa0gUsbBGjjLFs191AIXVIry+bYE0uaaBBQ==", + "license": "MIT", + "dependencies": { + "text-lower-case": "^1.2.11" + } + }, + "node_modules/text-param-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-param-case/-/text-param-case-1.2.11.tgz", + "integrity": "sha512-3EMMAMLSz/mJXOnATNnrS+dZAvghpq09VhOVYDOkUnbm5zlYc6iU5AZOKVDpiAVVllQ9P1h5IKVZzsEYrdIRGw==", + "license": "MIT", + "dependencies": { + "text-dot-case": "^1.2.11" + } + }, + "node_modules/text-pascal-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-pascal-case/-/text-pascal-case-1.2.11.tgz", + "integrity": "sha512-BNhQ1O/g/Q4dH5gPyLIJLDLDknl2dipBwV629ScsiZCKJaCLGXYhTXp23rp9Htg3O5OSSsiU3mqDKq+pBmwTSw==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11" + } + }, + "node_modules/text-path-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-path-case/-/text-path-case-1.2.11.tgz", + "integrity": "sha512-FsJU4BmMdtLtmnBK/XRJPqTwLF8yFiTEClHjxlQjSAG5Xt9R4p6D1WNaM1CI2dG5Lr4rsFM4jiVC620m0AsRbw==", + "license": "MIT", + "dependencies": { + "text-dot-case": "^1.2.11" + } + }, + "node_modules/text-sentence-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-sentence-case/-/text-sentence-case-1.2.11.tgz", + "integrity": "sha512-ApiVsvdLy+Wb8x7mZRVuoy8VO12jJ22G2djVM3ZZbUhXVIkqGgHxmiXRwdhRPoWGojK9n53m7jviJgBVNdRn+g==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11", + "text-upper-case-first": "^1.2.11" + } + }, + "node_modules/text-snake-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-snake-case/-/text-snake-case-1.2.11.tgz", + "integrity": "sha512-NOEQvjyyVABB41SS8dUx423Y6hWS+Z4TrAAJg1xzCkOD3q9y0JtdJjCvCA1FWI8oDu+HiIOp/N446uDM8j54XQ==", + "license": "MIT", + "dependencies": { + "text-dot-case": "^1.2.11" + } + }, + "node_modules/text-swap-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-swap-case/-/text-swap-case-1.2.11.tgz", + "integrity": "sha512-PBmC5xvZdDZ4suikydpeXH0s4JV2XHelMj9/OEXEbA3oLpdV2A+B4BspVDWVw7C2Gi5eCareqk/7EE8I1/WwgQ==", + "license": "MIT" + }, + "node_modules/text-title-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-title-case/-/text-title-case-1.2.11.tgz", + "integrity": "sha512-V1GZy0XlqdkYUQm0tqm1jqtYlXJqFVMreBCTUReOaz8d/JbozTSpZrcakIeV8+1bN7LsvfhPFhA5zREiax6YIA==", + "license": "MIT", + "dependencies": { + "text-no-case": "^1.2.11", + "text-upper-case-first": "^1.2.11" + } + }, + "node_modules/text-upper-case": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-upper-case/-/text-upper-case-1.2.11.tgz", + "integrity": "sha512-BfTL7yB1YIRlVGNdZUvno013hOq2cRs07fDR2ApppOXRDuKrEmsLDEY82xXlDzQHELp0jexqkI+NeyPIl6MtMw==", + "license": "MIT" + }, + "node_modules/text-upper-case-first": { + "version": "1.2.11", + "resolved": "https://registry.npmjs.org/text-upper-case-first/-/text-upper-case-first-1.2.11.tgz", + "integrity": "sha512-vgfbwKo8TEJbRsapR9LWWvIJRnv8u9aXVa6cyYOAQQmurCx54Cnt59x5fKdiq+hFaBJ51AbzCgMpbP3p65/pHQ==", + "license": "MIT" + }, + "node_modules/tinybench": { + "version": "2.9.0", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", + "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/tinyexec": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyrainbow": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/ts-algebra": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ts-algebra/-/ts-algebra-2.0.0.tgz", + "integrity": "sha512-FPAhNPFMrkwz76P7cdjdmiShwMynZYN6SgOujD1urY4oNm80Ou9oMdmbR45LotcKOXoy7wSmHkRFE6Mxbrhefw==", + "license": "MIT" + }, + "node_modules/ts-morph": { + "version": "28.0.0", + "resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-28.0.0.tgz", + "integrity": "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g==", + "license": "MIT", + "peer": true, + "dependencies": { + "@ts-morph/common": "~0.29.0", + "code-block-writer": "^13.0.3" + } + }, + "node_modules/ts-to-zod": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/ts-to-zod/-/ts-to-zod-5.1.0.tgz", + "integrity": "sha512-giqqlvRHunlJqG9tBL/KAO3wWIVZGF//mZiWLKm/fdQnKnz4EN2mtiK5cugN9slytBkdMEXQIaLvMzIScbhhFw==", + "license": "MIT", + "peer": true, + "dependencies": { + "@clack/prompts": "1.0.0-alpha.4", + "@oclif/core": "^4.5.4", + "@typescript/vfs": "^1.5.0", + "chokidar": "^4.0.3", + "listr2": "^9.0.4", + "slash": "^5.1.0", + "text-case": "^1.2.4", + "tslib": "^2.3.1", + "tsutils": "^3.21.0", + "typescript": "^5.2.2", + "zod": "^4.1.5" + }, + "bin": { + "ts-to-zod": "bin/run" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/tsutils": { + "version": "3.21.0", + "resolved": "https://registry.npmjs.org/tsutils/-/tsutils-3.21.0.tgz", + "integrity": "sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==", + "license": "MIT", + "dependencies": { + "tslib": "^1.8.1" + }, + "engines": { + "node": ">= 6" + }, + "peerDependencies": { + "typescript": ">=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta" + } + }, + "node_modules/tsutils/node_modules/tslib": { + "version": "1.14.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", + "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", + "license": "0BSD" + }, + "node_modules/tsx": { + "version": "4.23.15", + "resolved": "https://registry.npmjs.org/tsx/-/tsx-4.23.15.tgz", + "integrity": "sha512-Yiex1Ovn8z2xPpOWckIiysV1SSyRMY9BkLF++q0yKiDxCqRhosKfMg3janKkiLBwZ5c/YryloKwGZcrEmtwxKw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "esbuild": "~0.28.0" + }, + "bin": { + "tsx": "dist/cli.mjs" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + } + }, + "node_modules/type-fest": { + "version": "0.21.3", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", + "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "license": "MIT" + }, + "node_modules/vite": { + "version": "8.3.4", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.4.tgz", + "integrity": "sha512-IftLE8phJhdNRIGNEV4JCCvfNScoZQVfcXaN8TQropWGJtOHcu+iAB9pHcuGvmEb/kddw0LBe/jS8ztdC6xdiQ==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.29", + "rolldown": "~1.2.12", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.7.1", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vitest": { + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", + "es-module-lexer": "^2.0.0", + "expect-type": "^1.3.0", + "magic-string": "^0.30.21", + "obug": "^2.1.1", + "pathe": "^2.0.3", + "picomatch": "^4.0.3", + "std-env": "^4.0.0-rc.1", + "tinybench": "^2.9.0", + "tinyexec": "^1.0.2", + "tinyglobby": "^0.2.15", + "tinyrainbow": "^3.1.0", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", + "why-is-node-running": "^2.3.0" + }, + "bin": { + "vitest": "vitest.mjs" + }, + "engines": { + "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "@edge-runtime/vm": "*", + "@opentelemetry/api": "^1.9.0", + "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", + "happy-dom": "*", + "jsdom": "*", + "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + }, + "peerDependenciesMeta": { + "@edge-runtime/vm": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + }, + "@types/node": { + "optional": true + }, + "@vitest/browser-playwright": { + "optional": true + }, + "@vitest/browser-preview": { + "optional": true + }, + "@vitest/browser-webdriverio": { + "optional": true + }, + "@vitest/coverage-istanbul": { + "optional": true + }, + "@vitest/coverage-v8": { + "optional": true + }, + "@vitest/ui": { + "optional": true + }, + "happy-dom": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "vite": { + "optional": false + } + } + }, + "node_modules/whatwg-fetch": { + "version": "3.6.20", + "resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz", + "integrity": "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg==", + "license": "MIT" + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/why-is-node-running": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", + "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "dev": true, + "license": "MIT", + "dependencies": { + "siginfo": "^2.0.0", + "stackback": "0.0.2" + }, + "bin": { + "why-is-node-running": "cli.js" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/widest-line": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", + "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", + "license": "MIT", + "dependencies": { + "string-width": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wordwrap": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz", + "integrity": "sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q==", + "license": "MIT" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ws": { + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/wsl-utils": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-0.4.0.tgz", + "integrity": "sha512-9YmF+2sFEd+T7TkwlmE337F0IVzfDvDknhtpBQxxXzEOfgPphGlFYpyx0cTuCIFj8/p+sqwBYAeGxOMNSzPPDA==", + "license": "MIT", + "dependencies": { + "is-wsl": "^3.1.0", + "powershell-utils": "^0.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.3", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz", + "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==", + "license": "MIT", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, + "node_modules/zod": { + "version": "4.6.5", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz", + "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==", + "license": "MIT", + "peer": true, + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.25.2", + "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz", + "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==", + "license": "ISC", + "peerDependencies": { + "zod": "^3.25.28 || ^4" + } + }, + "node_modules/zod-to-ts": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/zod-to-ts/-/zod-to-ts-2.1.0.tgz", + "integrity": "sha512-jZP1GokTqR99FLmtGU+B9acjD9u/R++b++Vxe1sWpBQDd82/9/j5LyLZZ7/Oy3h2nxcz5NihikgX4D0hhdu3+g==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "typescript": "^5 || ^6", + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/actions/ai-action/package.json b/actions/ai-action/package.json new file mode 100644 index 0000000..008870b --- /dev/null +++ b/actions/ai-action/package.json @@ -0,0 +1,33 @@ +{ + "name": "@code0-tech/ai-action", + "version": "1.0.0", + "private": true, + "type": "module", + "main": "dist/index.js", + "scripts": { + "dev": "tsx watch src/index.ts", + "typecheck": "tsc --noEmit", + "build": "vite build", + "test": "vitest run", + "start": "node dist/index.js" + }, + "dependencies": { + "@code0-tech/hercules": "^1.6.0", + "@langchain/anthropic": "^1.0.0", + "@langchain/core": "^1.0.0", + "@langchain/groq": "^1.0.0", + "@langchain/mcp-adapters": "^2.0.1", + "@langchain/mistralai": "^1.0.0", + "@langchain/ollama": "^1.0.0", + "@langchain/openai": "^1.6.2", + "@langchain/tavily": "^1.2.0", + "langchain": "^1.5.16" + }, + "devDependencies": { + "@types/node": "^22.0.0", + "tsx": "^4.0.0", + "typescript": "^5.9.3", + "vite": "^8.0.3", + "vitest": "^4.1.10" + } +} diff --git a/actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts b/actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts new file mode 100644 index 0000000..c75b661 --- /dev/null +++ b/actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts @@ -0,0 +1,15 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; + +export const AiAgentRequestSchema = z.object({ + messages: z.array(AiMessageSchema), + thread_id: z.string().optional(), +}); +export type AiAgentRequest = z.infer; + +@Identifier("AI_AGENT_REQUEST") +@Name({ code: "en-US", content: "Agent request" }) +@DisplayMessage({ code: "en-US", content: "Agent request" }) +@Schema(AiAgentRequestSchema) +export class AiAgentRequestDataType {} diff --git a/actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts b/actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts new file mode 100644 index 0000000..4bd2356 --- /dev/null +++ b/actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts @@ -0,0 +1,15 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; + +export const AiAgentResponseSchema = z.object({ + messages: z.array(AiMessageSchema), + structured_response: z.looseObject({}).optional(), +}); +export type AiAgentResponse = z.infer; + +@Identifier("AI_AGENT_RESPONSE") +@Name({ code: "en-US", content: "Agent response" }) +@DisplayMessage({ code: "en-US", content: "Agent response" }) +@Schema(AiAgentResponseSchema) +export class AiAgentResponseDataType {} diff --git a/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts b/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts new file mode 100644 index 0000000..5acf945 --- /dev/null +++ b/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts @@ -0,0 +1,4 @@ +import type { AiAgentRequest } from "./Agent.request.datatype.js"; +import type { AiAgentResponse } from "./Agent.response.datatype.js"; + +export type AiAgentTransform = (request: AiAgentRequest) => Promise; diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts new file mode 100644 index 0000000..88a4846 --- /dev/null +++ b/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts @@ -0,0 +1,79 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + SubFlow, + ThrowsError, +} from "@code0-tech/hercules"; +import type { AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; +import type { AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; +import type { AiAgentTransform } from "../datatypes/Agent.transform.datatype.js"; +import type { AiMiddlewareTransform } from "../../middleware/datatypes/Middleware.transform.datatype.js"; +import type { AiModelTransform } from "../../model/datatypes/Model.transform.datatype.js"; +import { asList } from "../../shared/utils/Shared.asList.util.js"; +import { asSubFlow } from "../../shared/utils/Shared.asSubFlow.util.js"; +import { asText } from "../../shared/utils/Shared.asText.util.js"; +import { asToolEntries } from "../utils/Agent.asToolEntries.util.js"; +import type { AgentDefinition, ToolEntry } from "../utils/Agent.compileAgent.util.js"; +import { requireText } from "../../shared/utils/Shared.requireText.util.js"; +import { runAgent } from "../utils/Agent.runAgent.util.js"; +import { toolServers } from "../utils/Agent.toolServers.util.js"; +import { validateMcpServers } from "../../mcp/utils/Mcp.validateMcpServers.util.js"; + +@Identifier("ai::agent::create") +@DisplayIcon("tabler:robot") +@Signature( + "(name: TEXT, system_prompt: TEXT, model: TRANSFORM, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, middleware?: LIST>): TRANSFORM", +) +@Name({ code: "en-US", content: "Create agent" }) +@DisplayMessage({ code: "en-US", content: "Create agent ${name}" }) +@ThrowsError() +@Parameter({ + runtimeName: "name", + name: [{ code: "en-US", content: "Name" }], +}) +@Parameter({ + runtimeName: "system_prompt", + name: [{ code: "en-US", content: "System prompt" }], +}) +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], +}) +@Parameter({ + runtimeName: "tools", + name: [{ code: "en-US", content: "Tools" }], + optional: true, +}) +@Parameter({ + runtimeName: "middleware", + name: [{ code: "en-US", content: "Middleware" }], + optional: true, +}) +export class CreateAgentFunction { + run( + _context: FunctionContext, + name: string, + system_prompt: string, + model: AiModelTransform, + tools?: ToolEntry[], + middleware?: (AiMiddlewareTransform)[], + ): AiAgentTransform { + const definition: AgentDefinition = { + name: requireText(name, "ERROR_INVALID_AI_AGENT", "An agent needs a name."), + systemPrompt: asText(system_prompt ?? "", "system_prompt", "ERROR_INVALID_AI_AGENT"), + model: asSubFlow(model, "model"), + tools: asToolEntries(tools), + middleware: asList(middleware, "middleware").map((entry, index): SubFlow => + asSubFlow(entry, `middleware[${index}]`), + ), + }; + validateMcpServers(toolServers(definition.tools)); + + return (request: AiAgentRequest): Promise => runAgent(definition, request); + } +} diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts new file mode 100644 index 0000000..b480fed --- /dev/null +++ b/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts @@ -0,0 +1,89 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { AiAgentTransform } from "../datatypes/Agent.transform.datatype.js"; +import { AiAgentResponseSchema, type AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; +import type { AiChatResponse } from "../../chat/datatypes/Chat.response.datatype.js"; +import { AiChatRequestSchema, type AiChatRequest } from "../../chat/datatypes/Chat.request.datatype.js"; +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import { asText } from "../../shared/utils/Shared.asText.util.js"; +import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { toChatResponse } from "../../chat/utils/Chat.toChatResponse.util.js"; +import { toConversation } from "../../chat/utils/Chat.toConversation.util.js"; + +@Identifier("ai::agent::invoke") +@DisplayIcon("tabler:message-chatbot") +@Signature( + "(agent: TRANSFORM, prompt: TEXT, request?: AI_CHAT_REQUEST): AI_CHAT_RESPONSE", +) +@Name({ code: "en-US", content: "Invoke agent" }) +@DisplayMessage({ code: "en-US", content: "Ask the agent ${prompt}" }) +@ThrowsError() +@Parameter({ + runtimeName: "agent", + name: [{ code: "en-US", content: "Agent" }], +}) +@Parameter({ + runtimeName: "prompt", + name: [{ code: "en-US", content: "Prompt" }], +}) +@Parameter({ + runtimeName: "request", + name: [{ code: "en-US", content: "Request" }], + optional: true, +}) +export class InvokeAgentFunction { + async run( + _context: FunctionContext, + agent: AiAgentTransform, + prompt: string, + request?: AiChatRequest, + ): Promise { + if (!isSubFlow(agent)) { + throw new RuntimeError( + "ERROR_INVALID_AI_AGENT", + `The "agent" parameter has to be an agent as "ai::agent::create" returns one, but a ${typeof agent} was passed.`, + ); + } + + const parsed: AiChatRequest = parseOrThrow( + AiChatRequestSchema, + request ?? { messages: [] }, + "ERROR_INVALID_AI_CHAT_REQUEST", + "The chat request is not valid", + ); + const messages: AiMessage[] = toConversation( + parsed.messages, + asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"), + ); + if (messages.length === 0) { + throw new RuntimeError( + "ERROR_INVALID_AI_CHAT_REQUEST", + "There is nothing to ask: the prompt is empty and the request carries no messages.", + ); + } + + const answer: AiAgentResponse = parseOrThrow( + AiAgentResponseSchema, + (await agent({ messages })) ?? {}, + "ERROR_INVALID_AI_AGENT_RESPONSE", + "The agent did not answer with a valid agent response", + ); + + const last: AiMessage | undefined = answer.messages.at(-1); + if (!last) { + throw new RuntimeError("ERROR_INVALID_AI_AGENT_RESPONSE", "The agent answered with an empty conversation."); + } + + return toChatResponse(last, parsed.model ?? ""); + } +} diff --git a/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts b/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts new file mode 100644 index 0000000..a41f2f7 --- /dev/null +++ b/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts @@ -0,0 +1,20 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import { AiMcpServerSchema } from "../../mcp/datatypes/Mcp.server.datatype.js"; +import { asList } from "../../shared/utils/Shared.asList.util.js"; +import type { ToolEntry } from "./Agent.compileAgent.util.js"; +import { formatIssues } from "../../shared/utils/Shared.formatIssues.util.js"; +import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; + +export function asToolEntries(value: unknown): ToolEntry[] { + return asList(value, "tools").map((entry, index) => { + if (isSubFlow(entry)) return entry; + + const server = AiMcpServerSchema.safeParse(entry); + if (server.success) return server.data; + + throw new RuntimeError( + "ERROR_INVALID_AI_TOOL", + `Entry ${index + 1} of "tools" is neither a sub flow nor a valid MCP server: ${formatIssues(server.error.issues)}`, + ); + }); +} diff --git a/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts b/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts new file mode 100644 index 0000000..bbda351 --- /dev/null +++ b/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts @@ -0,0 +1,24 @@ +import type { SubFlow } from "@code0-tech/hercules"; +import type { ClientTool } from "@langchain/core/tools"; +import { tool } from "langchain"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; +import { emptyJsonSchema } from "../../shared/utils/Shared.emptyJsonSchema.util.js"; + +export function buildFlowTools(runs: SubFlow[]): ClientTool[] { + return runs.map((run, index) => { + const schema = run.inputSchema as Record | undefined; + + return tool( + (args: unknown) => + Promise.resolve(run(args as never)).then( + (result) => (typeof result === "string" ? result : JSON.stringify(result ?? null)), + (error: unknown) => `The tool failed: ${describeError(error)}`, + ), + { + name: `tool_${index + 1}`, + description: typeof schema?.description === "string" ? schema.description : "", + schema: (schema ?? emptyJsonSchema()) as never, + }, + ) as unknown as ClientTool; + }); +} diff --git a/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts b/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts new file mode 100644 index 0000000..23496d1 --- /dev/null +++ b/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts @@ -0,0 +1,50 @@ +import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; +import type { ClientTool } from "@langchain/core/tools"; +import { createAgent, type ReactAgent } from "langchain"; +import type { AiMcpServer } from "../../mcp/datatypes/Mcp.server.datatype.js"; +import { buildFlowMiddlewares } from "../../middleware/utils/Middleware.buildFlowMiddlewares.util.js"; +import { buildFlowTools } from "./Agent.buildFlowTools.util.js"; +import { buildMcpTools } from "../../mcp/utils/Mcp.buildMcpTools.util.js"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; +import { FlowChatModel } from "../../model/utils/Model.flowChatModel.util.js"; +import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; +import { toolServers } from "./Agent.toolServers.util.js"; + +export type ToolEntry = SubFlow | AiMcpServer; + +export interface AgentDefinition { + name: string; + systemPrompt: string; + model: SubFlow; + tools: ToolEntry[]; + middleware: SubFlow[]; +} + +export interface CompiledAgent { + agent: ReactAgent; + close: () => Promise; +} + +export async function compileAgent(definition: AgentDefinition): Promise { + const { tools: mcpTools, close } = await buildMcpTools(toolServers(definition.tools)); + + try { + const tools: ClientTool[] = [...buildFlowTools(definition.tools.filter(isSubFlow)), ...mcpTools]; + const agent = createAgent({ + model: new FlowChatModel({ run: definition.model }), + tools, + middleware: buildFlowMiddlewares(definition.middleware, definition.name), + name: definition.name, + ...(definition.systemPrompt ? { systemPrompt: definition.systemPrompt } : {}), + } as never) as unknown as ReactAgent; + + return { agent, close }; + } catch (error) { + await close().catch(() => undefined); + if (error instanceof RuntimeError) throw error; + throw new RuntimeError( + "ERROR_BUILDING_AI_AGENT", + `Could not build agent "${definition.name}": ${describeError(error)}`, + ); + } +} diff --git a/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts b/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts new file mode 100644 index 0000000..9715bf0 --- /dev/null +++ b/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts @@ -0,0 +1,30 @@ +import type { AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; +import { AiAgentRequestSchema, type AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; +import { compileAgent, type AgentDefinition, type CompiledAgent } from "./Agent.compileAgent.util.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; + +export async function runAgent(definition: AgentDefinition, request: AiAgentRequest): Promise { + const parsed: AiAgentRequest = parseOrThrow( + AiAgentRequestSchema, + request, + "ERROR_INVALID_AI_AGENT_REQUEST", + "The agent request is not valid", + ); + const compiled: CompiledAgent = await compileAgent(definition); + + try { + const result = await compiled.agent.invoke( + { messages: parsed.messages.map(toLangChainMessage) }, + parsed.thread_id ? { configurable: { thread_id: parsed.thread_id } } : undefined, + ); + + return { + messages: result.messages.map(toFlowMessage), + ...(result.structuredResponse ? { structured_response: result.structuredResponse } : {}), + }; + } finally { + await compiled.close().catch(() => undefined); + } +} diff --git a/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts b/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts new file mode 100644 index 0000000..118c36c --- /dev/null +++ b/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts @@ -0,0 +1,7 @@ +import type { AiMcpServer } from "../../mcp/datatypes/Mcp.server.datatype.js"; +import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; +import type { ToolEntry } from "./Agent.compileAgent.util.js"; + +export function toolServers(entries: ToolEntry[]): AiMcpServer[] { + return entries.filter((entry): entry is AiMcpServer => !isSubFlow(entry)); +} diff --git a/actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts new file mode 100644 index 0000000..cb344df --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts @@ -0,0 +1,16 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiChatMessageSchema } from "./Chat.message.datatype.js"; + +export const AiChatChoiceSchema = z.object({ + index: z.number(), + message: AiChatMessageSchema, + finish_reason: z.string(), +}); +export type AiChatChoice = z.infer; + +@Identifier("AI_CHAT_CHOICE") +@Name({ code: "en-US", content: "Chat choice" }) +@DisplayMessage({ code: "en-US", content: "Chat choice" }) +@Schema(AiChatChoiceSchema) +export class AiChatChoiceDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts new file mode 100644 index 0000000..3a99862 --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiChatContentPartSchema = z.looseObject({ type: z.string() }); +export type AiChatContentPart = z.infer; + +@Identifier("AI_CHAT_CONTENT_PART") +@Name({ code: "en-US", content: "Chat content part" }) +@DisplayMessage({ code: "en-US", content: "${type} part" }) +@Schema(AiChatContentPartSchema) +export class AiChatContentPartDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts new file mode 100644 index 0000000..e2f79b3 --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts @@ -0,0 +1,20 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiChatContentPartSchema } from "./Chat.contentPart.datatype.js"; +import { AiChatRoleSchema } from "./Chat.role.datatype.js"; +import { AiChatToolCallSchema } from "./Chat.toolCall.datatype.js"; + +export const AiChatMessageSchema = z.object({ + role: AiChatRoleSchema, + content: z.union([z.string(), z.array(AiChatContentPartSchema)]).nullish(), + name: z.string().optional(), + tool_calls: z.array(AiChatToolCallSchema).optional(), + tool_call_id: z.string().optional(), +}); +export type AiChatMessage = z.infer; + +@Identifier("AI_CHAT_MESSAGE") +@Name({ code: "en-US", content: "Chat message" }) +@DisplayMessage({ code: "en-US", content: "${role} message" }) +@Schema(AiChatMessageSchema) +export class AiChatMessageDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts new file mode 100644 index 0000000..c126f00 --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts @@ -0,0 +1,15 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiChatMessageSchema } from "./Chat.message.datatype.js"; + +export const AiChatRequestSchema = z.object({ + messages: z.array(AiChatMessageSchema), + model: z.string().optional(), +}); +export type AiChatRequest = z.infer; + +@Identifier("AI_CHAT_REQUEST") +@Name({ code: "en-US", content: "Chat request" }) +@DisplayMessage({ code: "en-US", content: "Chat request" }) +@Schema(AiChatRequestSchema) +export class AiChatRequestDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts new file mode 100644 index 0000000..4d15a2c --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts @@ -0,0 +1,20 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiChatChoiceSchema } from "./Chat.choice.datatype.js"; +import { AiChatUsageSchema } from "./Chat.usage.datatype.js"; + +export const AiChatResponseSchema = z.object({ + id: z.string(), + object: z.string(), + created: z.number(), + model: z.string(), + choices: z.array(AiChatChoiceSchema), + usage: AiChatUsageSchema.optional(), +}); +export type AiChatResponse = z.infer; + +@Identifier("AI_CHAT_RESPONSE") +@Name({ code: "en-US", content: "Chat response" }) +@DisplayMessage({ code: "en-US", content: "Chat response" }) +@Schema(AiChatResponseSchema) +export class AiChatResponseDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts new file mode 100644 index 0000000..24a8164 --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiChatRoleSchema = z.enum(["system", "user", "assistant", "tool"]); +export type AiChatRole = z.infer; + +@Identifier("AI_CHAT_ROLE") +@Name({ code: "en-US", content: "Chat role" }) +@DisplayMessage({ code: "en-US", content: "Chat role" }) +@Schema(AiChatRoleSchema) +export class AiChatRoleDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts new file mode 100644 index 0000000..79c4271 --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts @@ -0,0 +1,18 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiChatToolCallSchema = z.object({ + id: z.string(), + type: z.literal("function"), + function: z.object({ + name: z.string(), + arguments: z.string(), + }), +}); +export type AiChatToolCall = z.infer; + +@Identifier("AI_CHAT_TOOL_CALL") +@Name({ code: "en-US", content: "Chat tool call" }) +@DisplayMessage({ code: "en-US", content: "Chat tool call" }) +@Schema(AiChatToolCallSchema) +export class AiChatToolCallDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts new file mode 100644 index 0000000..475499b --- /dev/null +++ b/actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts @@ -0,0 +1,15 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiChatUsageSchema = z.object({ + prompt_tokens: z.number(), + completion_tokens: z.number(), + total_tokens: z.number(), +}); +export type AiChatUsage = z.infer; + +@Identifier("AI_CHAT_USAGE") +@Name({ code: "en-US", content: "Chat usage" }) +@DisplayMessage({ code: "en-US", content: "Chat usage" }) +@Schema(AiChatUsageSchema) +export class AiChatUsageDataType {} diff --git a/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts b/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts new file mode 100644 index 0000000..874d311 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts @@ -0,0 +1,25 @@ +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiMessageRole } from "../../message/datatypes/Message.role.datatype.js"; +import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; +import type { AiChatRole } from "../datatypes/Chat.role.datatype.js"; +import { toContentBlocks } from "./Chat.toContentBlocks.util.js"; +import { toToolCallBlock } from "./Chat.toToolCallBlock.util.js"; + +const ROLE_FROM_CHAT: Record = { + system: "system", + user: "human", + assistant: "ai", + tool: "tool", +}; + +export function fromChatMessage(message: AiChatMessage): AiMessage { + const flat: AiMessage = { + role: ROLE_FROM_CHAT[message.role], + content: [...toContentBlocks(message.content), ...(message.tool_calls ?? []).map(toToolCallBlock)], + }; + + if (message.name) flat.name = message.name; + if (message.tool_call_id) flat.tool_call_id = message.tool_call_id; + + return flat; +} diff --git a/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts b/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts new file mode 100644 index 0000000..5b95b45 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts @@ -0,0 +1,8 @@ +import type { AiMessage } from "../../message/datatypes/Message.datatype"; + +export function reportedModel(answer: AiMessage, fallbackModel: string): string { + const metadata = answer.response_metadata ?? {}; + if (typeof metadata.model_name === "string") return metadata.model_name; + if (typeof metadata.model === "string") return metadata.model; + return fallbackModel; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts new file mode 100644 index 0000000..19c1422 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts @@ -0,0 +1,8 @@ +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; + +export function toChatContent(message: AiMessage): string { + return message.content + .filter((block) => block.type === "text") + .map((block) => (typeof block.text === "string" ? block.text : "")) + .join(""); +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts new file mode 100644 index 0000000..023efe4 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts @@ -0,0 +1,27 @@ +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiMessageRole } from "../../message/datatypes/Message.role.datatype.js"; +import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; +import type { AiChatRole } from "../datatypes/Chat.role.datatype.js"; +import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; +import { toChatContent } from "./Chat.toChatContent.util.js"; +import { toChatToolCalls } from "./Chat.toChatToolCalls.util.js"; + +const ROLE_TO_CHAT: Record = { + system: "system", + human: "user", + ai: "assistant", + tool: "tool", +}; + +export function toChatMessage(message: AiMessage): AiChatMessage { + const toolCalls: AiChatToolCall[] = toChatToolCalls(message); + const content: string = toChatContent(message); + + return { + role: ROLE_TO_CHAT[message.role], + content: content.length > 0 || toolCalls.length === 0 ? content : null, + ...(message.name ? { name: message.name } : {}), + ...(message.tool_call_id ? { tool_call_id: message.tool_call_id } : {}), + ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}), + }; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts new file mode 100644 index 0000000..2cb66d7 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts @@ -0,0 +1,22 @@ +import { randomUUID } from "node:crypto"; +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; +import type { AiChatResponse } from "../datatypes/Chat.response.datatype.js"; +import type { AiChatUsage } from "../datatypes/Chat.usage.datatype.js"; +import { reportedModel } from "./Chat.reportedModel.util.js"; +import { toChatMessage } from "./Chat.toChatMessage.util.js"; +import { toChatUsage } from "./Chat.toChatUsage.util.js"; + +export function toChatResponse(answer: AiMessage, fallbackModel: string): AiChatResponse { + const message: AiChatMessage = toChatMessage(answer); + const usage: AiChatUsage | undefined = toChatUsage(answer); + + return { + id: answer.id ?? `chatcmpl-${randomUUID()}`, + object: "chat.completion", + created: Math.floor(Date.now() / 1000), + model: reportedModel(answer, fallbackModel), + choices: [{ index: 0, message, finish_reason: message.tool_calls ? "tool_calls" : "stop" }], + ...(usage ? { usage } : {}), + }; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts new file mode 100644 index 0000000..20d2785 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts @@ -0,0 +1,16 @@ +import { randomUUID } from "node:crypto"; +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; + +export function toChatToolCalls(message: AiMessage): AiChatToolCall[] { + return message.content + .filter((block) => block.type === "tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : randomUUID(), + type: "function" as const, + function: { + name: String(block.name ?? ""), + arguments: JSON.stringify(block.args ?? {}), + }, + })); +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts new file mode 100644 index 0000000..788ee17 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts @@ -0,0 +1,13 @@ +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiChatUsage } from "../datatypes/Chat.usage.datatype.js"; + +export function toChatUsage(message: AiMessage): AiChatUsage | undefined { + const usage = message.usage_metadata; + if (!usage) return undefined; + + const prompt: number = typeof usage.input_tokens === "number" ? usage.input_tokens : 0; + const completion: number = typeof usage.output_tokens === "number" ? usage.output_tokens : 0; + const total: number = typeof usage.total_tokens === "number" ? usage.total_tokens : prompt + completion; + + return { prompt_tokens: prompt, completion_tokens: completion, total_tokens: total }; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts new file mode 100644 index 0000000..706f271 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts @@ -0,0 +1,9 @@ +import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; +import type { AiChatContentPart } from "../datatypes/Chat.contentPart.datatype.js"; +import { toImageBlock } from "./Chat.toImageBlock.util.js"; + +export function toContentBlock(part: AiChatContentPart): AiContentBlock { + if (part.type === "text") return { type: "text", text: typeof part.text === "string" ? part.text : "" }; + if (part.type === "image_url") return toImageBlock(part); + return part; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts b/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts new file mode 100644 index 0000000..73a5843 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts @@ -0,0 +1,9 @@ +import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; +import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; +import { toContentBlock } from "./Chat.toContentBlock.util.js"; + +export function toContentBlocks(content: AiChatMessage["content"]): AiContentBlock[] { + if (typeof content === "string") return content.length > 0 ? [{ type: "text", text: content }] : []; + if (Array.isArray(content)) return content.map(toContentBlock); + return []; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts b/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts new file mode 100644 index 0000000..060e1e1 --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts @@ -0,0 +1,10 @@ +import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; +import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import { fromChatMessage } from "./Chat.fromChatMessage.util.js"; + +export function toConversation(history: AiChatMessage[], prompt: string): AiMessage[] { + const question: AiMessage[] = + prompt.length > 0 ? [{ role: "human", content: [{ type: "text", text: prompt }] }] : []; + + return [...history.map(fromChatMessage), ...question]; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts new file mode 100644 index 0000000..6691e8a --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts @@ -0,0 +1,12 @@ +import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; +import type { AiChatContentPart } from "../datatypes/Chat.contentPart.datatype.js"; + +export function toImageBlock(part: AiChatContentPart): AiContentBlock { + const image = part.image_url as { url?: string; detail?: string } | undefined; + + return { + type: "image", + ...(typeof image?.url === "string" ? { url: image.url } : {}), + ...(image?.detail ? { detail: image.detail } : {}), + }; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts new file mode 100644 index 0000000..f4e71fd --- /dev/null +++ b/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts @@ -0,0 +1,22 @@ +import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; +import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; + +export function toToolCallBlock(call: AiChatToolCall): AiContentBlock { + try { + return { + type: "tool_call", + id: call.id, + name: call.function.name, + args: JSON.parse(call.function.arguments || "{}") as Record, + }; + } catch (error) { + return { + type: "invalid_tool_call", + id: call.id, + name: call.function.name, + args: call.function.arguments, + error: describeError(error), + }; + } +} diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts new file mode 100644 index 0000000..cbc1bab --- /dev/null +++ b/actions/ai-action/src/index.ts @@ -0,0 +1,103 @@ +import "reflect-metadata"; +import { Action, CodeZeroEvent, type DataTypeClass, type RuntimeFunctionClass } from "@code0-tech/hercules"; +import { AiAgentRequestDataType } from "./agent/datatypes/Agent.request.datatype.js"; +import { AiAgentResponseDataType } from "./agent/datatypes/Agent.response.datatype.js"; +import { AiChatChoiceDataType } from "./chat/datatypes/Chat.choice.datatype.js"; +import { AiChatContentPartDataType } from "./chat/datatypes/Chat.contentPart.datatype.js"; +import { AiChatMessageDataType } from "./chat/datatypes/Chat.message.datatype.js"; +import { AiChatRequestDataType } from "./chat/datatypes/Chat.request.datatype.js"; +import { AiChatResponseDataType } from "./chat/datatypes/Chat.response.datatype.js"; +import { AiChatRoleDataType } from "./chat/datatypes/Chat.role.datatype.js"; +import { AiChatToolCallDataType } from "./chat/datatypes/Chat.toolCall.datatype.js"; +import { AiChatUsageDataType } from "./chat/datatypes/Chat.usage.datatype.js"; +import { AiMcpServerDataType } from "./mcp/datatypes/Mcp.server.datatype.js"; +import { AiMcpTransportDataType } from "./mcp/datatypes/Mcp.transport.datatype.js"; +import { AiContentBlockDataType } from "./message/datatypes/Message.contentBlock.datatype.js"; +import { AiMessageDataType } from "./message/datatypes/Message.datatype.js"; +import { AiMessageRoleDataType } from "./message/datatypes/Message.role.datatype.js"; +import { AiToolStatusDataType } from "./message/datatypes/Message.toolStatus.datatype.js"; +import { AiAgentStateDataType } from "./middleware/datatypes/Middleware.agentState.datatype.js"; +import { AiMiddlewareHookDataType } from "./middleware/datatypes/Middleware.hook.datatype.js"; +import { AiStateUpdateDataType } from "./middleware/datatypes/Middleware.stateUpdate.datatype.js"; +import { AiModelRequestDataType } from "./model/datatypes/Model.request.datatype.js"; +import { AiModelResponseDataType } from "./model/datatypes/Model.response.datatype.js"; +import { AiToolSpecDataType } from "./model/datatypes/Model.toolSpec.datatype.js"; +import { AiWebSearchHitDataType } from "./websearch/datatypes/WebSearch.hit.datatype.js"; +import { AiWebSearchResultDataType } from "./websearch/datatypes/WebSearch.result.datatype.js"; + +import { CreateAgentFunction } from "./agent/runtimefunctions/Agent.create.runtimefunction.js"; +import { InvokeAgentFunction } from "./agent/runtimefunctions/Agent.invoke.runtimefunction.js"; +import { TrimMessagesMiddlewareFunction } from "./middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; +import { OpenRouterModelFunction } from "./model/runtimefunctions/Model.openRouter.runtimefunction.js"; +import { WebSearchToolFunction } from "./websearch/runtimefunctions/WebSearch.search.runtimefunction.js"; + +import { connectToAquila } from "./shared/utils/Shared.connectToAquila.util.js"; + +const RECONNECT_DELAY_MS = 5000; + +const DATA_TYPES: DataTypeClass[] = [ + AiMessageRoleDataType, + AiToolStatusDataType, + AiContentBlockDataType, + AiMessageDataType, + AiToolSpecDataType, + AiModelRequestDataType, + AiModelResponseDataType, + + AiMiddlewareHookDataType, + AiAgentStateDataType, + AiStateUpdateDataType, + + AiMcpTransportDataType, + AiMcpServerDataType, + + AiWebSearchHitDataType, + AiWebSearchResultDataType, + + AiAgentRequestDataType, + AiAgentResponseDataType, + + AiChatRoleDataType, + AiChatContentPartDataType, + AiChatToolCallDataType, + AiChatMessageDataType, + AiChatRequestDataType, + AiChatUsageDataType, + AiChatChoiceDataType, + AiChatResponseDataType, +]; + +const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ + CreateAgentFunction, + InvokeAgentFunction, + OpenRouterModelFunction, + TrimMessagesMiddlewareFunction, + WebSearchToolFunction, +]; + +const action = new Action( + process.env.ACTION_ID ?? "ai-action", + process.env.VERSION ?? "1.0.0", + process.env.AQUILA_URL ?? "127.0.0.1:8081", + "code0-tech", + "tabler:robot", + "AI agent integration: build LangChain agents whose model, tools and middleware are flows of the project itself.", + [{ code: "en-US", content: "AI" }], +); + +DATA_TYPES.forEach((dataType) => action.registerDataTypeClass(dataType)); +RUNTIME_FUNCTIONS.forEach((runtimeFunction) => action.registerRuntimeFunction(runtimeFunction)); + +action.on(CodeZeroEvent.connected, () => { + console.log("Connected to aquila"); +}); + +action.on(CodeZeroEvent.error, (error: Error) => { + console.error("Stream error:", error.message); + console.log(`Attempting to reconnect in ${RECONNECT_DELAY_MS / 1000}s...`); + setTimeout(() => connectToAquila(action), RECONNECT_DELAY_MS); +}); + +connectToAquila(action); + +export { action }; diff --git a/actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts b/actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts new file mode 100644 index 0000000..33019f8 --- /dev/null +++ b/actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts @@ -0,0 +1,23 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMcpTransportSchema } from "./Mcp.transport.datatype.js"; + +export const AiMcpServerSchema = z.object({ + name: z.string().min(1), + transport: AiMcpTransportSchema.default("http"), + url: z.string().optional(), + headers: z.looseObject({}).optional(), + command: z.string().optional(), + args: z.array(z.string()).optional(), + env: z.looseObject({}).optional(), + cwd: z.string().optional(), + default_tool_timeout_ms: z.number().int().min(1).optional(), + allowed_tools: z.array(z.string()).optional(), +}); +export type AiMcpServer = z.infer; + +@Identifier("AI_MCP_SERVER") +@Name({ code: "en-US", content: "MCP server" }) +@DisplayMessage({ code: "en-US", content: "MCP server ${name}" }) +@Schema(AiMcpServerSchema) +export class AiMcpServerDataType {} diff --git a/actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts b/actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts new file mode 100644 index 0000000..2e067c6 --- /dev/null +++ b/actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiMcpTransportSchema = z.enum(["http", "sse", "stdio"]); +export type AiMcpTransport = z.infer; + +@Identifier("AI_MCP_TRANSPORT") +@Name({ code: "en-US", content: "MCP transport" }) +@DisplayMessage({ code: "en-US", content: "MCP transport" }) +@Schema(AiMcpTransportSchema) +export class AiMcpTransportDataType {} diff --git a/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts b/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts new file mode 100644 index 0000000..e97bb1d --- /dev/null +++ b/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts @@ -0,0 +1,30 @@ +import type { ClientTool } from "@langchain/core/tools"; +import { MultiServerMCPClient } from "@langchain/mcp-adapters"; +import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; +import { discoverTools } from "./Mcp.discoverTools.util.js"; +import { toConnection } from "./Mcp.toConnection.util.js"; +import { validateMcpServers } from "./Mcp.validateMcpServers.util.js"; + +export interface McpTools { + tools: ClientTool[]; + close: () => Promise; +} + +export async function buildMcpTools(servers: AiMcpServer[]): Promise { + if (servers.length === 0) return { tools: [], close: async () => undefined }; + + validateMcpServers(servers); + + const client = new MultiServerMCPClient({ + mcpServers: Object.fromEntries(servers.map((server) => [server.name, toConnection(server)])), + }); + + const discovered: ClientTool[] = await discoverTools(client); + const allowed = new Set(servers.flatMap((server) => server.allowed_tools ?? [])); + const tools: ClientTool[] = + allowed.size === 0 + ? discovered + : discovered.filter((tool) => allowed.has(tool.name.split("__").pop() ?? tool.name)); + + return { tools, close: () => client.close() }; +} diff --git a/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts b/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts new file mode 100644 index 0000000..b00b75d --- /dev/null +++ b/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts @@ -0,0 +1,16 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import type { ClientTool } from "@langchain/core/tools"; +import type { MultiServerMCPClient } from "@langchain/mcp-adapters"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; + +export async function discoverTools(client: MultiServerMCPClient): Promise { + try { + return (await client.getTools()) as unknown as ClientTool[]; + } catch (error) { + await client.close().catch(() => undefined); + throw new RuntimeError( + "ERROR_LOADING_AI_MCP_TOOLS", + `Could not load tools from the configured MCP servers: ${describeError(error)}`, + ); + } +} diff --git a/actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts b/actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts new file mode 100644 index 0000000..edf4e1f --- /dev/null +++ b/actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts @@ -0,0 +1,37 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import type { Connection } from "@langchain/mcp-adapters"; +import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; + +export function toConnection(server: AiMcpServer): Connection { + if (server.transport === "stdio") { + if (!server.command) { + throw new RuntimeError( + "ERROR_INVALID_AI_MCP_SERVER", + `MCP server "${server.name}" uses the stdio transport and therefore needs a command.`, + ); + } + + return { + transport: "stdio", + command: server.command, + args: server.args ?? [], + ...(server.env ? { env: server.env as Record } : {}), + ...(server.cwd ? { cwd: server.cwd } : {}), + ...(server.default_tool_timeout_ms ? { defaultToolTimeout: server.default_tool_timeout_ms } : {}), + } as Connection; + } + + if (!server.url) { + throw new RuntimeError( + "ERROR_INVALID_AI_MCP_SERVER", + `MCP server "${server.name}" uses the ${server.transport} transport and therefore needs a url.`, + ); + } + + return { + transport: server.transport, + url: server.url, + ...(server.headers ? { headers: server.headers as Record } : {}), + ...(server.default_tool_timeout_ms ? { defaultToolTimeout: server.default_tool_timeout_ms } : {}), + } as Connection; +} diff --git a/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts b/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts new file mode 100644 index 0000000..da5cb49 --- /dev/null +++ b/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts @@ -0,0 +1,16 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; +import { toConnection } from "./Mcp.toConnection.util.js"; + +export function validateMcpServers(servers: AiMcpServer[]): void { + const names: string[] = servers.map((server) => server.name); + const duplicate: string | undefined = names.find((name, index) => names.indexOf(name) !== index); + if (duplicate) { + throw new RuntimeError( + "ERROR_DUPLICATE_AI_MCP_SERVER", + `More than one MCP server is named "${duplicate}". MCP tool names are namespaced with the server name, so the names must be unique.`, + ); + } + + servers.forEach(toConnection); +} diff --git a/actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts b/actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts new file mode 100644 index 0000000..6164849 --- /dev/null +++ b/actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiContentBlockSchema = z.looseObject({ type: z.string() }); +export type AiContentBlock = z.infer; + +@Identifier("AI_CONTENT_BLOCK") +@Name({ code: "en-US", content: "Content block" }) +@DisplayMessage({ code: "en-US", content: "${type} block" }) +@Schema(AiContentBlockSchema) +export class AiContentBlockDataType {} diff --git a/actions/ai-action/src/message/datatypes/Message.datatype.ts b/actions/ai-action/src/message/datatypes/Message.datatype.ts new file mode 100644 index 0000000..14a76f3 --- /dev/null +++ b/actions/ai-action/src/message/datatypes/Message.datatype.ts @@ -0,0 +1,25 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiContentBlockSchema } from "./Message.contentBlock.datatype.js"; +import { AiMessageRoleSchema } from "./Message.role.datatype.js"; +import { AiToolStatusSchema } from "./Message.toolStatus.datatype.js"; + +export const AiMessageSchema = z.object({ + role: AiMessageRoleSchema, + content: z.array(AiContentBlockSchema), + tool_call_id: z.string().optional(), + name: z.string().optional(), + id: z.string().optional(), + status: AiToolStatusSchema.optional(), + artifact: z.any().optional(), + additional_kwargs: z.looseObject({}).optional(), + response_metadata: z.looseObject({}).optional(), + usage_metadata: z.looseObject({}).optional(), +}); +export type AiMessage = z.infer; + +@Identifier("AI_MESSAGE") +@Name({ code: "en-US", content: "Message" }) +@DisplayMessage({ code: "en-US", content: "${role} message" }) +@Schema(AiMessageSchema) +export class AiMessageDataType {} diff --git a/actions/ai-action/src/message/datatypes/Message.role.datatype.ts b/actions/ai-action/src/message/datatypes/Message.role.datatype.ts new file mode 100644 index 0000000..fa0990d --- /dev/null +++ b/actions/ai-action/src/message/datatypes/Message.role.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiMessageRoleSchema = z.enum(["system", "human", "ai", "tool"]); +export type AiMessageRole = z.infer; + +@Identifier("AI_MESSAGE_ROLE") +@Name({ code: "en-US", content: "Message role" }) +@DisplayMessage({ code: "en-US", content: "Message role" }) +@Schema(AiMessageRoleSchema) +export class AiMessageRoleDataType {} diff --git a/actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts b/actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts new file mode 100644 index 0000000..bef0a11 --- /dev/null +++ b/actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiToolStatusSchema = z.enum(["success", "error"]); +export type AiToolStatus = z.infer; + +@Identifier("AI_TOOL_STATUS") +@Name({ code: "en-US", content: "Tool status" }) +@DisplayMessage({ code: "en-US", content: "Tool status" }) +@Schema(AiToolStatusSchema) +export class AiToolStatusDataType {} diff --git a/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts b/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts new file mode 100644 index 0000000..b8fd741 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts @@ -0,0 +1,11 @@ +import { RemoveMessage, type BaseMessage } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; +import { toLangChainMessage } from "./Message.toLangChainMessage.util.js"; + +export function replaceMessages(previous: BaseMessage[], next: AiMessage[]): BaseMessage[] { + const removals = previous + .filter((message): message is BaseMessage & { id: string } => typeof message.id === "string") + .map((message) => new RemoveMessage({ id: message.id })); + + return [...removals, ...next.map(toLangChainMessage)]; +} diff --git a/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts b/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts new file mode 100644 index 0000000..81f1d67 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts @@ -0,0 +1,14 @@ +import { AIMessage, type UsageMetadata } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; +import { toInvalidToolCalls } from "./Message.toInvalidToolCalls.util.js"; +import { toToolCalls } from "./Message.toToolCalls.util.js"; +import type { MessageFields } from "./Message.toMessageFields.util.js"; + +export function toAiMessage(message: AiMessage, fields: MessageFields): AIMessage { + return new AIMessage({ + ...fields, + tool_calls: toToolCalls(message), + invalid_tool_calls: toInvalidToolCalls(message), + ...(message.usage_metadata ? { usage_metadata: message.usage_metadata as UsageMetadata } : {}), + }); +} diff --git a/actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts b/actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts new file mode 100644 index 0000000..e647b14 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts @@ -0,0 +1,40 @@ +import * as lc from "@langchain/core/messages"; +import type { AiContentBlock } from "../datatypes/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; +import type { AiMessageRole } from "../datatypes/Message.role.datatype.js"; +import { hasEntries } from "../../shared/utils/Shared.hasEntries.util.js"; + +const ROLE_BY_TYPE: Record = { + system: "system", + human: "human", + ai: "ai", + tool: "tool", +}; + +export function toFlowMessage(message: lc.BaseMessage): AiMessage { + const flat: AiMessage = { + role: ROLE_BY_TYPE[message.getType()] ?? "human", + content: message.contentBlocks as AiContentBlock[], + }; + + if (message.id) flat.id = message.id; + if (message.name) flat.name = message.name; + if (hasEntries(message.additional_kwargs)) flat.additional_kwargs = message.additional_kwargs; + if (hasEntries(message.response_metadata)) flat.response_metadata = message.response_metadata; + + if (lc.isToolMessage(message)) { + flat.tool_call_id = message.tool_call_id; + if (message.status) flat.status = message.status; + if (message.artifact !== undefined) flat.artifact = message.artifact; + } + + if (lc.isAIMessage(message)) { + if (message.usage_metadata) flat.usage_metadata = message.usage_metadata; + flat.content = [ + ...flat.content, + ...(message.invalid_tool_calls ?? []).map((call) => ({ ...call, type: "invalid_tool_call" })), + ]; + } + + return flat; +} diff --git a/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts b/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts new file mode 100644 index 0000000..9c0e2e9 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts @@ -0,0 +1,13 @@ +import type { InvalidToolCall } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; + +export function toInvalidToolCalls(message: AiMessage): InvalidToolCall[] { + return message.content + .filter((block) => block.type === "invalid_tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : undefined, + name: typeof block.name === "string" ? block.name : undefined, + args: typeof block.args === "string" ? block.args : undefined, + error: typeof block.error === "string" ? block.error : undefined, + })); +} diff --git a/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts b/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts new file mode 100644 index 0000000..8598060 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts @@ -0,0 +1,20 @@ +import { HumanMessage, SystemMessage, type BaseMessage } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; +import { toAiMessage } from "./Message.toAiMessage.util.js"; +import { toMessageFields, type MessageFields } from "./Message.toMessageFields.util.js"; +import { toToolMessage } from "./Message.toToolMessage.util.js"; + +export function toLangChainMessage(message: AiMessage): BaseMessage { + const fields: MessageFields = toMessageFields(message); + + switch (message.role) { + case "system": + return new SystemMessage(fields); + case "ai": + return toAiMessage(message, fields); + case "tool": + return toToolMessage(message, fields); + case "human": + return new HumanMessage(fields); + } +} diff --git a/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts b/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts new file mode 100644 index 0000000..ab2ff77 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts @@ -0,0 +1,22 @@ +import type { AiContentBlock } from "../datatypes/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; + +const CALL_BLOCK_TYPES: string[] = ["tool_call", "invalid_tool_call"]; + +export interface MessageFields { + content: AiContentBlock[]; + id?: string; + name?: string; + additional_kwargs?: Record; + response_metadata?: Record; +} + +export function toMessageFields(message: AiMessage): MessageFields { + return { + content: message.content.filter((block) => !CALL_BLOCK_TYPES.includes(block.type)), + ...(message.id ? { id: message.id } : {}), + ...(message.name ? { name: message.name } : {}), + ...(message.additional_kwargs ? { additional_kwargs: message.additional_kwargs } : {}), + ...(message.response_metadata ? { response_metadata: message.response_metadata } : {}), + }; +} diff --git a/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts b/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts new file mode 100644 index 0000000..2dc8091 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts @@ -0,0 +1,12 @@ +import type { ToolCall } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; + +export function toToolCalls(message: AiMessage): ToolCall[] { + return message.content + .filter((block) => block.type === "tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : undefined, + name: String(block.name ?? ""), + args: (block.args ?? {}) as Record, + })); +} diff --git a/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts b/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts new file mode 100644 index 0000000..c743888 --- /dev/null +++ b/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts @@ -0,0 +1,12 @@ +import { ToolMessage } from "@langchain/core/messages"; +import type { AiMessage } from "../datatypes/Message.datatype.js"; +import type { MessageFields } from "./Message.toMessageFields.util.js"; + +export function toToolMessage(message: AiMessage, fields: MessageFields): ToolMessage { + return new ToolMessage({ + ...fields, + tool_call_id: message.tool_call_id ?? "", + ...(message.status ? { status: message.status } : {}), + ...(message.artifact !== undefined ? { artifact: message.artifact } : {}), + }); +} diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts b/actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts new file mode 100644 index 0000000..88d9a5f --- /dev/null +++ b/actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts @@ -0,0 +1,20 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMiddlewareHookSchema } from "./Middleware.hook.datatype.js"; + +export const AiAgentStateSchema = z.object({ + messages: z.array(AiMessageSchema), + agent_name: z.string(), + hook: AiMiddlewareHookSchema, + structured_response: z.looseObject({}).optional(), + context: z.looseObject({}).optional(), + thread_id: z.string().optional(), +}); +export type AiAgentState = z.infer; + +@Identifier("AI_AGENT_STATE") +@Name({ code: "en-US", content: "AiAgent state" }) +@DisplayMessage({ code: "en-US", content: "State of ${agent_name} at ${hook}" }) +@Schema(AiAgentStateSchema) +export class AiAgentStateDataType {} diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts b/actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts new file mode 100644 index 0000000..e636d62 --- /dev/null +++ b/actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts @@ -0,0 +1,11 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiMiddlewareHookSchema = z.enum(["before_model", "after_model"]); +export type AiMiddlewareHook = z.infer; + +@Identifier("AI_MIDDLEWARE_HOOK") +@Name({ code: "en-US", content: "Middleware hook" }) +@DisplayMessage({ code: "en-US", content: "Middleware hook" }) +@Schema(AiMiddlewareHookSchema) +export class AiMiddlewareHookDataType {} diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts b/actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts new file mode 100644 index 0000000..322bf39 --- /dev/null +++ b/actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts @@ -0,0 +1,16 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; + +export const AiStateUpdateSchema = z.object({ + messages: z.array(AiMessageSchema).optional(), + jump_to: z.enum(["end", "model", "tools"]).optional(), + structured_response: z.looseObject({}).optional(), +}); +export type AiStateUpdate = z.infer; + +@Identifier("AI_STATE_UPDATE") +@Name({ code: "en-US", content: "State update" }) +@DisplayMessage({ code: "en-US", content: "State update" }) +@Schema(AiStateUpdateSchema) +export class AiStateUpdateDataType {} diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts b/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts new file mode 100644 index 0000000..6409acf --- /dev/null +++ b/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts @@ -0,0 +1,4 @@ +import type { AiAgentState } from "./Middleware.agentState.datatype.js"; +import type { AiStateUpdate } from "./Middleware.stateUpdate.datatype.js"; + +export type AiMiddlewareTransform = (state: AiAgentState) => Promise; diff --git a/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts b/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts new file mode 100644 index 0000000..b627007 --- /dev/null +++ b/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts @@ -0,0 +1,88 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { BaseMessage } from "@langchain/core/messages"; +import { countTokensApproximately, trimMessages } from "langchain"; +import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; +import type { AiMiddlewareTransform } from "../datatypes/Middleware.transform.datatype.js"; +import type { AiStateUpdate } from "../datatypes/Middleware.stateUpdate.datatype.js"; +import { AiAgentStateSchema, type AiAgentState } from "../datatypes/Middleware.agentState.datatype.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; + +type TrimStrategy = "first" | "last"; + +@Identifier("ai::middleware::trim_messages") +@DisplayIcon("tabler:scissors") +@Signature("(max_tokens: NUMBER, strategy?: TEXT, keep_system?: BOOLEAN): TRANSFORM") +@Name({ code: "en-US", content: "Trim messages" }) +@DisplayMessage({ + code: "en-US", + content: "Trim the conversation to ${max_tokens} tokens", +}) +@ThrowsError() +@Parameter({ + runtimeName: "max_tokens", + name: [{ code: "en-US", content: "Maximum tokens" }], +}) +@Parameter({ + runtimeName: "strategy", + name: [{ code: "en-US", content: "Strategy" }], + optional: true, +}) +@Parameter({ + runtimeName: "keep_system", + name: [{ code: "en-US", content: "Keep system prompt" }], + optional: true, +}) +export class TrimMessagesMiddlewareFunction { + run( + _context: FunctionContext, + max_tokens: number, + strategy?: string, + keep_system?: boolean, + ): AiMiddlewareTransform { + if (typeof max_tokens !== "number" || !Number.isFinite(max_tokens) || max_tokens <= 0) { + throw new RuntimeError("ERROR_INVALID_AI_STATE_UPDATE", "Trimming needs a positive token budget."); + } + if (strategy !== undefined && strategy !== "first" && strategy !== "last") { + throw new RuntimeError( + "ERROR_INVALID_AI_STATE_UPDATE", + `"${strategy}" is not a trim strategy; use "first" or "last".`, + ); + } + + const trimStrategy: TrimStrategy = strategy === "first" ? "first" : "last"; + const includeSystem: boolean = keep_system ?? true; + + return async (state: AiAgentState): Promise => { + const parsed: AiAgentState = parseOrThrow( + AiAgentStateSchema, + state, + "ERROR_INVALID_AI_AGENT_STATE", + "The agent state is not valid", + ); + + const trimmed: BaseMessage[] = await trimMessages(parsed.messages.map(toLangChainMessage), { + maxTokens: max_tokens, + tokenCounter: countTokensApproximately, + strategy: trimStrategy, + includeSystem, + allowPartial: false, + startOn: "human", + }); + + if (trimmed.length === parsed.messages.length) return {}; + + return { messages: trimmed.map(toFlowMessage) }; + }; + } +} diff --git a/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts b/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts new file mode 100644 index 0000000..28d53ad --- /dev/null +++ b/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts @@ -0,0 +1,16 @@ +import type { SubFlow } from "@code0-tech/hercules"; +import { createMiddleware, type AnyAgentMiddleware } from "langchain"; +import { createHookHandler } from "./Middleware.createHookHandler.util.js"; + +const JUMP_TARGETS = ["model", "tools", "end"] as const; + +export function buildFlowMiddlewares(runs: SubFlow[], agentName: string): AnyAgentMiddleware[] { + return runs.map( + (run, index) => + createMiddleware({ + name: `flow_middleware_${index + 1}`, + beforeModel: { hook: createHookHandler(run, agentName, "before_model"), canJumpTo: [...JUMP_TARGETS] }, + afterModel: { hook: createHookHandler(run, agentName, "after_model"), canJumpTo: [...JUMP_TARGETS] }, + } as never) as AnyAgentMiddleware, + ); +} diff --git a/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts b/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts new file mode 100644 index 0000000..ed9c7b3 --- /dev/null +++ b/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts @@ -0,0 +1,31 @@ +import type { SubFlow } from "@code0-tech/hercules"; +import type { AiMiddlewareHook } from "../datatypes/Middleware.hook.datatype.js"; +import { AiStateUpdateSchema } from "../datatypes/Middleware.stateUpdate.datatype.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { replaceMessages } from "../../message/utils/Message.replaceMessages.util.js"; +import { toFlowState, type AgentRuntime, type AgentState } from "./Middleware.toFlowState.util.js"; + +type HookResult = Record | undefined; + +export type HookHandler = (state: AgentState, runtime?: AgentRuntime) => Promise; + +export function createHookHandler(run: SubFlow, agentName: string, hook: AiMiddlewareHook): HookHandler { + return async (state: AgentState, runtime?: AgentRuntime): Promise => { + const raw = await run(toFlowState(state, runtime, agentName, hook) as never); + if (raw === undefined || raw === null) return undefined; + + const update = parseOrThrow( + AiStateUpdateSchema, + raw, + "ERROR_INVALID_AI_STATE_UPDATE", + `The middleware sub flow did not return a valid state update for the ${hook} phase`, + ); + if (!update.messages && !update.jump_to && !update.structured_response) return undefined; + + return { + ...(update.messages ? { messages: replaceMessages(state.messages, update.messages) } : {}), + ...(update.structured_response ? { structuredResponse: update.structured_response } : {}), + ...(update.jump_to ? { jumpTo: update.jump_to } : {}), + }; + }; +} diff --git a/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts b/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts new file mode 100644 index 0000000..900d94d --- /dev/null +++ b/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts @@ -0,0 +1,31 @@ +import type { BaseMessage } from "@langchain/core/messages"; +import type { AiAgentState } from "../datatypes/Middleware.agentState.datatype.js"; +import type { AiMiddlewareHook } from "../datatypes/Middleware.hook.datatype.js"; +import { hasEntries } from "../../shared/utils/Shared.hasEntries.util.js"; +import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; + +export interface AgentState { + messages: BaseMessage[]; + structuredResponse?: Record; +} + +export interface AgentRuntime { + context?: Record; + configurable?: { thread_id?: string; [key: string]: unknown }; +} + +export function toFlowState( + state: AgentState, + runtime: AgentRuntime | undefined, + agentName: string, + hook: AiMiddlewareHook, +): AiAgentState { + return { + messages: state.messages.map(toFlowMessage), + agent_name: agentName, + hook, + ...(state.structuredResponse ? { structured_response: state.structuredResponse } : {}), + ...(hasEntries(runtime?.context) ? { context: runtime?.context } : {}), + ...(typeof runtime?.configurable?.thread_id === "string" ? { thread_id: runtime.configurable.thread_id } : {}), + }; +} diff --git a/actions/ai-action/src/model/datatypes/Model.request.datatype.ts b/actions/ai-action/src/model/datatypes/Model.request.datatype.ts new file mode 100644 index 0000000..39e951d --- /dev/null +++ b/actions/ai-action/src/model/datatypes/Model.request.datatype.ts @@ -0,0 +1,19 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiToolChoiceSchema } from "./Model.toolChoice.datatype.js"; +import { AiToolSpecSchema } from "./Model.toolSpec.datatype.js"; + +export const AiModelRequestSchema = z.object({ + messages: z.array(AiMessageSchema), + tools: z.array(AiToolSpecSchema), + stop: z.array(z.string()).optional(), + tool_choice: AiToolChoiceSchema.optional(), +}); +export type AiModelRequest = z.infer; + +@Identifier("AI_MODEL_REQUEST") +@Name({ code: "en-US", content: "Model request" }) +@DisplayMessage({ code: "en-US", content: "Model request" }) +@Schema(AiModelRequestSchema) +export class AiModelRequestDataType {} diff --git a/actions/ai-action/src/model/datatypes/Model.response.datatype.ts b/actions/ai-action/src/model/datatypes/Model.response.datatype.ts new file mode 100644 index 0000000..ef12588 --- /dev/null +++ b/actions/ai-action/src/model/datatypes/Model.response.datatype.ts @@ -0,0 +1,14 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; + +export const AiModelResponseSchema = z.object({ + message: AiMessageSchema, +}); +export type AiModelResponse = z.infer; + +@Identifier("AI_MODEL_RESPONSE") +@Name({ code: "en-US", content: "Model response" }) +@DisplayMessage({ code: "en-US", content: "Model response" }) +@Schema(AiModelResponseSchema) +export class AiModelResponseDataType {} diff --git a/actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts b/actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts new file mode 100644 index 0000000..3e8e854 --- /dev/null +++ b/actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts @@ -0,0 +1,4 @@ +import { z } from "zod"; + +export const AiToolChoiceSchema = z.string(); +export type AiToolChoice = z.infer; diff --git a/actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts b/actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts new file mode 100644 index 0000000..5b4cf93 --- /dev/null +++ b/actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts @@ -0,0 +1,15 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiToolSpecSchema = z.object({ + name: z.string(), + description: z.string(), + input_schema: z.looseObject({}), +}); +export type AiToolSpec = z.infer; + +@Identifier("AI_TOOL_SPEC") +@Name({ code: "en-US", content: "Tool specification" }) +@DisplayMessage({ code: "en-US", content: "Tool ${name}" }) +@Schema(AiToolSpecSchema) +export class AiToolSpecDataType {} diff --git a/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts b/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts new file mode 100644 index 0000000..6b8215b --- /dev/null +++ b/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts @@ -0,0 +1,4 @@ +import type { AiModelRequest } from "./Model.request.datatype.js"; +import type { AiModelResponse } from "./Model.response.datatype.js"; + +export type AiModelTransform = (request: AiModelRequest) => Promise; diff --git a/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts new file mode 100644 index 0000000..a319561 --- /dev/null +++ b/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts @@ -0,0 +1,119 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; +import type { AIMessage, AIMessageChunk, BaseMessage } from "@langchain/core/messages"; +import type { Runnable } from "@langchain/core/runnables"; +import { ChatOpenAI, type ChatOpenAICallOptions } from "@langchain/openai"; +import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; +import type { AiModelResponse } from "../datatypes/Model.response.datatype.js"; +import type { AiModelTransform } from "../datatypes/Model.transform.datatype.js"; +import { AiModelRequestSchema, type AiModelRequest } from "../datatypes/Model.request.datatype.js"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { requireText } from "../../shared/utils/Shared.requireText.util.js"; + +const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; + +interface ToolDefinition { + type: "function"; + function: { + name: string; + description: string; + parameters: Record; + }; +} + +type BoundModel = Runnable; + +@Identifier("ai::model::openrouter") +@DisplayIcon("tabler:router") +@Signature( + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_tokens?: NUMBER): TRANSFORM", +) +@Name({ code: "en-US", content: "OpenRouter model" }) +@DisplayMessage({ code: "en-US", content: "OpenRouter ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Temperature" }], + optional: true, +}) +@Parameter({ + runtimeName: "max_tokens", + name: [{ code: "en-US", content: "Maximum tokens" }], + optional: true, +}) +export class OpenRouterModelFunction { + run( + _context: FunctionContext, + model: string, + api_key: string, + temperature?: number, + max_tokens?: number, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "An OpenRouter model needs a model identifier.", + ); + const chat: ChatOpenAI = new ChatOpenAI({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "An OpenRouter model needs an API key."), + configuration: { baseURL: OPENROUTER_BASE_URL }, + temperature, + maxTokens: max_tokens, + }); + + return async (request: AiModelRequest): Promise => { + const parsed: AiModelRequest = parseOrThrow( + AiModelRequestSchema, + request, + "ERROR_INVALID_AI_MODEL_REQUEST", + "The model request is not valid", + ); + + const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.input_schema, + }, + })); + const bound: BoundModel = tools.length > 0 ? chat.bindTools(tools) : chat; + const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); + + const answer: AIMessage = await bound + .invoke(messages, { + ...(parsed.stop ? { stop: parsed.stop } : {}), + ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), + }) + .catch((error: unknown) => { + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The OpenRouter call to "${identifier}" failed: ${describeError(error)}`, + ); + }); + + return { message: toFlowMessage(answer) }; + }; + } +} diff --git a/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts b/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts new file mode 100644 index 0000000..9338eaa --- /dev/null +++ b/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts @@ -0,0 +1,72 @@ +import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; +import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; +import { + BaseChatModel, + type BaseChatModelCallOptions, + type BindToolsInput, +} from "@langchain/core/language_models/chat_models"; +import { isAIMessage, type AIMessageChunk, type BaseMessage } from "@langchain/core/messages"; +import type { ChatResult } from "@langchain/core/outputs"; +import type { Runnable } from "@langchain/core/runnables"; +import type { AiModelRequest } from "../datatypes/Model.request.datatype.js"; +import type { AiToolSpec } from "../datatypes/Model.toolSpec.datatype.js"; +import { AiModelResponseSchema } from "../datatypes/Model.response.datatype.js"; +import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; +import { toToolSpec } from "./Model.toToolSpec.util.js"; + +type BoundFlowChatModel = Runnable; + +interface FlowChatModelFields { + run: SubFlow; + toolSpecs?: AiToolSpec[]; +} + +export class FlowChatModel extends BaseChatModel { + private readonly run: SubFlow; + private readonly toolSpecs: AiToolSpec[]; + + constructor(fields: FlowChatModelFields) { + super({}); + this.run = fields.run; + this.toolSpecs = fields.toolSpecs ?? []; + } + + _llmType(): string { + return "code0_flow"; + } + + bindTools(tools: BindToolsInput[]): BoundFlowChatModel { + return new FlowChatModel({ + run: this.run, + toolSpecs: tools.map(toToolSpec), + }) as unknown as BoundFlowChatModel; + } + + async _generate(messages: BaseMessage[], options: this["ParsedCallOptions"]): Promise { + const request: AiModelRequest = { + messages: messages.map(toFlowMessage), + tools: this.toolSpecs, + ...(options.stop ? { stop: options.stop } : {}), + ...(options.tool_choice ? { tool_choice: String(options.tool_choice) } : {}), + }; + + const answer = parseOrThrow( + AiModelResponseSchema, + (await this.run(request as never)) ?? {}, + "ERROR_INVALID_AI_MODEL_RESPONSE", + "The model sub flow did not return a valid model response", + ); + + const message: BaseMessage = toLangChainMessage(answer.message); + if (!isAIMessage(message)) { + throw new RuntimeError( + "ERROR_INVALID_AI_MODEL_RESPONSE", + `A model sub flow has to answer with an "ai" message, but answered with a "${answer.message.role}" message.`, + ); + } + + return { generations: [{ text: message.text, message }] }; + } +} diff --git a/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts b/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts new file mode 100644 index 0000000..751c98b --- /dev/null +++ b/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts @@ -0,0 +1,15 @@ +import type { BindToolsInput } from "@langchain/core/language_models/chat_models"; +import { isLangChainTool } from "@langchain/core/tools"; +import type { AiToolSpec } from "../datatypes/Model.toolSpec.datatype.js"; +import { toInputSchema } from "../../shared/utils/Shared.toInputSchema.util.js"; + +export function toToolSpec(tool: BindToolsInput): AiToolSpec { + const definition = tool as { name?: string; description?: string; input_schema?: unknown; schema?: unknown }; + const schema: unknown = isLangChainTool(tool) ? tool.schema : (definition.input_schema ?? definition.schema); + + return { + name: definition.name ?? "unknown", + description: definition.description ?? "", + input_schema: toInputSchema(schema), + }; +} diff --git a/actions/ai-action/src/shared/utils/Shared.asList.util.ts b/actions/ai-action/src/shared/utils/Shared.asList.util.ts new file mode 100644 index 0000000..45f1c0f --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.asList.util.ts @@ -0,0 +1,10 @@ +import { RuntimeError } from "@code0-tech/hercules"; + +export function asList(value: unknown, parameter: string): unknown[] { + if (value === undefined || value === null) return []; + if (Array.isArray(value)) return value; + throw new RuntimeError( + "ERROR_INVALID_AI_SUB_FLOW", + `The "${parameter}" parameter has to be a list, but a ${typeof value} was passed.`, + ); +} diff --git a/actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts b/actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts new file mode 100644 index 0000000..98e53f6 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts @@ -0,0 +1,10 @@ +import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; +import { isSubFlow } from "./Shared.isSubFlow.util.js"; + +export function asSubFlow(value: unknown, parameter: string): SubFlow { + if (isSubFlow(value)) return value; + throw new RuntimeError( + "ERROR_INVALID_AI_SUB_FLOW", + `The "${parameter}" parameter has to be a sub flow, but a ${typeof value} was passed.`, + ); +} diff --git a/actions/ai-action/src/shared/utils/Shared.asText.util.ts b/actions/ai-action/src/shared/utils/Shared.asText.util.ts new file mode 100644 index 0000000..30807a3 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.asText.util.ts @@ -0,0 +1,9 @@ +import { RuntimeError } from "@code0-tech/hercules"; + +export function asText(value: unknown, parameter: string, errorCode: string): string { + if (typeof value === "string") return value; + throw new RuntimeError( + errorCode, + `The "${parameter}" parameter has to be a text, but a ${typeof value} was passed.`, + ); +} diff --git a/actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts b/actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts new file mode 100644 index 0000000..e11c6bd --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts @@ -0,0 +1,7 @@ +import { Action, CodeZeroEvent } from "@code0-tech/hercules"; + +export function connectToAquila(action: Action): void { + action.connect(process.env.AUTH_TOKEN ?? "your_auth_token_here").catch((error: Error) => { + action.emit(CodeZeroEvent.error, error); + }); +} diff --git a/actions/ai-action/src/shared/utils/Shared.describeError.util.ts b/actions/ai-action/src/shared/utils/Shared.describeError.util.ts new file mode 100644 index 0000000..159df9c --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.describeError.util.ts @@ -0,0 +1,3 @@ +export function describeError(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} diff --git a/actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts b/actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts new file mode 100644 index 0000000..1c37663 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts @@ -0,0 +1,3 @@ +export function emptyJsonSchema(): Record { + return { type: "object", properties: {} }; +} diff --git a/actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts b/actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts new file mode 100644 index 0000000..ad231a7 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts @@ -0,0 +1,5 @@ +import type { $ZodIssue } from "zod/v4/core"; + +export function formatIssues(issues: readonly $ZodIssue[]): string { + return issues.map((issue) => `${issue.path.join(".") || ""}: ${issue.message}`).join("; "); +} diff --git a/actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts b/actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts new file mode 100644 index 0000000..5a8d4a7 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts @@ -0,0 +1,3 @@ +export function hasEntries(value: Record | undefined): boolean { + return value !== undefined && Object.keys(value).length > 0; +} diff --git a/actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts b/actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts new file mode 100644 index 0000000..c8f080f --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts @@ -0,0 +1,5 @@ +import type { SubFlow } from "@code0-tech/hercules"; + +export function isSubFlow(value: unknown): value is SubFlow { + return typeof value === "function"; +} diff --git a/actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts b/actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts new file mode 100644 index 0000000..5b337f5 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts @@ -0,0 +1,9 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import type { ZodType } from "zod"; +import { formatIssues } from "./Shared.formatIssues.util.js"; + +export function parseOrThrow(schema: ZodType, value: unknown, errorCode: string, problem: string): T { + const parsed = schema.safeParse(value); + if (parsed.success) return parsed.data; + throw new RuntimeError(errorCode, `${problem}: ${formatIssues(parsed.error.issues)}`); +} diff --git a/actions/ai-action/src/shared/utils/Shared.requireText.util.ts b/actions/ai-action/src/shared/utils/Shared.requireText.util.ts new file mode 100644 index 0000000..6a8bdf3 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.requireText.util.ts @@ -0,0 +1,6 @@ +import { RuntimeError } from "@code0-tech/hercules"; + +export function requireText(value: unknown, errorCode: string, problem: string): string { + if (typeof value === "string" && value.trim().length > 0) return value; + throw new RuntimeError(errorCode, problem); +} diff --git a/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts b/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts new file mode 100644 index 0000000..fdd4d88 --- /dev/null +++ b/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts @@ -0,0 +1,12 @@ +import { toJsonSchema } from "@langchain/core/utils/json_schema"; +import { emptyJsonSchema } from "./Shared.emptyJsonSchema.util.js"; + +export function toInputSchema(schema: unknown): Record { + if (!schema) return emptyJsonSchema(); + + try { + return toJsonSchema(schema as never) as Record; + } catch { + return emptyJsonSchema(); + } +} diff --git a/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts b/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts new file mode 100644 index 0000000..cf1f9db --- /dev/null +++ b/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts @@ -0,0 +1,16 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +export const AiWebSearchHitSchema = z.object({ + title: z.string(), + url: z.string(), + content: z.string(), + score: z.number().optional(), +}); +export type AiWebSearchHit = z.infer; + +@Identifier("AI_WEB_SEARCH_HIT") +@Name({ code: "en-US", content: "Web search hit" }) +@DisplayMessage({ code: "en-US", content: "${title}" }) +@Schema(AiWebSearchHitSchema) +export class AiWebSearchHitDataType {} diff --git a/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts b/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts new file mode 100644 index 0000000..7ce6e21 --- /dev/null +++ b/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts @@ -0,0 +1,16 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiWebSearchHitSchema } from "./WebSearch.hit.datatype.js"; + +export const AiWebSearchResultSchema = z.object({ + query: z.string(), + results: z.array(AiWebSearchHitSchema), + answer: z.string().optional(), +}); +export type AiWebSearchResult = z.infer; + +@Identifier("AI_WEB_SEARCH_RESULT") +@Name({ code: "en-US", content: "Web search result" }) +@DisplayMessage({ code: "en-US", content: "Web search for ${query}" }) +@Schema(AiWebSearchResultSchema) +export class AiWebSearchResultDataType {} diff --git a/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts b/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts new file mode 100644 index 0000000..14c2445 --- /dev/null +++ b/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts @@ -0,0 +1,74 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { TavilySearch } from "@langchain/tavily"; +import type { AiWebSearchResult } from "../datatypes/WebSearch.result.datatype.js"; +import { describeError } from "../../shared/utils/Shared.describeError.util.js"; +import { requireText } from "../../shared/utils/Shared.requireText.util.js"; +import { toSearchResult } from "../utils/WebSearch.toSearchResult.util.js"; + +type WebSearchTopic = "general" | "news" | "finance"; + +@Identifier("ai::tool::web_search") +@DisplayIcon("tabler:world-search") +@Signature( + "(query: TEXT, api_key: TEXT, max_results?: NUMBER, topic?: TEXT, include_answer?: BOOLEAN): AI_WEB_SEARCH_RESULT", +) +@Name({ code: "en-US", content: "Web search" }) +@DisplayMessage({ code: "en-US", content: "Search the web for ${query}" }) +@ThrowsError() +@Parameter({ + runtimeName: "query", + name: [{ code: "en-US", content: "Query" }], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], +}) +@Parameter({ + runtimeName: "max_results", + name: [{ code: "en-US", content: "Maximum results" }], + optional: true, +}) +@Parameter({ + runtimeName: "topic", + name: [{ code: "en-US", content: "Topic" }], + optional: true, +}) +@Parameter({ + runtimeName: "include_answer", + name: [{ code: "en-US", content: "Include answer" }], + optional: true, +}) +export class WebSearchToolFunction { + async run( + _context: FunctionContext, + query: string, + api_key: string, + max_results?: number, + topic?: WebSearchTopic, + include_answer?: boolean, + ): Promise { + const question: string = requireText(query, "ERROR_INVALID_AI_WEB_SEARCH", "A web search needs a query."); + const search = new TavilySearch({ + tavilyApiKey: requireText(api_key, "ERROR_INVALID_AI_WEB_SEARCH", "A web search needs a Tavily API key."), + maxResults: max_results ?? 5, + includeAnswer: include_answer ?? true, + ...(topic ? { topic } : {}), + }); + + const raw = await search.invoke({ query: question }).catch((error: unknown) => { + throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", `The web search failed: ${describeError(error)}`); + }); + + return toSearchResult(question, raw); + } +} diff --git a/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts b/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts new file mode 100644 index 0000000..dab4e36 --- /dev/null +++ b/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts @@ -0,0 +1,9 @@ +import { RuntimeError } from "@code0-tech/hercules"; + +export function parseSearchPayload(value: string): unknown { + try { + return JSON.parse(value); + } catch { + throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", "The web search returned an unreadable response."); + } +} diff --git a/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts b/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts new file mode 100644 index 0000000..4bbf537 --- /dev/null +++ b/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts @@ -0,0 +1,28 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import { AiWebSearchResultSchema, type AiWebSearchResult } from "../datatypes/WebSearch.result.datatype.js"; +import { parseSearchPayload } from "./WebSearch.parseSearchPayload.util.js"; + +export function toSearchResult(query: string, raw: unknown): AiWebSearchResult { + const payload: unknown = typeof raw === "string" ? parseSearchPayload(raw) : raw; + + if (payload && typeof payload === "object" && "error" in payload) { + throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", `The web search failed: ${String(payload.error)}`); + } + + const source = (payload ?? {}) as { results?: unknown; answer?: unknown }; + const results: unknown[] = Array.isArray(source.results) ? source.results : []; + + return AiWebSearchResultSchema.parse({ + query, + results: results.map((hit) => { + const entry = (hit ?? {}) as Record; + return { + title: String(entry.title ?? ""), + url: String(entry.url ?? ""), + content: String(entry.content ?? ""), + ...(typeof entry.score === "number" ? { score: entry.score } : {}), + }; + }), + ...(typeof source.answer === "string" && source.answer.length > 0 ? { answer: source.answer } : {}), + }); +} diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts new file mode 100644 index 0000000..6cb3b3b --- /dev/null +++ b/actions/ai-action/test/agent.test.ts @@ -0,0 +1,279 @@ +import "reflect-metadata"; +import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import type { AiAgentState } from "../src/middleware/datatypes/Middleware.agentState.datatype.js"; +import type { AiMessage } from "../src/message/datatypes/Message.datatype.js"; +import type { AiModelRequest } from "../src/model/datatypes/Model.request.datatype.js"; +import type { AiModelResponse } from "../src/model/datatypes/Model.response.datatype.js"; +import { CreateAgentFunction } from "../src/agent/runtimefunctions/Agent.create.runtimefunction.js"; +import { TrimMessagesMiddlewareFunction } from "../src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; + +function subFlow(implementation: (input: never) => unknown, inputSchema?: Record): SubFlow { + const flow = (async (input: never) => implementation(input)) as unknown as { + inputSchema?: unknown; + outputSchema?: unknown; + }; + if (inputSchema) flow.inputSchema = inputSchema; + return flow as unknown as SubFlow; +} + +function context(executionId = "execution-1"): FunctionContext { + return { + projectId: 1, + executionId, + matchedConfig: { projectId: 1, configValues: [], findConfig: () => undefined }, + executeFlow: async () => null, + }; +} + +function answer(text: string, toolCalls: { id: string; name: string; args: object }[] = []): AiModelResponse { + return { + message: { + role: "ai", + content: [ + ...(text.length > 0 ? [{ type: "text", text }] : []), + ...toolCalls.map((call) => ({ type: "tool_call", ...call })), + ], + }, + }; +} + +function scriptedModel(responses: AiModelResponse[]) { + const requests: AiModelRequest[] = []; + let call = 0; + const run = subFlow((input: never) => { + requests.push(input as unknown as AiModelRequest); + return responses[Math.min(call++, responses.length - 1)]; + }); + return { run, requests }; +} + +const create = new CreateAgentFunction(); + +function user(text: string): AiMessage { + return { role: "human", content: [{ type: "text", text }] }; +} + +function assistant(text: string): AiMessage { + return { role: "ai", content: [{ type: "text", text }] }; +} + +function textOf(message: AiMessage | undefined): string { + return (message?.content ?? []) + .filter((block) => block.type === "text") + .map((block) => String(block.text ?? "")) + .join(""); +} + +describe("ai::agent::create", () => { + it("returns the agent itself, which is a callable", () => { + const { run } = scriptedModel([answer("hello")]); + const agent = create.run(context(), "greeter", "You greet people.", run); + + expect(typeof agent).toEqual("function"); + }); + + it("needs a name", () => { + const { run } = scriptedModel([answer("hello")]); + expect(() => create.run(context(), "", "", run)).toThrow(RuntimeError); + }); + + it("rejects a model that is not a sub flow", () => { + expect(() => + create.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never), + ).toThrow(RuntimeError); + }); + + it("rejects an MCP server missing what its transport needs, while the flow is built", () => { + const { run } = scriptedModel([answer("hello")]); + expect(() => + create.run(context(), "greeter", "", run, [{ name: "docs", transport: "stdio" }] as never), + ).toThrow(RuntimeError); + }); + + it("rejects two MCP servers with the same name", () => { + const { run } = scriptedModel([answer("hello")]); + expect(() => + create.run(context(), "greeter", "", run, [ + { name: "docs", url: "https://a/mcp" }, + { name: "docs", url: "https://b/mcp" }, + ] as never), + ).toThrow(RuntimeError); + }); +}); + +describe("the agent loop", () => { + it("runs the model sub flow and returns its answer", async () => { + const { run, requests } = scriptedModel([answer("Hi there.")]); + const agent = create.run(context(), "greeter", "You greet people.", run); + + const result = await agent({ messages: [user("hello")] }); + + expect(requests).toHaveLength(1); + expect(requests[0].messages.map((m) => m.role)).toEqual(["system", "human"]); + expect(requests[0].messages[0].content).toEqual([{ type: "text", text: "You greet people." }]); + expect(textOf(result.messages.at(-1))).toEqual("Hi there."); + }); + + it("advertises every tool sub flow to the model and calls the one it picks", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "tool_1", args: { order: "A-1" } }]), + answer("Order A-1 has shipped."), + ]); + const calls: unknown[] = []; + const lookup = subFlow( + (input: never) => { + calls.push(input); + return { status: "shipped" }; + }, + { type: "object", description: "Looks an order up.", properties: { order: { type: "string" } } }, + ); + + const agent = create.run(context(), "support", "", run, [lookup]); + const result = await agent({ messages: [user("where is A-1?")] }); + + expect(requests[0].tools).toEqual([ + { + name: "tool_1", + description: "Looks an order up.", + input_schema: expect.objectContaining({ type: "object" }), + }, + ]); + expect(calls).toEqual([{ order: "A-1" }]); + expect(requests[1].messages.map((m) => m.role)).toEqual(["human", "ai", "tool"]); + expect(requests[1].messages.at(-1)?.content).toEqual([{ type: "text", text: '{"status":"shipped"}' }]); + expect(textOf(result.messages.at(-1))).toEqual("Order A-1 has shipped."); + }); + + it("reports a failing tool to the model instead of aborting the run", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "tool_1", args: {} }]), + answer("That did not work."), + ]); + const broken = subFlow(() => { + throw new Error("the warehouse is offline"); + }); + + const agent = create.run(context(), "support", "", run, [broken]); + const result = await agent({ messages: [user("status?")] }); + + expect(JSON.stringify(requests[1].messages.at(-1)?.content)).toContain("the warehouse is offline"); + expect(textOf(result.messages.at(-1))).toEqual("That did not work."); + }); + + it("lets a middleware sub flow rewrite the conversation before the model call", async () => { + const { run, requests } = scriptedModel([answer("ok")]); + const redact = subFlow((input: never) => { + const state = input as unknown as { + hook: string; + messages: { role: string; content: { type: string; text?: string }[] }[]; + }; + if (state.hook !== "before_model") return null; + return { + messages: state.messages.map((message) => ({ + ...message, + content: message.content.map((block) => + block.type === "text" ? { ...block, text: block.text?.replace(/\d{4,}/g, "****") } : block, + ), + })), + }; + }); + + const agent = create.run(context(), "support", "", run, [], [redact]); + await agent({ messages: [user("my card is 4111111111111111")] }); + + expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "my card is ****" }]); + }); + + it("lets a middleware sub flow end the run before the model is called", async () => { + const { run, requests } = scriptedModel([answer("should not be reached")]); + const block = subFlow(() => ({ jump_to: "end" })); + + const agent = create.run(context(), "support", "", run, [], [block]); + await agent({ messages: [user("hello")] }); + + expect(requests).toHaveLength(0); + }); + + it("calls one middleware sub flow for both the before and the after phase", async () => { + const { run } = scriptedModel([answer("ok")]); + const hooks: string[] = []; + const observe = subFlow((input: never) => { + hooks.push((input as unknown as { hook: string }).hook); + return null; + }); + + const agent = create.run(context(), "support", "", run, [], [observe]); + const result = await agent({ messages: [user("hello")] }); + + expect(hooks).toEqual(["before_model", "after_model"]); + expect(textOf(result.messages.at(-1))).toEqual("ok"); + }); + + it("takes sub flow tools and MCP servers in the same list", async () => { + const { run, requests } = scriptedModel([answer("ok")]); + const lookup = subFlow(() => ({ status: "shipped" }), { type: "object", description: "Looks an order up." }); + + expect(() => + create.run(context(), "support", "", run, [lookup, { name: "docs", transport: "stdio" }] as never), + ).toThrow(/needs a command/); + + const agent = create.run(context(), "support", "", run, [lookup]); + await agent({ messages: [user("hello")] }); + expect(requests[0].tools.map((t) => t.name)).toEqual(["tool_1"]); + }); + + it("rejects a tool entry that is neither a sub flow nor an MCP server", async () => { + const { run } = scriptedModel([answer("ok")]); + expect(() => create.run(context(), "support", "", run, [{ nonsense: true }] as never)).toThrow( + /Entry 1 of "tools"/, + ); + }); + + it("fails with a clear error when the model sub flow answers with the wrong shape", async () => { + const run = subFlow(() => ({ message: { role: "ai", content: "not a list" } })); + const agent = create.run(context(), "greeter", "", run); + + await expect(agent({ messages: [user("hello")] })).rejects.toThrow(/did not return a valid model response/); + }); +}); + +describe("what a middleware flow is handed", () => { + it("forwards the run's thread, not just the messages", async () => { + const seen: AiAgentState[] = []; + const { run } = scriptedModel([answer("ok")]); + const observe = subFlow((input: never) => { + seen.push(input as unknown as AiAgentState); + return {}; + }); + + const agent = create.run(context(), "support", "You are helpful.", run, [], [observe]); + await agent({ messages: [user("hello")], thread_id: "thread-1" }); + + expect(seen[0].thread_id).toEqual("thread-1"); + expect(seen[0].context).toBeUndefined(); + expect(Object.keys(seen[0])).toEqual(["messages", "agent_name", "hook", "thread_id"]); + }); +}); + +describe("composing the shipped functions into an agent", () => { + it("uses ai::middleware::trim_messages as a real middleware", async () => { + const trim = new TrimMessagesMiddlewareFunction(); + const middlewareFlow = trim.run(context(), 200, "last", true); + + const { run, requests } = scriptedModel([answer("ok")]); + const long = Array.from({ length: 12 }, (_, turn) => + turn % 2 === 0 + ? user(`question ${turn} ${"padding ".repeat(40)}`) + : assistant(`answer ${turn} ${"padding ".repeat(40)}`), + ); + + const agent = create.run(context(), "support", "You are helpful.", run, [], [middlewareFlow]); + const result = await agent({ messages: long }); + + expect(requests).toHaveLength(1); + expect(requests[0].messages.length).toBeLessThan(long.length + 1); + expect(requests[0].messages[0].role).toEqual("system"); + expect(textOf(result.messages.at(-1))).toEqual("ok"); + }); +}); diff --git a/actions/ai-action/test/dataTypes.test.ts b/actions/ai-action/test/dataTypes.test.ts new file mode 100644 index 0000000..4b064d7 --- /dev/null +++ b/actions/ai-action/test/dataTypes.test.ts @@ -0,0 +1,289 @@ +import "reflect-metadata"; +import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages"; +import { describe, expect, it } from "vitest"; +import { fromChatMessage } from "../src/chat/utils/Chat.fromChatMessage.util.js"; +import { toChatMessage } from "../src/chat/utils/Chat.toChatMessage.util.js"; +import { toChatResponse } from "../src/chat/utils/Chat.toChatResponse.util.js"; +import { toFlowMessage } from "../src/message/utils/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../src/message/utils/Message.toLangChainMessage.util.js"; +import type { AiChatMessage } from "../src/chat/datatypes/Chat.message.datatype.js"; +import { AiMcpServerSchema } from "../src/mcp/datatypes/Mcp.server.datatype.js"; +import { AiMessageSchema } from "../src/message/datatypes/Message.datatype.js"; +import { AiStateUpdateSchema } from "../src/middleware/datatypes/Middleware.stateUpdate.datatype.js"; +import { AiModelRequestSchema } from "../src/model/datatypes/Model.request.datatype.js"; +import { AiModelResponseSchema } from "../src/model/datatypes/Model.response.datatype.js"; + +describe("AiModelResponseSchema", () => { + it("accepts a tool-only turn, which carries no text block at all", () => { + const parsed = AiModelResponseSchema.parse({ + message: { + role: "ai", + content: [{ type: "tool_call", id: "call-1", name: "tool_1", args: { q: "x" } }], + }, + }); + expect(parsed.message.content).toHaveLength(1); + }); + + it("keeps a reasoning block, which is the point of using content blocks", () => { + const parsed = AiModelResponseSchema.parse({ + message: { + role: "ai", + content: [ + { type: "reasoning", reasoning: "a chain of thought" }, + { type: "text", text: "the answer" }, + ], + }, + }); + expect(parsed.message.content[0]).toEqual({ type: "reasoning", reasoning: "a chain of thought" }); + }); + + it("rejects a response without a message", () => { + expect(() => AiModelResponseSchema.parse({ content: "hello" })).toThrow(); + }); + + it("rejects a content block without a type", () => { + expect(() => + AiModelResponseSchema.parse({ message: { role: "ai", content: [{ text: "no type" }] } }), + ).toThrow(); + }); +}); + +describe("AiModelRequestSchema", () => { + it("requires the conversation and the advertised tools", () => { + expect(() => AiModelRequestSchema.parse({ messages: [] })).toThrow(); + expect(() => AiModelRequestSchema.parse({ messages: [], tools: [] })).not.toThrow(); + }); +}); + +describe("AiStateUpdateSchema", () => { + it("accepts an empty update, which is how an observing middleware answers", () => { + expect(AiStateUpdateSchema.parse({})).toEqual({}); + }); + + it("rejects a jump target the agent has no node for", () => { + expect(() => AiStateUpdateSchema.parse({ jump_to: "somewhere" })).toThrow(); + }); +}); + +describe("AiMcpServerSchema", () => { + it("defaults to the streamable http transport", () => { + expect(AiMcpServerSchema.parse({ name: "docs", url: "https://mcp.example.com/mcp" }).transport).toEqual("http"); + }); + + it("keeps headers as a free-form map", () => { + const parsed = AiMcpServerSchema.parse({ + name: "docs", + url: "https://mcp.example.com/mcp", + headers: { Authorization: "Bearer token" }, + }); + expect(parsed.headers).toEqual({ Authorization: "Bearer token" }); + }); +}); + +describe("message conversion", () => { + it("maps every LangChain message type onto a role", () => { + expect(toFlowMessage(new SystemMessage("s")).role).toEqual("system"); + expect(toFlowMessage(new HumanMessage("h")).role).toEqual("human"); + expect(toFlowMessage(new AIMessage("a")).role).toEqual("ai"); + expect(toFlowMessage(new ToolMessage({ content: "t", tool_call_id: "call-1" })).role).toEqual("tool"); + }); + + it("carries tool calls across as tool_call content blocks", () => { + const flat = toFlowMessage( + new AIMessage({ content: "", tool_calls: [{ id: "call-1", name: "tool_1", args: { q: "x" } }] }), + ); + expect(AiMessageSchema.parse(flat).content).toEqual([ + { type: "text", text: "" }, + { type: "tool_call", id: "call-1", name: "tool_1", args: { q: "x" } }, + ]); + }); + + it("keeps every content block instead of flattening them to text", () => { + const flat = toFlowMessage( + new AIMessage({ + content: [ + { type: "reasoning", reasoning: "a chain of thought" }, + { type: "text", text: "the answer" }, + ], + }), + ); + expect(flat.content).toEqual([ + { type: "reasoning", reasoning: "a chain of thought" }, + { type: "text", text: "the answer" }, + ]); + }); + + it("keeps an image block, which a flattened message would have lost", () => { + const flat = toFlowMessage( + new HumanMessage({ + content: [ + { type: "text", text: "what is this" }, + { type: "image", url: "https://example.com/a.png", mime_type: "image/png" }, + ], + }), + ); + expect(flat.content[1]).toEqual({ + type: "image", + url: "https://example.com/a.png", + mime_type: "image/png", + }); + }); + + it("keeps the provider's metadata and token usage on a generation", () => { + const flat = toFlowMessage( + new AIMessage({ + content: "done", + response_metadata: { finish_reason: "stop", model_name: "claude" }, + usage_metadata: { input_tokens: 1, output_tokens: 2, total_tokens: 3 }, + }), + ); + expect(flat.response_metadata).toMatchObject({ finish_reason: "stop", model_name: "claude" }); + expect(flat.usage_metadata).toMatchObject({ input_tokens: 1, output_tokens: 2, total_tokens: 3 }); + }); + + it("round-trips every message shape through a flow and back", () => { + for (const message of [ + new SystemMessage("s"), + new HumanMessage({ + content: [ + { type: "text", text: "look" }, + { type: "image", url: "https://example.com/a.png", mime_type: "image/png" }, + ], + }), + new AIMessage({ + content: [ + { type: "reasoning", reasoning: "chain" }, + { type: "text", text: "a" }, + ], + tool_calls: [{ id: "call-1", name: "tool_1", args: { q: "x" } }], + response_metadata: { finish_reason: "tool_calls" }, + usage_metadata: { input_tokens: 1, output_tokens: 2, total_tokens: 3 }, + }), + new ToolMessage({ + content: "t", + tool_call_id: "call-1", + name: "tool_1", + artifact: { rows: [1, 2, 3] }, + status: "error", + }), + new AIMessage({ + content: "", + additional_kwargs: { refusal: "no" }, + invalid_tool_calls: [{ id: "call-2", name: "tool_1", args: "{broken", error: "bad json" }], + }), + ]) { + const flat = toFlowMessage(message); + const rebuilt = toFlowMessage(toLangChainMessage(flat)); + expect(rebuilt).toEqual(flat); + } + }); + + it("keeps a tool message's artifact and status, which the model never sees", () => { + const flat = toFlowMessage( + new ToolMessage({ + content: "42 rows", + tool_call_id: "call-1", + name: "query", + artifact: { rows: [1, 2, 3] }, + status: "error", + }), + ); + expect(flat.artifact).toEqual({ rows: [1, 2, 3] }); + expect(flat.status).toEqual("error"); + + const rebuilt = toLangChainMessage(flat) as ToolMessage; + expect(rebuilt.artifact).toEqual({ rows: [1, 2, 3] }); + expect(rebuilt.status).toEqual("error"); + }); + + it("keeps a provider's extras, which have no standard field of their own", () => { + const flat = toFlowMessage(new AIMessage({ content: "hi", additional_kwargs: { refusal: "no" } })); + expect(flat.additional_kwargs).toEqual({ refusal: "no" }); + expect(toLangChainMessage(flat).additional_kwargs).toEqual({ refusal: "no" }); + }); + + it("keeps a malformed tool call, so a middleware can repair it", () => { + const flat = toFlowMessage( + new AIMessage({ + content: "", + invalid_tool_calls: [{ id: "call-1", name: "query", args: "{not json", error: "bad json" }], + }), + ); + expect(flat.content.filter((block: { type: string }) => block.type === "invalid_tool_call")).toEqual([ + { type: "invalid_tool_call", id: "call-1", name: "query", args: "{not json", error: "bad json" }, + ]); + + const rebuilt = toLangChainMessage(flat) as AIMessage; + expect(rebuilt.invalid_tool_calls).toEqual([ + { id: "call-1", name: "query", args: "{not json", error: "bad json" }, + ]); + expect(rebuilt.content).toEqual([{ type: "text", text: "" }]); + }); + + it("does not invent empty metadata where the provider sent none", () => { + const flat = toFlowMessage(new HumanMessage("plain")); + expect(flat.additional_kwargs).toBeUndefined(); + expect(flat.response_metadata).toBeUndefined(); + }); + + it("does not duplicate a tool call when rebuilding a generation", () => { + const flat = toFlowMessage( + new AIMessage({ content: "", tool_calls: [{ id: "call-1", name: "tool_1", args: {} }] }), + ); + const rebuilt = toLangChainMessage(flat); + expect(rebuilt.contentBlocks.filter((block: { type: string }) => block.type === "tool_call")).toHaveLength(1); + expect((rebuilt as AIMessage).tool_calls).toHaveLength(1); + }); +}); + +describe("OpenAI chat completion conversion", () => { + it("maps every OpenAI role onto one of ours and back", () => { + const roles: AiChatMessage["role"][] = ["system", "user", "assistant", "tool"]; + expect(roles.map((role) => fromChatMessage({ role, content: "x" }).role)).toEqual([ + "system", + "human", + "ai", + "tool", + ]); + expect(roles.map((role) => toChatMessage(fromChatMessage({ role, content: "x" })).role)).toEqual(roles); + }); + + it("says null rather than an empty string when a turn only asks for tools", () => { + const message = toChatMessage({ + role: "ai", + content: [{ type: "tool_call", id: "call-1", name: "tool_1", args: { a: 1 } }], + }); + + expect(message.content).toBeNull(); + expect(message.tool_calls).toEqual([ + { id: "call-1", type: "function", function: { name: "tool_1", arguments: '{"a":1}' } }, + ]); + }); + + it("reports a turn that asks for tools as finish_reason tool_calls", () => { + const response = toChatResponse( + { + role: "ai", + content: [{ type: "tool_call", id: "call-1", name: "tool_1", args: {} }], + }, + "fallback-model", + ); + + expect(response.choices[0].finish_reason).toEqual("tool_calls"); + expect(response.model).toEqual("fallback-model"); + expect(response.id).toMatch(/^chatcmpl-/); + }); + + it("carries an unknown content part through rather than destroying it", () => { + const flat = fromChatMessage({ + role: "user", + content: [{ type: "input_audio", input_audio: { data: "AAA", format: "wav" } }], + }); + + expect(flat.content).toEqual([{ type: "input_audio", input_audio: { data: "AAA", format: "wav" } }]); + }); + + it("leaves out usage when the model reported none", () => { + expect(toChatResponse({ role: "ai", content: [{ type: "text", text: "hi" }] }, "m").usage).toBeUndefined(); + }); +}); diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts new file mode 100644 index 0000000..831c81d --- /dev/null +++ b/actions/ai-action/test/functions.test.ts @@ -0,0 +1,335 @@ +import "reflect-metadata"; +import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import type { AiContentBlock } from "../src/message/datatypes/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../src/message/datatypes/Message.datatype.js"; +import { AiChatResponseSchema } from "../src/chat/datatypes/Chat.response.datatype.js"; +import type { AiModelRequest } from "../src/model/datatypes/Model.request.datatype.js"; +import { AiModelResponseSchema, type AiModelResponse } from "../src/model/datatypes/Model.response.datatype.js"; +import { AiStateUpdateSchema } from "../src/middleware/datatypes/Middleware.stateUpdate.datatype.js"; +import { AiWebSearchResultSchema } from "../src/websearch/datatypes/WebSearch.result.datatype.js"; +import { TrimMessagesMiddlewareFunction } from "../src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; +import { OpenRouterModelFunction } from "../src/model/runtimefunctions/Model.openRouter.runtimefunction.js"; +import { WebSearchToolFunction } from "../src/websearch/runtimefunctions/WebSearch.search.runtimefunction.js"; +import { CreateAgentFunction } from "../src/agent/runtimefunctions/Agent.create.runtimefunction.js"; +import { InvokeAgentFunction } from "../src/agent/runtimefunctions/Agent.invoke.runtimefunction.js"; + +const model = new OpenRouterModelFunction(); +const middleware = new TrimMessagesMiddlewareFunction(); +const search = new WebSearchToolFunction(); +const create = new CreateAgentFunction(); + +function context(): FunctionContext { + return { + projectId: 1, + executionId: "functions-execution", + matchedConfig: { projectId: 1, configValues: [], findConfig: () => undefined }, + executeFlow: async () => null, + }; +} + +function state(count: number, hook: "before_model" | "after_model" = "before_model") { + const text = (value: string) => [{ type: "text", text: value }]; + const messages: AiMessage[] = [{ role: "system", content: text("You are helpful.") }]; + for (let turn = 0; turn < count; turn += 1) { + messages.push({ role: "human", content: text(`question ${turn} ${"padding ".repeat(40)}`) }); + messages.push({ role: "ai", content: text(`answer ${turn} ${"padding ".repeat(40)}`) }); + } + return { messages, agent_name: "support", hook }; +} + +describe("ai::model::openrouter", () => { + it("returns a callable, which is what TRANSFORM<_, _> is", () => { + const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); + expect(typeof transform).toEqual("function"); + }); + + it("needs a model identifier and an API key", () => { + expect(() => model.run(context(), "", "key")).toThrow(RuntimeError); + expect(() => model.run(context(), "anthropic/claude-opus-5", "")).toThrow(RuntimeError); + }); + + it("rejects a call whose argument is not a model request", async () => { + const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); + await expect(transform({ messages: [] } as never)).rejects.toThrow(/model request is not valid/); + }); + + it("reports a failed call as a runtime error rather than leaking the provider's", async () => { + const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-invalid-key-for-test"); + await expect( + transform({ messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] } as never), + ).rejects.toThrow(RuntimeError); + }, 30_000); + + it("is accepted by ai::agent::create as the agent's model", () => { + const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); + const agent = create.run(context(), "support", "You are helpful.", transform); + expect(typeof agent).toEqual("function"); + }); +}); + +describe("ai::middleware::trim_messages", () => { + it("returns a callable, which is what TRANSFORM<_, _> is", () => { + const transform = middleware.run(context(), 200); + expect(typeof transform).toEqual("function"); + }); + + it("rejects a budget that is not a positive number", () => { + expect(() => middleware.run(context(), 0)).toThrow(RuntimeError); + expect(() => middleware.run(context(), Number.NaN)).toThrow(RuntimeError); + }); + + it("rejects a strategy it has no meaning for", () => { + expect(() => middleware.run(context(), 500, "middle")).toThrow(/not a trim strategy/); + }); + + it("returns no change when the conversation already fits", async () => { + const update = await middleware.run(context(), 100_000)(state(1)); + expect(update).toEqual({}); + }); + + it("drops whole messages until the conversation fits the budget", async () => { + const before = state(12); + const update = await middleware.run(context(), 200)(before); + + const parsed = AiStateUpdateSchema.parse(update); + expect(parsed.messages).toBeDefined(); + expect(parsed.messages!.length).toBeLessThan(before.messages.length); + expect(parsed.messages!.at(-1)?.content).toEqual(before.messages.at(-1)?.content); + }); + + it("keeps the system prompt when it trims", async () => { + const update = await middleware.run(context(), 200, "last", true)(state(12)); + const parsed = AiStateUpdateSchema.parse(update); + expect(parsed.messages![0].role).toEqual("system"); + }); + + it("rejects a state that is not an agent state", async () => { + const transform = middleware.run(context(), 500); + await expect(transform({ messages: [] } as never)).rejects.toThrow(/agent state is not valid/); + }); + + it("produces an update the agent will accept", async () => { + const update = await middleware.run(context(), 200)(state(12)); + expect(() => AiStateUpdateSchema.parse(update)).not.toThrow(); + }); +}); + +describe("ai::tool::web_search", () => { + it("needs a query and an API key", async () => { + await expect(search.run(context(), "", "key")).rejects.toThrow(RuntimeError); + await expect(search.run(context(), " ", "key")).rejects.toThrow(RuntimeError); + await expect(search.run(context(), "what is langchain", "")).rejects.toThrow(RuntimeError); + }); + + it("reports a failed search as a runtime error", async () => { + await expect(search.run(context(), "what is langchain", "tvly-invalid-key-for-test")).rejects.toThrow( + RuntimeError, + ); + }, 30_000); +}); + +describe("the contracts the functions implement", () => { + it("the model function's output is a valid AI_MODEL_RESPONSE", () => { + expect(() => + AiModelResponseSchema.parse({ + message: { + role: "ai", + content: [ + { type: "reasoning", reasoning: "thinking it through" }, + { type: "tool_call", id: "call_0", name: "tool_1", args: { q: "x" } }, + ], + response_metadata: { finish_reason: "tool_calls" }, + usage_metadata: { input_tokens: 10, output_tokens: 5, total_tokens: 15 }, + }, + }), + ).not.toThrow(); + }); + + it("the search function's output is a valid AI_WEB_SEARCH_RESULT", () => { + expect(() => + AiWebSearchResultSchema.parse({ + query: "what is langchain", + results: [{ title: "LangChain", url: "https://x", content: "a framework", score: 0.9 }], + answer: "A framework for LLM applications.", + }), + ).not.toThrow(); + }); +}); + +describe("ai::agent::invoke", () => { + const invoke = new InvokeAgentFunction(); + + function scriptedModel(responses: AiModelResponse[]) { + const requests: AiModelRequest[] = []; + let call = 0; + const run = (async (input: never) => { + requests.push(input as unknown as AiModelRequest); + return responses[Math.min(call++, responses.length - 1)]; + }) as unknown as SubFlow; + return { run, requests }; + } + + function generation(content: AiContentBlock[], usage?: Record): AiModelResponse { + return { + message: { + role: "ai", + content, + response_metadata: { model_name: "anthropic/claude-opus-5" }, + ...(usage ? { usage_metadata: usage } : {}), + }, + }; + } + + it("answers an OpenAI request with an OpenAI chat completion", async () => { + const { run, requests } = scriptedModel([ + generation([{ type: "text", text: "Hi there." }], { + input_tokens: 11, + output_tokens: 3, + total_tokens: 14, + }), + ]); + const agent = create.run(context(), "greeter", "You greet people.", run); + + const response = await invoke.run(context(), agent, "hello", { + model: "my-agent", + messages: [{ role: "system", content: "Be brief." }], + }); + + const parsed = AiChatResponseSchema.parse(response); + expect(parsed.object).toEqual("chat.completion"); + expect(parsed.model).toEqual("anthropic/claude-opus-5"); + expect(parsed.choices).toHaveLength(1); + expect(parsed.choices[0].finish_reason).toEqual("stop"); + expect(parsed.choices[0].message).toEqual({ role: "assistant", content: "Hi there.", name: "greeter" }); + expect(parsed.usage).toEqual({ prompt_tokens: 11, completion_tokens: 3, total_tokens: 14 }); + + expect(requests[0].messages.map((message) => message.role)).toEqual(["system", "system", "human"]); + }); + + it("translates a multimodal prompt into content blocks", async () => { + const { run, requests } = scriptedModel([generation([{ type: "text", text: "A cat." }])]); + const agent = create.run(context(), "describer", "", run); + + await invoke.run(context(), agent, "", { + messages: [ + { + role: "user", + content: [ + { type: "text", text: "what is this?" }, + { type: "image_url", image_url: { url: "https://example.com/a.png" } }, + ], + }, + ], + }); + + expect(requests[0].messages.at(-1)?.content).toEqual([ + { type: "text", text: "what is this?" }, + { type: "image", url: "https://example.com/a.png" }, + ]); + }); + + it("translates the tool calls and results of a prompt into blocks", async () => { + const { run, requests } = scriptedModel([ + generation([{ type: "tool_call", id: "call-1", name: "tool_1", args: { order: "A-1" } }]), + generation([{ type: "text", text: "Order A-1 has shipped." }]), + ]); + const lookup = (async () => ({ status: "shipped" })) as unknown as SubFlow; + const agent = create.run(context(), "support", "", run, [lookup]); + + const response = await invoke.run(context(), agent, "and A-1?", { + messages: [ + { role: "user", content: "where is A-0?" }, + { + role: "assistant", + content: null, + tool_calls: [ + { id: "call-0", type: "function", function: { name: "tool_1", arguments: '{"order":"A-0"}' } }, + ], + }, + { role: "tool", tool_call_id: "call-0", content: '{"status":"delivered"}' }, + ], + }); + + const asked = requests[0].messages.find((message) => message.role === "ai"); + expect(asked?.content).toEqual([{ type: "tool_call", id: "call-0", name: "tool_1", args: { order: "A-0" } }]); + const result = requests[0].messages.find((message) => message.role === "tool"); + expect(result?.tool_call_id).toEqual("call-0"); + + const parsed = AiChatResponseSchema.parse(response); + expect(parsed.choices[0].finish_reason).toEqual("stop"); + expect(parsed.choices[0].message.content).toEqual("Order A-1 has shipped."); + }); + + it("keeps a malformed tool call instead of failing the request", async () => { + const { run, requests } = scriptedModel([generation([{ type: "text", text: "ok" }])]); + const agent = create.run(context(), "support", "", run); + + await invoke.run(context(), agent, "again?", { + messages: [ + { + role: "assistant", + content: null, + tool_calls: [ + { id: "call-0", type: "function", function: { name: "tool_1", arguments: "{broken" } }, + ], + }, + ], + }); + + const asked = requests[0].messages.find((message) => message.role === "ai"); + expect(asked?.content[0]).toMatchObject({ type: "invalid_tool_call", id: "call-0", args: "{broken" }); + }); + + it("does not carry a reasoning block out, because the format has no field for it", async () => { + const { run } = scriptedModel([ + generation([ + { type: "reasoning", reasoning: "the user greeted me" }, + { type: "text", text: "Hi." }, + ]), + ]); + const agent = create.run(context(), "greeter", "", run); + + const response = await invoke.run(context(), agent, "hello"); + + expect(response.choices[0].message.content).toEqual("Hi."); + }); + + it("takes just a prompt, with no request at all", async () => { + const { run, requests } = scriptedModel([generation([{ type: "text", text: "Hi." }])]); + const agent = create.run(context(), "greeter", "", run); + + const response = await invoke.run(context(), agent, "hello"); + + expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "hello" }]); + expect(response.choices[0].message.content).toEqual("Hi."); + }); + + it("appends the prompt to the conversation the request carries", async () => { + const { run, requests } = scriptedModel([generation([{ type: "text", text: "Still fine." }])]); + const agent = create.run(context(), "greeter", "", run); + + await invoke.run(context(), agent, "and now?", { + messages: [ + { role: "user", content: "how are you?" }, + { role: "assistant", content: "fine" }, + ], + }); + + expect(requests[0].messages.map((message) => message.role)).toEqual(["human", "ai", "human"]); + expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "and now?" }]); + }); + + it("rejects anything that is not an agent", async () => { + await expect(invoke.run(context(), { id: "agent-1" } as never, "hello")).rejects.toThrow(/has to be an agent/); + }); + + it("rejects having nothing to ask", async () => { + const { run } = scriptedModel([generation([{ type: "text", text: "ok" }])]); + const agent = create.run(context(), "greeter", "", run); + + await expect(invoke.run(context(), agent, "")).rejects.toThrow(/nothing to ask/); + await expect(invoke.run(context(), agent, "", { messages: [] })).rejects.toThrow(/nothing to ask/); + await expect(invoke.run(context(), agent, "hi", { messages: "nope" } as never)).rejects.toThrow(/not valid/); + }); +}); diff --git a/actions/ai-action/tsconfig.json b/actions/ai-action/tsconfig.json new file mode 100644 index 0000000..d013e69 --- /dev/null +++ b/actions/ai-action/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "moduleResolution": "Bundler", + "declaration": true, + "outDir": "dist", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "allowImportingTsExtensions": true, + "noEmit": true, + "baseUrl": ".", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "types": ["node", "vite/client"] + }, + "include": [ + "src/**/*", + "test/**/*", + "vite.config.ts" + ] +} \ No newline at end of file diff --git a/actions/ai-action/vite.config.ts b/actions/ai-action/vite.config.ts new file mode 100644 index 0000000..dc45894 --- /dev/null +++ b/actions/ai-action/vite.config.ts @@ -0,0 +1,18 @@ +import { defineConfig } from 'vite'; +import { resolve } from 'path'; + +export default defineConfig({ + build: { + target: "node18", + ssr: resolve(__dirname, 'src/index.ts'), + rollupOptions: { + external: (id) => + [ + 'fs', + 'path', + 'typescript', + '@code0-tech/hercules' + ].includes(id) || id.startsWith('node:') + } + } +}); From 7e759e972d533e11a54042b6d05f0fdc7b645823 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Wed, 4 Nov 2026 18:05:30 +0100 Subject: [PATCH 02/19] feat: enhance agent and middleware definitions with runtime function interfaces for improved type safety --- .../datatypes/Agent.transform.datatype.ts | 10 ++- .../Agent.create.runtimefunction.ts | 18 +++-- .../Agent.invoke.runtimefunction.ts | 3 +- actions/ai-action/src/index.ts | 2 +- .../Middleware.transform.datatype.ts | 10 ++- ...Middleware.trimMessages.runtimefunction.ts | 42 +++++++----- .../datatypes/Model.transform.datatype.ts | 10 ++- .../Model.openRouter.runtimefunction.ts | 66 ++++++++++--------- 8 files changed, 100 insertions(+), 61 deletions(-) diff --git a/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts b/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts index 5acf945..962a13c 100644 --- a/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts +++ b/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts @@ -1,4 +1,12 @@ +import type { SubFlowFunctionDefinition } from "@code0-tech/hercules"; import type { AiAgentRequest } from "./Agent.request.datatype.js"; import type { AiAgentResponse } from "./Agent.response.datatype.js"; -export type AiAgentTransform = (request: AiAgentRequest) => Promise; +/** + * An agent returned from a runtime function. Hercules only turns a returned value + * into a sub flow the flow can invoke when it is a {@link SubFlowFunctionDefinition}; + * a bare closure reaches the value serializer and is rejected as an unsupported type. + */ +export interface AiAgentTransform extends SubFlowFunctionDefinition { + run(request: AiAgentRequest): Promise; +} diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts index 88a4846..3b92710 100644 --- a/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts +++ b/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts @@ -9,11 +9,9 @@ import { SubFlow, ThrowsError, } from "@code0-tech/hercules"; -import type { AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; -import type { AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; +import { AiAgentRequestSchema, type AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; +import { AiAgentResponseSchema, type AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; import type { AiAgentTransform } from "../datatypes/Agent.transform.datatype.js"; -import type { AiMiddlewareTransform } from "../../middleware/datatypes/Middleware.transform.datatype.js"; -import type { AiModelTransform } from "../../model/datatypes/Model.transform.datatype.js"; import { asList } from "../../shared/utils/Shared.asList.util.js"; import { asSubFlow } from "../../shared/utils/Shared.asSubFlow.util.js"; import { asText } from "../../shared/utils/Shared.asText.util.js"; @@ -59,9 +57,9 @@ export class CreateAgentFunction { _context: FunctionContext, name: string, system_prompt: string, - model: AiModelTransform, + model: unknown, tools?: ToolEntry[], - middleware?: (AiMiddlewareTransform)[], + middleware?: unknown[], ): AiAgentTransform { const definition: AgentDefinition = { name: requireText(name, "ERROR_INVALID_AI_AGENT", "An agent needs a name."), @@ -74,6 +72,12 @@ export class CreateAgentFunction { }; validateMcpServers(toolServers(definition.tools)); - return (request: AiAgentRequest): Promise => runAgent(definition, request); + return { + name: `agent:${definition.name}`, + description: definition.systemPrompt || `The agent ${definition.name}`, + inputSchema: AiAgentRequestSchema, + outputSchema: AiAgentResponseSchema, + run: (request: AiAgentRequest): Promise => runAgent(definition, request), + }; } } diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts index b480fed..15e8932 100644 --- a/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts +++ b/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts @@ -9,7 +9,6 @@ import { Signature, ThrowsError, } from "@code0-tech/hercules"; -import type { AiAgentTransform } from "../datatypes/Agent.transform.datatype.js"; import { AiAgentResponseSchema, type AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; import type { AiChatResponse } from "../../chat/datatypes/Chat.response.datatype.js"; import { AiChatRequestSchema, type AiChatRequest } from "../../chat/datatypes/Chat.request.datatype.js"; @@ -44,7 +43,7 @@ import { toConversation } from "../../chat/utils/Chat.toConversation.util.js"; export class InvokeAgentFunction { async run( _context: FunctionContext, - agent: AiAgentTransform, + agent: unknown, prompt: string, request?: AiChatRequest, ): Promise { diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts index cbc1bab..0d95d54 100644 --- a/actions/ai-action/src/index.ts +++ b/actions/ai-action/src/index.ts @@ -76,7 +76,7 @@ const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ ]; const action = new Action( - process.env.ACTION_ID ?? "ai-action", + process.env.ACTION_ID ?? "testing-action", process.env.VERSION ?? "1.0.0", process.env.AQUILA_URL ?? "127.0.0.1:8081", "code0-tech", diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts b/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts index 6409acf..6f2d68e 100644 --- a/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts +++ b/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts @@ -1,4 +1,12 @@ +import type { SubFlowFunctionDefinition } from "@code0-tech/hercules"; import type { AiAgentState } from "./Middleware.agentState.datatype.js"; import type { AiStateUpdate } from "./Middleware.stateUpdate.datatype.js"; -export type AiMiddlewareTransform = (state: AiAgentState) => Promise; +/** + * A middleware returned from a runtime function. Hercules only turns a returned value + * into a sub flow the flow can invoke when it is a {@link SubFlowFunctionDefinition}; + * a bare closure reaches the value serializer and is rejected as an unsupported type. + */ +export interface AiMiddlewareTransform extends SubFlowFunctionDefinition { + run(state: AiAgentState): Promise; +} diff --git a/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts b/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts index b627007..0f4d0f9 100644 --- a/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts +++ b/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts @@ -14,7 +14,7 @@ import { countTokensApproximately, trimMessages } from "langchain"; import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; import type { AiMiddlewareTransform } from "../datatypes/Middleware.transform.datatype.js"; -import type { AiStateUpdate } from "../datatypes/Middleware.stateUpdate.datatype.js"; +import { AiStateUpdateSchema, type AiStateUpdate } from "../datatypes/Middleware.stateUpdate.datatype.js"; import { AiAgentStateSchema, type AiAgentState } from "../datatypes/Middleware.agentState.datatype.js"; import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; @@ -63,26 +63,32 @@ export class TrimMessagesMiddlewareFunction { const trimStrategy: TrimStrategy = strategy === "first" ? "first" : "last"; const includeSystem: boolean = keep_system ?? true; - return async (state: AiAgentState): Promise => { - const parsed: AiAgentState = parseOrThrow( - AiAgentStateSchema, - state, - "ERROR_INVALID_AI_AGENT_STATE", - "The agent state is not valid", - ); + return { + name: `trim_messages:${trimStrategy}:${max_tokens}`, + description: `Trims the conversation to ${max_tokens} tokens`, + inputSchema: AiAgentStateSchema, + outputSchema: AiStateUpdateSchema, + run: async (state: AiAgentState): Promise => { + const parsed: AiAgentState = parseOrThrow( + AiAgentStateSchema, + state, + "ERROR_INVALID_AI_AGENT_STATE", + "The agent state is not valid", + ); - const trimmed: BaseMessage[] = await trimMessages(parsed.messages.map(toLangChainMessage), { - maxTokens: max_tokens, - tokenCounter: countTokensApproximately, - strategy: trimStrategy, - includeSystem, - allowPartial: false, - startOn: "human", - }); + const trimmed: BaseMessage[] = await trimMessages(parsed.messages.map(toLangChainMessage), { + maxTokens: max_tokens, + tokenCounter: countTokensApproximately, + strategy: trimStrategy, + includeSystem, + allowPartial: false, + startOn: "human", + }); - if (trimmed.length === parsed.messages.length) return {}; + if (trimmed.length === parsed.messages.length) return {}; - return { messages: trimmed.map(toFlowMessage) }; + return { messages: trimmed.map(toFlowMessage) }; + }, }; } } diff --git a/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts b/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts index 6b8215b..52d2348 100644 --- a/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts +++ b/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts @@ -1,4 +1,12 @@ +import type { SubFlowFunctionDefinition } from "@code0-tech/hercules"; import type { AiModelRequest } from "./Model.request.datatype.js"; import type { AiModelResponse } from "./Model.response.datatype.js"; -export type AiModelTransform = (request: AiModelRequest) => Promise; +/** + * A model returned from a runtime function. Hercules only turns a returned value into + * a sub flow the flow can invoke when it is a {@link SubFlowFunctionDefinition}; a + * bare closure reaches the value serializer and is rejected as an unsupported type. + */ +export interface AiModelTransform extends SubFlowFunctionDefinition { + run(request: AiModelRequest): Promise; +} diff --git a/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts index a319561..9c51504 100644 --- a/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts +++ b/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts @@ -15,7 +15,7 @@ import type { Runnable } from "@langchain/core/runnables"; import { ChatOpenAI, type ChatOpenAICallOptions } from "@langchain/openai"; import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; -import type { AiModelResponse } from "../datatypes/Model.response.datatype.js"; +import { AiModelResponseSchema, type AiModelResponse } from "../datatypes/Model.response.datatype.js"; import type { AiModelTransform } from "../datatypes/Model.transform.datatype.js"; import { AiModelRequestSchema, type AiModelRequest } from "../datatypes/Model.request.datatype.js"; import { describeError } from "../../shared/utils/Shared.describeError.util.js"; @@ -82,38 +82,44 @@ export class OpenRouterModelFunction { maxTokens: max_tokens, }); - return async (request: AiModelRequest): Promise => { - const parsed: AiModelRequest = parseOrThrow( - AiModelRequestSchema, - request, - "ERROR_INVALID_AI_MODEL_REQUEST", - "The model request is not valid", - ); + return { + name: `openrouter:${identifier}`, + description: `OpenRouter model ${identifier}`, + inputSchema: AiModelRequestSchema, + outputSchema: AiModelResponseSchema, + run: async (request: AiModelRequest): Promise => { + const parsed: AiModelRequest = parseOrThrow( + AiModelRequestSchema, + request, + "ERROR_INVALID_AI_MODEL_REQUEST", + "The model request is not valid", + ); - const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.input_schema, - }, - })); - const bound: BoundModel = tools.length > 0 ? chat.bindTools(tools) : chat; - const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); + const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.input_schema, + }, + })); + const bound: BoundModel = tools.length > 0 ? chat.bindTools(tools) : chat; + const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); - const answer: AIMessage = await bound - .invoke(messages, { - ...(parsed.stop ? { stop: parsed.stop } : {}), - ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), - }) - .catch((error: unknown) => { - throw new RuntimeError( - "ERROR_AI_MODEL_CALL_FAILED", - `The OpenRouter call to "${identifier}" failed: ${describeError(error)}`, - ); - }); + const answer: AIMessage = await bound + .invoke(messages, { + ...(parsed.stop ? { stop: parsed.stop } : {}), + ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), + }) + .catch((error: unknown) => { + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The OpenRouter call to "${identifier}" failed: ${describeError(error)}`, + ); + }); - return { message: toFlowMessage(answer) }; + return { message: toFlowMessage(answer) }; + }, }; } } From 6c526f62d750670ed8e0bf574ca1e8521e44094a Mon Sep 17 00:00:00 2001 From: nicosammito Date: Wed, 4 Nov 2026 18:05:38 +0100 Subject: [PATCH 03/19] deps: update @code0-tech/hercules and @code0-tech/tucana to latest versions for improved functionality --- actions/ai-action/package-lock.json | 16 ++++++++-------- actions/ai-action/package.json | 2 +- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/actions/ai-action/package-lock.json b/actions/ai-action/package-lock.json index 44c14c8..1ae7183 100644 --- a/actions/ai-action/package-lock.json +++ b/actions/ai-action/package-lock.json @@ -8,7 +8,7 @@ "name": "@code0-tech/ai-action", "version": "1.0.0", "dependencies": { - "@code0-tech/hercules": "^1.6.0", + "@code0-tech/hercules": "^1.7.2", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", @@ -85,15 +85,15 @@ } }, "node_modules/@code0-tech/hercules": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.6.0.tgz", - "integrity": "sha512-1Ed4RcLdjFuTLUHuYP5yu3nQpHQDiE8gg0d4ZYFt/gRbKfHTPhmwxZ/V/Rj0Y0BxLLooIdc8bNKa2UgDxK+aqw==", + "version": "1.7.2", + "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.7.2.tgz", + "integrity": "sha512-xRfolLdKOWC+oiNa7XRo8EeQSylwgq6XkcLhB0YocU8XeEc7qSaHWKJSNnhIDLOmAZzpa7OmpxZj6YFeweUqJg==", "license": "ISC", "bin": { "hercules": "bin/hercules.js" }, "peerDependencies": { - "@code0-tech/tucana": "0.0.82", + "@code0-tech/tucana": "0.0.83", "@grpc/grpc-js": "^1.14.3", "@protobuf-ts/grpc-backend": "^2.11.1", "@protobuf-ts/grpc-transport": "^2.11.1", @@ -107,9 +107,9 @@ } }, "node_modules/@code0-tech/tucana": { - "version": "0.0.82", - "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.82.tgz", - "integrity": "sha512-9ImPNeGV09BeLT0M8/F08DHDe10MO6UI/VfE7i2aEYtRsB9DS3jIAGrcMEV67RXdmAj5ZWTtvxWVGOkem0CljQ==", + "version": "0.0.83", + "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.83.tgz", + "integrity": "sha512-scBOjgf3oIQF8pUlskqPHqfzPvgCJgG1+/tt9RAKWZ1IdCdSqTRG768uEVeTjpuryiGRiO0p8r4bCXNEQNRtRg==", "license": "MIT", "peer": true }, diff --git a/actions/ai-action/package.json b/actions/ai-action/package.json index 008870b..1325be8 100644 --- a/actions/ai-action/package.json +++ b/actions/ai-action/package.json @@ -12,7 +12,7 @@ "start": "node dist/index.js" }, "dependencies": { - "@code0-tech/hercules": "^1.6.0", + "@code0-tech/hercules": "^1.7.2", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", From 30c0b4854ecc249f16ed22e8d4c27157a74f15cf Mon Sep 17 00:00:00 2001 From: nicosammito Date: Sat, 7 Nov 2026 02:49:42 +0100 Subject: [PATCH 04/19] feat: add new utility functions and data types for enhanced agent and chat functionalities, update Dockerfile to expose default port --- actions/ai-action/Dockerfile | 3 + actions/ai-action/package-lock.json | 76 +-- actions/ai-action/package.json | 3 +- .../datatypes/Agent.transform.datatype.ts | 12 - .../Agent.create.runtimefunction.ts | 83 --- .../Agent.invoke.runtimefunction.ts | 88 --- .../agent/utils/Agent.asToolEntries.util.ts | 20 - .../agent/utils/Agent.buildFlowTools.util.ts | 24 - .../agent/utils/Agent.compileAgent.util.ts | 50 -- .../src/agent/utils/Agent.runAgent.util.ts | 30 - .../src/agent/utils/Agent.toolServers.util.ts | 7 - .../chat/datatypes/Chat.response.datatype.ts | 20 - .../chat/utils/Chat.fromChatMessage.util.ts | 25 - .../src/chat/utils/Chat.reportedModel.util.ts | 8 - .../src/chat/utils/Chat.toChatMessage.util.ts | 27 - .../chat/utils/Chat.toChatResponse.util.ts | 22 - .../chat/utils/Chat.toChatToolCalls.util.ts | 16 - .../src/chat/utils/Chat.toChatUsage.util.ts | 13 - .../chat/utils/Chat.toContentBlock.util.ts | 9 - .../chat/utils/Chat.toContentBlocks.util.ts | 9 - .../chat/utils/Chat.toConversation.util.ts | 10 - .../src/chat/utils/Chat.toImageBlock.util.ts | 12 - .../chat/utils/Chat.toToolCallBlock.util.ts | 22 - .../agent/Agent.approval.datatype.ts | 28 + .../agent}/Agent.request.datatype.ts | 3 +- .../agent}/Agent.response.datatype.ts | 8 +- .../datatypes/agent/Agent.step.datatype.ts | 26 + .../chat}/Chat.choice.datatype.ts | 0 .../chat}/Chat.contentPart.datatype.ts | 0 .../chat}/Chat.message.datatype.ts | 0 .../chat}/Chat.request.datatype.ts | 0 .../datatypes/chat/Chat.response.datatype.ts | 54 ++ .../chat}/Chat.role.datatype.ts | 0 .../chat}/Chat.toolCall.datatype.ts | 0 .../chat}/Chat.usage.datatype.ts | 0 .../mcp}/Mcp.server.datatype.ts | 0 .../mcp}/Mcp.transport.datatype.ts | 0 .../message}/Message.contentBlock.datatype.ts | 0 .../message}/Message.datatype.ts | 0 .../message}/Message.role.datatype.ts | 0 .../message}/Message.toolStatus.datatype.ts | 0 .../Middleware.agentState.datatype.ts | 3 +- .../middleware}/Middleware.hook.datatype.ts | 0 .../Middleware.stateUpdate.datatype.ts | 2 +- .../Middleware.transform.datatype.ts | 0 .../model}/Model.request.datatype.ts | 7 +- .../model}/Model.response.datatype.ts | 2 +- .../model/Model.responseFormat.datatype.ts | 25 + .../model}/Model.toolChoice.datatype.ts | 0 .../model}/Model.toolSpec.datatype.ts | 0 .../model}/Model.transform.datatype.ts | 0 actions/ai-action/src/index.ts | 145 +++-- .../src/mcp/utils/Mcp.buildMcpTools.util.ts | 30 - .../src/mcp/utils/Mcp.discoverTools.util.ts | 16 - .../mcp/utils/Mcp.validateMcpServers.util.ts | 16 - .../utils/Message.replaceMessages.util.ts | 11 - .../message/utils/Message.toAiMessage.util.ts | 14 - .../utils/Message.toInvalidToolCalls.util.ts | 13 - .../utils/Message.toLangChainMessage.util.ts | 20 - .../utils/Message.toMessageFields.util.ts | 22 - .../message/utils/Message.toToolCalls.util.ts | 12 - .../utils/Message.toToolMessage.util.ts | 12 - .../Middleware.buildFlowMiddlewares.util.ts | 16 - .../Middleware.createHookHandler.util.ts | 31 - .../utils/Middleware.toFlowState.util.ts | 31 - .../src/model/Model.flowChatModel.ts | 200 ++++++ .../Model.openRouter.runtimefunction.ts | 125 ---- .../model/utils/Model.flowChatModel.util.ts | 72 --- .../src/model/utils/Model.toToolSpec.util.ts | 15 - .../openai/OpenAi.server.runtimeevent.ts | 81 +++ .../agent/Agent.create.runtimefunction.ts | 611 ++++++++++++++++++ ...ddleware.humanInTheLoop.runtimefunction.ts | 256 ++++++++ ...Middleware.trimMessages.runtimefunction.ts | 33 +- .../model/Model.openRouter.runtimefunction.ts | 314 +++++++++ ...nAi.openWebUiFormatting.runtimefunction.ts | 118 ++++ .../openai/OpenAi.respond.runtimefunction.ts | 63 ++ .../src/server/openai/OpenAi.server.ts | 349 ++++++++++ .../src/server/openai/OpenAi.startServer.ts | 20 + .../shared/utils/Shared.toInputSchema.util.ts | 12 - .../ai-action/src/types/agent/Agent.types.ts | 16 + .../src/types/message/Message.types.ts | 9 + .../src/types/middleware/Approval.types.ts | 17 + .../src/types/middleware/Middleware.types.ts | 16 + .../src/types/openai/OpenAi.types.ts | 40 ++ .../src/types/openai/OpenAiServer.types.ts | 25 + .../ai-action/src/types/shared/Log.types.ts | 15 + .../ai-action/src/types/shared/Proto.types.ts | 4 + .../utils/chat/Chat.fromChatMessage.util.ts | 73 +++ .../chat}/Chat.toChatContent.util.ts | 2 +- .../src/utils/chat/Chat.toChatMessage.util.ts | 38 ++ .../utils/chat/Chat.toChatResponse.util.ts | 64 ++ .../mcp}/Mcp.toConnection.util.ts | 2 +- .../src/utils/message/Message.textOf.util.ts | 14 + .../message}/Message.toFlowMessage.util.ts | 17 +- .../Message.toLangChainMessage.util.ts | 59 ++ .../utils/middleware/Approval.askFor.util.ts | 13 + .../utils/middleware/Approval.codeOf.util.ts | 10 + .../middleware/Approval.describeCall.util.ts | 7 + .../utils/middleware/Approval.markers.util.ts | 17 + .../utils/middleware/Approval.newCode.util.ts | 4 + .../utils/middleware/Approval.settle.util.ts | 9 + .../Middleware.createHookHandler.util.ts | 53 ++ .../utils/openai/OpenAi.corsHeaders.util.ts | 11 + .../src/utils/openai/OpenAi.errorBody.util.ts | 6 + .../openai/OpenAi.normalizeRoute.util.ts | 11 + .../src/utils/openai/OpenAi.parsePath.util.ts | 32 + .../src/utils/openai/OpenAi.pending.util.ts | 54 ++ .../src/utils/openai/OpenAi.sendJson.util.ts | 16 + .../utils/openai/OpenAi.textSetting.util.ts | 17 + .../utils/openai/OpenAi.toEndpoints.util.ts | 39 ++ .../utils/openai/OpenAi.toModelList.util.ts | 22 + .../src/utils/openai/OpenAi.toStream.util.ts | 44 ++ .../utils/shared/Log.describeValue.util.ts | 28 + .../src/utils/shared/Log.emit.util.ts | 38 ++ .../src/utils/shared/Log.logger.util.ts | 18 + .../shared}/Shared.asList.util.ts | 0 .../shared}/Shared.asSubFlow.util.ts | 0 .../shared}/Shared.asText.util.ts | 0 .../shared}/Shared.connectToAquila.util.ts | 0 .../shared}/Shared.describeError.util.ts | 0 .../shared}/Shared.emptyJsonSchema.util.ts | 0 .../shared}/Shared.formatIssues.util.ts | 0 .../shared/Shared.fromProtoValue.util.ts | 34 + .../shared}/Shared.hasEntries.util.ts | 0 .../shared}/Shared.isSubFlow.util.ts | 0 .../shared}/Shared.parseOrThrow.util.ts | 0 .../shared}/Shared.requireText.util.ts | 0 .../shared/Shared.stripUndefined.util.ts | 29 + .../utils/shared/Shared.toPlainSchema.util.ts | 33 + .../datatypes/WebSearch.hit.datatype.ts | 16 - .../datatypes/WebSearch.result.datatype.ts | 16 - .../WebSearch.search.runtimefunction.ts | 74 --- .../WebSearch.parseSearchPayload.util.ts | 9 - .../utils/WebSearch.toSearchResult.util.ts | 28 - actions/ai-action/test/agent.test.ts | 407 ++++++++++-- actions/ai-action/test/approval.test.ts | 305 +++++++++ actions/ai-action/test/dataTypes.test.ts | 22 +- actions/ai-action/test/functions.test.ts | 287 +++++--- actions/ai-action/test/log.test.ts | 86 +++ actions/ai-action/test/openai.test.ts | 548 ++++++++++++++++ actions/ai-action/test/registration.test.ts | 81 +++ actions/ai-action/test/stripUndefined.test.ts | 72 +++ 142 files changed, 4923 insertions(+), 1389 deletions(-) delete mode 100644 actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts delete mode 100644 actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts delete mode 100644 actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts delete mode 100644 actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts delete mode 100644 actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts delete mode 100644 actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts delete mode 100644 actions/ai-action/src/agent/utils/Agent.runAgent.util.ts delete mode 100644 actions/ai-action/src/agent/utils/Agent.toolServers.util.ts delete mode 100644 actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toConversation.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts delete mode 100644 actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts create mode 100644 actions/ai-action/src/datatypes/agent/Agent.approval.datatype.ts rename actions/ai-action/src/{agent/datatypes => datatypes/agent}/Agent.request.datatype.ts (80%) rename actions/ai-action/src/{agent/datatypes => datatypes/agent}/Agent.response.datatype.ts (54%) create mode 100644 actions/ai-action/src/datatypes/agent/Agent.step.datatype.ts rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.choice.datatype.ts (100%) rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.contentPart.datatype.ts (100%) rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.message.datatype.ts (100%) rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.request.datatype.ts (100%) create mode 100644 actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.role.datatype.ts (100%) rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.toolCall.datatype.ts (100%) rename actions/ai-action/src/{chat/datatypes => datatypes/chat}/Chat.usage.datatype.ts (100%) rename actions/ai-action/src/{mcp/datatypes => datatypes/mcp}/Mcp.server.datatype.ts (100%) rename actions/ai-action/src/{mcp/datatypes => datatypes/mcp}/Mcp.transport.datatype.ts (100%) rename actions/ai-action/src/{message/datatypes => datatypes/message}/Message.contentBlock.datatype.ts (100%) rename actions/ai-action/src/{message/datatypes => datatypes/message}/Message.datatype.ts (100%) rename actions/ai-action/src/{message/datatypes => datatypes/message}/Message.role.datatype.ts (100%) rename actions/ai-action/src/{message/datatypes => datatypes/message}/Message.toolStatus.datatype.ts (100%) rename actions/ai-action/src/{middleware/datatypes => datatypes/middleware}/Middleware.agentState.datatype.ts (86%) rename actions/ai-action/src/{middleware/datatypes => datatypes/middleware}/Middleware.hook.datatype.ts (100%) rename actions/ai-action/src/{middleware/datatypes => datatypes/middleware}/Middleware.stateUpdate.datatype.ts (88%) rename actions/ai-action/src/{middleware/datatypes => datatypes/middleware}/Middleware.transform.datatype.ts (100%) rename actions/ai-action/src/{model/datatypes => datatypes/model}/Model.request.datatype.ts (62%) rename actions/ai-action/src/{model/datatypes => datatypes/model}/Model.response.datatype.ts (85%) create mode 100644 actions/ai-action/src/datatypes/model/Model.responseFormat.datatype.ts rename actions/ai-action/src/{model/datatypes => datatypes/model}/Model.toolChoice.datatype.ts (100%) rename actions/ai-action/src/{model/datatypes => datatypes/model}/Model.toolSpec.datatype.ts (100%) rename actions/ai-action/src/{model/datatypes => datatypes/model}/Model.transform.datatype.ts (100%) delete mode 100644 actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts delete mode 100644 actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts delete mode 100644 actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.replaceMessages.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toAiMessage.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toMessageFields.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toToolCalls.util.ts delete mode 100644 actions/ai-action/src/message/utils/Message.toToolMessage.util.ts delete mode 100644 actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts delete mode 100644 actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts delete mode 100644 actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts create mode 100644 actions/ai-action/src/model/Model.flowChatModel.ts delete mode 100644 actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts delete mode 100644 actions/ai-action/src/model/utils/Model.flowChatModel.util.ts delete mode 100644 actions/ai-action/src/model/utils/Model.toToolSpec.util.ts create mode 100644 actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts create mode 100644 actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts rename actions/ai-action/src/{middleware/runtimefunctions => runtimefunctions/middleware}/Middleware.trimMessages.runtimefunction.ts (68%) create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts create mode 100644 actions/ai-action/src/server/openai/OpenAi.server.ts create mode 100644 actions/ai-action/src/server/openai/OpenAi.startServer.ts delete mode 100644 actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts create mode 100644 actions/ai-action/src/types/agent/Agent.types.ts create mode 100644 actions/ai-action/src/types/message/Message.types.ts create mode 100644 actions/ai-action/src/types/middleware/Approval.types.ts create mode 100644 actions/ai-action/src/types/middleware/Middleware.types.ts create mode 100644 actions/ai-action/src/types/openai/OpenAi.types.ts create mode 100644 actions/ai-action/src/types/openai/OpenAiServer.types.ts create mode 100644 actions/ai-action/src/types/shared/Log.types.ts create mode 100644 actions/ai-action/src/types/shared/Proto.types.ts create mode 100644 actions/ai-action/src/utils/chat/Chat.fromChatMessage.util.ts rename actions/ai-action/src/{chat/utils => utils/chat}/Chat.toChatContent.util.ts (79%) create mode 100644 actions/ai-action/src/utils/chat/Chat.toChatMessage.util.ts create mode 100644 actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts rename actions/ai-action/src/{mcp/utils => utils/mcp}/Mcp.toConnection.util.ts (94%) create mode 100644 actions/ai-action/src/utils/message/Message.textOf.util.ts rename actions/ai-action/src/{message/utils => utils/message}/Message.toFlowMessage.util.ts (61%) create mode 100644 actions/ai-action/src/utils/message/Message.toLangChainMessage.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.askFor.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.codeOf.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.describeCall.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.markers.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.newCode.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Approval.settle.util.ts create mode 100644 actions/ai-action/src/utils/middleware/Middleware.createHookHandler.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.corsHeaders.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.errorBody.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.normalizeRoute.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.parsePath.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.pending.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.textSetting.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.toModelList.util.ts create mode 100644 actions/ai-action/src/utils/openai/OpenAi.toStream.util.ts create mode 100644 actions/ai-action/src/utils/shared/Log.describeValue.util.ts create mode 100644 actions/ai-action/src/utils/shared/Log.emit.util.ts create mode 100644 actions/ai-action/src/utils/shared/Log.logger.util.ts rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.asList.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.asSubFlow.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.asText.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.connectToAquila.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.describeError.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.emptyJsonSchema.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.formatIssues.util.ts (100%) create mode 100644 actions/ai-action/src/utils/shared/Shared.fromProtoValue.util.ts rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.hasEntries.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.isSubFlow.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.parseOrThrow.util.ts (100%) rename actions/ai-action/src/{shared/utils => utils/shared}/Shared.requireText.util.ts (100%) create mode 100644 actions/ai-action/src/utils/shared/Shared.stripUndefined.util.ts create mode 100644 actions/ai-action/src/utils/shared/Shared.toPlainSchema.util.ts delete mode 100644 actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts delete mode 100644 actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts delete mode 100644 actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts delete mode 100644 actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts delete mode 100644 actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts create mode 100644 actions/ai-action/test/approval.test.ts create mode 100644 actions/ai-action/test/log.test.ts create mode 100644 actions/ai-action/test/openai.test.ts create mode 100644 actions/ai-action/test/registration.test.ts create mode 100644 actions/ai-action/test/stripUndefined.test.ts diff --git a/actions/ai-action/Dockerfile b/actions/ai-action/Dockerfile index 8d9f6c7..5e636be 100644 --- a/actions/ai-action/Dockerfile +++ b/actions/ai-action/Dockerfile @@ -10,4 +10,7 @@ COPY . . RUN npm run build +# The action serves the OpenAI protocol itself, on AI_OPENAI_PORT (8080 by default). +EXPOSE 8080 + CMD ["npm", "run", "start"] diff --git a/actions/ai-action/package-lock.json b/actions/ai-action/package-lock.json index 1ae7183..f1de115 100644 --- a/actions/ai-action/package-lock.json +++ b/actions/ai-action/package-lock.json @@ -8,7 +8,7 @@ "name": "@code0-tech/ai-action", "version": "1.0.0", "dependencies": { - "@code0-tech/hercules": "^1.7.2", + "@code0-tech/hercules": "^1.8.0", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", @@ -16,7 +16,6 @@ "@langchain/mistralai": "^1.0.0", "@langchain/ollama": "^1.0.0", "@langchain/openai": "^1.6.2", - "@langchain/tavily": "^1.2.0", "langchain": "^1.5.16" }, "devDependencies": { @@ -58,9 +57,9 @@ } }, "node_modules/@cfworker/json-schema": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.1.tgz", - "integrity": "sha512-gAmrUZSGtKc3AiBL71iNWxDsyUC5uMaKKGdvzYsBoTW/xi42JQHl7eKV2OYzCUqvc+D2RCcf7EXY2iCyFIk6og==", + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@cfworker/json-schema/-/json-schema-4.1.6.tgz", + "integrity": "sha512-YzVGTHXf4bzlyAL5KAvHYCdNbbt6zM5cYkAgxqxQPDQM6aZ4ShIIN5yJ+6q7YeonnevxT8k/LmD2tJi/jOiKkg==", "license": "MIT" }, "node_modules/@clack/core": { @@ -85,15 +84,15 @@ } }, "node_modules/@code0-tech/hercules": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.7.2.tgz", - "integrity": "sha512-xRfolLdKOWC+oiNa7XRo8EeQSylwgq6XkcLhB0YocU8XeEc7qSaHWKJSNnhIDLOmAZzpa7OmpxZj6YFeweUqJg==", + "version": "1.8.0", + "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.8.0.tgz", + "integrity": "sha512-0zIDkZoPneZP5a0wPjJEnOLMTTvJ6JeAco9JFVXzkui+S69g2WDFX92V8rm+29sIPorzgxy4Nvnn8M9TFhcF7A==", "license": "ISC", "bin": { "hercules": "bin/hercules.js" }, "peerDependencies": { - "@code0-tech/tucana": "0.0.83", + "@code0-tech/tucana": "0.0.84", "@grpc/grpc-js": "^1.14.3", "@protobuf-ts/grpc-backend": "^2.11.1", "@protobuf-ts/grpc-transport": "^2.11.1", @@ -107,9 +106,9 @@ } }, "node_modules/@code0-tech/tucana": { - "version": "0.0.83", - "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.83.tgz", - "integrity": "sha512-scBOjgf3oIQF8pUlskqPHqfzPvgCJgG1+/tt9RAKWZ1IdCdSqTRG768uEVeTjpuryiGRiO0p8r4bCXNEQNRtRg==", + "version": "0.0.84", + "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.84.tgz", + "integrity": "sha512-Rom4uDDrfRaC6YyLlxdqAmMDe4n6OuEdtzBukidYJXwIrMkz626/9sKZ9gSmqdCq0FfHEb3R+PpFbpg7KClEEw==", "license": "MIT", "peer": true }, @@ -621,16 +620,16 @@ } }, "node_modules/@langchain/core": { - "version": "1.2.17", - "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.2.17.tgz", - "integrity": "sha512-aLQLSed6oLCMLtJHrINhnFmsu79G2UiDlRslbOx+TSN9NmU+WuDv1OtVxrLpYglhXNy53elSduMVk3XBPG9ulw==", + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.3.5.tgz", + "integrity": "sha512-7mk6lrHhD9vGZ+HnUhbHJzWTuJVktV+XSgDFmDlFu6qOHuNao4iuu5wqOgFNyx3Khjv7PydgbWOwcYeRXZ/ygA==", "license": "MIT", "peer": true, "dependencies": { - "@cfworker/json-schema": "^4.0.2", + "@cfworker/json-schema": "^4.1.4", "@standard-schema/spec": "^1.1.0", "js-tiktoken": "^1.0.12", - "langsmith": ">=0.5.0 <1.0.0", + "langsmith": ">=0.11.0 <1.0.0", "mustache": "^4.2.0", "p-queue": "^6.6.2", "zod": "^3.25.76 || ^4" @@ -687,18 +686,18 @@ } }, "node_modules/@langchain/langgraph-sdk": { - "version": "1.12.3", - "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.12.3.tgz", - "integrity": "sha512-o5Qd1pepsJKHmHGIcWhOlZe2fvlPs2AEkVOxqzbL3R8IiMBPH2gNG8/kwK36czEnagiJtu4RUn02mKbGRwd5dQ==", + "version": "1.12.10", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.12.10.tgz", + "integrity": "sha512-S4YI8GNMotQsIuLbQFNfReooWmxkpYoD2p3Wn/aUgObWV2dxUi8qexs95XSOd12as9OPoDEp0sl8/cisbrNMKA==", "license": "MIT", "dependencies": { - "@langchain/protocol": "^0.0.19", + "@langchain/protocol": "^0.0.20", "@types/json-schema": "^7.0.15", "p-queue": "^9.0.1", "p-retry": "^7.1.1" }, "peerDependencies": { - "@langchain/core": "^1.1.48", + "@langchain/core": "^1.3.2", "react": "^18 || ^19", "react-dom": "^18 || ^19" }, @@ -711,6 +710,12 @@ } } }, + "node_modules/@langchain/langgraph-sdk/node_modules/@langchain/protocol": { + "version": "0.0.20", + "resolved": "https://registry.npmjs.org/@langchain/protocol/-/protocol-0.0.20.tgz", + "integrity": "sha512-sxlkDG2/HGyjDFLTJ8B/o3oglRjOv8iLCFgrV0550/Vym3V6RZ0SUjAQFe8jrLQw8ZXjERy3swJp5OODBSrUYA==", + "license": "MIT" + }, "node_modules/@langchain/langgraph-sdk/node_modules/eventemitter3": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz", @@ -718,9 +723,9 @@ "license": "MIT" }, "node_modules/@langchain/langgraph-sdk/node_modules/p-queue": { - "version": "9.3.3", - "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.3.tgz", - "integrity": "sha512-NXAOdnEe5FsZJfT4oK84lE1Y5cFFdWlRuOo5tww8DyNMxyRXwn39fIkUtNLKppcPC+UYU/bXujNCUGDv01y7CA==", + "version": "9.3.5", + "resolved": "https://registry.npmjs.org/p-queue/-/p-queue-9.3.5.tgz", + "integrity": "sha512-Lki/zhXFVmDhesBUn/yHRLW9Bte7mE7xoFHzTR8sIomV7a2z+LxYAPkGvdfidNiu4fKSfjtawixxSHcZci5QcQ==", "license": "MIT", "dependencies": { "eventemitter3": "^5.0.4", @@ -824,21 +829,6 @@ "integrity": "sha512-9hKcRrH7cBX6gfutdfXPoft1OCchHe4FEpALoDJMl5Qu+n/YG5ynZmyu8+8cxORlPwHBoKTxggvXz+76M1yX1Q==", "license": "MIT" }, - "node_modules/@langchain/tavily": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/@langchain/tavily/-/tavily-1.2.0.tgz", - "integrity": "sha512-aPLPgtw8+b/Rnr3H+X8H8z98T/Y7JuCE4B5eqRDHoEWgZvMDUFF7divqwQqCTMq2deQttlVrm5bN5JbKaAR7/w==", - "license": "MIT", - "dependencies": { - "zod": "^3.25.76 || ^4" - }, - "engines": { - "node": ">=20" - }, - "peerDependencies": { - "@langchain/core": "^1.0.0" - } - }, "node_modules/@mistralai/mistralai": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/@mistralai/mistralai/-/mistralai-2.2.1.tgz", @@ -2155,9 +2145,9 @@ } }, "node_modules/langsmith": { - "version": "0.10.10", - "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.10.10.tgz", - "integrity": "sha512-I83MmN/tqU662yHfv7DCMlJh8eFuRdY2Ri9rlvM61DGEsVdnVkOa0eyv9DpsstBM5dS877o5GDn+qHwZWfSgRg==", + "version": "0.11.8", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.11.8.tgz", + "integrity": "sha512-rAskvQCNjwGqwjA9fOJGugZ1vLB66yaivxWGSTA9ldtF9+P00gvXH1DEr0kW798cyUyBlZolFO0kPb//zDNc7w==", "license": "MIT", "dependencies": { "p-queue": "6.6.2" diff --git a/actions/ai-action/package.json b/actions/ai-action/package.json index 1325be8..2dd8cf7 100644 --- a/actions/ai-action/package.json +++ b/actions/ai-action/package.json @@ -12,7 +12,7 @@ "start": "node dist/index.js" }, "dependencies": { - "@code0-tech/hercules": "^1.7.2", + "@code0-tech/hercules": "^1.8.0", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", @@ -20,7 +20,6 @@ "@langchain/mistralai": "^1.0.0", "@langchain/ollama": "^1.0.0", "@langchain/openai": "^1.6.2", - "@langchain/tavily": "^1.2.0", "langchain": "^1.5.16" }, "devDependencies": { diff --git a/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts b/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts deleted file mode 100644 index 962a13c..0000000 --- a/actions/ai-action/src/agent/datatypes/Agent.transform.datatype.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { SubFlowFunctionDefinition } from "@code0-tech/hercules"; -import type { AiAgentRequest } from "./Agent.request.datatype.js"; -import type { AiAgentResponse } from "./Agent.response.datatype.js"; - -/** - * An agent returned from a runtime function. Hercules only turns a returned value - * into a sub flow the flow can invoke when it is a {@link SubFlowFunctionDefinition}; - * a bare closure reaches the value serializer and is rejected as an unsupported type. - */ -export interface AiAgentTransform extends SubFlowFunctionDefinition { - run(request: AiAgentRequest): Promise; -} diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts deleted file mode 100644 index 3b92710..0000000 --- a/actions/ai-action/src/agent/runtimefunctions/Agent.create.runtimefunction.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { - DisplayIcon, - DisplayMessage, - FunctionContext, - Identifier, - Name, - Parameter, - Signature, - SubFlow, - ThrowsError, -} from "@code0-tech/hercules"; -import { AiAgentRequestSchema, type AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; -import { AiAgentResponseSchema, type AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; -import type { AiAgentTransform } from "../datatypes/Agent.transform.datatype.js"; -import { asList } from "../../shared/utils/Shared.asList.util.js"; -import { asSubFlow } from "../../shared/utils/Shared.asSubFlow.util.js"; -import { asText } from "../../shared/utils/Shared.asText.util.js"; -import { asToolEntries } from "../utils/Agent.asToolEntries.util.js"; -import type { AgentDefinition, ToolEntry } from "../utils/Agent.compileAgent.util.js"; -import { requireText } from "../../shared/utils/Shared.requireText.util.js"; -import { runAgent } from "../utils/Agent.runAgent.util.js"; -import { toolServers } from "../utils/Agent.toolServers.util.js"; -import { validateMcpServers } from "../../mcp/utils/Mcp.validateMcpServers.util.js"; - -@Identifier("ai::agent::create") -@DisplayIcon("tabler:robot") -@Signature( - "(name: TEXT, system_prompt: TEXT, model: TRANSFORM, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, middleware?: LIST>): TRANSFORM", -) -@Name({ code: "en-US", content: "Create agent" }) -@DisplayMessage({ code: "en-US", content: "Create agent ${name}" }) -@ThrowsError() -@Parameter({ - runtimeName: "name", - name: [{ code: "en-US", content: "Name" }], -}) -@Parameter({ - runtimeName: "system_prompt", - name: [{ code: "en-US", content: "System prompt" }], -}) -@Parameter({ - runtimeName: "model", - name: [{ code: "en-US", content: "Model" }], -}) -@Parameter({ - runtimeName: "tools", - name: [{ code: "en-US", content: "Tools" }], - optional: true, -}) -@Parameter({ - runtimeName: "middleware", - name: [{ code: "en-US", content: "Middleware" }], - optional: true, -}) -export class CreateAgentFunction { - run( - _context: FunctionContext, - name: string, - system_prompt: string, - model: unknown, - tools?: ToolEntry[], - middleware?: unknown[], - ): AiAgentTransform { - const definition: AgentDefinition = { - name: requireText(name, "ERROR_INVALID_AI_AGENT", "An agent needs a name."), - systemPrompt: asText(system_prompt ?? "", "system_prompt", "ERROR_INVALID_AI_AGENT"), - model: asSubFlow(model, "model"), - tools: asToolEntries(tools), - middleware: asList(middleware, "middleware").map((entry, index): SubFlow => - asSubFlow(entry, `middleware[${index}]`), - ), - }; - validateMcpServers(toolServers(definition.tools)); - - return { - name: `agent:${definition.name}`, - description: definition.systemPrompt || `The agent ${definition.name}`, - inputSchema: AiAgentRequestSchema, - outputSchema: AiAgentResponseSchema, - run: (request: AiAgentRequest): Promise => runAgent(definition, request), - }; - } -} diff --git a/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts b/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts deleted file mode 100644 index 15e8932..0000000 --- a/actions/ai-action/src/agent/runtimefunctions/Agent.invoke.runtimefunction.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { - DisplayIcon, - DisplayMessage, - FunctionContext, - Identifier, - Name, - Parameter, - RuntimeError, - Signature, - ThrowsError, -} from "@code0-tech/hercules"; -import { AiAgentResponseSchema, type AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; -import type { AiChatResponse } from "../../chat/datatypes/Chat.response.datatype.js"; -import { AiChatRequestSchema, type AiChatRequest } from "../../chat/datatypes/Chat.request.datatype.js"; -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import { asText } from "../../shared/utils/Shared.asText.util.js"; -import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; -import { toChatResponse } from "../../chat/utils/Chat.toChatResponse.util.js"; -import { toConversation } from "../../chat/utils/Chat.toConversation.util.js"; - -@Identifier("ai::agent::invoke") -@DisplayIcon("tabler:message-chatbot") -@Signature( - "(agent: TRANSFORM, prompt: TEXT, request?: AI_CHAT_REQUEST): AI_CHAT_RESPONSE", -) -@Name({ code: "en-US", content: "Invoke agent" }) -@DisplayMessage({ code: "en-US", content: "Ask the agent ${prompt}" }) -@ThrowsError() -@Parameter({ - runtimeName: "agent", - name: [{ code: "en-US", content: "Agent" }], -}) -@Parameter({ - runtimeName: "prompt", - name: [{ code: "en-US", content: "Prompt" }], -}) -@Parameter({ - runtimeName: "request", - name: [{ code: "en-US", content: "Request" }], - optional: true, -}) -export class InvokeAgentFunction { - async run( - _context: FunctionContext, - agent: unknown, - prompt: string, - request?: AiChatRequest, - ): Promise { - if (!isSubFlow(agent)) { - throw new RuntimeError( - "ERROR_INVALID_AI_AGENT", - `The "agent" parameter has to be an agent as "ai::agent::create" returns one, but a ${typeof agent} was passed.`, - ); - } - - const parsed: AiChatRequest = parseOrThrow( - AiChatRequestSchema, - request ?? { messages: [] }, - "ERROR_INVALID_AI_CHAT_REQUEST", - "The chat request is not valid", - ); - const messages: AiMessage[] = toConversation( - parsed.messages, - asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"), - ); - if (messages.length === 0) { - throw new RuntimeError( - "ERROR_INVALID_AI_CHAT_REQUEST", - "There is nothing to ask: the prompt is empty and the request carries no messages.", - ); - } - - const answer: AiAgentResponse = parseOrThrow( - AiAgentResponseSchema, - (await agent({ messages })) ?? {}, - "ERROR_INVALID_AI_AGENT_RESPONSE", - "The agent did not answer with a valid agent response", - ); - - const last: AiMessage | undefined = answer.messages.at(-1); - if (!last) { - throw new RuntimeError("ERROR_INVALID_AI_AGENT_RESPONSE", "The agent answered with an empty conversation."); - } - - return toChatResponse(last, parsed.model ?? ""); - } -} diff --git a/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts b/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts deleted file mode 100644 index a41f2f7..0000000 --- a/actions/ai-action/src/agent/utils/Agent.asToolEntries.util.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { RuntimeError } from "@code0-tech/hercules"; -import { AiMcpServerSchema } from "../../mcp/datatypes/Mcp.server.datatype.js"; -import { asList } from "../../shared/utils/Shared.asList.util.js"; -import type { ToolEntry } from "./Agent.compileAgent.util.js"; -import { formatIssues } from "../../shared/utils/Shared.formatIssues.util.js"; -import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; - -export function asToolEntries(value: unknown): ToolEntry[] { - return asList(value, "tools").map((entry, index) => { - if (isSubFlow(entry)) return entry; - - const server = AiMcpServerSchema.safeParse(entry); - if (server.success) return server.data; - - throw new RuntimeError( - "ERROR_INVALID_AI_TOOL", - `Entry ${index + 1} of "tools" is neither a sub flow nor a valid MCP server: ${formatIssues(server.error.issues)}`, - ); - }); -} diff --git a/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts b/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts deleted file mode 100644 index bbda351..0000000 --- a/actions/ai-action/src/agent/utils/Agent.buildFlowTools.util.ts +++ /dev/null @@ -1,24 +0,0 @@ -import type { SubFlow } from "@code0-tech/hercules"; -import type { ClientTool } from "@langchain/core/tools"; -import { tool } from "langchain"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; -import { emptyJsonSchema } from "../../shared/utils/Shared.emptyJsonSchema.util.js"; - -export function buildFlowTools(runs: SubFlow[]): ClientTool[] { - return runs.map((run, index) => { - const schema = run.inputSchema as Record | undefined; - - return tool( - (args: unknown) => - Promise.resolve(run(args as never)).then( - (result) => (typeof result === "string" ? result : JSON.stringify(result ?? null)), - (error: unknown) => `The tool failed: ${describeError(error)}`, - ), - { - name: `tool_${index + 1}`, - description: typeof schema?.description === "string" ? schema.description : "", - schema: (schema ?? emptyJsonSchema()) as never, - }, - ) as unknown as ClientTool; - }); -} diff --git a/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts b/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts deleted file mode 100644 index 23496d1..0000000 --- a/actions/ai-action/src/agent/utils/Agent.compileAgent.util.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; -import type { ClientTool } from "@langchain/core/tools"; -import { createAgent, type ReactAgent } from "langchain"; -import type { AiMcpServer } from "../../mcp/datatypes/Mcp.server.datatype.js"; -import { buildFlowMiddlewares } from "../../middleware/utils/Middleware.buildFlowMiddlewares.util.js"; -import { buildFlowTools } from "./Agent.buildFlowTools.util.js"; -import { buildMcpTools } from "../../mcp/utils/Mcp.buildMcpTools.util.js"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; -import { FlowChatModel } from "../../model/utils/Model.flowChatModel.util.js"; -import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; -import { toolServers } from "./Agent.toolServers.util.js"; - -export type ToolEntry = SubFlow | AiMcpServer; - -export interface AgentDefinition { - name: string; - systemPrompt: string; - model: SubFlow; - tools: ToolEntry[]; - middleware: SubFlow[]; -} - -export interface CompiledAgent { - agent: ReactAgent; - close: () => Promise; -} - -export async function compileAgent(definition: AgentDefinition): Promise { - const { tools: mcpTools, close } = await buildMcpTools(toolServers(definition.tools)); - - try { - const tools: ClientTool[] = [...buildFlowTools(definition.tools.filter(isSubFlow)), ...mcpTools]; - const agent = createAgent({ - model: new FlowChatModel({ run: definition.model }), - tools, - middleware: buildFlowMiddlewares(definition.middleware, definition.name), - name: definition.name, - ...(definition.systemPrompt ? { systemPrompt: definition.systemPrompt } : {}), - } as never) as unknown as ReactAgent; - - return { agent, close }; - } catch (error) { - await close().catch(() => undefined); - if (error instanceof RuntimeError) throw error; - throw new RuntimeError( - "ERROR_BUILDING_AI_AGENT", - `Could not build agent "${definition.name}": ${describeError(error)}`, - ); - } -} diff --git a/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts b/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts deleted file mode 100644 index 9715bf0..0000000 --- a/actions/ai-action/src/agent/utils/Agent.runAgent.util.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { AiAgentResponse } from "../datatypes/Agent.response.datatype.js"; -import { AiAgentRequestSchema, type AiAgentRequest } from "../datatypes/Agent.request.datatype.js"; -import { compileAgent, type AgentDefinition, type CompiledAgent } from "./Agent.compileAgent.util.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; -import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; - -export async function runAgent(definition: AgentDefinition, request: AiAgentRequest): Promise { - const parsed: AiAgentRequest = parseOrThrow( - AiAgentRequestSchema, - request, - "ERROR_INVALID_AI_AGENT_REQUEST", - "The agent request is not valid", - ); - const compiled: CompiledAgent = await compileAgent(definition); - - try { - const result = await compiled.agent.invoke( - { messages: parsed.messages.map(toLangChainMessage) }, - parsed.thread_id ? { configurable: { thread_id: parsed.thread_id } } : undefined, - ); - - return { - messages: result.messages.map(toFlowMessage), - ...(result.structuredResponse ? { structured_response: result.structuredResponse } : {}), - }; - } finally { - await compiled.close().catch(() => undefined); - } -} diff --git a/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts b/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts deleted file mode 100644 index 118c36c..0000000 --- a/actions/ai-action/src/agent/utils/Agent.toolServers.util.ts +++ /dev/null @@ -1,7 +0,0 @@ -import type { AiMcpServer } from "../../mcp/datatypes/Mcp.server.datatype.js"; -import { isSubFlow } from "../../shared/utils/Shared.isSubFlow.util.js"; -import type { ToolEntry } from "./Agent.compileAgent.util.js"; - -export function toolServers(entries: ToolEntry[]): AiMcpServer[] { - return entries.filter((entry): entry is AiMcpServer => !isSubFlow(entry)); -} diff --git a/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts b/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts deleted file mode 100644 index 4d15a2c..0000000 --- a/actions/ai-action/src/chat/datatypes/Chat.response.datatype.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; -import { z } from "zod"; -import { AiChatChoiceSchema } from "./Chat.choice.datatype.js"; -import { AiChatUsageSchema } from "./Chat.usage.datatype.js"; - -export const AiChatResponseSchema = z.object({ - id: z.string(), - object: z.string(), - created: z.number(), - model: z.string(), - choices: z.array(AiChatChoiceSchema), - usage: AiChatUsageSchema.optional(), -}); -export type AiChatResponse = z.infer; - -@Identifier("AI_CHAT_RESPONSE") -@Name({ code: "en-US", content: "Chat response" }) -@DisplayMessage({ code: "en-US", content: "Chat response" }) -@Schema(AiChatResponseSchema) -export class AiChatResponseDataType {} diff --git a/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts b/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts deleted file mode 100644 index 874d311..0000000 --- a/actions/ai-action/src/chat/utils/Chat.fromChatMessage.util.ts +++ /dev/null @@ -1,25 +0,0 @@ -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import type { AiMessageRole } from "../../message/datatypes/Message.role.datatype.js"; -import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; -import type { AiChatRole } from "../datatypes/Chat.role.datatype.js"; -import { toContentBlocks } from "./Chat.toContentBlocks.util.js"; -import { toToolCallBlock } from "./Chat.toToolCallBlock.util.js"; - -const ROLE_FROM_CHAT: Record = { - system: "system", - user: "human", - assistant: "ai", - tool: "tool", -}; - -export function fromChatMessage(message: AiChatMessage): AiMessage { - const flat: AiMessage = { - role: ROLE_FROM_CHAT[message.role], - content: [...toContentBlocks(message.content), ...(message.tool_calls ?? []).map(toToolCallBlock)], - }; - - if (message.name) flat.name = message.name; - if (message.tool_call_id) flat.tool_call_id = message.tool_call_id; - - return flat; -} diff --git a/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts b/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts deleted file mode 100644 index 5b95b45..0000000 --- a/actions/ai-action/src/chat/utils/Chat.reportedModel.util.ts +++ /dev/null @@ -1,8 +0,0 @@ -import type { AiMessage } from "../../message/datatypes/Message.datatype"; - -export function reportedModel(answer: AiMessage, fallbackModel: string): string { - const metadata = answer.response_metadata ?? {}; - if (typeof metadata.model_name === "string") return metadata.model_name; - if (typeof metadata.model === "string") return metadata.model; - return fallbackModel; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts deleted file mode 100644 index 023efe4..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toChatMessage.util.ts +++ /dev/null @@ -1,27 +0,0 @@ -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import type { AiMessageRole } from "../../message/datatypes/Message.role.datatype.js"; -import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; -import type { AiChatRole } from "../datatypes/Chat.role.datatype.js"; -import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; -import { toChatContent } from "./Chat.toChatContent.util.js"; -import { toChatToolCalls } from "./Chat.toChatToolCalls.util.js"; - -const ROLE_TO_CHAT: Record = { - system: "system", - human: "user", - ai: "assistant", - tool: "tool", -}; - -export function toChatMessage(message: AiMessage): AiChatMessage { - const toolCalls: AiChatToolCall[] = toChatToolCalls(message); - const content: string = toChatContent(message); - - return { - role: ROLE_TO_CHAT[message.role], - content: content.length > 0 || toolCalls.length === 0 ? content : null, - ...(message.name ? { name: message.name } : {}), - ...(message.tool_call_id ? { tool_call_id: message.tool_call_id } : {}), - ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}), - }; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts deleted file mode 100644 index 2cb66d7..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toChatResponse.util.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; -import type { AiChatResponse } from "../datatypes/Chat.response.datatype.js"; -import type { AiChatUsage } from "../datatypes/Chat.usage.datatype.js"; -import { reportedModel } from "./Chat.reportedModel.util.js"; -import { toChatMessage } from "./Chat.toChatMessage.util.js"; -import { toChatUsage } from "./Chat.toChatUsage.util.js"; - -export function toChatResponse(answer: AiMessage, fallbackModel: string): AiChatResponse { - const message: AiChatMessage = toChatMessage(answer); - const usage: AiChatUsage | undefined = toChatUsage(answer); - - return { - id: answer.id ?? `chatcmpl-${randomUUID()}`, - object: "chat.completion", - created: Math.floor(Date.now() / 1000), - model: reportedModel(answer, fallbackModel), - choices: [{ index: 0, message, finish_reason: message.tool_calls ? "tool_calls" : "stop" }], - ...(usage ? { usage } : {}), - }; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts deleted file mode 100644 index 20d2785..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toChatToolCalls.util.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { randomUUID } from "node:crypto"; -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; - -export function toChatToolCalls(message: AiMessage): AiChatToolCall[] { - return message.content - .filter((block) => block.type === "tool_call") - .map((block) => ({ - id: typeof block.id === "string" ? block.id : randomUUID(), - type: "function" as const, - function: { - name: String(block.name ?? ""), - arguments: JSON.stringify(block.args ?? {}), - }, - })); -} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts b/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts deleted file mode 100644 index 788ee17..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toChatUsage.util.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import type { AiChatUsage } from "../datatypes/Chat.usage.datatype.js"; - -export function toChatUsage(message: AiMessage): AiChatUsage | undefined { - const usage = message.usage_metadata; - if (!usage) return undefined; - - const prompt: number = typeof usage.input_tokens === "number" ? usage.input_tokens : 0; - const completion: number = typeof usage.output_tokens === "number" ? usage.output_tokens : 0; - const total: number = typeof usage.total_tokens === "number" ? usage.total_tokens : prompt + completion; - - return { prompt_tokens: prompt, completion_tokens: completion, total_tokens: total }; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts deleted file mode 100644 index 706f271..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toContentBlock.util.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; -import type { AiChatContentPart } from "../datatypes/Chat.contentPart.datatype.js"; -import { toImageBlock } from "./Chat.toImageBlock.util.js"; - -export function toContentBlock(part: AiChatContentPart): AiContentBlock { - if (part.type === "text") return { type: "text", text: typeof part.text === "string" ? part.text : "" }; - if (part.type === "image_url") return toImageBlock(part); - return part; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts b/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts deleted file mode 100644 index 73a5843..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toContentBlocks.util.ts +++ /dev/null @@ -1,9 +0,0 @@ -import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; -import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; -import { toContentBlock } from "./Chat.toContentBlock.util.js"; - -export function toContentBlocks(content: AiChatMessage["content"]): AiContentBlock[] { - if (typeof content === "string") return content.length > 0 ? [{ type: "text", text: content }] : []; - if (Array.isArray(content)) return content.map(toContentBlock); - return []; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts b/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts deleted file mode 100644 index 060e1e1..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toConversation.util.ts +++ /dev/null @@ -1,10 +0,0 @@ -import type { AiChatMessage } from "../datatypes/Chat.message.datatype.js"; -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; -import { fromChatMessage } from "./Chat.fromChatMessage.util.js"; - -export function toConversation(history: AiChatMessage[], prompt: string): AiMessage[] { - const question: AiMessage[] = - prompt.length > 0 ? [{ role: "human", content: [{ type: "text", text: prompt }] }] : []; - - return [...history.map(fromChatMessage), ...question]; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts deleted file mode 100644 index 6691e8a..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toImageBlock.util.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; -import type { AiChatContentPart } from "../datatypes/Chat.contentPart.datatype.js"; - -export function toImageBlock(part: AiChatContentPart): AiContentBlock { - const image = part.image_url as { url?: string; detail?: string } | undefined; - - return { - type: "image", - ...(typeof image?.url === "string" ? { url: image.url } : {}), - ...(image?.detail ? { detail: image.detail } : {}), - }; -} diff --git a/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts b/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts deleted file mode 100644 index f4e71fd..0000000 --- a/actions/ai-action/src/chat/utils/Chat.toToolCallBlock.util.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { AiContentBlock } from "../../message/datatypes/Message.contentBlock.datatype.js"; -import type { AiChatToolCall } from "../datatypes/Chat.toolCall.datatype.js"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; - -export function toToolCallBlock(call: AiChatToolCall): AiContentBlock { - try { - return { - type: "tool_call", - id: call.id, - name: call.function.name, - args: JSON.parse(call.function.arguments || "{}") as Record, - }; - } catch (error) { - return { - type: "invalid_tool_call", - id: call.id, - name: call.function.name, - args: call.function.arguments, - error: describeError(error), - }; - } -} diff --git a/actions/ai-action/src/datatypes/agent/Agent.approval.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.approval.datatype.ts new file mode 100644 index 0000000..87ca100 --- /dev/null +++ b/actions/ai-action/src/datatypes/agent/Agent.approval.datatype.ts @@ -0,0 +1,28 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +/** + * A tool call the agent asked about instead of running. + * + * It is what a person needs to judge the call - which tool, with which arguments - + * and it is in the answer so a flow can act on it without reading the text. The + * decision itself comes back as the next message of the conversation: a chat client + * has no other channel, and the model reads the reply in context. + */ +export const AiAgentApprovalSchema = z.object({ + name: z.string(), + args: z.looseObject({}).optional(), + /** + * The code this call is approved or declined with. Only "APPROVE " of this + * very question lets it run, so a flow building buttons elsewhere has to send + * exactly that back as the next message. + */ + code: z.string().optional(), +}); +export type AiAgentApproval = z.infer; + +@Identifier("AI_AGENT_APPROVAL") +@Name({ code: "en-US", content: "Approval request" }) +@DisplayMessage({ code: "en-US", content: "${name}" }) +@Schema(AiAgentApprovalSchema) +export class AiAgentApprovalDataType {} diff --git a/actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.request.datatype.ts similarity index 80% rename from actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts rename to actions/ai-action/src/datatypes/agent/Agent.request.datatype.ts index c75b661..61a1da9 100644 --- a/actions/ai-action/src/agent/datatypes/Agent.request.datatype.ts +++ b/actions/ai-action/src/datatypes/agent/Agent.request.datatype.ts @@ -1,10 +1,9 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; export const AiAgentRequestSchema = z.object({ messages: z.array(AiMessageSchema), - thread_id: z.string().optional(), }); export type AiAgentRequest = z.infer; diff --git a/actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.response.datatype.ts similarity index 54% rename from actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts rename to actions/ai-action/src/datatypes/agent/Agent.response.datatype.ts index 4bd2356..be02294 100644 --- a/actions/ai-action/src/agent/datatypes/Agent.response.datatype.ts +++ b/actions/ai-action/src/datatypes/agent/Agent.response.datatype.ts @@ -1,10 +1,16 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiAgentApprovalSchema } from "./Agent.approval.datatype.js"; +import { AiAgentStepSchema } from "./Agent.step.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; export const AiAgentResponseSchema = z.object({ messages: z.array(AiMessageSchema), structured_response: z.looseObject({}).optional(), + /** Every tool the agent used, in the order it used them. */ + steps: z.array(AiAgentStepSchema).optional(), + /** The calls the agent asked about instead of running them. */ + awaiting_approval: z.array(AiAgentApprovalSchema).optional(), }); export type AiAgentResponse = z.infer; diff --git a/actions/ai-action/src/datatypes/agent/Agent.step.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.step.datatype.ts new file mode 100644 index 0000000..c93442c --- /dev/null +++ b/actions/ai-action/src/datatypes/agent/Agent.step.datatype.ts @@ -0,0 +1,26 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +/** + * One tool the agent used while it worked on an answer. + * + * A chat completion only carries the last message, so everything the agent did on the + * way - which tools it called, with what, and what came back - would be lost by the + * time the answer reaches a client. These steps carry it: a flow can log them, and a + * client that knows the field can show what happened instead of just the result. + */ +export const AiAgentStepSchema = z.object({ + name: z.string(), + args: z.looseObject({}).optional(), + /** What the tool answered, as text - a tool may return anything. */ + result: z.string().optional(), + /** Set when the call failed, instead of a result. */ + error: z.string().optional(), +}); +export type AiAgentStep = z.infer; + +@Identifier("AI_AGENT_STEP") +@Name({ code: "en-US", content: "Agent step" }) +@DisplayMessage({ code: "en-US", content: "${name}" }) +@Schema(AiAgentStepSchema) +export class AiAgentStepDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.choice.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.choice.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.choice.datatype.ts diff --git a/actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.contentPart.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.contentPart.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.contentPart.datatype.ts diff --git a/actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.message.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.message.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.message.datatype.ts diff --git a/actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.request.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts diff --git a/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts new file mode 100644 index 0000000..7a02e72 --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts @@ -0,0 +1,54 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiAgentApprovalSchema } from "../agent/Agent.approval.datatype.js"; +import { AiAgentStepSchema } from "../agent/Agent.step.datatype.js"; +import { AiChatChoiceSchema } from "./Chat.choice.datatype.js"; +import { AiChatUsageSchema } from "./Chat.usage.datatype.js"; + +export const AiChatResponseSchema = z.object({ + id: z.string(), + object: z.string(), + /** + * The answer as plain text, so a flow can use it without walking into + * `choices`. Not part of the OpenAI schema: the rest of this type mirrors a + * chat completion, this field is ours. Empty when the model produced no text + * (e.g. an answer that is only tool calls). + */ + response: z.string(), + /** + * What the model thought before it answered, as plain text, present only when it + * reported any. Not part of the OpenAI schema: `response` carries what the model + * said, this carries what it thought, next to it rather than mixed into it. + */ + reasoning: z.string().optional(), + created: z.number(), + model: z.string(), + choices: z.array(AiChatChoiceSchema), + usage: AiChatUsageSchema.optional(), + /** + * The answer in the type the node was asked to produce, present only when a type + * was passed as `output_schema`. The signature carries that type as a generic, so + * the flow reads this field as the very type it picked rather than as an object. + */ + structured_response: z.looseObject({}).optional(), + /** + * Every tool the agent used for this answer, with its arguments and what came + * back. Not part of the OpenAI schema - a chat completion has no field for the + * middle of a run - but without it everything the agent did is lost on the way to + * the client. + */ + steps: z.array(AiAgentStepSchema).optional(), + /** + * Present when the answer is a question about tool calls the agent held back. The + * answer's text asks it, so any chat client shows it; the decision comes back as + * the next message of the conversation. + */ + awaiting_approval: z.array(AiAgentApprovalSchema).optional(), +}); +export type AiChatResponse = z.infer; + +@Identifier("AI_CHAT_RESPONSE") +@Name({ code: "en-US", content: "Chat response" }) +@DisplayMessage({ code: "en-US", content: "Chat response" }) +@Schema(AiChatResponseSchema) +export class AiChatResponseDataType {} diff --git a/actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.role.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.role.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.role.datatype.ts diff --git a/actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.toolCall.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.toolCall.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.toolCall.datatype.ts diff --git a/actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.usage.datatype.ts similarity index 100% rename from actions/ai-action/src/chat/datatypes/Chat.usage.datatype.ts rename to actions/ai-action/src/datatypes/chat/Chat.usage.datatype.ts diff --git a/actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts b/actions/ai-action/src/datatypes/mcp/Mcp.server.datatype.ts similarity index 100% rename from actions/ai-action/src/mcp/datatypes/Mcp.server.datatype.ts rename to actions/ai-action/src/datatypes/mcp/Mcp.server.datatype.ts diff --git a/actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts b/actions/ai-action/src/datatypes/mcp/Mcp.transport.datatype.ts similarity index 100% rename from actions/ai-action/src/mcp/datatypes/Mcp.transport.datatype.ts rename to actions/ai-action/src/datatypes/mcp/Mcp.transport.datatype.ts diff --git a/actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts b/actions/ai-action/src/datatypes/message/Message.contentBlock.datatype.ts similarity index 100% rename from actions/ai-action/src/message/datatypes/Message.contentBlock.datatype.ts rename to actions/ai-action/src/datatypes/message/Message.contentBlock.datatype.ts diff --git a/actions/ai-action/src/message/datatypes/Message.datatype.ts b/actions/ai-action/src/datatypes/message/Message.datatype.ts similarity index 100% rename from actions/ai-action/src/message/datatypes/Message.datatype.ts rename to actions/ai-action/src/datatypes/message/Message.datatype.ts diff --git a/actions/ai-action/src/message/datatypes/Message.role.datatype.ts b/actions/ai-action/src/datatypes/message/Message.role.datatype.ts similarity index 100% rename from actions/ai-action/src/message/datatypes/Message.role.datatype.ts rename to actions/ai-action/src/datatypes/message/Message.role.datatype.ts diff --git a/actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts b/actions/ai-action/src/datatypes/message/Message.toolStatus.datatype.ts similarity index 100% rename from actions/ai-action/src/message/datatypes/Message.toolStatus.datatype.ts rename to actions/ai-action/src/datatypes/message/Message.toolStatus.datatype.ts diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.agentState.datatype.ts similarity index 86% rename from actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts rename to actions/ai-action/src/datatypes/middleware/Middleware.agentState.datatype.ts index 88d9a5f..55fa1e9 100644 --- a/actions/ai-action/src/middleware/datatypes/Middleware.agentState.datatype.ts +++ b/actions/ai-action/src/datatypes/middleware/Middleware.agentState.datatype.ts @@ -1,6 +1,6 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; import { AiMiddlewareHookSchema } from "./Middleware.hook.datatype.js"; export const AiAgentStateSchema = z.object({ @@ -9,7 +9,6 @@ export const AiAgentStateSchema = z.object({ hook: AiMiddlewareHookSchema, structured_response: z.looseObject({}).optional(), context: z.looseObject({}).optional(), - thread_id: z.string().optional(), }); export type AiAgentState = z.infer; diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.hook.datatype.ts similarity index 100% rename from actions/ai-action/src/middleware/datatypes/Middleware.hook.datatype.ts rename to actions/ai-action/src/datatypes/middleware/Middleware.hook.datatype.ts diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.stateUpdate.datatype.ts similarity index 88% rename from actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts rename to actions/ai-action/src/datatypes/middleware/Middleware.stateUpdate.datatype.ts index 322bf39..6a9f6ec 100644 --- a/actions/ai-action/src/middleware/datatypes/Middleware.stateUpdate.datatype.ts +++ b/actions/ai-action/src/datatypes/middleware/Middleware.stateUpdate.datatype.ts @@ -1,6 +1,6 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; export const AiStateUpdateSchema = z.object({ messages: z.array(AiMessageSchema).optional(), diff --git a/actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.transform.datatype.ts similarity index 100% rename from actions/ai-action/src/middleware/datatypes/Middleware.transform.datatype.ts rename to actions/ai-action/src/datatypes/middleware/Middleware.transform.datatype.ts diff --git a/actions/ai-action/src/model/datatypes/Model.request.datatype.ts b/actions/ai-action/src/datatypes/model/Model.request.datatype.ts similarity index 62% rename from actions/ai-action/src/model/datatypes/Model.request.datatype.ts rename to actions/ai-action/src/datatypes/model/Model.request.datatype.ts index 39e951d..9190dea 100644 --- a/actions/ai-action/src/model/datatypes/Model.request.datatype.ts +++ b/actions/ai-action/src/datatypes/model/Model.request.datatype.ts @@ -1,6 +1,7 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; +import { AiResponseFormatSchema } from "./Model.responseFormat.datatype.js"; import { AiToolChoiceSchema } from "./Model.toolChoice.datatype.js"; import { AiToolSpecSchema } from "./Model.toolSpec.datatype.js"; @@ -9,6 +10,10 @@ export const AiModelRequestSchema = z.object({ tools: z.array(AiToolSpecSchema), stop: z.array(z.string()).optional(), tool_choice: AiToolChoiceSchema.optional(), + // Carrying this field is how a model node declares that it can constrain its + // own output: the agent reads the declared request schema of the model it was + // handed, and only asks for a native structured answer when the field is there. + response_format: AiResponseFormatSchema.optional(), }); export type AiModelRequest = z.infer; diff --git a/actions/ai-action/src/model/datatypes/Model.response.datatype.ts b/actions/ai-action/src/datatypes/model/Model.response.datatype.ts similarity index 85% rename from actions/ai-action/src/model/datatypes/Model.response.datatype.ts rename to actions/ai-action/src/datatypes/model/Model.response.datatype.ts index ef12588..cd74c6e 100644 --- a/actions/ai-action/src/model/datatypes/Model.response.datatype.ts +++ b/actions/ai-action/src/datatypes/model/Model.response.datatype.ts @@ -1,6 +1,6 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; -import { AiMessageSchema } from "../../message/datatypes/Message.datatype.js"; +import { AiMessageSchema } from "../message/Message.datatype.js"; export const AiModelResponseSchema = z.object({ message: AiMessageSchema, diff --git a/actions/ai-action/src/datatypes/model/Model.responseFormat.datatype.ts b/actions/ai-action/src/datatypes/model/Model.responseFormat.datatype.ts new file mode 100644 index 0000000..4357db5 --- /dev/null +++ b/actions/ai-action/src/datatypes/model/Model.responseFormat.datatype.ts @@ -0,0 +1,25 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; + +/** + * The type an answer has to come back in, as it reaches a model sub flow. + * + * It is deliberately provider-neutral: the schema and its name travel, and every + * model node turns them into whatever its own provider expects - OpenAI's + * `response_format`, Anthropic's `outputConfig`, Google's `responseSchema`. A model + * node that cannot constrain its output at all simply leaves the field out of its + * request schema, which is how it tells the agent to fall back to a tool call. + */ +export const AiResponseFormatSchema = z.object({ + name: z.string(), + schema: z.looseObject({}), + description: z.string().optional(), + strict: z.boolean().optional(), +}); +export type AiResponseFormat = z.infer; + +@Identifier("AI_RESPONSE_FORMAT") +@Name({ code: "en-US", content: "Response format" }) +@DisplayMessage({ code: "en-US", content: "Response format ${name}" }) +@Schema(AiResponseFormatSchema) +export class AiResponseFormatDataType {} diff --git a/actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts b/actions/ai-action/src/datatypes/model/Model.toolChoice.datatype.ts similarity index 100% rename from actions/ai-action/src/model/datatypes/Model.toolChoice.datatype.ts rename to actions/ai-action/src/datatypes/model/Model.toolChoice.datatype.ts diff --git a/actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts b/actions/ai-action/src/datatypes/model/Model.toolSpec.datatype.ts similarity index 100% rename from actions/ai-action/src/model/datatypes/Model.toolSpec.datatype.ts rename to actions/ai-action/src/datatypes/model/Model.toolSpec.datatype.ts diff --git a/actions/ai-action/src/model/datatypes/Model.transform.datatype.ts b/actions/ai-action/src/datatypes/model/Model.transform.datatype.ts similarity index 100% rename from actions/ai-action/src/model/datatypes/Model.transform.datatype.ts rename to actions/ai-action/src/datatypes/model/Model.transform.datatype.ts diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts index 0d95d54..0e7dca8 100644 --- a/actions/ai-action/src/index.ts +++ b/actions/ai-action/src/index.ts @@ -1,39 +1,56 @@ import "reflect-metadata"; -import { Action, CodeZeroEvent, type DataTypeClass, type RuntimeFunctionClass } from "@code0-tech/hercules"; -import { AiAgentRequestDataType } from "./agent/datatypes/Agent.request.datatype.js"; -import { AiAgentResponseDataType } from "./agent/datatypes/Agent.response.datatype.js"; -import { AiChatChoiceDataType } from "./chat/datatypes/Chat.choice.datatype.js"; -import { AiChatContentPartDataType } from "./chat/datatypes/Chat.contentPart.datatype.js"; -import { AiChatMessageDataType } from "./chat/datatypes/Chat.message.datatype.js"; -import { AiChatRequestDataType } from "./chat/datatypes/Chat.request.datatype.js"; -import { AiChatResponseDataType } from "./chat/datatypes/Chat.response.datatype.js"; -import { AiChatRoleDataType } from "./chat/datatypes/Chat.role.datatype.js"; -import { AiChatToolCallDataType } from "./chat/datatypes/Chat.toolCall.datatype.js"; -import { AiChatUsageDataType } from "./chat/datatypes/Chat.usage.datatype.js"; -import { AiMcpServerDataType } from "./mcp/datatypes/Mcp.server.datatype.js"; -import { AiMcpTransportDataType } from "./mcp/datatypes/Mcp.transport.datatype.js"; -import { AiContentBlockDataType } from "./message/datatypes/Message.contentBlock.datatype.js"; -import { AiMessageDataType } from "./message/datatypes/Message.datatype.js"; -import { AiMessageRoleDataType } from "./message/datatypes/Message.role.datatype.js"; -import { AiToolStatusDataType } from "./message/datatypes/Message.toolStatus.datatype.js"; -import { AiAgentStateDataType } from "./middleware/datatypes/Middleware.agentState.datatype.js"; -import { AiMiddlewareHookDataType } from "./middleware/datatypes/Middleware.hook.datatype.js"; -import { AiStateUpdateDataType } from "./middleware/datatypes/Middleware.stateUpdate.datatype.js"; -import { AiModelRequestDataType } from "./model/datatypes/Model.request.datatype.js"; -import { AiModelResponseDataType } from "./model/datatypes/Model.response.datatype.js"; -import { AiToolSpecDataType } from "./model/datatypes/Model.toolSpec.datatype.js"; -import { AiWebSearchHitDataType } from "./websearch/datatypes/WebSearch.hit.datatype.js"; -import { AiWebSearchResultDataType } from "./websearch/datatypes/WebSearch.result.datatype.js"; - -import { CreateAgentFunction } from "./agent/runtimefunctions/Agent.create.runtimefunction.js"; -import { InvokeAgentFunction } from "./agent/runtimefunctions/Agent.invoke.runtimefunction.js"; -import { TrimMessagesMiddlewareFunction } from "./middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; -import { OpenRouterModelFunction } from "./model/runtimefunctions/Model.openRouter.runtimefunction.js"; -import { WebSearchToolFunction } from "./websearch/runtimefunctions/WebSearch.search.runtimefunction.js"; - -import { connectToAquila } from "./shared/utils/Shared.connectToAquila.util.js"; +import { + Action, + CodeZeroEvent, + type DataTypeClass, + type PlainValue, + type RuntimeEventClass, + type RuntimeFunctionClass, +} from "@code0-tech/hercules"; +import { AiAgentApprovalDataType } from "./datatypes/agent/Agent.approval.datatype.js"; +import { AiAgentStepDataType } from "./datatypes/agent/Agent.step.datatype.js"; +import { AiAgentRequestDataType } from "./datatypes/agent/Agent.request.datatype.js"; +import { AiAgentResponseDataType } from "./datatypes/agent/Agent.response.datatype.js"; +import { AiChatChoiceDataType } from "./datatypes/chat/Chat.choice.datatype.js"; +import { AiChatContentPartDataType } from "./datatypes/chat/Chat.contentPart.datatype.js"; +import { AiChatMessageDataType } from "./datatypes/chat/Chat.message.datatype.js"; +import { AiChatRequestDataType } from "./datatypes/chat/Chat.request.datatype.js"; +import { AiChatResponseDataType } from "./datatypes/chat/Chat.response.datatype.js"; +import { AiChatRoleDataType } from "./datatypes/chat/Chat.role.datatype.js"; +import { AiChatToolCallDataType } from "./datatypes/chat/Chat.toolCall.datatype.js"; +import { AiChatUsageDataType } from "./datatypes/chat/Chat.usage.datatype.js"; +import { AiMcpServerDataType } from "./datatypes/mcp/Mcp.server.datatype.js"; +import { AiMcpTransportDataType } from "./datatypes/mcp/Mcp.transport.datatype.js"; +import { AiContentBlockDataType } from "./datatypes/message/Message.contentBlock.datatype.js"; +import { AiMessageDataType } from "./datatypes/message/Message.datatype.js"; +import { AiMessageRoleDataType } from "./datatypes/message/Message.role.datatype.js"; +import { AiToolStatusDataType } from "./datatypes/message/Message.toolStatus.datatype.js"; +import { AiAgentStateDataType } from "./datatypes/middleware/Middleware.agentState.datatype.js"; +import { AiMiddlewareHookDataType } from "./datatypes/middleware/Middleware.hook.datatype.js"; +import { AiStateUpdateDataType } from "./datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import { AiModelRequestDataType } from "./datatypes/model/Model.request.datatype.js"; +import { AiModelResponseDataType } from "./datatypes/model/Model.response.datatype.js"; +import { AiResponseFormatDataType } from "./datatypes/model/Model.responseFormat.datatype.js"; +import { AiToolSpecDataType } from "./datatypes/model/Model.toolSpec.datatype.js"; + +import { CreateAgentFunction } from "./runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { HumanInTheLoopMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; +import { TrimMessagesMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; +import { OpenRouterModelFunction } from "./runtimefunctions/model/Model.openRouter.runtimefunction.js"; + +import { OpenAiOpenWebUiFormattingFunction } from "./runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.js"; +import { OpenAiRespondFunction } from "./runtimefunctions/openai/OpenAi.respond.runtimefunction.js"; + +import { AiOpenAiServerRuntimeEvent } from "./runtimeevents/openai/OpenAi.server.runtimeevent.js"; +import { startOpenAiServer } from "./server/openai/OpenAi.startServer.js"; + +import type { ActionExecutionRequest, ActionFlow } from "@code0-tech/tucana/aquila"; + +import { connectToAquila } from "./utils/shared/Shared.connectToAquila.util.js"; +import { logger } from "./utils/shared/Log.logger.util.js"; const RECONNECT_DELAY_MS = 5000; +const log = logger("action"); const DATA_TYPES: DataTypeClass[] = [ AiMessageRoleDataType, @@ -41,6 +58,7 @@ const DATA_TYPES: DataTypeClass[] = [ AiContentBlockDataType, AiMessageDataType, AiToolSpecDataType, + AiResponseFormatDataType, AiModelRequestDataType, AiModelResponseDataType, @@ -51,9 +69,8 @@ const DATA_TYPES: DataTypeClass[] = [ AiMcpTransportDataType, AiMcpServerDataType, - AiWebSearchHitDataType, - AiWebSearchResultDataType, - + AiAgentApprovalDataType, + AiAgentStepDataType, AiAgentRequestDataType, AiAgentResponseDataType, @@ -65,16 +82,21 @@ const DATA_TYPES: DataTypeClass[] = [ AiChatUsageDataType, AiChatChoiceDataType, AiChatResponseDataType, + ]; const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ CreateAgentFunction, - InvokeAgentFunction, + HumanInTheLoopMiddlewareFunction, + OpenAiOpenWebUiFormattingFunction, + OpenAiRespondFunction, OpenRouterModelFunction, TrimMessagesMiddlewareFunction, - WebSearchToolFunction, ]; +/** Events the action itself fires, rather than ones a platform adapter triggers. */ +const RUNTIME_EVENTS: RuntimeEventClass[] = [AiOpenAiServerRuntimeEvent]; + const action = new Action( process.env.ACTION_ID ?? "testing-action", process.env.VERSION ?? "1.0.0", @@ -87,17 +109,58 @@ const action = new Action( DATA_TYPES.forEach((dataType) => action.registerDataTypeClass(dataType)); RUNTIME_FUNCTIONS.forEach((runtimeFunction) => action.registerRuntimeFunction(runtimeFunction)); +RUNTIME_EVENTS.forEach((event) => action.registerRuntimeEventClass(event)); action.on(CodeZeroEvent.connected, () => { - console.log("Connected to aquila"); + log.info("connected to aquila", { + data_types: DATA_TYPES.length, + runtime_functions: RUNTIME_FUNCTIONS.length, + runtime_events: RUNTIME_EVENTS.length, + flows: action.flows.size, + }); }); action.on(CodeZeroEvent.error, (error: Error) => { - console.error("Stream error:", error.message); - console.log(`Attempting to reconnect in ${RECONNECT_DELAY_MS / 1000}s...`); + log.error(`stream error, reconnecting in ${RECONNECT_DELAY_MS / 1000}s`, { error: error.message }); setTimeout(() => connectToAquila(action), RECONNECT_DELAY_MS); }); +// Which flows the action knows decides what the OpenAI endpoint serves, so every +// change to the registry is logged: a client finding no model is answered here. +action.on(CodeZeroEvent.flowUpdated, (flow: ActionFlow) => { + log.info(`flow ${flow.flowId} of project ${flow.projectSlug} is bound to ${flow.type}`, { + name: flow.name, + settings: flow.settings.map((setting: { flowSettingId: string }) => setting.flowSettingId), + }); +}); + +action.on(CodeZeroEvent.flowDeleted, (flowId: bigint) => { + log.info(`flow ${flowId} is gone`, { flows: action.flows.size }); +}); + +action.on(CodeZeroEvent.executionRequestReceived, (request: ActionExecutionRequest) => { + log.debug("aquila asks for an execution", { + execution_id: request.executionIdentifier, + function: request.functionIdentifier, + }); +}); + +action.on(CodeZeroEvent.moduleUpdated, () => { + log.debug("the module configuration was updated"); +}); + connectToAquila(action); +// The action serves the OpenAI protocol itself: the server answers on its own port and +// runs the flow a request is for, so it only needs the flows aquila reports and a way +// to execute one. +startOpenAiServer({ + flows: () => action.flows.values(), + reserveExecutionId: () => action.reserveExecutionId(), + executeFlowWithId: (executionId: string, flowId: bigint, payload: PlainValue) => + action.executeFlowWithId(executionId, flowId, payload), +}).catch((error: unknown) => { + console.error("Could not start the OpenAI endpoint:", error instanceof Error ? error.message : error); +}); + export { action }; diff --git a/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts b/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts deleted file mode 100644 index e97bb1d..0000000 --- a/actions/ai-action/src/mcp/utils/Mcp.buildMcpTools.util.ts +++ /dev/null @@ -1,30 +0,0 @@ -import type { ClientTool } from "@langchain/core/tools"; -import { MultiServerMCPClient } from "@langchain/mcp-adapters"; -import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; -import { discoverTools } from "./Mcp.discoverTools.util.js"; -import { toConnection } from "./Mcp.toConnection.util.js"; -import { validateMcpServers } from "./Mcp.validateMcpServers.util.js"; - -export interface McpTools { - tools: ClientTool[]; - close: () => Promise; -} - -export async function buildMcpTools(servers: AiMcpServer[]): Promise { - if (servers.length === 0) return { tools: [], close: async () => undefined }; - - validateMcpServers(servers); - - const client = new MultiServerMCPClient({ - mcpServers: Object.fromEntries(servers.map((server) => [server.name, toConnection(server)])), - }); - - const discovered: ClientTool[] = await discoverTools(client); - const allowed = new Set(servers.flatMap((server) => server.allowed_tools ?? [])); - const tools: ClientTool[] = - allowed.size === 0 - ? discovered - : discovered.filter((tool) => allowed.has(tool.name.split("__").pop() ?? tool.name)); - - return { tools, close: () => client.close() }; -} diff --git a/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts b/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts deleted file mode 100644 index b00b75d..0000000 --- a/actions/ai-action/src/mcp/utils/Mcp.discoverTools.util.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { RuntimeError } from "@code0-tech/hercules"; -import type { ClientTool } from "@langchain/core/tools"; -import type { MultiServerMCPClient } from "@langchain/mcp-adapters"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; - -export async function discoverTools(client: MultiServerMCPClient): Promise { - try { - return (await client.getTools()) as unknown as ClientTool[]; - } catch (error) { - await client.close().catch(() => undefined); - throw new RuntimeError( - "ERROR_LOADING_AI_MCP_TOOLS", - `Could not load tools from the configured MCP servers: ${describeError(error)}`, - ); - } -} diff --git a/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts b/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts deleted file mode 100644 index da5cb49..0000000 --- a/actions/ai-action/src/mcp/utils/Mcp.validateMcpServers.util.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { RuntimeError } from "@code0-tech/hercules"; -import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; -import { toConnection } from "./Mcp.toConnection.util.js"; - -export function validateMcpServers(servers: AiMcpServer[]): void { - const names: string[] = servers.map((server) => server.name); - const duplicate: string | undefined = names.find((name, index) => names.indexOf(name) !== index); - if (duplicate) { - throw new RuntimeError( - "ERROR_DUPLICATE_AI_MCP_SERVER", - `More than one MCP server is named "${duplicate}". MCP tool names are namespaced with the server name, so the names must be unique.`, - ); - } - - servers.forEach(toConnection); -} diff --git a/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts b/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts deleted file mode 100644 index b8fd741..0000000 --- a/actions/ai-action/src/message/utils/Message.replaceMessages.util.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { RemoveMessage, type BaseMessage } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; -import { toLangChainMessage } from "./Message.toLangChainMessage.util.js"; - -export function replaceMessages(previous: BaseMessage[], next: AiMessage[]): BaseMessage[] { - const removals = previous - .filter((message): message is BaseMessage & { id: string } => typeof message.id === "string") - .map((message) => new RemoveMessage({ id: message.id })); - - return [...removals, ...next.map(toLangChainMessage)]; -} diff --git a/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts b/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts deleted file mode 100644 index 81f1d67..0000000 --- a/actions/ai-action/src/message/utils/Message.toAiMessage.util.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { AIMessage, type UsageMetadata } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; -import { toInvalidToolCalls } from "./Message.toInvalidToolCalls.util.js"; -import { toToolCalls } from "./Message.toToolCalls.util.js"; -import type { MessageFields } from "./Message.toMessageFields.util.js"; - -export function toAiMessage(message: AiMessage, fields: MessageFields): AIMessage { - return new AIMessage({ - ...fields, - tool_calls: toToolCalls(message), - invalid_tool_calls: toInvalidToolCalls(message), - ...(message.usage_metadata ? { usage_metadata: message.usage_metadata as UsageMetadata } : {}), - }); -} diff --git a/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts b/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts deleted file mode 100644 index 9c0e2e9..0000000 --- a/actions/ai-action/src/message/utils/Message.toInvalidToolCalls.util.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { InvalidToolCall } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; - -export function toInvalidToolCalls(message: AiMessage): InvalidToolCall[] { - return message.content - .filter((block) => block.type === "invalid_tool_call") - .map((block) => ({ - id: typeof block.id === "string" ? block.id : undefined, - name: typeof block.name === "string" ? block.name : undefined, - args: typeof block.args === "string" ? block.args : undefined, - error: typeof block.error === "string" ? block.error : undefined, - })); -} diff --git a/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts b/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts deleted file mode 100644 index 8598060..0000000 --- a/actions/ai-action/src/message/utils/Message.toLangChainMessage.util.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { HumanMessage, SystemMessage, type BaseMessage } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; -import { toAiMessage } from "./Message.toAiMessage.util.js"; -import { toMessageFields, type MessageFields } from "./Message.toMessageFields.util.js"; -import { toToolMessage } from "./Message.toToolMessage.util.js"; - -export function toLangChainMessage(message: AiMessage): BaseMessage { - const fields: MessageFields = toMessageFields(message); - - switch (message.role) { - case "system": - return new SystemMessage(fields); - case "ai": - return toAiMessage(message, fields); - case "tool": - return toToolMessage(message, fields); - case "human": - return new HumanMessage(fields); - } -} diff --git a/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts b/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts deleted file mode 100644 index ab2ff77..0000000 --- a/actions/ai-action/src/message/utils/Message.toMessageFields.util.ts +++ /dev/null @@ -1,22 +0,0 @@ -import type { AiContentBlock } from "../datatypes/Message.contentBlock.datatype.js"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; - -const CALL_BLOCK_TYPES: string[] = ["tool_call", "invalid_tool_call"]; - -export interface MessageFields { - content: AiContentBlock[]; - id?: string; - name?: string; - additional_kwargs?: Record; - response_metadata?: Record; -} - -export function toMessageFields(message: AiMessage): MessageFields { - return { - content: message.content.filter((block) => !CALL_BLOCK_TYPES.includes(block.type)), - ...(message.id ? { id: message.id } : {}), - ...(message.name ? { name: message.name } : {}), - ...(message.additional_kwargs ? { additional_kwargs: message.additional_kwargs } : {}), - ...(message.response_metadata ? { response_metadata: message.response_metadata } : {}), - }; -} diff --git a/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts b/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts deleted file mode 100644 index 2dc8091..0000000 --- a/actions/ai-action/src/message/utils/Message.toToolCalls.util.ts +++ /dev/null @@ -1,12 +0,0 @@ -import type { ToolCall } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; - -export function toToolCalls(message: AiMessage): ToolCall[] { - return message.content - .filter((block) => block.type === "tool_call") - .map((block) => ({ - id: typeof block.id === "string" ? block.id : undefined, - name: String(block.name ?? ""), - args: (block.args ?? {}) as Record, - })); -} diff --git a/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts b/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts deleted file mode 100644 index c743888..0000000 --- a/actions/ai-action/src/message/utils/Message.toToolMessage.util.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ToolMessage } from "@langchain/core/messages"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; -import type { MessageFields } from "./Message.toMessageFields.util.js"; - -export function toToolMessage(message: AiMessage, fields: MessageFields): ToolMessage { - return new ToolMessage({ - ...fields, - tool_call_id: message.tool_call_id ?? "", - ...(message.status ? { status: message.status } : {}), - ...(message.artifact !== undefined ? { artifact: message.artifact } : {}), - }); -} diff --git a/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts b/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts deleted file mode 100644 index 28d53ad..0000000 --- a/actions/ai-action/src/middleware/utils/Middleware.buildFlowMiddlewares.util.ts +++ /dev/null @@ -1,16 +0,0 @@ -import type { SubFlow } from "@code0-tech/hercules"; -import { createMiddleware, type AnyAgentMiddleware } from "langchain"; -import { createHookHandler } from "./Middleware.createHookHandler.util.js"; - -const JUMP_TARGETS = ["model", "tools", "end"] as const; - -export function buildFlowMiddlewares(runs: SubFlow[], agentName: string): AnyAgentMiddleware[] { - return runs.map( - (run, index) => - createMiddleware({ - name: `flow_middleware_${index + 1}`, - beforeModel: { hook: createHookHandler(run, agentName, "before_model"), canJumpTo: [...JUMP_TARGETS] }, - afterModel: { hook: createHookHandler(run, agentName, "after_model"), canJumpTo: [...JUMP_TARGETS] }, - } as never) as AnyAgentMiddleware, - ); -} diff --git a/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts b/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts deleted file mode 100644 index ed9c7b3..0000000 --- a/actions/ai-action/src/middleware/utils/Middleware.createHookHandler.util.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { SubFlow } from "@code0-tech/hercules"; -import type { AiMiddlewareHook } from "../datatypes/Middleware.hook.datatype.js"; -import { AiStateUpdateSchema } from "../datatypes/Middleware.stateUpdate.datatype.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; -import { replaceMessages } from "../../message/utils/Message.replaceMessages.util.js"; -import { toFlowState, type AgentRuntime, type AgentState } from "./Middleware.toFlowState.util.js"; - -type HookResult = Record | undefined; - -export type HookHandler = (state: AgentState, runtime?: AgentRuntime) => Promise; - -export function createHookHandler(run: SubFlow, agentName: string, hook: AiMiddlewareHook): HookHandler { - return async (state: AgentState, runtime?: AgentRuntime): Promise => { - const raw = await run(toFlowState(state, runtime, agentName, hook) as never); - if (raw === undefined || raw === null) return undefined; - - const update = parseOrThrow( - AiStateUpdateSchema, - raw, - "ERROR_INVALID_AI_STATE_UPDATE", - `The middleware sub flow did not return a valid state update for the ${hook} phase`, - ); - if (!update.messages && !update.jump_to && !update.structured_response) return undefined; - - return { - ...(update.messages ? { messages: replaceMessages(state.messages, update.messages) } : {}), - ...(update.structured_response ? { structuredResponse: update.structured_response } : {}), - ...(update.jump_to ? { jumpTo: update.jump_to } : {}), - }; - }; -} diff --git a/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts b/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts deleted file mode 100644 index 900d94d..0000000 --- a/actions/ai-action/src/middleware/utils/Middleware.toFlowState.util.ts +++ /dev/null @@ -1,31 +0,0 @@ -import type { BaseMessage } from "@langchain/core/messages"; -import type { AiAgentState } from "../datatypes/Middleware.agentState.datatype.js"; -import type { AiMiddlewareHook } from "../datatypes/Middleware.hook.datatype.js"; -import { hasEntries } from "../../shared/utils/Shared.hasEntries.util.js"; -import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; - -export interface AgentState { - messages: BaseMessage[]; - structuredResponse?: Record; -} - -export interface AgentRuntime { - context?: Record; - configurable?: { thread_id?: string; [key: string]: unknown }; -} - -export function toFlowState( - state: AgentState, - runtime: AgentRuntime | undefined, - agentName: string, - hook: AiMiddlewareHook, -): AiAgentState { - return { - messages: state.messages.map(toFlowMessage), - agent_name: agentName, - hook, - ...(state.structuredResponse ? { structured_response: state.structuredResponse } : {}), - ...(hasEntries(runtime?.context) ? { context: runtime?.context } : {}), - ...(typeof runtime?.configurable?.thread_id === "string" ? { thread_id: runtime.configurable.thread_id } : {}), - }; -} diff --git a/actions/ai-action/src/model/Model.flowChatModel.ts b/actions/ai-action/src/model/Model.flowChatModel.ts new file mode 100644 index 0000000..f172a78 --- /dev/null +++ b/actions/ai-action/src/model/Model.flowChatModel.ts @@ -0,0 +1,200 @@ +import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; +import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; +import { + BaseChatModel, + type BaseChatModelCallOptions, + type BindToolsInput, +} from "@langchain/core/language_models/chat_models"; +import { isAIMessage, type AIMessageChunk, type BaseMessage } from "@langchain/core/messages"; +import { isLangChainTool } from "@langchain/core/tools"; +import { toJsonSchema } from "@langchain/core/utils/json_schema"; +import type { ChatResult } from "@langchain/core/outputs"; +import type { Runnable } from "@langchain/core/runnables"; +import type { ModelProfile } from "@langchain/core/language_models/profile"; +import type { AiModelRequest } from "../datatypes/model/Model.request.datatype.js"; +import type { AiResponseFormat } from "../datatypes/model/Model.responseFormat.datatype.js"; +import type { AiToolSpec } from "../datatypes/model/Model.toolSpec.datatype.js"; +import { AiModelResponseSchema } from "../datatypes/model/Model.response.datatype.js"; +import { parseOrThrow } from "../utils/shared/Shared.parseOrThrow.util.js"; +import { stripUndefined } from "../utils/shared/Shared.stripUndefined.util.js"; +import { toFlowMessage } from "../utils/message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../utils/message/Message.toLangChainMessage.util.js"; +import { logger } from "../utils/shared/Log.logger.util.js"; +import { emptyJsonSchema } from "../utils/shared/Shared.emptyJsonSchema.util.js"; +import { toPlainSchema } from "../utils/shared/Shared.toPlainSchema.util.js"; + +type BoundFlowChatModel = Runnable; + +const log = logger("model"); + +interface FlowChatModelFields { + run: SubFlow; + toolSpecs?: AiToolSpec[]; + boundOptions?: Record; +} + +/** + * The response format a model sub flow is asked for, read off what langchain bound. + * + * langchain writes one option per provider dialect - OpenAI's `response_format`, + * Anthropic's `outputConfig`, Google's `responseSchema` - and a model sub flow is + * none of those, so the OpenAI-shaped one is unwrapped back into the schema and its + * name. That is the whole of what a provider needs; which dialect it has to be + * written in is the model node's business, not ours. + */ +function toResponseFormat(value: unknown): AiResponseFormat | undefined { + const bound = value as { type?: string; json_schema?: Record } | undefined; + if (!bound || typeof bound !== "object" || bound.type !== "json_schema") return undefined; + + const declared: Record | undefined = bound.json_schema; + const schema: unknown = declared?.schema; + if (!schema || typeof schema !== "object") return undefined; + + return stripUndefined({ + name: typeof declared?.name === "string" ? declared.name : "extract", + schema: schema as Record, + description: typeof declared?.description === "string" ? declared.description : undefined, + strict: typeof declared?.strict === "boolean" ? declared.strict : undefined, + }); +} + +export class FlowChatModel extends BaseChatModel { + private readonly run: SubFlow; + private readonly toolSpecs: AiToolSpec[]; + /** + * What langchain bound to the model alongside the tools - the tool choice above + * all. These arrive as the second argument of {@link bindTools} rather than as + * call options, so they have to be carried on the instance to reach `_generate`. + */ + private readonly boundOptions: Record; + /** Whether the model sub flow declared that it can constrain its own output. */ + private readonly nativeOutput: boolean; + + constructor(fields: FlowChatModelFields) { + super({}); + this.run = fields.run; + this.toolSpecs = fields.toolSpecs ?? []; + this.boundOptions = fields.boundOptions ?? {}; + + // A model sub flow is a proxy for a provider this action knows nothing about, + // so whether a native structured answer is possible cannot be decided here. + // The only thing that crosses the boundary is the sub flow's declared input + // schema, and that is enough: a model node that handles `response_format` + // says so by carrying the field, and one that cannot leaves it out. + const declared: Record | undefined = toPlainSchema(fields.run.inputSchema); + const properties: unknown = declared?.properties; + this.nativeOutput = + typeof properties === "object" && properties !== null && "response_format" in properties; + } + + _llmType(): string { + return "code0_flow"; + } + + /** + * What langchain asks before it decides how to get a structured answer: with + * `structuredOutput` set it hands the schema to the provider and reads the answer + * back off the message, and without it it binds the schema as an `extract` tool + * and forces a tool call instead. Both paths work here; this only picks the one + * the model behind the sub flow can actually serve. + */ + get profile(): ModelProfile { + return this.nativeOutput ? { structuredOutput: true } : {}; + } + + /** + * The second argument is not optional in practice: langchain binds the tool + * choice through it, and for a structured answer asked for as a tool it binds + * `tool_choice: "any"` - the only thing that makes the model call the `extract` + * tool at all. Dropping it leaves the tool merely offered, the model free to + * answer prose, and the structured answer missing (code0-tech/centaurus: the + * agent then fails with ERROR_INVALID_AI_AGENT_RESPONSE). + */ + bindTools(tools: BindToolsInput[], kwargs?: Record): BoundFlowChatModel { + const specs: AiToolSpec[] = tools.map((tool): AiToolSpec => { + const definition = tool as { name?: string; description?: string; input_schema?: unknown; schema?: unknown }; + // A tool can reach the model as a langchain tool, as a bare definition, + // or - this is how langchain binds the structured output an + // `output_schema` asks for - in the OpenAI function shape, which carries + // name, description and schema one level down. + const wrapped = (tool as { function?: { name?: string; description?: string; parameters?: unknown } }) + .function; + const fn = wrapped && typeof wrapped === "object" ? wrapped : {}; + const schema: unknown = isLangChainTool(tool) + ? tool.schema + : (definition.input_schema ?? definition.schema ?? fn.parameters); + + let inputSchema: Record; + if (!schema) { + inputSchema = emptyJsonSchema(); + } else { + try { + inputSchema = toJsonSchema(schema as never) as Record; + } catch { + inputSchema = emptyJsonSchema(); + } + } + + // The schema is whatever the tool declared, so it is stripped with the + // rest: it travels to the model sub flow as an argument, where + // `undefined` is rejected. + return stripUndefined({ + name: definition.name ?? fn.name ?? "unknown", + description: definition.description ?? fn.description ?? "", + input_schema: inputSchema, + }); + }); + log.debug( + `${specs.length} tools are bound to the model`, + specs.map((spec) => spec.name), + ); + return new FlowChatModel({ + run: this.run, + toolSpecs: specs, + boundOptions: { ...this.boundOptions, ...kwargs }, + }) as unknown as BoundFlowChatModel; + } + + async _generate(messages: BaseMessage[], options: this["ParsedCallOptions"]): Promise { + // A call option is the more specific of the two, so it wins over what was + // bound for the whole model. + const toolChoice: unknown = options.tool_choice ?? this.boundOptions.tool_choice; + const responseFormat: AiResponseFormat | undefined = toResponseFormat(this.boundOptions.response_format); + + const request: AiModelRequest = { + messages: messages.map(toFlowMessage), + tools: this.toolSpecs, + ...(options.stop ? { stop: options.stop } : {}), + ...(toolChoice ? { tool_choice: String(toolChoice) } : {}), + ...(responseFormat ? { response_format: responseFormat } : {}), + }; + + log.debug(`calling the model sub flow with ${request.messages.length} messages`, request); + + const started: number = Date.now(); + const raw: unknown = await this.run(request as never).catch((error: unknown) => { + log.error(`the model sub flow failed after ${Date.now() - started}ms`, { + error: error instanceof Error ? error.message : String(error), + }); + throw error; + }); + log.debug(`the model sub flow answered after ${Date.now() - started}ms with`, raw); + + const answer = parseOrThrow( + AiModelResponseSchema, + (raw as never) ?? {}, + "ERROR_INVALID_AI_MODEL_RESPONSE", + "The model sub flow did not return a valid model response", + ); + + const message: BaseMessage = toLangChainMessage(answer.message); + if (!isAIMessage(message)) { + throw new RuntimeError( + "ERROR_INVALID_AI_MODEL_RESPONSE", + `A model sub flow has to answer with an "ai" message, but answered with a "${answer.message.role}" message.`, + ); + } + + return { generations: [{ text: message.text, message }] }; + } +} diff --git a/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts deleted file mode 100644 index 9c51504..0000000 --- a/actions/ai-action/src/model/runtimefunctions/Model.openRouter.runtimefunction.ts +++ /dev/null @@ -1,125 +0,0 @@ -import { - DisplayIcon, - DisplayMessage, - FunctionContext, - Identifier, - Name, - Parameter, - RuntimeError, - Signature, - ThrowsError, -} from "@code0-tech/hercules"; -import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; -import type { AIMessage, AIMessageChunk, BaseMessage } from "@langchain/core/messages"; -import type { Runnable } from "@langchain/core/runnables"; -import { ChatOpenAI, type ChatOpenAICallOptions } from "@langchain/openai"; -import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; -import { AiModelResponseSchema, type AiModelResponse } from "../datatypes/Model.response.datatype.js"; -import type { AiModelTransform } from "../datatypes/Model.transform.datatype.js"; -import { AiModelRequestSchema, type AiModelRequest } from "../datatypes/Model.request.datatype.js"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; -import { requireText } from "../../shared/utils/Shared.requireText.util.js"; - -const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; - -interface ToolDefinition { - type: "function"; - function: { - name: string; - description: string; - parameters: Record; - }; -} - -type BoundModel = Runnable; - -@Identifier("ai::model::openrouter") -@DisplayIcon("tabler:router") -@Signature( - "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_tokens?: NUMBER): TRANSFORM", -) -@Name({ code: "en-US", content: "OpenRouter model" }) -@DisplayMessage({ code: "en-US", content: "OpenRouter ${model}" }) -@ThrowsError() -@Parameter({ - runtimeName: "model", - name: [{ code: "en-US", content: "Model" }], -}) -@Parameter({ - runtimeName: "api_key", - name: [{ code: "en-US", content: "API key" }], -}) -@Parameter({ - runtimeName: "temperature", - name: [{ code: "en-US", content: "Temperature" }], - optional: true, -}) -@Parameter({ - runtimeName: "max_tokens", - name: [{ code: "en-US", content: "Maximum tokens" }], - optional: true, -}) -export class OpenRouterModelFunction { - run( - _context: FunctionContext, - model: string, - api_key: string, - temperature?: number, - max_tokens?: number, - ): AiModelTransform { - const identifier: string = requireText( - model, - "ERROR_INVALID_AI_MODEL", - "An OpenRouter model needs a model identifier.", - ); - const chat: ChatOpenAI = new ChatOpenAI({ - model: identifier, - apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "An OpenRouter model needs an API key."), - configuration: { baseURL: OPENROUTER_BASE_URL }, - temperature, - maxTokens: max_tokens, - }); - - return { - name: `openrouter:${identifier}`, - description: `OpenRouter model ${identifier}`, - inputSchema: AiModelRequestSchema, - outputSchema: AiModelResponseSchema, - run: async (request: AiModelRequest): Promise => { - const parsed: AiModelRequest = parseOrThrow( - AiModelRequestSchema, - request, - "ERROR_INVALID_AI_MODEL_REQUEST", - "The model request is not valid", - ); - - const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.input_schema, - }, - })); - const bound: BoundModel = tools.length > 0 ? chat.bindTools(tools) : chat; - const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); - - const answer: AIMessage = await bound - .invoke(messages, { - ...(parsed.stop ? { stop: parsed.stop } : {}), - ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), - }) - .catch((error: unknown) => { - throw new RuntimeError( - "ERROR_AI_MODEL_CALL_FAILED", - `The OpenRouter call to "${identifier}" failed: ${describeError(error)}`, - ); - }); - - return { message: toFlowMessage(answer) }; - }, - }; - } -} diff --git a/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts b/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts deleted file mode 100644 index 9338eaa..0000000 --- a/actions/ai-action/src/model/utils/Model.flowChatModel.util.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { RuntimeError, type SubFlow } from "@code0-tech/hercules"; -import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; -import { - BaseChatModel, - type BaseChatModelCallOptions, - type BindToolsInput, -} from "@langchain/core/language_models/chat_models"; -import { isAIMessage, type AIMessageChunk, type BaseMessage } from "@langchain/core/messages"; -import type { ChatResult } from "@langchain/core/outputs"; -import type { Runnable } from "@langchain/core/runnables"; -import type { AiModelRequest } from "../datatypes/Model.request.datatype.js"; -import type { AiToolSpec } from "../datatypes/Model.toolSpec.datatype.js"; -import { AiModelResponseSchema } from "../datatypes/Model.response.datatype.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; -import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; -import { toToolSpec } from "./Model.toToolSpec.util.js"; - -type BoundFlowChatModel = Runnable; - -interface FlowChatModelFields { - run: SubFlow; - toolSpecs?: AiToolSpec[]; -} - -export class FlowChatModel extends BaseChatModel { - private readonly run: SubFlow; - private readonly toolSpecs: AiToolSpec[]; - - constructor(fields: FlowChatModelFields) { - super({}); - this.run = fields.run; - this.toolSpecs = fields.toolSpecs ?? []; - } - - _llmType(): string { - return "code0_flow"; - } - - bindTools(tools: BindToolsInput[]): BoundFlowChatModel { - return new FlowChatModel({ - run: this.run, - toolSpecs: tools.map(toToolSpec), - }) as unknown as BoundFlowChatModel; - } - - async _generate(messages: BaseMessage[], options: this["ParsedCallOptions"]): Promise { - const request: AiModelRequest = { - messages: messages.map(toFlowMessage), - tools: this.toolSpecs, - ...(options.stop ? { stop: options.stop } : {}), - ...(options.tool_choice ? { tool_choice: String(options.tool_choice) } : {}), - }; - - const answer = parseOrThrow( - AiModelResponseSchema, - (await this.run(request as never)) ?? {}, - "ERROR_INVALID_AI_MODEL_RESPONSE", - "The model sub flow did not return a valid model response", - ); - - const message: BaseMessage = toLangChainMessage(answer.message); - if (!isAIMessage(message)) { - throw new RuntimeError( - "ERROR_INVALID_AI_MODEL_RESPONSE", - `A model sub flow has to answer with an "ai" message, but answered with a "${answer.message.role}" message.`, - ); - } - - return { generations: [{ text: message.text, message }] }; - } -} diff --git a/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts b/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts deleted file mode 100644 index 751c98b..0000000 --- a/actions/ai-action/src/model/utils/Model.toToolSpec.util.ts +++ /dev/null @@ -1,15 +0,0 @@ -import type { BindToolsInput } from "@langchain/core/language_models/chat_models"; -import { isLangChainTool } from "@langchain/core/tools"; -import type { AiToolSpec } from "../datatypes/Model.toolSpec.datatype.js"; -import { toInputSchema } from "../../shared/utils/Shared.toInputSchema.util.js"; - -export function toToolSpec(tool: BindToolsInput): AiToolSpec { - const definition = tool as { name?: string; description?: string; input_schema?: unknown; schema?: unknown }; - const schema: unknown = isLangChainTool(tool) ? tool.schema : (definition.input_schema ?? definition.schema); - - return { - name: definition.name ?? "unknown", - description: definition.description ?? "", - input_schema: toInputSchema(schema), - }; -} diff --git a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts new file mode 100644 index 0000000..41b61ff --- /dev/null +++ b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts @@ -0,0 +1,81 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + Editable, + EventSetting, + Identifier, + Name, + Signature, + type RuntimeEventRunnable, +} from "@code0-tech/hercules"; + +/** + * A flow bound to this event is one model of an OpenAI-compatible endpoint the action + * serves itself (see {@link startOpenAiServer}). Nothing else hosts it: the action + * opens the HTTP port, answers `GET /models` from the flows bound here, and runs the + * matching flow for `POST /chat/completions`. + * + * The flow is handed the client's request as an `AI_CHAT_REQUEST` - the type + * `ai::agent::create` takes - and answers it with `ai::openai::respond`, from wherever + * in the flow that belongs, so a flow that logs or stores something after the agent + * still answers with the agent's reply. A flow that never responds falls back to its + * own return value. + * + * `route` is the path the endpoint lives under, with the project's slug in front of + * it, and unique per project. `model` is the name a client sees and picks, which every + * flow has to carry: a client only ever asks for a model, so a flow without one has + * no name to be asked for. `api_key` is the flow's to set or leave: the server opens + * a port of its own, so without a key anyone who reaches it can run the flow. + */ +@Identifier("ai::openai::server") +@DisplayIcon("tabler:ai") +@Editable() +@Signature("(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST") +@Name({ code: "en-US", content: "OpenAI endpoint" }) +@Description({ + code: "en-US", + content: + "Serves this flow as one model of an OpenAI-compatible endpoint. Any OpenAI client - Open WebUI among them - can be pointed at the project's route and talk to the flow; the request arrives as a chat request, and the flow answers it with \"Respond to the OpenAI request\". The model name is what the client lists and picks.", +}) +@DisplayMessage({ code: "en-US", content: "OpenAI request for ${model} on ${route}" }) +@Alias({ code: "en-US", content: "openai;chat;completions;endpoint;open web ui;llm;api" }) +@EventSetting({ + identifier: "route", + unique: "PROJECT", + name: [{ code: "en-US", content: "Route" }], + description: [ + { + code: "en-US", + content: + "The path this endpoint lives under, e.g. /v1. A client is pointed at the project's slug followed by this route as its base URL and appends /chat/completions and /models itself.", + }, + ], + defaultValue: "/v1", +}) +@EventSetting({ + identifier: "model", + unique: "PROJECT", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model name clients see and ask for, unique within the project. It can say what this flow does rather than name a provider's model - a client lists this name, so the endpoint serves nothing until it is set.", + }, + ], +}) +@EventSetting({ + identifier: "api_key", + optional: true, + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The key a client has to send as its bearer token. Left empty, the endpoint answers without authentication - only do that where nothing else can reach it.", + }, + ], +}) +export class AiOpenAiServerRuntimeEvent implements RuntimeEventRunnable {} diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts new file mode 100644 index 0000000..30718a7 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts @@ -0,0 +1,611 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + SubFlow, + ThrowsError, +} from "@code0-tech/hercules"; +import type { ClientTool } from "@langchain/core/tools"; +import { MultiServerMCPClient } from "@langchain/mcp-adapters"; +import { createAgent, createMiddleware, tool, type AnyAgentMiddleware, type ReactAgent } from "langchain"; +import type { AiAgentApproval } from "../../datatypes/agent/Agent.approval.datatype.js"; +import { AiAgentRequestSchema, type AiAgentRequest } from "../../datatypes/agent/Agent.request.datatype.js"; +import { AiAgentResponseSchema, type AiAgentResponse } from "../../datatypes/agent/Agent.response.datatype.js"; +import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; +import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; +import { AiMcpServerSchema, type AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { AgentDefinition, ToolEntry } from "../../types/agent/Agent.types.js"; +import type { Logger } from "../../types/shared/Log.types.js"; +import { asList } from "../../utils/shared/Shared.asList.util.js"; +import { asSubFlow } from "../../utils/shared/Shared.asSubFlow.util.js"; +import { asText } from "../../utils/shared/Shared.asText.util.js"; +import { codeOf } from "../../utils/middleware/Approval.codeOf.util.js"; +import { createHookHandler } from "../../utils/middleware/Middleware.createHookHandler.util.js"; +import { DECIDED } from "../../utils/middleware/Approval.markers.util.js"; +import { describeError } from "../../utils/shared/Shared.describeError.util.js"; +import { emptyJsonSchema } from "../../utils/shared/Shared.emptyJsonSchema.util.js"; +import { FlowChatModel } from "../../model/Model.flowChatModel.js"; +import { formatIssues } from "../../utils/shared/Shared.formatIssues.util.js"; +import { fromChatMessage } from "../../utils/chat/Chat.fromChatMessage.util.js"; +import { isSubFlow } from "../../utils/shared/Shared.isSubFlow.util.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; +import { textOf } from "../../utils/message/Message.textOf.util.js"; +import { toChatResponse } from "../../utils/chat/Chat.toChatResponse.util.js"; +import { toConnection } from "../../utils/mcp/Mcp.toConnection.util.js"; +import { toFlowMessage } from "../../utils/message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; +import { toPlainSchema } from "../../utils/shared/Shared.toPlainSchema.util.js"; + +/** What the model APIs accept as a tool name: letters, digits, underscore, dash. */ +const TOOL_NAME_ALLOWED = /[^a-zA-Z0-9_-]+/g; + +/** Where a middleware may send the run instead of letting it carry on. */ +const JUMP_TARGETS = ["model", "tools", "end"] as const; + +/** + * What the extraction turn asks for, once the agent has finished working. + * + * The conversation is handed over as one message rather than replayed turn by turn: + * this call binds no tools, and a conversation that still carries tool calls without + * the tools they belong to is rejected by some providers. Flattened to text it asks + * nothing of the provider but the type. + */ +const EXTRACTION_PROMPT = + "The conversation above is finished. Answer with what it produced, in the type you were given, and add nothing that was not said in it."; + +@Identifier("ai::agent::create") +@DisplayIcon("tabler:ai") +@Signature( + "(name: TEXT, system_prompt: TEXT, model: TRANSFORM, prompt: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, output_schema?: T, request?: AI_CHAT_REQUEST, middleware?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", +) +@Name({ code: "en-US", content: "Create agent" }) +@DisplayMessage({ code: "en-US", content: "Ask the agent ${name} ${prompt}" }) +@ThrowsError() +@Parameter({ + runtimeName: "name", + name: [{ code: "en-US", content: "Name" }], + description: [ + { + code: "en-US", + content: + "The agent's own name. It identifies the agent in the node's message and in the logs, and is what an error names when the agent fails.", + }, + ], +}) +@Parameter({ + runtimeName: "system_prompt", + name: [{ code: "en-US", content: "System prompt" }], + description: [ + { + code: "en-US", + content: + "The standing instructions the agent works under - its role, what it may and may not do, how the answer should read. They are sent ahead of every turn, so they hold for the whole conversation rather than for this prompt alone.", + }, + ], +}) +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model the agent thinks with, built by one of the model nodes. The model decides which provider is called and on what key; the agent only hands it the conversation and the tools.", + }, + ], +}) +@Parameter({ + runtimeName: "prompt", + name: [{ code: "en-US", content: "Prompt" }], + description: [ + { + code: "en-US", + content: + "The question put to the agent in this run. It is appended to the messages the request already carries, so it is the last thing the agent reads before answering. It may be left empty when the request already carries the question.", + }, + ], +}) +@Parameter({ + runtimeName: "tools", + name: [{ code: "en-US", content: "Tools" }], + description: [ + { + code: "en-US", + content: + "What the agent may reach for while it works: flows of this project, each offered as a tool under its own name, and MCP servers, whose tools are discovered on connect. The agent decides on its own which of them to call, and how often.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "output_schema", + name: [{ code: "en-US", content: "Output type" }], + description: [ + { + code: "en-US", + content: + "The data type the answer has to come back in, so the flow can read the fields instead of parsing prose. It has to be an object type; left empty, the agent answers in plain text.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "request", + name: [{ code: "en-US", content: "Request" }], + description: [ + { + code: "en-US", + content: + "A conversation to continue, in the chat format an OpenAI-compatible client sends. Its messages go ahead of the prompt, which is how a chat endpoint hands the agent everything that was said before.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "middleware", + name: [{ code: "en-US", content: "Middleware" }], + description: [ + { + code: "en-US", + content: + "Steps that sit between the agent and its model and may change what happens on each turn - trimming the conversation, asking before a tool runs. They are applied in the order they are listed.", + }, + ], + optional: true, +}) +export class CreateAgentFunction { + /** + * Builds the agent and runs it in one node, rather than returning the agent for a + * second node to invoke. A returned agent would be a sub flow function, and the + * sub flow references it carries - its model above all - only live while the node + * that minted them is outstanding, so an agent invoked by a later node can never + * reach its model (see code0-tech/taurus#346). Running it here keeps this node's + * call open for as long as the agent works, which is exactly what those + * references are scoped to. + * + * The parameters are ordered by how often a flow reaches for them: what every + * agent needs first, then the tools and the answer's type, and the conversation + * and middleware knobs last. + */ + async run( + _context: FunctionContext, + name: string, + system_prompt: string, + model: unknown, + prompt: string, + tools?: ToolEntry[], + output_schema?: unknown, + request?: AiChatRequest, + middleware?: unknown[], + ): Promise { + const log: Logger = logger("agent", _context.executionId); + const toolLog: Logger = logger("tool", _context.executionId); + log.info(`the node asks the agent "${name}"`, { + prompt, + tools: Array.isArray(tools) ? tools.length : 0, + middleware: Array.isArray(middleware) ? middleware.length : 0, + request, + output_schema, + }); + + // The "output_schema" parameter is a TYPE: the data type the flow wants the + // agent to answer in. Its value reaches the action as that type's JSON schema + // - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` + // unwraps either way. langchain only accepts a plain JSON schema as a + // response format when it describes an object (it keys off `properties`), and + // a structured answer has to be an object anyway to come back as a data + // type's value, so a schema for anything else is rejected here rather than + // deep inside the agent. + let outputSchema: Record | undefined; + if (output_schema !== undefined && output_schema !== null) { + outputSchema = toPlainSchema(output_schema); + if (!outputSchema || typeof outputSchema !== "object") { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + `The "output_schema" parameter has to be a type, but a ${typeof output_schema} was passed.`, + ); + } + if (!("properties" in outputSchema)) { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + 'The agent can only answer in an object type: the type passed as "output_schema" has no properties.', + ); + } + } + + const definition: AgentDefinition = { + name: requireText(name, "ERROR_INVALID_AI_AGENT", "An agent needs a name."), + systemPrompt: asText(system_prompt ?? "", "system_prompt", "ERROR_INVALID_AI_AGENT"), + model: asSubFlow(model, "model"), + // A tool is either a flow of the project or an MCP server; which entry was + // neither is part of the error, because that is what makes it fixable. + tools: asList(tools, "tools").map((entry, index): ToolEntry => { + if (isSubFlow(entry)) return entry; + + const server = AiMcpServerSchema.safeParse(entry); + if (server.success) return server.data; + + throw new RuntimeError( + "ERROR_INVALID_AI_TOOL", + `Entry ${index + 1} of "tools" is neither a sub flow nor a valid MCP server: ${formatIssues(server.error.issues)}`, + ); + }), + middleware: asList(middleware, "middleware").map((entry, index): SubFlow => + asSubFlow(entry, `middleware[${index}]`), + ), + ...(outputSchema ? { outputSchema } : {}), + }; + + const servers: AiMcpServer[] = definition.tools.filter((entry): entry is AiMcpServer => !isSubFlow(entry)); + + // MCP tool names are namespaced with the server name, so the names have to be + // unique; and every connection is built here, where a server that cannot be + // connected to fails the node rather than a tool call deep inside the agent. + const serverNames: string[] = servers.map((server) => server.name); + const duplicate: string | undefined = serverNames.find( + (named, index) => serverNames.indexOf(named) !== index, + ); + if (duplicate) { + throw new RuntimeError( + "ERROR_DUPLICATE_AI_MCP_SERVER", + `More than one MCP server is named "${duplicate}". MCP tool names are namespaced with the server name, so the names must be unique.`, + ); + } + servers.forEach(toConnection); + + const parsed: AiChatRequest = parseOrThrow( + AiChatRequestSchema, + request ?? { messages: [] }, + "ERROR_INVALID_AI_CHAT_REQUEST", + "The chat request is not valid", + ); + const question: string = asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"); + const conversation: AiMessage[] = [ + ...parsed.messages.map(fromChatMessage), + ...(question.length > 0 + ? [{ role: "human", content: [{ type: "text", text: question }] } as AiMessage] + : []), + ]; + if (conversation.length === 0) { + throw new RuntimeError( + "ERROR_INVALID_AI_CHAT_REQUEST", + "There is nothing to ask: the prompt is empty and the request carries no messages.", + ); + } + + const started: number = Date.now(); + log.info(`running the agent "${definition.name}"`, { + messages: conversation.length, + tools: definition.tools.length, + middleware: definition.middleware.length, + output_schema: definition.outputSchema, + system_prompt: definition.systemPrompt, + }); + + const agentRequest: AiAgentRequest = parseOrThrow( + AiAgentRequestSchema, + { messages: conversation }, + "ERROR_INVALID_AI_AGENT_REQUEST", + "The agent request is not valid", + ); + + const flows: SubFlow[] = definition.tools.filter(isSubFlow); + log.debug(`building the agent "${definition.name}"`, { + mcp_servers: servers.map((server) => server.name), + flow_tools: flows.length, + }); + + // The MCP connections stay open for as long as the agent may call a tool, so + // closing them is the one thing that has to happen on every way out below. + let mcpTools: ClientTool[] = []; + let close: () => Promise = async (): Promise => undefined; + if (servers.length > 0) { + const client = new MultiServerMCPClient({ + mcpServers: Object.fromEntries(servers.map((server) => [server.name, toConnection(server)])), + }); + close = (): Promise => client.close(); + + let discovered: ClientTool[]; + try { + discovered = (await client.getTools()) as unknown as ClientTool[]; + } catch (error: unknown) { + await client.close().catch(() => undefined); + throw new RuntimeError( + "ERROR_LOADING_AI_MCP_TOOLS", + `Could not load tools from the configured MCP servers: ${describeError(error)}`, + ); + } + + const allowed = new Set(servers.flatMap((server) => server.allowed_tools ?? [])); + mcpTools = + allowed.size === 0 + ? discovered + : discovered.filter((entry) => allowed.has(entry.name.split("__").pop() ?? entry.name)); + } + + let agent: ReactAgent; + try { + // Two sub flows may share a title, and the model needs to tell the tools + // they become apart. + const taken = new Set(); + const agentTools: ClientTool[] = [ + ...flows.map((flow, index): ClientTool => { + const schema: Record | undefined = toPlainSchema(flow.inputSchema); + + // The name the caller gave the sub flow, turned into something a + // model will accept. The sub flow carries it itself; its schema + // `title` is the older place to put it and is still read. A sub + // flow that carries neither falls back to its position, so a + // nameless tool is still addressable. + // + // A sub flow is a callable, so `name` is only the caller's name + // when hercules defined it over the intrinsic `Function.name` - + // which it does enumerably. Read plainly, a sub flow the caller + // left unnamed would be advertised under whatever the wrapping + // function happens to be called, and the schema's title would + // never be reached. + const named: PropertyDescriptor | undefined = Object.getOwnPropertyDescriptor(flow, "name"); + const declared: unknown = + (named?.enumerable ? named.value : undefined) ?? schema?.title ?? schema?.name; + const cleaned: string = + typeof declared === "string" + ? declared.trim().replace(TOOL_NAME_ALLOWED, "_").replace(/^_+|_+$/g, "").slice(0, 64) + : ""; + let toolName: string = cleaned.length > 0 ? cleaned : `tool_${index + 1}`; + if (taken.has(toolName)) { + let suffix = 2; + while (taken.has(`${toolName}_${suffix}`)) suffix += 1; + toolName = `${toolName}_${suffix}`; + } + taken.add(toolName); + + const described: unknown = flow.description ?? schema?.description; + const description: string = typeof described === "string" ? described : ""; + toolLog.debug(`the tool "${toolName}" is built from a flow`, { + declared, + description, + schema, + }); + + return tool( + (args: unknown) => { + const calledAt: number = Date.now(); + toolLog.info(`the agent calls the tool "${toolName}" with`, args); + + return Promise.resolve(flow(args as never)).then( + (result) => { + toolLog.info( + `the tool "${toolName}" answered after ${Date.now() - calledAt}ms with`, + result, + ); + return typeof result === "string" ? result : JSON.stringify(result ?? null); + }, + (error: unknown) => { + toolLog.error(`the tool "${toolName}" failed after ${Date.now() - calledAt}ms`, { + error: describeError(error), + }); + return `The tool failed: ${describeError(error)}`; + }, + ); + }, + { + name: toolName, + description, + schema: (schema ?? emptyJsonSchema()) as never, + }, + ) as unknown as ClientTool; + }), + ...mcpTools, + ]; + log.debug( + `the agent "${definition.name}" has ${agentTools.length} tools`, + agentTools.map((entry) => (entry as { name?: string }).name), + ); + + agent = createAgent({ + model: new FlowChatModel({ run: definition.model }), + tools: agentTools, + middleware: definition.middleware.map( + (flow, index): AnyAgentMiddleware => + createMiddleware({ + name: `flow_middleware_${index + 1}`, + beforeModel: { + hook: createHookHandler(flow, definition.name, "before_model"), + canJumpTo: [...JUMP_TARGETS], + }, + afterModel: { + hook: createHookHandler(flow, definition.name, "after_model"), + canJumpTo: [...JUMP_TARGETS], + }, + } as never) as AnyAgentMiddleware, + ), + name: definition.name, + ...(definition.systemPrompt ? { systemPrompt: definition.systemPrompt } : {}), + // An output type is only asked for here when the agent has no tools + // to offer. langchain sends the type and the tools in one request - + // as a response format, or as an extract tool with the tool call + // forced - and a provider may refuse that combination outright + // ("tools is incompatible with response_format"). With tools bound + // the type is asked for afterwards instead, in a turn of its own. + ...(definition.outputSchema && agentTools.length === 0 + ? { responseFormat: definition.outputSchema } + : {}), + } as never) as unknown as ReactAgent; + } catch (error: unknown) { + log.error(`the agent "${definition.name}" could not be built`, { error: describeError(error) }); + await close().catch(() => undefined); + if (error instanceof RuntimeError) throw error; + throw new RuntimeError( + "ERROR_BUILDING_AI_AGENT", + `Could not build agent "${definition.name}": ${describeError(error)}`, + ); + } + + let answer: AiAgentResponse; + try { + log.debug("the conversation the agent starts from", agentRequest.messages); + const result = await agent.invoke({ messages: agentRequest.messages.map(toLangChainMessage) }); + + // The run only ever produced what is in the conversation, so both what it + // did and what it is waiting for are read back off it. + const produced: AiMessage[] = (result.messages ?? []).map(toFlowMessage); + + // Every tool the agent called, with the arguments it used and what came + // back. A chat completion carries one message, so without this the whole + // middle of a run - the part that explains how the answer came about - + // never leaves the node. + const steps: AiAgentStep[] = []; + for (const message of produced) { + for (const block of message.content ?? []) { + if (block.type !== "tool_call" || typeof block.name !== "string") continue; + + const id: unknown = block.id; + const answered: AiMessage | undefined = produced.find( + (entry) => entry.role === "tool" && entry.tool_call_id === id, + ); + const text: string | undefined = answered ? textOf(answered) : undefined; + const failed: boolean = answered?.status === "error"; + + steps.push({ + name: block.name, + ...(block.args && typeof block.args === "object" + ? { args: block.args as Record } + : {}), + ...(text !== undefined && !failed ? { result: text } : {}), + ...(text !== undefined && failed ? { error: text } : {}), + }); + } + } + + // What the answer is waiting for, read back off the question it asked: the + // calls and the code they are answered with. A flow gets them as data - + // enough to build buttons elsewhere - and the node needs to know nothing + // about which tools a middleware guarded. + const ending: AiMessage | undefined = produced.at(-1); + const asked: string = ending ? textOf(ending) : ""; + const code: string | undefined = codeOf(asked); + const pending: AiAgentApproval[] = []; + if (code && !asked.includes(`${DECIDED} `)) { + for (const line of asked.split("\n")) { + const described: string = line.trim(); + if (!described.endsWith(")")) continue; + + const call: string = described.slice(0, -1); + const opens: number = call.indexOf("("); + if (opens <= 0) continue; + + let args: Record | undefined; + try { + args = JSON.parse(call.slice(opens + 1)) as Record; + } catch { + args = undefined; + } + + pending.push({ name: call.slice(0, opens), ...(args ? { args } : {}), code }); + } + } + + if (pending.length > 0) { + log.info(`the agent "${definition.name}" is waiting for approval`, pending); + } + + answer = parseOrThrow( + AiAgentResponseSchema, + { + messages: produced, + ...(result.structuredResponse ? { structured_response: result.structuredResponse } : {}), + ...(steps.length > 0 ? { steps } : {}), + ...(pending.length > 0 ? { awaiting_approval: pending } : {}), + }, + "ERROR_INVALID_AI_AGENT_RESPONSE", + "The agent did not answer with a valid agent response", + ); + log.info( + `the agent "${definition.name}" finished after ${Date.now() - started}ms with ${answer.messages.length} messages`, + { structured_response: answer.structured_response }, + ); + log.debug("the conversation the agent ends with", answer.messages); + + // The second phase: the agent has finished working, so the type can now + // be asked for on its own, with no tools in the request to collide with + // it. This is the turn langchain cannot do for us - it ends its loop as + // soon as the model answers without a tool call, and the type has to be + // asked for in a request of its own. + if (definition.outputSchema && !answer.structured_response) { + const transcript: string = answer.messages + .map((message) => { + const said: string = textOf(message); + return said.length > 0 ? `${message.role}: ${said}` : ""; + }) + .filter((line) => line.length > 0) + .join("\n\n"); + + log.debug(`asking the agent "${definition.name}" for the type on its own`, { + transcript: transcript.length, + }); + + const extractor = createAgent({ + model: new FlowChatModel({ run: definition.model }), + tools: [], + responseFormat: definition.outputSchema, + } as never) as unknown as ReactAgent; + + const extracted = await extractor.invoke({ + messages: [ + toLangChainMessage({ + role: "human", + content: [{ type: "text", text: `${transcript}\n\n${EXTRACTION_PROMPT}` }], + }), + ], + }); + + if (extracted.structuredResponse) { + answer = { ...answer, structured_response: extracted.structuredResponse }; + log.info(`the agent "${definition.name}" answered the type on the second turn`, { + structured_response: answer.structured_response, + }); + } + } + } catch (error: unknown) { + log.error(`the agent "${definition.name}" failed after ${Date.now() - started}ms`, { + error: error instanceof Error ? error.message : String(error), + stack: error instanceof Error ? error.stack : undefined, + }); + throw error; + } finally { + await close().catch(() => undefined); + } + + const last: AiMessage | undefined = answer.messages.at(-1); + if (!last) { + throw new RuntimeError("ERROR_INVALID_AI_AGENT_RESPONSE", "The agent answered with an empty conversation."); + } + + // An agent asked for a type has to answer in it: without the structured answer + // the node's return value would be missing the very field the flow reads. By + // here the type has been asked for on its own as well, so this is a model + // that would not answer in it either way. + if (outputSchema && !answer.structured_response) { + throw new RuntimeError( + "ERROR_INVALID_AI_AGENT_RESPONSE", + `The agent "${definition.name}" did not answer in the type passed as "output_schema", not even when asked for it on its own.`, + ); + } + + const response: AiChatResponse = toChatResponse(last, parsed.model ?? "", answer.structured_response, { + ...(answer.steps ? { steps: answer.steps } : {}), + ...(answer.awaiting_approval ? { awaitingApproval: answer.awaiting_approval } : {}), + }); + log.info(`the agent "${definition.name}" answers the node with`, response); + return response; + } +} diff --git a/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts new file mode 100644 index 0000000..5c79e6b --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts @@ -0,0 +1,256 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { AiContentBlock } from "../../datatypes/message/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import { AiAgentStateSchema, type AiAgentState } from "../../datatypes/middleware/Middleware.agentState.datatype.js"; +import { AiStateUpdateSchema, type AiStateUpdate } from "../../datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import type { AiMiddlewareTransform } from "../../datatypes/middleware/Middleware.transform.datatype.js"; +import type { ApprovalDecision, OpenQuestion, ToolCall } from "../../types/middleware/Approval.types.js"; +import { APPROVE, DECIDED, DECLINE } from "../../utils/middleware/Approval.markers.util.js"; +import { asList } from "../../utils/shared/Shared.asList.util.js"; +import { askFor } from "../../utils/middleware/Approval.askFor.util.js"; +import { codeOf } from "../../utils/middleware/Approval.codeOf.util.js"; +import { describeCall } from "../../utils/middleware/Approval.describeCall.util.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { newCode } from "../../utils/middleware/Approval.newCode.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; +import { settle } from "../../utils/middleware/Approval.settle.util.js"; +import { textOf } from "../../utils/message/Message.textOf.util.js"; + +const log = logger("middleware"); + +@Identifier("ai::middleware::human_in_the_loop") +@DisplayIcon("tabler:message-ai") +@Signature("(tools: LIST): TRANSFORM") +@Name({ code: "en-US", content: "Human in the loop" }) +@DisplayMessage({ code: "en-US", content: "Ask before running ${tools}" }) +@ThrowsError() +@Parameter({ + runtimeName: "tools", + name: [{ code: "en-US", content: "Tools" }], + description: [ + { + code: "en-US", + content: + "The tools the agent has to ask about before running them. Instead of running one, it answers with what it wants to do and ends the turn; the reply to that question - the next message of the conversation - decides.", + }, + ], +}) +export class HumanInTheLoopMiddlewareFunction { + /** + * A middleware that makes an agent ask before it runs certain tools, and holds it + * to the answer. + * + * It is a middleware like any other, so an agent gets it the same way it gets a + * trimmer or a flow of the project - the agent node itself knows nothing about + * approvals. + * + * Asking happens by answering: the calls are held back and the turn ends with the + * question, so the request a client is waiting on is finished and a person has all + * the time they need. The reply arrives as the next message of the conversation - + * a chat client has no other channel, and an OpenAI client resends the whole + * conversation anyway. + * + * Whether it approved is decided by matching the question's code, never by the + * agent asking again: a model that re-states a call a person refused gets nothing, + * and so does one that re-states a call nobody answered. Each question is spent + * once, so every call needs an approval of its own. + */ + run(_context: FunctionContext, tools: unknown[]): AiMiddlewareTransform { + const guarded: string[] = asList(tools, "tools").map((tool, index) => + requireText( + tool, + "ERROR_INVALID_AI_STATE_UPDATE", + `Entry ${index + 1} of "tools" has to be the name of a tool to ask about.`, + ), + ); + if (guarded.length === 0) { + throw new RuntimeError( + "ERROR_INVALID_AI_STATE_UPDATE", + "Human in the loop needs at least one tool to ask about.", + ); + } + + const names = new Set(guarded); + + return { + name: `human_in_the_loop:${guarded.join(",")}`, + description: `Asks before running ${guarded.join(", ")}`, + inputSchema: AiAgentStateSchema, + outputSchema: AiStateUpdateSchema, + run: async (state: AiAgentState): Promise => { + const parsed: AiAgentState = parseOrThrow( + AiAgentStateSchema, + state, + "ERROR_INVALID_AI_AGENT_STATE", + "The agent state is not valid", + ); + + // Only the phase after the model has tool calls to hold back. + if (parsed.hook !== "after_model") return {}; + + const last: AiMessage | undefined = parsed.messages.at(-1); + if (!last || last.role !== "ai") return {}; + + // The tool calls the message asks for, with the arguments the model + // chose, narrowed to the ones this middleware guards. + const held: ToolCall[] = []; + const declined: ToolCall[] = []; + const approved: ToolCall[] = []; + const calls: ToolCall[] = (last.content ?? []) + .filter( + (block): block is AiContentBlock & { name: string } => + block.type === "tool_call" && typeof block.name === "string", + ) + .map((block) => ({ name: block.name, args: (block.args ?? {}) as Record })) + .filter((call) => names.has(call.name)); + if (calls.length === 0) return {}; + + const earlier: AiMessage[] = parsed.messages.slice(0, -1); + // Spent questions are rewritten in place, so one answer cannot serve + // two calls. + const settled = new Map(); + let open: string | undefined; + let declinedCode: string | undefined; + + for (const call of calls) { + // The newest question about this call that has not been spent. A + // spent question carries DECIDED and is skipped, so an approval is + // used for the one call it was given for - the next call of the + // same tool, with the same arguments, has to be asked about again. + const needle: string = describeCall(call); + let question: OpenQuestion | undefined; + + for (let at = earlier.length - 1; at >= 0 && !question; at -= 1) { + const message: AiMessage = earlier[at]; + if (message.role !== "ai") continue; + + const text: string = textOf(message); + if (!text.includes(needle) || text.includes(`${DECIDED} `)) continue; + + const code: string | undefined = codeOf(text); + if (!code) continue; + + // What the person answered, matched rather than understood. + // Only "APPROVE " of this very question approves, and + // only "DECLINE " refuses; everything else leaves it + // open, a plain "yes" included. No wording, no language and no + // model decides here. An answer releases the run that directly + // follows it and nothing later: once the agent has spoken + // again, the approval is spent - which is what makes it + // single-use without anything being stored. + const wanted: string = code.toUpperCase(); + let decision: ApprovalDecision = "open"; + + for (const reply of earlier.slice(at + 1)) { + if (reply.role === "human") { + const said: string = textOf(reply).toUpperCase(); + if (decision === "open" && said.includes(`${DECLINE} ${wanted}`)) decision = "declined"; + else if (decision === "open" && said.includes(`${APPROVE} ${wanted}`)) + decision = "approved"; + continue; + } + + if (reply.role === "ai" && decision !== "open") { + decision = "spent"; + break; + } + } + + question = { at, text, code, decision }; + } + + if (!question) { + held.push(call); + continue; + } + + switch (question.decision) { + case "approved": + settled.set(question.at, settle(earlier[question.at], question.code)); + approved.push(call); + break; + case "declined": + settled.set(question.at, settle(earlier[question.at], question.code)); + declined.push(call); + declinedCode ??= question.code; + break; + case "open": + // The question stands; its code is still the one that + // decides, so it is repeated rather than replaced. + held.push(call); + open ??= question.code; + break; + case "spent": + log.debug("an earlier approval was already spent, so this call is asked about again", { + call: describeCall(call), + code: question.code, + }); + held.push(call); + break; + } + } + + if (settled.size === 0 && held.length === 0) return {}; + const history: AiMessage[] = earlier.map((message, at) => settled.get(at) ?? message); + + // Anything undecided ends the turn with the question - running half of + // what the model wanted while asking about the rest would be a + // decision nobody made. + if (held.length > 0) { + const code: string = open ?? newCode(); + log.info(`the agent asks before it runs (${code})`, held.map(describeCall)); + return { + messages: [ + ...history, + { + role: "ai", + content: [{ type: "text", text: askFor(held, code) }], + ...(last.id ? { id: last.id } : {}), + }, + ], + jump_to: "end", + }; + } + + if (declined.length > 0) { + log.info("the agent does not run what was declined", declined.map(describeCall)); + return { + messages: [ + ...history, + { + role: "ai", + content: [ + { + type: "text", + text: [ + `${DECLINE} ${declinedCode ?? newCode()}`, + ...declined.map(describeCall), + ].join("\n"), + }, + ], + ...(last.id ? { id: last.id } : {}), + }, + ], + jump_to: "end", + }; + } + + // Everything was approved: the calls stay as the model made them, and + // only the questions behind them are marked as spent. + log.info("the agent runs what was approved", approved.map(describeCall)); + return { messages: [...history, last] }; + }, + }; + } +} diff --git a/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts similarity index 68% rename from actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts rename to actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts index 0f4d0f9..f28b744 100644 --- a/actions/ai-action/src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts @@ -11,12 +11,12 @@ import { } from "@code0-tech/hercules"; import type { BaseMessage } from "@langchain/core/messages"; import { countTokensApproximately, trimMessages } from "langchain"; -import { toFlowMessage } from "../../message/utils/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../../message/utils/Message.toLangChainMessage.util.js"; -import type { AiMiddlewareTransform } from "../datatypes/Middleware.transform.datatype.js"; -import { AiStateUpdateSchema, type AiStateUpdate } from "../datatypes/Middleware.stateUpdate.datatype.js"; -import { AiAgentStateSchema, type AiAgentState } from "../datatypes/Middleware.agentState.datatype.js"; -import { parseOrThrow } from "../../shared/utils/Shared.parseOrThrow.util.js"; +import { toFlowMessage } from "../../utils/message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; +import type { AiMiddlewareTransform } from "../../datatypes/middleware/Middleware.transform.datatype.js"; +import { AiStateUpdateSchema, type AiStateUpdate } from "../../datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import { AiAgentStateSchema, type AiAgentState } from "../../datatypes/middleware/Middleware.agentState.datatype.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; type TrimStrategy = "first" | "last"; @@ -32,15 +32,36 @@ type TrimStrategy = "first" | "last"; @Parameter({ runtimeName: "max_tokens", name: [{ code: "en-US", content: "Maximum tokens" }], + description: [ + { + code: "en-US", + content: + "The size the conversation is cut down to before it is sent to the model, counted in tokens and approximated rather than counted by the model's own tokenizer. It has to be a positive number.", + }, + ], }) @Parameter({ runtimeName: "strategy", name: [{ code: "en-US", content: "Strategy" }], + description: [ + { + code: "en-US", + content: + "Which end of the conversation survives the cut: \"last\" keeps the most recent messages, \"first\" keeps the oldest ones. Defaults to \"last\", which is what keeps an ongoing conversation usable.", + }, + ], optional: true, }) @Parameter({ runtimeName: "keep_system", name: [{ code: "en-US", content: "Keep system prompt" }], + description: [ + { + code: "en-US", + content: + "Whether the system prompt is kept even when the rest is cut away. On by default, because an agent that loses its instructions mid-conversation stops behaving as it was set up to.", + }, + ], optional: true, }) export class TrimMessagesMiddlewareFunction { diff --git a/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts new file mode 100644 index 0000000..aa23b74 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts @@ -0,0 +1,314 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; +import type { AIMessage, AIMessageChunk, BaseMessage } from "@langchain/core/messages"; +import type { Runnable } from "@langchain/core/runnables"; +import { ChatOpenAI, type ChatOpenAICallOptions } from "@langchain/openai"; +import { toFlowMessage } from "../../utils/message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; +import { AiModelResponseSchema, type AiModelResponse } from "../../datatypes/model/Model.response.datatype.js"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import { AiModelRequestSchema, type AiModelRequest } from "../../datatypes/model/Model.request.datatype.js"; +import { describeError } from "../../utils/shared/Shared.describeError.util.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; + +const log = logger("model:openrouter"); + +/** + * OpenRouter's own web search, as a server tool: the provider runs the search and + * hands the model the excerpts, so the flow needs no search tool and no key of its + * own. It replaces the deprecated "web" plugin and the ":online" model suffix, and + * unlike those it leaves the model to decide whether a search is needed at all. + */ +const WEB_SEARCH_TOOL = { type: "openrouter:web_search" } as const; + +/** + * Route a request only to a provider that supports every parameter it carries. + * + * OpenRouter serves one model from many provider endpoints, and they do not support + * the same parameters: of the 26 endpoints behind "openai/gpt-oss-120b", some take + * no tools at all, some take tools but no "response_format", some the reverse. The + * model's own parameter list is the union over all of them, so a parameter the model + * supports still reaches an endpoint that does not - and then the request is either + * rejected outright or, worse, the provider gives up mid-generation and OpenRouter + * answers 200 with whatever text it had, as if the parameter had simply been + * ignored. This is filtered against the parameters actually sent, so a request that + * asks for nothing special keeps every endpoint it had. + */ +const REQUIRE_SUPPORTED_PARAMETERS = { provider: { require_parameters: true } } as const; + +/** + * What OpenRouter actually objected to. + * + * The OpenAI client turns a rejection into "400 Provider returned error" and leaves + * the reason in the body: OpenRouter puts the upstream provider's own message under + * `error.metadata`, and that is the only part that says which parameter was refused. + * Without it a model that cannot do what was asked of it is indistinguishable from a + * wrong key. + */ +function describeProviderError(error: unknown): string { + const described: string = describeError(error); + const body = (error as { error?: { message?: unknown; metadata?: unknown } } | undefined)?.error; + if (!body || typeof body !== "object") return described; + + const details: string[] = []; + if (typeof body.message === "string" && !described.includes(body.message)) details.push(body.message); + if (body.metadata !== undefined) details.push(JSON.stringify(body.metadata)); + + return details.length > 0 ? `${described} (${details.join(": ")})` : described; +} + +interface ToolDefinition { + type: "function"; + function: { + name: string; + description: string; + parameters: Record; + }; +} + +type BoundModel = Runnable; + +@Identifier("ai::model::openrouter") +@DisplayIcon("simple:openrouter") +@Signature( + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_tokens?: NUMBER, web_search?: BOOLEAN, structured_output?: BOOLEAN): TRANSFORM", +) +@Name({ code: "en-US", content: "OpenRouter model" }) +@DisplayMessage({ code: "en-US", content: "OpenRouter ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The OpenRouter model identifier, written as provider and model, for example \"anthropic/claude-sonnet-4.5\". It decides which model OpenRouter routes the request to.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The OpenRouter API key the requests are sent with. It is what the usage is billed against, so it belongs in a secret rather than in the node.", + }, + ], +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Temperature" }], + description: [ + { + code: "en-US", + content: + "How much the model is allowed to vary its answers: low values keep them focused and repeatable, higher ones make them more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_tokens", + name: [{ code: "en-US", content: "Maximum tokens" }], + description: [ + { + code: "en-US", + content: + "The ceiling on how long a single answer may get, counted in tokens. An answer that reaches it is cut off mid-sentence, so leave it empty unless the length has to be bounded.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "structured_output", + name: [{ code: "en-US", content: "Structured output" }], + description: [ + { + code: "en-US", + content: + "Lets the agent ask this model for an output type directly, so the provider constrains the answer and the model cannot write anything else. On unless switched off. Switched off, an output type is asked for as a forced tool call instead - which a model is free to ignore, and which some models break on outright, so turn it off only for a model that cannot constrain its own output.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "web_search", + name: [{ code: "en-US", content: "Web search" }], + description: [ + { + code: "en-US", + content: + "Lets the model search the web through OpenRouter, which runs the search and hands the model the excerpts - so the flow needs no search tool and no key of its own. Off unless switched on; the model still decides for itself whether a search is needed.", + }, + ], + optional: true, +}) +export class OpenRouterModelFunction { + /** + * "web_search" is off unless the node switches it on. It sits on the model rather + * than on the agent because only the model knows its provider: the agent holds + * its model as a transform and could do nothing with the switch but pass it on. + */ + run( + _context: FunctionContext, + model: string, + api_key: string, + temperature?: number, + max_tokens?: number, + web_search?: boolean, + structured_output?: boolean, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "An OpenRouter model needs a model identifier.", + ); + const chat: ChatOpenAI = new ChatOpenAI({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "An OpenRouter model needs an API key."), + configuration: { baseURL: OPENROUTER_BASE_URL }, + temperature, + maxTokens: max_tokens, + modelKwargs: { ...REQUIRE_SUPPORTED_PARAMETERS }, + }); + + // What the agent reads to decide how to get a structured answer: carrying + // "response_format" is this node saying it can constrain its own output, and + // dropping it sends the agent down the tool call instead. The switch has to + // reach the agent as a schema, because a sub flow carries nothing else. + const requestSchema = + structured_output === false ? AiModelRequestSchema.omit({ response_format: true }) : AiModelRequestSchema; + + return { + name: `openrouter:${identifier}`, + description: `OpenRouter model ${identifier}`, + inputSchema: requestSchema, + outputSchema: AiModelResponseSchema, + run: async (request: AiModelRequest): Promise => { + const parsed: AiModelRequest = parseOrThrow( + AiModelRequestSchema, + request, + "ERROR_INVALID_AI_MODEL_REQUEST", + "The model request is not valid", + ); + + const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.input_schema, + }, + })); + const bindable: (ToolDefinition | typeof WEB_SEARCH_TOOL)[] = [ + ...tools, + ...(web_search === true ? [WEB_SEARCH_TOOL] : []), + ]; + const bound: BoundModel = bindable.length > 0 ? chat.bindTools(bindable as never) : chat; + const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); + + // The type the answer has to come back in, in the OpenAI dialect. + // OpenRouter constrains the generation itself, so the model cannot + // answer anything but matching JSON and the agent needs no tool call + // to get a structured answer out of it - but only the model and the + // provider it is routed to decide whether that is possible at all, + // and one that cannot do it rejects the whole call. Hence the switch: + // the field is only read when the node was told this model can serve + // it. "strict" is forwarded as asked for, which means OpenAI requires + // every nested object to close itself with "additionalProperties": + // false rather than answering loosely. + const responseFormat = structured_output === false ? undefined : parsed.response_format; + + // What a model answered is only half of a failed run: whether it was + // asked to call a tool at all, and whether it then did, is the other + // half, and only this node sees both. + log.debug(`calling "${identifier}" with`, { + messages: parsed.messages.length, + tools: bindable.length, + tool_choice: parsed.tool_choice, + response_format: responseFormat?.name, + }); + + const answer: AIMessage = await bound + .invoke(messages, { + ...(parsed.stop ? { stop: parsed.stop } : {}), + ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), + ...(responseFormat + ? { + response_format: { + type: "json_schema", + json_schema: { + name: responseFormat.name, + schema: responseFormat.schema, + ...(responseFormat.description + ? { description: responseFormat.description } + : {}), + ...(responseFormat.strict !== undefined + ? { strict: responseFormat.strict } + : {}), + }, + }, + } + : {}), + }) + .catch((error: unknown) => { + // Which parameter a provider refused is only answerable + // against what was actually sent, and a rejected call is + // exactly when nobody can reconstruct that from the flow. + log.error(`the call to "${identifier}" was rejected, having sent`, { + tools: bindable, + tool_choice: parsed.tool_choice, + response_format: responseFormat, + }); + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The OpenRouter call to "${identifier}" failed: ${describeProviderError(error)}`, + ); + }); + + const reply = toFlowMessage(answer); + const metadata = answer.response_metadata as { finish_reason?: unknown } | undefined; + log.debug(`"${identifier}" answered with`, { + blocks: (reply.content ?? []).map((block) => block.type), + tool_calls: (reply.content ?? []) + .filter((block) => block.type === "tool_call") + .map((block) => block.name), + finish_reason: (answer.response_metadata as { finish_reason?: unknown })?.finish_reason, + }); + + // A provider that gave up mid-generation still answers 200 through + // OpenRouter, with whatever text it had produced and "error" as the + // finish reason. Taken at face value that is a valid answer, and the + // run fails later and elsewhere - the agent gets blamed for not + // answering in the type it was asked for, when in truth it was never + // asked. The finish reason is the only place this is visible, so it + // is read here, where the provider's own vocabulary still applies. + if (metadata?.finish_reason === "error") { + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The OpenRouter call to "${identifier}" was cut short: the provider gave up mid-generation and reported "error" as the finish reason. This is what a model that cannot serve a parameter it was given does, so the usual cause is a request it does not support - a forced tool call above all, which is how an output type is asked for from a model that cannot constrain its own output.`, + ); + } + + return { message: reply }; + }, + }; + } +} diff --git a/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts new file mode 100644 index 0000000..a1d49d7 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts @@ -0,0 +1,118 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; +import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; + +/** Open WebUI reads these blocks out of the answer's text, so they have to survive as markup. */ +const ESCAPES: Record = { "&": "&", "<": "<", ">": ">", '"': """ }; + +/** Text as it can stand inside an attribute. */ +const escaped = (text: string): string => text.replace(/[&<>"]/g, (character) => ESCAPES[character] ?? character); + +/** A value as an attribute Open WebUI can read back, which is its JSON, escaped. */ +const asAttribute = (value: unknown): string => escaped(JSON.stringify(value ?? null)); + +/** Already-formatted text, which must not be wrapped a second time. */ +const FORMATTED = /
` and + * `
` out of the text, which is what this node puts + * there: the same information, in the one place the client looks. + * + * The node sits between the agent and ${ai::openai::respond}, and only changes the + * text - the fields stay as they are, so a flow that reads them after this node + * still gets the data rather than the markup. An answer with nothing to show, and + * one that came through here already, are returned untouched. + */ + run(context: FunctionContext, response: unknown): AiChatResponse { + const log = logger("openai", context.executionId); + const answer: AiChatResponse = parseOrThrow( + AiChatResponseSchema, + response, + "ERROR_INVALID_AI_OPENAI_RESPONSE", + "The answer to format for Open WebUI has to be a chat response", + ); + + const steps: AiAgentStep[] = answer.steps ?? []; + const thought: string = answer.reasoning?.trim() ?? ""; + if (thought.length === 0 && steps.length === 0) return answer; + + if (FORMATTED.test(answer.response)) { + log.debug("this answer was already formatted for Open WebUI, so it is left as it is"); + return answer; + } + + const blocks: string[] = []; + + // Reasoning is shown as what the model said to itself, which Open WebUI renders + // as a quote under the summary - so every line of it is quoted. + if (thought.length > 0) { + const quoted: string = thought + .split("\n") + .map((line) => `> ${line}`) + .join("\n"); + blocks.push(`
\nThought\n${quoted}\n
`); + } + + // One block per tool the agent used. A call that failed has its error where the + // result would be: the block is what happened, and nothing happening is worse + // to look at than a failure. + steps.forEach((step, index) => { + const result: unknown = step.error !== undefined ? step.error : (step.result ?? ""); + const summary: string = step.error !== undefined ? "Tool Failed" : "Tool Executed"; + + blocks.push( + `
\n` + + `${summary}\n
`, + ); + }); + + const content: string = [...blocks, answer.response].filter((part) => part.length > 0).join("\n"); + log.info("formatted the answer for Open WebUI", { reasoning: thought.length > 0, steps: steps.length }); + + return { + ...answer, + response: content, + // Only the first choice is the answer - the node produces one, and a client + // reading `choices` has to see the same text the streaming path sends. + choices: answer.choices.map((choice, index) => + index === 0 ? { ...choice, message: { ...choice.message, content } } : choice, + ), + }; + } +} diff --git a/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts new file mode 100644 index 0000000..f1e407c --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts @@ -0,0 +1,63 @@ +import { + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; +import { pendingResponses } from "../../utils/openai/OpenAi.pending.util.js"; + +@Identifier("ai::openai::respond") +@DisplayIcon("tabler:ai") +@Signature("(response: AI_CHAT_RESPONSE): void") +@Name({ code: "en-US", content: "Respond to the OpenAI request" }) +@DisplayMessage({ code: "en-US", content: "Answer the OpenAI request with ${response}" }) +@ThrowsError() +@Parameter({ + runtimeName: "response", + name: [{ code: "en-US", content: "Response" }], + description: [{ code: "en-US", content: "The answer the client receives, e.g. the one an agent produced." }], +}) +export class OpenAiRespondFunction { + /** + * Answers the HTTP request an OpenAI client is holding open, from wherever in the + * flow the node sits. + * + * Without it the answer would have to be the flow's return value, which is only + * the agent's as long as nothing follows it - a flow that logs, stores or branches + * after the agent would answer with whatever its last node happened to produce. + * + * Which request is answered needs no parameter: the endpoint reserved the flow's + * execution id before starting it, and this node runs as part of that execution, + * so `executionId` names the waiting request. + * + * The request is answered the moment this runs; the flow carries on, and anything + * after this node no longer changes what the client got. A second call, or a run + * of a flow nobody is waiting on - a manual execution from the editor, say - is + * logged rather than failed: the flow did nothing wrong, there is simply no + * connection to write to. + */ + run(context: FunctionContext, response: unknown): null { + const log = logger("openai", context.executionId); + const answer: AiChatResponse = parseOrThrow( + AiChatResponseSchema, + response, + "ERROR_INVALID_AI_OPENAI_RESPONSE", + "The answer for an OpenAI client has to be a chat response", + ); + + if (pendingResponses.settle(context.executionId, answer)) { + log.info("answered the waiting OpenAI request", { model: answer.model }); + } else { + log.info("nothing is waiting for this execution's answer, so it goes nowhere", { model: answer.model }); + } + + return null; + } +} diff --git a/actions/ai-action/src/server/openai/OpenAi.server.ts b/actions/ai-action/src/server/openai/OpenAi.server.ts new file mode 100644 index 0000000..f0563e5 --- /dev/null +++ b/actions/ai-action/src/server/openai/OpenAi.server.ts @@ -0,0 +1,349 @@ +import { randomUUID } from "node:crypto"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { PlainValue } from "@code0-tech/hercules"; +import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; +import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import type { Logger } from "../../types/shared/Log.types.js"; +import type { OpenAiEndpoint, OpenAiRequestPath } from "../../types/openai/OpenAi.types.js"; +import type { OpenAiServerHost, OpenAiServerOptions } from "../../types/openai/OpenAiServer.types.js"; +import { corsHeaders } from "../../utils/openai/OpenAi.corsHeaders.util.js"; +import { describeError } from "../../utils/shared/Shared.describeError.util.js"; +import { errorBody } from "../../utils/openai/OpenAi.errorBody.util.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { parseRequestPath } from "../../utils/openai/OpenAi.parsePath.util.js"; +import { pendingResponses } from "../../utils/openai/OpenAi.pending.util.js"; +import { sendJson } from "../../utils/openai/OpenAi.sendJson.util.js"; +import { toEndpoints } from "../../utils/openai/OpenAi.toEndpoints.util.js"; +import { toModelList } from "../../utils/openai/OpenAi.toModelList.util.js"; +import { toStreamChunks } from "../../utils/openai/OpenAi.toStream.util.js"; + +const DEFAULT_PORT = 8080; +/** The endpoint is reachable from outside, so a body is read only up to this. */ +const MAX_BODY_BYTES = 10 * 1024 * 1024; +const log: Logger = logger("openai"); + +export class OpenAiServer { + private readonly server: Server; + private readonly port: number; + private readonly host: string; + + constructor( + private readonly action: OpenAiServerHost, + options: OpenAiServerOptions = {}, + ) { + this.port = options.port ?? Number(process.env.AI_OPENAI_PORT ?? process.env.PORT ?? DEFAULT_PORT); + this.host = options.host ?? "0.0.0.0"; + log.info("the OpenAI endpoint is configured", { port: this.port, host: this.host }); + this.server = createServer((request, response) => { + // One identifier per request, so every line of one call can be read as a + // sequence even while several clients are talking to the action. + const trace: Logger = log.child(randomUUID().slice(0, 8)); + const started: number = Date.now(); + + trace.info(`${request.method ?? "GET"} ${request.url ?? "/"}`, { + headers: request.headers, + remote: request.socket.remoteAddress, + }); + response.on("finish", () => { + trace.info(`answered ${response.statusCode} in ${Date.now() - started}ms`); + }); + + this.handle(request, response, trace).catch((error: unknown) => { + trace.error("the request failed before an answer was sent", { + error: describeError(error), + stack: error instanceof Error ? error.stack : undefined, + }); + if (response.headersSent) { + response.end(); + return; + } + sendJson(response, 500, errorBody(describeError(error), "internal_error"), trace); + }); + }); + } + + listen(): Promise<{ port: number; host: string }> { + return new Promise((resolve, reject) => { + this.server.once("error", reject); + this.server.listen(this.port, this.host, () => { + this.server.removeListener("error", reject); + log.info("listening", { port: this.address, host: this.host }); + resolve({ port: this.port, host: this.host }); + }); + }); + } + + close(): Promise { + log.info("closing the OpenAI endpoint"); + return new Promise((resolve) => this.server.close(() => resolve())); + } + + /** The port the server actually listens on, which matters when 0 was asked for. */ + get address(): number { + const address = this.server.address(); + return address && typeof address === "object" ? address.port : this.port; + } + + private async handle(request: IncomingMessage, response: ServerResponse, trace: Logger): Promise { + const method: string = (request.method ?? "GET").toUpperCase(); + + // A preflight asks what is allowed and carries neither key nor body, so it is + // answered before anything is looked up. + if (method === "OPTIONS") { + trace.debug("answering a preflight"); + response.writeHead(204, corsHeaders()); + response.end(); + return; + } + + const path: OpenAiRequestPath | undefined = parseRequestPath(request.url ?? "/"); + if (!path) { + trace.warn("no endpoint of the protocol matches this path", { url: request.url }); + sendJson(response, 404, errorBody("Unknown endpoint.", "invalid_request_error"), trace); + return; + } + trace.debug("the path resolves to", path); + + const flows: ActionFlow[] = this.action.flows(); + const known: OpenAiEndpoint[] = toEndpoints(flows); + // The endpoints of one route, which is the project's slug plus the flow's + // route: the route alone is only unique inside a project. + const endpoints: OpenAiEndpoint[] = known.filter( + (endpoint) => endpoint.slug === path.slug && endpoint.route === path.route, + ); + trace.debug(`${flows.length} flows known, ${known.length} of them endpoints, ${endpoints.length} on this route`, { + all: known.map((endpoint) => ({ + flow: `${endpoint.flow.flowId}`, + slug: endpoint.slug, + route: endpoint.route, + model: endpoint.model, + guarded: Boolean(endpoint.apiKey), + })), + }); + + if (endpoints.length === 0) { + trace.warn("no flow serves this route", { slug: path.slug, route: path.route }); + sendJson( + response, + 404, + errorBody(`No flow serves ${path.kind === "models" ? "models" : "completions"} here.`, "invalid_request_error"), + trace, + ); + return; + } + + // Each flow of a route may carry its own key, so a request is let through by + // the key of the endpoint it is for - checked again per flow below. + const authorization: string | undefined = request.headers.authorization ?? undefined; + const apiKeyHeader = request.headers["api-key"]; + // Either header a client may send the key in. + const token: string | undefined = + authorization?.replace(/^Bearer\s+/i, "").trim() || + (Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader)?.trim() || + undefined; + trace.debug("the request carries a bearer token", { present: Boolean(token) }); + + if (path.kind === "models") { + const listed: OpenAiEndpoint[] = endpoints.filter( + (endpoint) => !endpoint.apiKey || endpoint.apiKey === token, + ); + if (listed.length === 0) { + trace.warn("the token matches no endpoint of this route, so nothing is listed"); + sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key"), trace); + return; + } + trace.info( + `listing ${listed.length} of ${endpoints.length} models`, + listed.map((endpoint) => endpoint.model), + ); + sendJson(response, 200, toModelList(listed), trace); + return; + } + + if (method !== "POST") { + trace.warn("completions were asked for with the wrong method", { method }); + response.setHeader("allow", "POST, OPTIONS"); + sendJson( + response, + 405, + errorBody(`Completions are asked for with POST, not ${method}.`, "invalid_request_error"), + trace, + ); + return; + } + + let read = 0; + const parts: Buffer[] = []; + for await (const chunk of request) { + const part = chunk as Buffer; + read += part.byteLength; + if (read > MAX_BODY_BYTES) throw new Error("the request body is too large"); + parts.push(part); + } + const body: string = Buffer.concat(parts).toString("utf8"); + trace.debug(`the body is ${Buffer.byteLength(body)} bytes`, body); + + let parsed: unknown; + try { + parsed = JSON.parse(body || "{}"); + } catch (error: unknown) { + trace.warn("the body is not valid JSON", { error: describeError(error) }); + sendJson(response, 400, errorBody("The request body is not valid JSON.", "invalid_request_error"), trace); + return; + } + + const payload = parsed as { model?: string; stream?: boolean }; + // A client sends the model it picked from `/models`, so that name decides; a + // request naming nothing - or naming a model this route does not have - is + // served by the route's only flow, because then there is nothing else it + // could have meant. + const asked: string = payload.model?.trim() ?? ""; + const endpoint: OpenAiEndpoint | undefined = + endpoints.find((candidate) => candidate.model === asked) ?? + (endpoints.length === 1 ? endpoints[0] : undefined); + if (!endpoint) { + trace.warn("no flow of this route carries the model asked for", { + asked: payload.model ?? null, + available: endpoints.map((candidate) => candidate.model), + }); + sendJson( + response, + 404, + errorBody(`The model "${payload.model ?? ""}" does not exist.`, "invalid_request_error", "model_not_found"), + trace, + ); + return; + } + trace.info("the request is for", { + model: endpoint.model, + asked_for: payload.model ?? null, + flow: `${endpoint.flow.flowId}`, + project: endpoint.slug, + stream: payload.stream === true, + }); + + if (endpoint.apiKey && endpoint.apiKey !== token) { + trace.warn("the token does not match the key the flow declared", { model: endpoint.model }); + sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key"), trace); + return; + } + + const validation = AiChatRequestSchema.safeParse(parsed); + const request_: AiChatRequest | undefined = validation.data; + if (!request_ || request_.messages.length === 0) { + trace.warn("the request carries nothing to answer", { + issues: validation.error?.issues, + messages: request_?.messages.length ?? 0, + }); + sendJson( + response, + 400, + errorBody("The request carries no messages to answer.", "invalid_request_error"), + trace, + ); + return; + } + + const answer: AiChatResponse | undefined = await this.run(endpoint, request_, trace); + if (!answer) { + sendJson( + response, + 502, + errorBody( + `The flow serving "${endpoint.model}" did not answer with a chat response.`, + "internal_error", + ), + trace, + ); + return; + } + + if (payload.stream === true) { + const chunks: string[] = toStreamChunks(answer); + trace.debug(`answering 200 as a stream of ${chunks.length} chunks`, chunks); + + response.writeHead(200, { + ...corsHeaders(), + "content-type": "text/event-stream", + "cache-control": "no-cache", + connection: "keep-alive", + }); + for (const chunk of chunks) response.write(`data: ${chunk}\n\n`); + response.end(); + return; + } + sendJson(response, 200, answer, trace); + } + + /** + * Runs the flow and takes its answer, from whichever of the two comes first. + * + * `ai::openai::respond` is the way a flow answers: it settles the request from + * wherever in the flow it sits, so nodes after it - logging, storing, a second + * branch - no longer change what the client got. The flow's return value is only + * used when the flow ended without ever responding, which keeps a flow of two + * nodes working without a respond node. + */ + private async run( + endpoint: OpenAiEndpoint, + request: AiChatRequest, + trace: Logger, + ): Promise { + const started: number = Date.now(); + // Reserved before the flow starts, because the wait has to exist by the time + // its respond node runs - which can be before executeFlow even resolves. + const executionId: string = this.action.reserveExecutionId(); + + trace.debug(`running flow ${endpoint.flow.flowId} as execution ${executionId} with`, request); + + const responded: Promise<{ answer: AiChatResponse }> = pendingResponses + .open(executionId, endpoint.model) + .then((answer) => ({ answer })); + const finished: Promise<{ result: PlainValue }> = this.action + .executeFlowWithId(executionId, endpoint.flow.flowId, request as unknown as PlainValue) + .then((result) => ({ result })); + + try { + const outcome = await Promise.race([responded, finished]); + + if ("answer" in outcome) { + trace.info(`the flow answered through respond after ${Date.now() - started}ms`); + return this.named(outcome.answer, endpoint, trace); + } + + trace.debug( + `flow ${endpoint.flow.flowId} ended after ${Date.now() - started}ms without responding, taking its result`, + outcome.result, + ); + const validation = AiChatResponseSchema.safeParse(outcome.result); + if (!validation.data) { + trace.error("the flow neither responded nor returned a chat response", { + issues: validation.error?.issues, + }); + return undefined; + } + return this.named(validation.data, endpoint, trace); + } catch (error: unknown) { + trace.error(`flow ${endpoint.flow.flowId} failed after ${Date.now() - started}ms`, { + error: describeError(error), + }); + throw error; + } finally { + // Whatever happened, nothing is waiting any more: a later respond call + // finds no connection rather than settling a request that is gone. + pendingResponses.close(executionId); + } + } + + /** + * The answer with a model name on it. A client matches what comes back against + * the model it asked for, so the flow's own name stands in where a flow - or an + * agent that reported no model - left the field empty. + */ + private named(answer: AiChatResponse, endpoint: OpenAiEndpoint, trace: Logger): AiChatResponse { + if (answer.model.trim().length > 0) return answer; + trace.debug("the answer carries no model, so the flow's own name stands in", { model: endpoint.model }); + return { ...answer, model: endpoint.model }; + } +} diff --git a/actions/ai-action/src/server/openai/OpenAi.startServer.ts b/actions/ai-action/src/server/openai/OpenAi.startServer.ts new file mode 100644 index 0000000..a382e60 --- /dev/null +++ b/actions/ai-action/src/server/openai/OpenAi.startServer.ts @@ -0,0 +1,20 @@ +import type { OpenAiServerHost, OpenAiServerOptions } from "../../types/openai/OpenAiServer.types.js"; +import { logger } from "../../utils/shared/Log.logger.util.js"; +import { OpenAiServer } from "./OpenAi.server.js"; + +const log = logger("openai"); + +/** + * Starts the OpenAI endpoint of every project this action serves. It is the action's + * own HTTP server: a flow bound to `ai::openai::server` is reachable the moment + * aquila tells the action about it, with nothing in between to configure. + */ +export async function startOpenAiServer( + action: OpenAiServerHost, + options: OpenAiServerOptions = {}, +): Promise { + const server = new OpenAiServer(action, options); + const { host, port } = await server.listen(); + log.info(`OpenAI endpoint listening on http://${host}:${port}//`); + return server; +} diff --git a/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts b/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts deleted file mode 100644 index fdd4d88..0000000 --- a/actions/ai-action/src/shared/utils/Shared.toInputSchema.util.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { toJsonSchema } from "@langchain/core/utils/json_schema"; -import { emptyJsonSchema } from "./Shared.emptyJsonSchema.util.js"; - -export function toInputSchema(schema: unknown): Record { - if (!schema) return emptyJsonSchema(); - - try { - return toJsonSchema(schema as never) as Record; - } catch { - return emptyJsonSchema(); - } -} diff --git a/actions/ai-action/src/types/agent/Agent.types.ts b/actions/ai-action/src/types/agent/Agent.types.ts new file mode 100644 index 0000000..d63689b --- /dev/null +++ b/actions/ai-action/src/types/agent/Agent.types.ts @@ -0,0 +1,16 @@ +import type { SubFlow } from "@code0-tech/hercules"; +import type { AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; + +/** A tool of an agent: a flow of the project, or an MCP server to discover tools from. */ +export type ToolEntry = SubFlow | AiMcpServer; + +/** Everything an agent is built from, as the node collected it. */ +export interface AgentDefinition { + name: string; + systemPrompt: string; + model: SubFlow; + tools: ToolEntry[]; + middleware: SubFlow[]; + /** The JSON schema of the type the agent has to answer in, when one was asked for. */ + outputSchema?: Record; +} diff --git a/actions/ai-action/src/types/message/Message.types.ts b/actions/ai-action/src/types/message/Message.types.ts new file mode 100644 index 0000000..42909dd --- /dev/null +++ b/actions/ai-action/src/types/message/Message.types.ts @@ -0,0 +1,9 @@ +import type { AiContentBlock } from "../../datatypes/message/Message.contentBlock.datatype.js"; + +export interface MessageFields { + content: AiContentBlock[]; + id?: string; + name?: string; + additional_kwargs?: Record; + response_metadata?: Record; +} diff --git a/actions/ai-action/src/types/middleware/Approval.types.ts b/actions/ai-action/src/types/middleware/Approval.types.ts new file mode 100644 index 0000000..1212270 --- /dev/null +++ b/actions/ai-action/src/types/middleware/Approval.types.ts @@ -0,0 +1,17 @@ +/** A tool call, as the parts of the approval exchange pass it around. */ +export interface ToolCall { + name: string; + args?: Record; +} + +/** What a reply did to a question, as far as matching can tell. */ +export type ApprovalDecision = "approved" | "declined" | "open" | "spent"; + +/** A question of a conversation, with where it sits and what became of it. */ +export interface OpenQuestion { + /** Its position in the conversation, which is where it gets marked as used. */ + at: number; + text: string; + code: string; + decision: ApprovalDecision; +} diff --git a/actions/ai-action/src/types/middleware/Middleware.types.ts b/actions/ai-action/src/types/middleware/Middleware.types.ts new file mode 100644 index 0000000..d3c87c7 --- /dev/null +++ b/actions/ai-action/src/types/middleware/Middleware.types.ts @@ -0,0 +1,16 @@ +import type { BaseMessage } from "@langchain/core/messages"; + +export interface AgentState { + messages: BaseMessage[]; + structuredResponse?: Record; +} + +export interface AgentRuntime { + context?: Record; +} + +/** What a hook may answer with: a state update, or nothing to change. */ +export type HookResult = Record | undefined; + +/** A middleware hook as the agent calls it, for one phase of one agent. */ +export type HookHandler = (state: AgentState, runtime?: AgentRuntime) => Promise; diff --git a/actions/ai-action/src/types/openai/OpenAi.types.ts b/actions/ai-action/src/types/openai/OpenAi.types.ts new file mode 100644 index 0000000..8a5be53 --- /dev/null +++ b/actions/ai-action/src/types/openai/OpenAi.types.ts @@ -0,0 +1,40 @@ +import type { ActionFlow } from "@code0-tech/tucana/aquila"; + +/** The flow type every flow of an OpenAI endpoint carries. */ +export const OPENAI_EVENT = "ai::openai::server"; + +/** One model a project serves, and the flow behind it. */ +export interface OpenAiEndpoint { + flow: ActionFlow; + /** The project the flow belongs to, as it appears in the path. */ + slug: string; + route: string; + /** The name clients see and pick. */ + model: string; + /** The bearer token a client has to send, when the flow asked for one. */ + apiKey?: string; +} + +export type OpenAiEndpointKind = "chat_completions" | "models"; + +/** A request path, split into what decides which flow answers it. */ +export interface OpenAiRequestPath { + /** The project, which is the first path segment and what scopes a route. */ + slug: string; + route: string; + kind: OpenAiEndpointKind; +} + +/** One entry of the answer to `GET /models`. */ +export interface OpenAiModel { + id: string; + object: "model"; + created: number; + owned_by: string; +} + +/** The answer to `GET /models`. */ +export interface OpenAiModelList { + object: "list"; + data: OpenAiModel[]; +} diff --git a/actions/ai-action/src/types/openai/OpenAiServer.types.ts b/actions/ai-action/src/types/openai/OpenAiServer.types.ts new file mode 100644 index 0000000..079b018 --- /dev/null +++ b/actions/ai-action/src/types/openai/OpenAiServer.types.ts @@ -0,0 +1,25 @@ +import type { PlainValue } from "@code0-tech/hercules"; +import type { ActionFlow } from "@code0-tech/tucana/aquila"; + +/** + * What the server needs of the action: the flows it currently knows, the execution a + * flow is about to run as, and a way to run it. + * + * Taking only this much keeps the server testable without a connection to aquila - and + * the reserved execution is what lets the respond node find the request waiting for it. + */ +export interface OpenAiServerHost { + flows: () => ActionFlow[]; + reserveExecutionId: () => string; + executeFlowWithId: (executionId: string, flowId: bigint, payload: PlainValue) => Promise; +} + +export interface OpenAiServerOptions { + port?: number; + host?: string; +} + +/** An error in the shape an OpenAI client expects. */ +export interface OpenAiErrorBody { + error: { message: string; type: string; code?: string }; +} diff --git a/actions/ai-action/src/types/shared/Log.types.ts b/actions/ai-action/src/types/shared/Log.types.ts new file mode 100644 index 0000000..dfcd2aa --- /dev/null +++ b/actions/ai-action/src/types/shared/Log.types.ts @@ -0,0 +1,15 @@ +/** How much is written, from the quietest to everything. */ +export const LOG_LEVELS = ["debug", "info", "warn", "error", "off"] as const; +export type LogLevel = (typeof LOG_LEVELS)[number]; + +/** A level that actually writes, which is every one but `off`. */ +export type WritingLevel = Exclude; + +export interface Logger { + debug: (message: string, details?: unknown) => void; + info: (message: string, details?: unknown) => void; + warn: (message: string, details?: unknown) => void; + error: (message: string, details?: unknown) => void; + /** A logger of the same scope, with something to tie lines of one run together. */ + child: (correlation: string) => Logger; +} diff --git a/actions/ai-action/src/types/shared/Proto.types.ts b/actions/ai-action/src/types/shared/Proto.types.ts new file mode 100644 index 0000000..8cf427c --- /dev/null +++ b/actions/ai-action/src/types/shared/Proto.types.ts @@ -0,0 +1,4 @@ +/** A protobuf `shared.Struct` as it reaches the action: every value still wrapped. */ +export interface ProtoStruct { + fields: Record; +} diff --git a/actions/ai-action/src/utils/chat/Chat.fromChatMessage.util.ts b/actions/ai-action/src/utils/chat/Chat.fromChatMessage.util.ts new file mode 100644 index 0000000..1e38cbe --- /dev/null +++ b/actions/ai-action/src/utils/chat/Chat.fromChatMessage.util.ts @@ -0,0 +1,73 @@ +import type { AiContentBlock } from "../../datatypes/message/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { AiMessageRole } from "../../datatypes/message/Message.role.datatype.js"; +import type { AiChatMessage } from "../../datatypes/chat/Chat.message.datatype.js"; +import type { AiChatRole } from "../../datatypes/chat/Chat.role.datatype.js"; +import { describeError } from "../shared/Shared.describeError.util.js"; + +const ROLE_FROM_CHAT: Record = { + system: "system", + user: "human", + assistant: "ai", + tool: "tool", +}; + +export function fromChatMessage(message: AiChatMessage): AiMessage { + const content: AiChatMessage["content"] = message.content; + + const flat: AiMessage = { + role: ROLE_FROM_CHAT[message.role], + content: [ + // A client may send the content as one string or as parts; a part is + // carried over as it is unless it is one of the two shapes the chat + // protocol spells differently to a message block. + ...(typeof content === "string" + ? content.length > 0 + ? [{ type: "text", text: content } as AiContentBlock] + : [] + : Array.isArray(content) + ? content.map((part): AiContentBlock => { + if (part.type === "text") { + return { type: "text", text: typeof part.text === "string" ? part.text : "" }; + } + + if (part.type === "image_url") { + const image = part.image_url as { url?: string; detail?: string } | undefined; + return { + type: "image", + ...(typeof image?.url === "string" ? { url: image.url } : {}), + ...(image?.detail ? { detail: image.detail } : {}), + }; + } + + return part; + }) + : []), + // The arguments travel as a JSON string, and a model that wrote nothing + // parsable is kept as the invalid call it made rather than dropped. + ...(message.tool_calls ?? []).map((call): AiContentBlock => { + try { + return { + type: "tool_call", + id: call.id, + name: call.function.name, + args: JSON.parse(call.function.arguments || "{}") as Record, + }; + } catch (error) { + return { + type: "invalid_tool_call", + id: call.id, + name: call.function.name, + args: call.function.arguments, + error: describeError(error), + }; + } + }), + ], + }; + + if (message.name) flat.name = message.name; + if (message.tool_call_id) flat.tool_call_id = message.tool_call_id; + + return flat; +} diff --git a/actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts b/actions/ai-action/src/utils/chat/Chat.toChatContent.util.ts similarity index 79% rename from actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts rename to actions/ai-action/src/utils/chat/Chat.toChatContent.util.ts index 19c1422..506651a 100644 --- a/actions/ai-action/src/chat/utils/Chat.toChatContent.util.ts +++ b/actions/ai-action/src/utils/chat/Chat.toChatContent.util.ts @@ -1,4 +1,4 @@ -import type { AiMessage } from "../../message/datatypes/Message.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; export function toChatContent(message: AiMessage): string { return message.content diff --git a/actions/ai-action/src/utils/chat/Chat.toChatMessage.util.ts b/actions/ai-action/src/utils/chat/Chat.toChatMessage.util.ts new file mode 100644 index 0000000..850c889 --- /dev/null +++ b/actions/ai-action/src/utils/chat/Chat.toChatMessage.util.ts @@ -0,0 +1,38 @@ +import { randomUUID } from "node:crypto"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { AiMessageRole } from "../../datatypes/message/Message.role.datatype.js"; +import type { AiChatMessage } from "../../datatypes/chat/Chat.message.datatype.js"; +import type { AiChatRole } from "../../datatypes/chat/Chat.role.datatype.js"; +import type { AiChatToolCall } from "../../datatypes/chat/Chat.toolCall.datatype.js"; +import { toChatContent } from "./Chat.toChatContent.util.js"; + +const ROLE_TO_CHAT: Record = { + system: "system", + human: "user", + ai: "assistant", + tool: "tool", +}; + +export function toChatMessage(message: AiMessage): AiChatMessage { + // A call reaches a client as a function call with its arguments as a string, and + // an id it can answer under - which a model that left it out still needs. + const toolCalls: AiChatToolCall[] = message.content + .filter((block) => block.type === "tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : randomUUID(), + type: "function" as const, + function: { + name: String(block.name ?? ""), + arguments: JSON.stringify(block.args ?? {}), + }, + })); + const content: string = toChatContent(message); + + return { + role: ROLE_TO_CHAT[message.role], + content: content.length > 0 || toolCalls.length === 0 ? content : null, + ...(message.name ? { name: message.name } : {}), + ...(message.tool_call_id ? { tool_call_id: message.tool_call_id } : {}), + ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}), + }; +} diff --git a/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts b/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts new file mode 100644 index 0000000..20c0d83 --- /dev/null +++ b/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts @@ -0,0 +1,64 @@ +import { randomUUID } from "node:crypto"; +import type { AiAgentApproval } from "../../datatypes/agent/Agent.approval.datatype.js"; +import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { AiChatMessage } from "../../datatypes/chat/Chat.message.datatype.js"; +import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import type { AiChatUsage } from "../../datatypes/chat/Chat.usage.datatype.js"; +import { toChatContent } from "./Chat.toChatContent.util.js"; +import { toChatMessage } from "./Chat.toChatMessage.util.js"; + +export function toChatResponse( + answer: AiMessage, + fallbackModel: string, + structuredResponse?: Record, + extras: { steps?: AiAgentStep[]; awaitingApproval?: AiAgentApproval[] } = {}, +): AiChatResponse { + const message: AiChatMessage = toChatMessage(answer); + + // What the provider counted, if it counted anything: a total it did not report is + // the two halves added up, and a model that reported neither has no usage at all. + const counted = answer.usage_metadata; + const prompt: number = typeof counted?.input_tokens === "number" ? counted.input_tokens : 0; + const completion: number = typeof counted?.output_tokens === "number" ? counted.output_tokens : 0; + const usage: AiChatUsage | undefined = counted + ? { + prompt_tokens: prompt, + completion_tokens: completion, + total_tokens: typeof counted.total_tokens === "number" ? counted.total_tokens : prompt + completion, + } + : undefined; + + // What the model thought before it answered, if it reported anything: reasoning + // arrives as its own kind of block, under whichever key the provider chose. + const reasoning: string = answer.content + .filter((block) => block.type === "reasoning" || block.type === "thinking") + .map((block) => { + const thought: unknown = block.reasoning ?? block.thinking ?? block.text; + return typeof thought === "string" ? thought : ""; + }) + .join(""); + + // The model that actually answered, under whichever key the provider put it; the + // flow's own name stands in when it named none. + const metadata: Record = answer.response_metadata ?? {}; + + return { + id: answer.id ?? `chatcmpl-${randomUUID()}`, + object: "chat.completion", + response: toChatContent(answer), + ...(reasoning.length > 0 ? { reasoning } : {}), + created: Math.floor(Date.now() / 1000), + model: + typeof metadata.model_name === "string" + ? metadata.model_name + : typeof metadata.model === "string" + ? metadata.model + : fallbackModel, + choices: [{ index: 0, message, finish_reason: message.tool_calls ? "tool_calls" : "stop" }], + ...(usage ? { usage } : {}), + ...(structuredResponse ? { structured_response: structuredResponse } : {}), + ...(extras.steps?.length ? { steps: extras.steps } : {}), + ...(extras.awaitingApproval?.length ? { awaiting_approval: extras.awaitingApproval } : {}), + }; +} diff --git a/actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts b/actions/ai-action/src/utils/mcp/Mcp.toConnection.util.ts similarity index 94% rename from actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts rename to actions/ai-action/src/utils/mcp/Mcp.toConnection.util.ts index edf4e1f..41c14fd 100644 --- a/actions/ai-action/src/mcp/utils/Mcp.toConnection.util.ts +++ b/actions/ai-action/src/utils/mcp/Mcp.toConnection.util.ts @@ -1,6 +1,6 @@ import { RuntimeError } from "@code0-tech/hercules"; import type { Connection } from "@langchain/mcp-adapters"; -import type { AiMcpServer } from "../datatypes/Mcp.server.datatype.js"; +import type { AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; export function toConnection(server: AiMcpServer): Connection { if (server.transport === "stdio") { diff --git a/actions/ai-action/src/utils/message/Message.textOf.util.ts b/actions/ai-action/src/utils/message/Message.textOf.util.ts new file mode 100644 index 0000000..5df5152 --- /dev/null +++ b/actions/ai-action/src/utils/message/Message.textOf.util.ts @@ -0,0 +1,14 @@ +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; + +/** + * The plain text of a message, which is every text block of it joined. + * + * A message carries blocks rather than a string - it may hold tool calls, images or + * reasoning next to what was said - so reading "what does this message say" is this + * one step, in one place, instead of in every caller. + */ +export const textOf = (message: AiMessage): string => + (message.content ?? []) + .filter((block) => block.type === "text") + .map((block) => String(block.text ?? "")) + .join(""); diff --git a/actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts b/actions/ai-action/src/utils/message/Message.toFlowMessage.util.ts similarity index 61% rename from actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts rename to actions/ai-action/src/utils/message/Message.toFlowMessage.util.ts index e647b14..f7080d8 100644 --- a/actions/ai-action/src/message/utils/Message.toFlowMessage.util.ts +++ b/actions/ai-action/src/utils/message/Message.toFlowMessage.util.ts @@ -1,8 +1,9 @@ import * as lc from "@langchain/core/messages"; -import type { AiContentBlock } from "../datatypes/Message.contentBlock.datatype.js"; -import type { AiMessage } from "../datatypes/Message.datatype.js"; -import type { AiMessageRole } from "../datatypes/Message.role.datatype.js"; -import { hasEntries } from "../../shared/utils/Shared.hasEntries.util.js"; +import type { AiContentBlock } from "../../datatypes/message/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { AiMessageRole } from "../../datatypes/message/Message.role.datatype.js"; +import { hasEntries } from "../shared/Shared.hasEntries.util.js"; +import { stripUndefined } from "../shared/Shared.stripUndefined.util.js"; const ROLE_BY_TYPE: Record = { system: "system", @@ -11,6 +12,12 @@ const ROLE_BY_TYPE: Record = { tool: "tool", }; +/** + * A langchain message as the flow sees it. Everything a provider put on the message - + * content blocks, metadata, usage - is carried over, but stripped of `undefined`: + * these messages are handed to hercules both as a sub flow argument and as a node + * result, and its serializer rejects `undefined` outright. + */ export function toFlowMessage(message: lc.BaseMessage): AiMessage { const flat: AiMessage = { role: ROLE_BY_TYPE[message.getType()] ?? "human", @@ -36,5 +43,5 @@ export function toFlowMessage(message: lc.BaseMessage): AiMessage { ]; } - return flat; + return stripUndefined(flat); } diff --git a/actions/ai-action/src/utils/message/Message.toLangChainMessage.util.ts b/actions/ai-action/src/utils/message/Message.toLangChainMessage.util.ts new file mode 100644 index 0000000..5e4153e --- /dev/null +++ b/actions/ai-action/src/utils/message/Message.toLangChainMessage.util.ts @@ -0,0 +1,59 @@ +import { + AIMessage, + HumanMessage, + SystemMessage, + ToolMessage, + type BaseMessage, + type UsageMetadata, +} from "@langchain/core/messages"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import type { MessageFields } from "../../types/message/Message.types.js"; + +/** The block types a langchain message carries as calls rather than as content. */ +const CALL_BLOCK_TYPES: string[] = ["tool_call", "invalid_tool_call"]; + +export function toLangChainMessage(message: AiMessage): BaseMessage { + const fields: MessageFields = { + content: message.content.filter((block) => !CALL_BLOCK_TYPES.includes(block.type)), + ...(message.id ? { id: message.id } : {}), + ...(message.name ? { name: message.name } : {}), + ...(message.additional_kwargs ? { additional_kwargs: message.additional_kwargs } : {}), + ...(message.response_metadata ? { response_metadata: message.response_metadata } : {}), + }; + + switch (message.role) { + case "system": + return new SystemMessage(fields); + case "ai": + // The calls are blocks of the content on our side and fields of the + // message on langchain's, so they move out of the content here. + return new AIMessage({ + ...fields, + tool_calls: message.content + .filter((block) => block.type === "tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : undefined, + name: String(block.name ?? ""), + args: (block.args ?? {}) as Record, + })), + invalid_tool_calls: message.content + .filter((block) => block.type === "invalid_tool_call") + .map((block) => ({ + id: typeof block.id === "string" ? block.id : undefined, + name: typeof block.name === "string" ? block.name : undefined, + args: typeof block.args === "string" ? block.args : undefined, + error: typeof block.error === "string" ? block.error : undefined, + })), + ...(message.usage_metadata ? { usage_metadata: message.usage_metadata as UsageMetadata } : {}), + }); + case "tool": + return new ToolMessage({ + ...fields, + tool_call_id: message.tool_call_id ?? "", + ...(message.status ? { status: message.status } : {}), + ...(message.artifact !== undefined ? { artifact: message.artifact } : {}), + }); + case "human": + return new HumanMessage(fields); + } +} diff --git a/actions/ai-action/src/utils/middleware/Approval.askFor.util.ts b/actions/ai-action/src/utils/middleware/Approval.askFor.util.ts new file mode 100644 index 0000000..242da93 --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.askFor.util.ts @@ -0,0 +1,13 @@ +import type { ToolCall } from "../../types/middleware/Approval.types.js"; +import { APPROVE, DECLINE } from "./Approval.markers.util.js"; +import { describeCall } from "./Approval.describeCall.util.js"; + +/** + * The question an agent answers with instead of running the calls: what it wants to + * do, and the two answers that decide about it. + * + * The code belongs to this one question, so an approval cannot be reused for a later + * call and an answer copied out of an older message cannot release a new one. + */ +export const askFor = (calls: ToolCall[], code: string): string => + [...calls.map(describeCall), "", `${APPROVE} ${code}`, `${DECLINE} ${code}`].join("\n"); diff --git a/actions/ai-action/src/utils/middleware/Approval.codeOf.util.ts b/actions/ai-action/src/utils/middleware/Approval.codeOf.util.ts new file mode 100644 index 0000000..8cb0abe --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.codeOf.util.ts @@ -0,0 +1,10 @@ +import { APPROVE, CODE } from "./Approval.markers.util.js"; + +/** + * The code a question was asked under, read out of its own marker line. + * + * A message is a question by that line alone, not by any wording - which is what lets + * the exchange work in a flow of any language. + */ +export const codeOf = (text: string): string | undefined => + new RegExp(`^${APPROVE} (${CODE})$`, "m").exec(text)?.[1]; diff --git a/actions/ai-action/src/utils/middleware/Approval.describeCall.util.ts b/actions/ai-action/src/utils/middleware/Approval.describeCall.util.ts new file mode 100644 index 0000000..dc29767 --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.describeCall.util.ts @@ -0,0 +1,7 @@ +import type { ToolCall } from "../../types/middleware/Approval.types.js"; + +/** + * How a call is written into a question and recognised in it. The arguments are part + * of it: an approved refund of one order says nothing about another. + */ +export const describeCall = (call: ToolCall): string => `${call.name}(${JSON.stringify(call.args ?? {})})`; diff --git a/actions/ai-action/src/utils/middleware/Approval.markers.util.ts b/actions/ai-action/src/utils/middleware/Approval.markers.util.ts new file mode 100644 index 0000000..84fffac --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.markers.util.ts @@ -0,0 +1,17 @@ +/** + * The three markers the approval exchange writes and reads, and the whole of its + * language. + * + * A question carries no sentence: a flow may be answered in any language, and an + * agent's own words would have to be matched to be trusted. So the message is the + * calls plus the two words that decide, and the marker lines are what identifies it + * again - nothing here has to be read by a person to work. + */ +export const APPROVE = "APPROVE"; +export const DECLINE = "DECLINE"; + +/** Marks a question as answered, so no second call can lean on it. */ +export const DECIDED = "DECIDED"; + +/** The shape of a question's code, which is what ties an answer to one question. */ +export const CODE = "[0-9a-f]{4,12}"; diff --git a/actions/ai-action/src/utils/middleware/Approval.newCode.util.ts b/actions/ai-action/src/utils/middleware/Approval.newCode.util.ts new file mode 100644 index 0000000..db747d4 --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.newCode.util.ts @@ -0,0 +1,4 @@ +import { randomBytes } from "node:crypto"; + +/** A fresh code for one question, which is what makes an approval single-use. */ +export const newCode = (): string => randomBytes(3).toString("hex"); diff --git a/actions/ai-action/src/utils/middleware/Approval.settle.util.ts b/actions/ai-action/src/utils/middleware/Approval.settle.util.ts new file mode 100644 index 0000000..d17eff2 --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Approval.settle.util.ts @@ -0,0 +1,9 @@ +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; +import { DECIDED } from "./Approval.markers.util.js"; +import { textOf } from "../message/Message.textOf.util.js"; + +/** The question with its code marked as used, so it cannot be used twice. */ +export const settle = (message: AiMessage, code: string): AiMessage => ({ + ...message, + content: [{ type: "text", text: `${textOf(message)}\n\n${DECIDED} ${code}` }], +}); diff --git a/actions/ai-action/src/utils/middleware/Middleware.createHookHandler.util.ts b/actions/ai-action/src/utils/middleware/Middleware.createHookHandler.util.ts new file mode 100644 index 0000000..5a32aa4 --- /dev/null +++ b/actions/ai-action/src/utils/middleware/Middleware.createHookHandler.util.ts @@ -0,0 +1,53 @@ +import type { SubFlow } from "@code0-tech/hercules"; +import { RemoveMessage, type BaseMessage } from "@langchain/core/messages"; +import type { AiMiddlewareHook } from "../../datatypes/middleware/Middleware.hook.datatype.js"; +import { AiStateUpdateSchema } from "../../datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import { hasEntries } from "../shared/Shared.hasEntries.util.js"; +import { parseOrThrow } from "../shared/Shared.parseOrThrow.util.js"; +import { stripUndefined } from "../shared/Shared.stripUndefined.util.js"; +import { toFlowMessage } from "../message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../message/Message.toLangChainMessage.util.js"; +import type { AgentRuntime, AgentState, HookHandler, HookResult } from "../../types/middleware/Middleware.types.js"; + +export function createHookHandler(run: SubFlow, agentName: string, hook: AiMiddlewareHook): HookHandler { + return async (state: AgentState, runtime?: AgentRuntime): Promise => { + // The state is stripped as a whole: `context` and `structured_response` are + // whatever the agent put there, and a sub flow argument may not carry + // `undefined`. + const raw = await run( + stripUndefined({ + messages: state.messages.map(toFlowMessage), + agent_name: agentName, + hook, + ...(state.structuredResponse ? { structured_response: state.structuredResponse } : {}), + ...(hasEntries(runtime?.context) ? { context: runtime?.context } : {}), + }) as never, + ); + if (raw === undefined || raw === null) return undefined; + + const update = parseOrThrow( + AiStateUpdateSchema, + raw, + "ERROR_INVALID_AI_STATE_UPDATE", + `The middleware sub flow did not return a valid state update for the ${hook} phase`, + ); + if (!update.messages && !update.jump_to && !update.structured_response) return undefined; + + return { + // A middleware returns the conversation it wants, not a patch of it, so + // every message that had an id is removed before the new ones are added. + ...(update.messages + ? { + messages: [ + ...state.messages + .filter((message): message is BaseMessage & { id: string } => typeof message.id === "string") + .map((message) => new RemoveMessage({ id: message.id })), + ...update.messages.map(toLangChainMessage), + ], + } + : {}), + ...(update.structured_response ? { structuredResponse: update.structured_response } : {}), + ...(update.jump_to ? { jumpTo: update.jump_to } : {}), + }; + }; +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.corsHeaders.util.ts b/actions/ai-action/src/utils/openai/OpenAi.corsHeaders.util.ts new file mode 100644 index 0000000..03dc621 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.corsHeaders.util.ts @@ -0,0 +1,11 @@ +/** + * What a browser needs before it may call the endpoint from a page, and what a client + * sends a preflight for. The server is reached from other origins by design - a client + * runs wherever it runs - so the headers are open. + */ +export const corsHeaders = (): Record => ({ + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization, content-type, api-key", + "access-control-max-age": "86400", +}); diff --git a/actions/ai-action/src/utils/openai/OpenAi.errorBody.util.ts b/actions/ai-action/src/utils/openai/OpenAi.errorBody.util.ts new file mode 100644 index 0000000..bc2ab88 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.errorBody.util.ts @@ -0,0 +1,6 @@ +import type { OpenAiErrorBody } from "../../types/openai/OpenAiServer.types.js"; + +/** An error as an OpenAI client reads it, which is the only shape it understands. */ +export const errorBody = (message: string, type: string, code?: string): OpenAiErrorBody => ({ + error: { message, type, ...(code ? { code } : {}) }, +}); diff --git a/actions/ai-action/src/utils/openai/OpenAi.normalizeRoute.util.ts b/actions/ai-action/src/utils/openai/OpenAi.normalizeRoute.util.ts new file mode 100644 index 0000000..d18b9da --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.normalizeRoute.util.ts @@ -0,0 +1,11 @@ +/** + * A route as it is compared: leading slash, no trailing one. + * + * `/v1`, `v1/` and `/v1/` are the same endpoint, and a flow saying `/` serves the + * project's root - so a flow is reachable however its route was typed. + */ +export function normalizeRoute(route: string): string { + const trimmed: string = route.trim().replace(/\/+$/, ""); + if (trimmed.length === 0) return ""; + return trimmed.startsWith("/") ? trimmed : `/${trimmed}`; +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.parsePath.util.ts b/actions/ai-action/src/utils/openai/OpenAi.parsePath.util.ts new file mode 100644 index 0000000..262a654 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.parsePath.util.ts @@ -0,0 +1,32 @@ +import type { OpenAiEndpointKind, OpenAiRequestPath } from "../../types/openai/OpenAi.types.js"; +import { normalizeRoute } from "./OpenAi.normalizeRoute.util.js"; + +const ENDPOINTS: Record = { + "/chat/completions": "chat_completions", + "/models": "models", +}; + +/** + * Splits a request path into the project, the flow's route and the endpoint. + * + * A client is configured with a base URL and appends the endpoint itself, so the path + * reads `///chat/completions`. The project comes first because a + * route is only unique inside one: without the slug two projects asking for `/v1` + * would answer each other's requests. + */ +export function parseRequestPath(path: string): OpenAiRequestPath | undefined { + const [withoutQuery] = path.split("?"); + const clean: string = normalizeRoute(withoutQuery ?? ""); + + const endpoint: [string, OpenAiEndpointKind] | undefined = Object.entries(ENDPOINTS).find(([suffix]) => + clean.endsWith(suffix), + ); + if (!endpoint) return undefined; + + const [suffix, kind] = endpoint; + const base: string = clean.slice(0, -suffix.length); + const [slug, ...rest] = base.split("/").filter((segment) => segment.length > 0); + if (!slug) return undefined; + + return { slug, route: normalizeRoute(rest.join("/")), kind }; +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts b/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts new file mode 100644 index 0000000..6749b29 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts @@ -0,0 +1,54 @@ +import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import { logger } from "../shared/Log.logger.util.js"; + +const log = logger("openai"); + +interface Waiting { + resolve: (response: AiChatResponse) => void; + model: string; +} + +/** + * The HTTP requests currently waiting for a flow to answer them, keyed by the + * execution the flow runs as. + * + * The server and `ai::openai::respond` are two halves of one exchange that never meet + * in code: the server opens a wait before it starts the flow, the node closes it from + * wherever in that flow it sits. They find each other through the execution id - the + * server reserves it up front, and a runtime function of that flow is handed the very + * same id as its `FunctionContext.executionId`, so nothing has to be passed through + * the flow for them to match. + */ +class PendingResponses { + private readonly waiting = new Map(); + + /** Opens a wait and resolves once the flow responds, if it ever does. */ + open(executionId: string, model: string): Promise { + return new Promise((resolve) => { + this.waiting.set(executionId, { resolve, model }); + log.debug(`waiting for execution ${executionId} to answer`, { model, waiting: this.waiting.size }); + }); + } + + /** True when the answer was handed to a request that is still waiting for it. */ + settle(executionId: string, response: AiChatResponse): boolean { + const waiting: Waiting | undefined = this.waiting.get(executionId); + if (!waiting) return false; + + this.waiting.delete(executionId); + waiting.resolve(response); + log.debug(`execution ${executionId} answered its request`, { waiting: this.waiting.size }); + return true; + } + + /** Drops a wait whose request is gone, so a late answer finds nothing to settle. */ + close(executionId: string): void { + this.waiting.delete(executionId); + } + + get size(): number { + return this.waiting.size; + } +} + +export const pendingResponses = new PendingResponses(); diff --git a/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts b/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts new file mode 100644 index 0000000..0c2dd09 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts @@ -0,0 +1,16 @@ +import type { ServerResponse } from "node:http"; +import type { Logger } from "../../types/shared/Log.types.js"; +import { corsHeaders } from "./OpenAi.corsHeaders.util.js"; + +/** Answers with JSON, which is every answer of this endpoint but a stream. */ +export function sendJson(response: ServerResponse, status: number, body: unknown, trace: Logger): void { + const payload: string = JSON.stringify(body); + trace.debug(`answering ${status} as json`, body); + + response.writeHead(status, { + ...corsHeaders(), + "content-type": "application/json", + "content-length": Buffer.byteLength(payload), + }); + response.end(payload); +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.textSetting.util.ts b/actions/ai-action/src/utils/openai/OpenAi.textSetting.util.ts new file mode 100644 index 0000000..e65c3bf --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.textSetting.util.ts @@ -0,0 +1,17 @@ +import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import { toAllowedValue } from "@code0-tech/tucana/helpers"; + +/** + * A flow setting as plain text, or undefined when it is unset or not text. + * + * Settings arrive as protobuf values, so reading one is this unwrapping step - and an + * empty setting is treated as unset, because a route or a model name of "" names + * nothing. + */ +export function textSetting(flow: ActionFlow, identifier: string): string | undefined { + const setting = flow.settings.find((entry) => entry.flowSettingId.toLowerCase() === identifier); + if (!setting?.value) return undefined; + + const value: unknown = toAllowedValue(setting.value); + return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined; +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts b/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts new file mode 100644 index 0000000..8abe25c --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts @@ -0,0 +1,39 @@ +import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import { OPENAI_EVENT, type OpenAiEndpoint } from "../../types/openai/OpenAi.types.js"; +import { logger } from "../shared/Log.logger.util.js"; +import { normalizeRoute } from "./OpenAi.normalizeRoute.util.js"; +import { textSetting } from "./OpenAi.textSetting.util.js"; + +const log = logger("openai"); + +/** + * The endpoints the action currently serves. + * + * A flow missing its route or its model name is left out rather than guessed at: the + * route is what makes it reachable and the model is what a client asks for, so + * standing in for either would answer under a name nobody picked. It is logged, + * because a model missing from a client's list is otherwise a silent gap. + */ +export function toEndpoints(flows: ActionFlow[]): OpenAiEndpoint[] { + return flows + .filter((flow) => flow.type === OPENAI_EVENT) + .map((flow): OpenAiEndpoint | undefined => { + const route: string | undefined = textSetting(flow, "route"); + const model: string | undefined = textSetting(flow, "model"); + const slug: string = flow.projectSlug.trim(); + + if (!route || !model || slug.length === 0) { + log.warn(`flow ${flow.flowId} is bound to the OpenAI endpoint but serves nothing`, { + name: flow.name, + route: route ?? null, + model: model ?? null, + project: slug || null, + }); + return undefined; + } + + const apiKey: string | undefined = textSetting(flow, "api_key"); + return { flow, slug, route: normalizeRoute(route), model, ...(apiKey ? { apiKey } : {}) }; + }) + .filter((endpoint): endpoint is OpenAiEndpoint => endpoint !== undefined); +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.toModelList.util.ts b/actions/ai-action/src/utils/openai/OpenAi.toModelList.util.ts new file mode 100644 index 0000000..9e1d09f --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.toModelList.util.ts @@ -0,0 +1,22 @@ +import type { OpenAiEndpoint, OpenAiModel, OpenAiModelList } from "../../types/openai/OpenAi.types.js"; + +/** + * The answer to `GET /models`: the flows serving this route, by the model name each + * one carries. A client asks for this before it sends a message - Open WebUI lists + * what it finds here and treats a failure as a broken connection - and the list is + * built from the flows themselves, so adding a flow adds a model with nothing else + * to configure. + */ +export function toModelList(endpoints: OpenAiEndpoint[]): OpenAiModelList { + const created: number = Math.floor(Date.now() / 1000); + const seen = new Set(); + const data: OpenAiModel[] = []; + + for (const endpoint of endpoints) { + if (seen.has(endpoint.model)) continue; + seen.add(endpoint.model); + data.push({ id: endpoint.model, object: "model", created, owned_by: endpoint.slug }); + } + + return { object: "list", data }; +} diff --git a/actions/ai-action/src/utils/openai/OpenAi.toStream.util.ts b/actions/ai-action/src/utils/openai/OpenAi.toStream.util.ts new file mode 100644 index 0000000..6d72a69 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.toStream.util.ts @@ -0,0 +1,44 @@ +import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; + +/** + * A finished answer as the chunks a streaming client expects. + * + * A flow answers in one piece - it runs an agent to the end before it returns - so + * there is nothing to stream token by token. Clients still ask for `stream: true` by + * default (Open WebUI does), and a client that asked for a stream cannot read a plain + * body, so the answer is sent as the two chunks of a stream that happens to arrive at + * once: the content, then the end. + */ +export function toStreamChunks(response: AiChatResponse): string[] { + const head = { + id: response.id, + object: "chat.completion.chunk", + created: response.created, + model: response.model, + }; + const content: string = response.response; + const toolCalls = response.choices[0]?.message.tool_calls; + + return [ + JSON.stringify({ + ...head, + choices: [ + { + index: 0, + delta: { role: "assistant", content, ...(toolCalls ? { tool_calls: toolCalls } : {}) }, + finish_reason: null, + }, + ], + // What the agent did travels with the stream too, so a client that reads + // these fields is not worse off for having asked for a stream. + ...(response.steps ? { steps: response.steps } : {}), + ...(response.awaiting_approval ? { awaiting_approval: response.awaiting_approval } : {}), + }), + JSON.stringify({ + ...head, + choices: [{ index: 0, delta: {}, finish_reason: response.choices[0]?.finish_reason ?? "stop" }], + ...(response.usage ? { usage: response.usage } : {}), + }), + "[DONE]", + ]; +} diff --git a/actions/ai-action/src/utils/shared/Log.describeValue.util.ts b/actions/ai-action/src/utils/shared/Log.describeValue.util.ts new file mode 100644 index 0000000..0ae2160 --- /dev/null +++ b/actions/ai-action/src/utils/shared/Log.describeValue.util.ts @@ -0,0 +1,28 @@ +/** Keys whose value never reaches a log line, wherever they sit in a payload. */ +const SECRETS = /^(api[-_]?key|authorization|auth|token|password|secret|[a-z]+[-_]?api[-_]?key)$/i; +const REDACTED = "[redacted]"; +const MAX_VALUE_CHARS = 2000; + +/** + * A value as a log line: secrets dropped, long values cut, cycles survived. + * + * Everything logged goes through here, so no line can carry an API key, a payload + * cannot bury the rest of a run, and a value that refers to itself does not throw + * where it is only meant to be described. + */ +export function describeValue(value: unknown): string { + const seen = new WeakSet(); + const text: string = + JSON.stringify(value, (key: string, entry: unknown): unknown => { + if (SECRETS.test(key)) return REDACTED; + if (typeof entry === "bigint") return `${entry}`; + if (typeof entry === "function") return "[function]"; + if (typeof entry === "object" && entry !== null) { + if (seen.has(entry)) return "[circular]"; + seen.add(entry); + } + return entry; + }) ?? String(value); + + return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}…(${text.length} chars)` : text; +} diff --git a/actions/ai-action/src/utils/shared/Log.emit.util.ts b/actions/ai-action/src/utils/shared/Log.emit.util.ts new file mode 100644 index 0000000..d03ff58 --- /dev/null +++ b/actions/ai-action/src/utils/shared/Log.emit.util.ts @@ -0,0 +1,38 @@ +import { LOG_LEVELS, type LogLevel, type WritingLevel } from "../../types/shared/Log.types.js"; +import { describeValue } from "./Log.describeValue.util.js"; + +/** + * Writes one line, if a line of this level is written at all. + * + * How much is logged comes from `AI_LOG_LEVEL`: `debug` by default so a run can be + * followed end to end while the action is being tried out, and off under vitest, + * where the lines would bury the test output. Set `AI_LOG_LEVEL=off` to silence it, + * or `AI_LOG_LEVEL=debug` in a test run to see everything. + */ +export function emit( + level: WritingLevel, + scope: string, + correlation: string | undefined, + message: string, + details?: unknown, +): void { + const configured: string | undefined = process.env.AI_LOG_LEVEL?.trim().toLowerCase(); + const wanted: LogLevel = + configured && (LOG_LEVELS as readonly string[]).includes(configured) + ? (configured as LogLevel) + : process.env.VITEST || process.env.NODE_ENV === "test" + ? "off" + : "debug"; + if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(wanted)) return; + + const line: string = [ + new Date().toISOString(), + level.toUpperCase().padEnd(5), + `[ai${scope ? `:${scope}` : ""}]${correlation ? ` (${correlation})` : ""}`, + message, + ].join(" "); + + const write = level === "error" ? console.error : level === "warn" ? console.warn : console.log; + if (details === undefined) write(line); + else write(`${line} ${describeValue(details)}`); +} diff --git a/actions/ai-action/src/utils/shared/Log.logger.util.ts b/actions/ai-action/src/utils/shared/Log.logger.util.ts new file mode 100644 index 0000000..7d378e8 --- /dev/null +++ b/actions/ai-action/src/utils/shared/Log.logger.util.ts @@ -0,0 +1,18 @@ +import type { Logger } from "../../types/shared/Log.types.js"; +import { emit } from "./Log.emit.util.js"; + +/** + * The action's logging, scoped by what it is about (`openai`, `agent`, `model`). + * + * Every line goes through here rather than to `console` directly, so one environment + * variable turns the whole run quiet or loud, and so nothing logs an API key. + */ +export function logger(scope: string, correlation?: string): Logger { + return { + debug: (message, details) => emit("debug", scope, correlation, message, details), + info: (message, details) => emit("info", scope, correlation, message, details), + warn: (message, details) => emit("warn", scope, correlation, message, details), + error: (message, details) => emit("error", scope, correlation, message, details), + child: (next: string) => logger(scope, next), + }; +} diff --git a/actions/ai-action/src/shared/utils/Shared.asList.util.ts b/actions/ai-action/src/utils/shared/Shared.asList.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.asList.util.ts rename to actions/ai-action/src/utils/shared/Shared.asList.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts b/actions/ai-action/src/utils/shared/Shared.asSubFlow.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.asSubFlow.util.ts rename to actions/ai-action/src/utils/shared/Shared.asSubFlow.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.asText.util.ts b/actions/ai-action/src/utils/shared/Shared.asText.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.asText.util.ts rename to actions/ai-action/src/utils/shared/Shared.asText.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts b/actions/ai-action/src/utils/shared/Shared.connectToAquila.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.connectToAquila.util.ts rename to actions/ai-action/src/utils/shared/Shared.connectToAquila.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.describeError.util.ts b/actions/ai-action/src/utils/shared/Shared.describeError.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.describeError.util.ts rename to actions/ai-action/src/utils/shared/Shared.describeError.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts b/actions/ai-action/src/utils/shared/Shared.emptyJsonSchema.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.emptyJsonSchema.util.ts rename to actions/ai-action/src/utils/shared/Shared.emptyJsonSchema.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts b/actions/ai-action/src/utils/shared/Shared.formatIssues.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.formatIssues.util.ts rename to actions/ai-action/src/utils/shared/Shared.formatIssues.util.ts diff --git a/actions/ai-action/src/utils/shared/Shared.fromProtoValue.util.ts b/actions/ai-action/src/utils/shared/Shared.fromProtoValue.util.ts new file mode 100644 index 0000000..96a817a --- /dev/null +++ b/actions/ai-action/src/utils/shared/Shared.fromProtoValue.util.ts @@ -0,0 +1,34 @@ +import type { ProtoStruct } from "../../types/shared/Proto.types.js"; + +/** + * One wrapped protobuf value as the plain JSON it stands for. + * + * It has a single caller and still stands on its own: a struct nests, so unwrapping + * one needs a function that can call itself, which no call site can do inline. + */ +export function fromProtoValue(value: unknown): unknown { + const kind = (value as { kind?: { oneofKind?: string } })?.kind; + if (!kind?.oneofKind) return null; + + const wrapped: unknown = (kind as Record)[kind.oneofKind]; + + switch (kind.oneofKind) { + case "stringValue": + case "boolValue": + return wrapped; + case "numberValue": { + const number = (wrapped as { number?: { oneofKind?: string } })?.number; + if (!number?.oneofKind) return null; + // An int64 reaches us as a bigint, which JSON cannot carry. + return Number((number as Record)[number.oneofKind]); + } + case "structValue": + return Object.fromEntries( + Object.entries((wrapped as ProtoStruct).fields).map(([key, field]) => [key, fromProtoValue(field)]), + ); + case "listValue": + return ((wrapped as { values?: unknown[] })?.values ?? []).map(fromProtoValue); + default: + return null; + } +} diff --git a/actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts b/actions/ai-action/src/utils/shared/Shared.hasEntries.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.hasEntries.util.ts rename to actions/ai-action/src/utils/shared/Shared.hasEntries.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts b/actions/ai-action/src/utils/shared/Shared.isSubFlow.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.isSubFlow.util.ts rename to actions/ai-action/src/utils/shared/Shared.isSubFlow.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts b/actions/ai-action/src/utils/shared/Shared.parseOrThrow.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.parseOrThrow.util.ts rename to actions/ai-action/src/utils/shared/Shared.parseOrThrow.util.ts diff --git a/actions/ai-action/src/shared/utils/Shared.requireText.util.ts b/actions/ai-action/src/utils/shared/Shared.requireText.util.ts similarity index 100% rename from actions/ai-action/src/shared/utils/Shared.requireText.util.ts rename to actions/ai-action/src/utils/shared/Shared.requireText.util.ts diff --git a/actions/ai-action/src/utils/shared/Shared.stripUndefined.util.ts b/actions/ai-action/src/utils/shared/Shared.stripUndefined.util.ts new file mode 100644 index 0000000..7402e8b --- /dev/null +++ b/actions/ai-action/src/utils/shared/Shared.stripUndefined.util.ts @@ -0,0 +1,29 @@ +/** + * Drops every `undefined` from a value, at any depth. + * + * Hercules turns what a runtime function returns - and every argument of a sub flow + * call - into a protobuf value, and that serializer has no representation for + * `undefined`: it throws `Unsupported value type: undefined` and the whole execution + * fails with an unhelpful UNKNOWN_ERROR. Provider payloads carry such keys routinely + * (an unset `system_fingerprint`, a tool call without an error, token details a model + * did not report), so anything a model or an API produced has to be cleaned before it + * crosses that boundary. A key whose value is undefined is left out entirely, which + * is what an optional field in our schemas means anyway. + */ +export function stripUndefined(value: T): T { + if (Array.isArray(value)) { + // An entry dropped from a list would shift every later index, so an + // undefined entry becomes null instead of disappearing. + return value.map((entry: unknown) => (entry === undefined ? null : stripUndefined(entry))) as T; + } + + if (typeof value === "object" && value !== null) { + const cleaned: Record = {}; + for (const [key, entry] of Object.entries(value as Record)) { + if (entry !== undefined) cleaned[key] = stripUndefined(entry); + } + return cleaned as T; + } + + return value; +} diff --git a/actions/ai-action/src/utils/shared/Shared.toPlainSchema.util.ts b/actions/ai-action/src/utils/shared/Shared.toPlainSchema.util.ts new file mode 100644 index 0000000..8880d44 --- /dev/null +++ b/actions/ai-action/src/utils/shared/Shared.toPlainSchema.util.ts @@ -0,0 +1,33 @@ +import { fromProtoValue } from "./Shared.fromProtoValue.util.js"; + +/** + * The sub flow's schema as plain JSON, or undefined when it declared none. + * + * A sub flow's `inputSchema` arrives as the raw protobuf `shared.Struct` - hercules + * hands the message through untouched - so every value is still wrapped in its `kind` + * oneof. Reading a JSON schema off that directly yields nothing: it has to be + * unwrapped back into plain JSON first. A schema that is already plain is passed + * through, so this holds either way. + */ +export function toPlainSchema(value: unknown): Record | undefined { + if (typeof value !== "object" || value === null) return undefined; + + const fields = (value as { fields?: unknown }).fields; + if (typeof fields === "object" && fields !== null) { + const entries: [string, unknown][] = Object.entries(fields as Record); + // A `Struct` is told apart from a plain schema by its wrapped field values. + const isStruct: boolean = + entries.length === 0 || + entries.some( + ([, entry]) => + typeof (entry as { kind?: { oneofKind?: unknown } })?.kind === "object" && + typeof (entry as { kind: { oneofKind?: unknown } }).kind?.oneofKind === "string", + ); + + if (isStruct) { + return Object.fromEntries(entries.map(([key, field]) => [key, fromProtoValue(field)])); + } + } + + return value as Record; +} diff --git a/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts b/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts deleted file mode 100644 index cf1f9db..0000000 --- a/actions/ai-action/src/websearch/datatypes/WebSearch.hit.datatype.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; -import { z } from "zod"; - -export const AiWebSearchHitSchema = z.object({ - title: z.string(), - url: z.string(), - content: z.string(), - score: z.number().optional(), -}); -export type AiWebSearchHit = z.infer; - -@Identifier("AI_WEB_SEARCH_HIT") -@Name({ code: "en-US", content: "Web search hit" }) -@DisplayMessage({ code: "en-US", content: "${title}" }) -@Schema(AiWebSearchHitSchema) -export class AiWebSearchHitDataType {} diff --git a/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts b/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts deleted file mode 100644 index 7ce6e21..0000000 --- a/actions/ai-action/src/websearch/datatypes/WebSearch.result.datatype.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; -import { z } from "zod"; -import { AiWebSearchHitSchema } from "./WebSearch.hit.datatype.js"; - -export const AiWebSearchResultSchema = z.object({ - query: z.string(), - results: z.array(AiWebSearchHitSchema), - answer: z.string().optional(), -}); -export type AiWebSearchResult = z.infer; - -@Identifier("AI_WEB_SEARCH_RESULT") -@Name({ code: "en-US", content: "Web search result" }) -@DisplayMessage({ code: "en-US", content: "Web search for ${query}" }) -@Schema(AiWebSearchResultSchema) -export class AiWebSearchResultDataType {} diff --git a/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts b/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts deleted file mode 100644 index 14c2445..0000000 --- a/actions/ai-action/src/websearch/runtimefunctions/WebSearch.search.runtimefunction.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - DisplayIcon, - DisplayMessage, - FunctionContext, - Identifier, - Name, - Parameter, - RuntimeError, - Signature, - ThrowsError, -} from "@code0-tech/hercules"; -import { TavilySearch } from "@langchain/tavily"; -import type { AiWebSearchResult } from "../datatypes/WebSearch.result.datatype.js"; -import { describeError } from "../../shared/utils/Shared.describeError.util.js"; -import { requireText } from "../../shared/utils/Shared.requireText.util.js"; -import { toSearchResult } from "../utils/WebSearch.toSearchResult.util.js"; - -type WebSearchTopic = "general" | "news" | "finance"; - -@Identifier("ai::tool::web_search") -@DisplayIcon("tabler:world-search") -@Signature( - "(query: TEXT, api_key: TEXT, max_results?: NUMBER, topic?: TEXT, include_answer?: BOOLEAN): AI_WEB_SEARCH_RESULT", -) -@Name({ code: "en-US", content: "Web search" }) -@DisplayMessage({ code: "en-US", content: "Search the web for ${query}" }) -@ThrowsError() -@Parameter({ - runtimeName: "query", - name: [{ code: "en-US", content: "Query" }], -}) -@Parameter({ - runtimeName: "api_key", - name: [{ code: "en-US", content: "API key" }], -}) -@Parameter({ - runtimeName: "max_results", - name: [{ code: "en-US", content: "Maximum results" }], - optional: true, -}) -@Parameter({ - runtimeName: "topic", - name: [{ code: "en-US", content: "Topic" }], - optional: true, -}) -@Parameter({ - runtimeName: "include_answer", - name: [{ code: "en-US", content: "Include answer" }], - optional: true, -}) -export class WebSearchToolFunction { - async run( - _context: FunctionContext, - query: string, - api_key: string, - max_results?: number, - topic?: WebSearchTopic, - include_answer?: boolean, - ): Promise { - const question: string = requireText(query, "ERROR_INVALID_AI_WEB_SEARCH", "A web search needs a query."); - const search = new TavilySearch({ - tavilyApiKey: requireText(api_key, "ERROR_INVALID_AI_WEB_SEARCH", "A web search needs a Tavily API key."), - maxResults: max_results ?? 5, - includeAnswer: include_answer ?? true, - ...(topic ? { topic } : {}), - }); - - const raw = await search.invoke({ query: question }).catch((error: unknown) => { - throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", `The web search failed: ${describeError(error)}`); - }); - - return toSearchResult(question, raw); - } -} diff --git a/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts b/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts deleted file mode 100644 index dab4e36..0000000 --- a/actions/ai-action/src/websearch/utils/WebSearch.parseSearchPayload.util.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { RuntimeError } from "@code0-tech/hercules"; - -export function parseSearchPayload(value: string): unknown { - try { - return JSON.parse(value); - } catch { - throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", "The web search returned an unreadable response."); - } -} diff --git a/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts b/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts deleted file mode 100644 index 4bbf537..0000000 --- a/actions/ai-action/src/websearch/utils/WebSearch.toSearchResult.util.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { RuntimeError } from "@code0-tech/hercules"; -import { AiWebSearchResultSchema, type AiWebSearchResult } from "../datatypes/WebSearch.result.datatype.js"; -import { parseSearchPayload } from "./WebSearch.parseSearchPayload.util.js"; - -export function toSearchResult(query: string, raw: unknown): AiWebSearchResult { - const payload: unknown = typeof raw === "string" ? parseSearchPayload(raw) : raw; - - if (payload && typeof payload === "object" && "error" in payload) { - throw new RuntimeError("ERROR_AI_WEB_SEARCH_FAILED", `The web search failed: ${String(payload.error)}`); - } - - const source = (payload ?? {}) as { results?: unknown; answer?: unknown }; - const results: unknown[] = Array.isArray(source.results) ? source.results : []; - - return AiWebSearchResultSchema.parse({ - query, - results: results.map((hit) => { - const entry = (hit ?? {}) as Record; - return { - title: String(entry.title ?? ""), - url: String(entry.url ?? ""), - content: String(entry.content ?? ""), - ...(typeof entry.score === "number" ? { score: entry.score } : {}), - }; - }), - ...(typeof source.answer === "string" && source.answer.length > 0 ? { answer: source.answer } : {}), - }); -} diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts index 6cb3b3b..e0e38fd 100644 --- a/actions/ai-action/test/agent.test.ts +++ b/actions/ai-action/test/agent.test.ts @@ -1,12 +1,12 @@ import "reflect-metadata"; import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; import { describe, expect, it } from "vitest"; -import type { AiAgentState } from "../src/middleware/datatypes/Middleware.agentState.datatype.js"; -import type { AiMessage } from "../src/message/datatypes/Message.datatype.js"; -import type { AiModelRequest } from "../src/model/datatypes/Model.request.datatype.js"; -import type { AiModelResponse } from "../src/model/datatypes/Model.response.datatype.js"; -import { CreateAgentFunction } from "../src/agent/runtimefunctions/Agent.create.runtimefunction.js"; -import { TrimMessagesMiddlewareFunction } from "../src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; +import type { AiAgentState } from "../src/datatypes/middleware/Middleware.agentState.datatype.js"; +import type { AiMessage } from "../src/datatypes/message/Message.datatype.js"; +import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; +import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { TrimMessagesMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; function subFlow(implementation: (input: never) => unknown, inputSchema?: Record): SubFlow { const flow = (async (input: never) => implementation(input)) as unknown as { @@ -17,6 +17,20 @@ function subFlow(implementation: (input: never) => unknown, inputSchema?: Record return flow as unknown as SubFlow; } +/** + * Mirrors how hercules hands a sub flow function to a consuming node: the producing + * node returns a definition, the node that receives it gets a callable sub flow. + */ +function asFlowValue(definition: { run: (...args: never[]) => R | Promise }): (...args: unknown[]) => Promise { + const call = definition.run.bind(definition) as unknown as (...args: unknown[]) => R | Promise; + return (...args: unknown[]) => Promise.resolve(call(...args)); +} + +/** The assistant text of a chat response, which is what the node answers with. */ +function replyOf(response: { choices: { message: { content?: unknown } }[] }): string { + return String(response.choices[0]?.message.content ?? ""); +} + function context(executionId = "execution-1"): FunctionContext { return { projectId: 1, @@ -38,18 +52,36 @@ function answer(text: string, toolCalls: { id: string; name: string; args: objec }; } -function scriptedModel(responses: AiModelResponse[]) { +function scriptedModel(responses: AiModelResponse[], inputSchema?: Record) { const requests: AiModelRequest[] = []; let call = 0; const run = subFlow((input: never) => { requests.push(input as unknown as AiModelRequest); return responses[Math.min(call++, responses.length - 1)]; - }); + }, inputSchema); return { run, requests }; } +/** + * The input schema of a model node that can constrain its own output, which is how + * such a node tells the agent to ask the provider for the type directly instead of + * binding it as a tool the model has to call. + */ +const nativeModelSchema: Record = { + type: "object", + properties: { messages: {}, tools: {}, response_format: {} }, +}; + const create = new CreateAgentFunction(); +/** A data type's JSON schema, which is what a `TYPE` parameter carries. */ +const orderType: Record = { + title: "Order", + type: "object", + properties: { order: { type: "string" }, status: { type: "string" } }, + required: ["order", "status"], +}; + function user(text: string): AiMessage { return { role: "human", content: [{ type: "text", text }] }; } @@ -65,54 +97,219 @@ function textOf(message: AiMessage | undefined): string { .join(""); } +/** Wraps a plain schema the way aquila sends a sub flow's input schema: a shared.Struct. */ +function asStruct(plain: Record): unknown { + const asValue = (value: unknown): unknown => { + if (typeof value === "string") return { kind: { oneofKind: "stringValue", stringValue: value } }; + if (typeof value === "boolean") return { kind: { oneofKind: "boolValue", boolValue: value } }; + if (typeof value === "number") + return { + kind: { + oneofKind: "numberValue", + numberValue: { number: { oneofKind: "integer", integer: BigInt(value) } }, + }, + }; + if (Array.isArray(value)) return { kind: { oneofKind: "listValue", listValue: { values: value.map(asValue) } } }; + if (value && typeof value === "object") + return { kind: { oneofKind: "structValue", structValue: asStruct(value as Record) } }; + return { kind: { oneofKind: "nullValue", nullValue: 0 } }; + }; + + return { fields: Object.fromEntries(Object.entries(plain).map(([key, value]) => [key, asValue(value)])) }; +} + describe("ai::agent::create", () => { - it("returns the agent itself, which is a callable", () => { + it("answers with a chat response, because it runs the agent itself", async () => { const { run } = scriptedModel([answer("hello")]); - const agent = create.run(context(), "greeter", "You greet people.", run); + const response = await create.run(context(), "greeter", "You greet people.", run, "hi"); + + expect(response.object).toEqual("chat.completion"); + expect(replyOf(response)).toEqual("hello"); + }); + + it("answers in the type it was given, next to the chat response", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), + ]); + + const response = await create.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + + // The type travels to the model as the tool it has to call to answer. + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Order"]); + expect(response.structured_response).toEqual({ order: "A-1", status: "shipped" }); + }); + + it("forces the tool call that carries the type, because an offered tool is one the model may skip", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), + ]); + + await create.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + + expect(requests[0].tool_choice).toBe("any"); + }); + + it("leaves the tool choice alone when no type was asked for", async () => { + const { run, requests } = scriptedModel([answer("hello")]); + await create.run(context(), "greeter", "", run, "hi"); + + expect(requests[0].tool_choice).toBeUndefined(); + }); + + it("asks a model that can constrain its own output for the type directly", async () => { + const { run, requests } = scriptedModel( + [answer(JSON.stringify({ order: "A-3", status: "packed" }))], + nativeModelSchema, + ); + + const response = await create.run(context(), "support", "", run, "where is A-3?", undefined, orderType); + + // No tool to call and nothing to force: the type travels as the format the + // answer has to be written in, and is read back off the message. + expect(requests[0].tools).toEqual([]); + expect(requests[0].tool_choice).toBeUndefined(); + expect(requests[0].response_format?.schema).toMatchObject({ + properties: { order: { type: "string" }, status: { type: "string" } }, + }); + expect(response.structured_response).toEqual({ order: "A-3", status: "packed" }); + }); + + it("asks for the type in a turn of its own when the agent has tools, because a provider may refuse both at once", async () => { + const { run, requests } = scriptedModel( + [answer("I made you a user object."), answer(JSON.stringify({ order: "A-4", status: "open" }))], + nativeModelSchema, + ); + const flowTool = subFlow(() => "ok"); + + const response = await create.run(context(), "support", "", run, "make one", [flowTool], orderType); + + // First the agent works, with its tools and no type in the request. + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["tool_1"]); + expect(requests[0].response_format).toBeUndefined(); + expect(requests[0].tool_choice).toBeUndefined(); + + // Then the type is asked for alone, with nothing bound beside it. + expect(requests[1].tools).toEqual([]); + expect(requests[1].response_format?.schema).toMatchObject({ properties: { order: { type: "string" } } }); + expect(response.structured_response).toEqual({ order: "A-4", status: "open" }); + }); + + it("asks for the type as a tool call on its own when the model cannot constrain its output", async () => { + const { run, requests } = scriptedModel([ + answer("I made you a user object."), + answer("", [{ id: "call-1", name: "Order", args: { order: "A-6", status: "open" } }]), + ]); + + const response = await create.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); + + // The flow tool is bound for the work, and the extract tool alone for the + // type - never the two together, which is what a provider refuses. + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["tool_1"]); + expect(requests[1].tools.map((tool) => tool.name)).toEqual(["Order"]); + expect(response.structured_response).toEqual({ order: "A-6", status: "open" }); + }); + + it("keeps the agent's own answer as the reply, not the extraction turn's", async () => { + const { run } = scriptedModel( + [answer("I made you a user object."), answer(JSON.stringify({ order: "A-5", status: "open" }))], + nativeModelSchema, + ); + + const response = await create.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); - expect(typeof agent).toEqual("function"); + expect(replyOf(response)).toEqual("I made you a user object."); }); - it("needs a name", () => { + it("asks for no format when a model that could constrain its output was given no type", async () => { + const { run, requests } = scriptedModel([answer("hello")], nativeModelSchema); + await create.run(context(), "greeter", "", run, "hi"); + + expect(requests[0].response_format).toBeUndefined(); + }); + + it("takes the type as the struct aquila wraps it in", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Order", args: { order: "A-2", status: "delivered" } }]), + ]); + + const response = await create.run( + context(), + "support", + "", + run, + "where is A-2?", + undefined, + asStruct(orderType), + ); + + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Order"]); + expect(response.structured_response).toEqual({ order: "A-2", status: "delivered" }); + }); + + it("leaves the structured answer out when no type was asked for", async () => { const { run } = scriptedModel([answer("hello")]); - expect(() => create.run(context(), "", "", run)).toThrow(RuntimeError); + const response = await create.run(context(), "greeter", "", run, "hi"); + + expect(response.structured_response).toBeUndefined(); }); - it("rejects a model that is not a sub flow", () => { - expect(() => - create.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never), - ).toThrow(RuntimeError); + it("rejects a type the agent cannot answer in", async () => { + const { run } = scriptedModel([answer("hello")]); + await expect( + create.run(context(), "support", "", run, "hi", undefined, { type: "string" }), + ).rejects.toThrow(/no properties/); }); - it("rejects an MCP server missing what its transport needs, while the flow is built", () => { + it("fails when the agent ignores the type it was asked to answer in", async () => { + const { run } = scriptedModel([answer("just text")]); + await expect(create.run(context(), "support", "", run, "hi", undefined, orderType)).rejects.toThrow( + /did not answer in the type/, + ); + }); + + it("needs a name", async () => { + const { run } = scriptedModel([answer("hello")]); + await expect(create.run(context(), "", "", run, "hi")).rejects.toThrow(RuntimeError); + }); + + it("needs something to ask", async () => { + const { run } = scriptedModel([answer("hello")]); + await expect(create.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + }); + + it("rejects a model that is not a sub flow", async () => { + await expect( + create.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never, "hi"), + ).rejects.toThrow(RuntimeError); + }); + + it("rejects an MCP server missing what its transport needs, before the agent runs", async () => { const { run } = scriptedModel([answer("hello")]); - expect(() => - create.run(context(), "greeter", "", run, [{ name: "docs", transport: "stdio" }] as never), - ).toThrow(RuntimeError); + await expect( + create.run(context(), "greeter", "", run, "hi", [{ name: "docs", transport: "stdio" }] as never), + ).rejects.toThrow(RuntimeError); }); - it("rejects two MCP servers with the same name", () => { + it("rejects two MCP servers with the same name", async () => { const { run } = scriptedModel([answer("hello")]); - expect(() => - create.run(context(), "greeter", "", run, [ + await expect( + create.run(context(), "greeter", "", run, "hi", [ { name: "docs", url: "https://a/mcp" }, { name: "docs", url: "https://b/mcp" }, ] as never), - ).toThrow(RuntimeError); + ).rejects.toThrow(RuntimeError); }); }); describe("the agent loop", () => { it("runs the model sub flow and returns its answer", async () => { const { run, requests } = scriptedModel([answer("Hi there.")]); - const agent = create.run(context(), "greeter", "You greet people.", run); - - const result = await agent({ messages: [user("hello")] }); + const response = await create.run(context(), "greeter", "You greet people.", run, "hello"); expect(requests).toHaveLength(1); expect(requests[0].messages.map((m) => m.role)).toEqual(["system", "human"]); expect(requests[0].messages[0].content).toEqual([{ type: "text", text: "You greet people." }]); - expect(textOf(result.messages.at(-1))).toEqual("Hi there."); + expect(replyOf(response)).toEqual("Hi there."); }); it("advertises every tool sub flow to the model and calls the one it picks", async () => { @@ -129,8 +326,7 @@ describe("the agent loop", () => { { type: "object", description: "Looks an order up.", properties: { order: { type: "string" } } }, ); - const agent = create.run(context(), "support", "", run, [lookup]); - const result = await agent({ messages: [user("where is A-1?")] }); + const response = await create.run(context(), "support", "", run, "where is A-1?", [lookup]); expect(requests[0].tools).toEqual([ { @@ -142,7 +338,7 @@ describe("the agent loop", () => { expect(calls).toEqual([{ order: "A-1" }]); expect(requests[1].messages.map((m) => m.role)).toEqual(["human", "ai", "tool"]); expect(requests[1].messages.at(-1)?.content).toEqual([{ type: "text", text: '{"status":"shipped"}' }]); - expect(textOf(result.messages.at(-1))).toEqual("Order A-1 has shipped."); + expect(replyOf(response)).toEqual("Order A-1 has shipped."); }); it("reports a failing tool to the model instead of aborting the run", async () => { @@ -154,11 +350,10 @@ describe("the agent loop", () => { throw new Error("the warehouse is offline"); }); - const agent = create.run(context(), "support", "", run, [broken]); - const result = await agent({ messages: [user("status?")] }); + const response = await create.run(context(), "support", "", run, "status?", [broken]); expect(JSON.stringify(requests[1].messages.at(-1)?.content)).toContain("the warehouse is offline"); - expect(textOf(result.messages.at(-1))).toEqual("That did not work."); + expect(replyOf(response)).toEqual("That did not work."); }); it("lets a middleware sub flow rewrite the conversation before the model call", async () => { @@ -179,8 +374,17 @@ describe("the agent loop", () => { }; }); - const agent = create.run(context(), "support", "", run, [], [redact]); - await agent({ messages: [user("my card is 4111111111111111")] }); + await create.run( + context(), + "support", + "", + run, + "my card is 4111111111111111", + [], + undefined, + undefined, + [redact], + ); expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "my card is ****" }]); }); @@ -189,10 +393,21 @@ describe("the agent loop", () => { const { run, requests } = scriptedModel([answer("should not be reached")]); const block = subFlow(() => ({ jump_to: "end" })); - const agent = create.run(context(), "support", "", run, [], [block]); - await agent({ messages: [user("hello")] }); + const response = await create.run( + context(), + "support", + "", + run, + "hello", + [], + undefined, + undefined, + [block], + ); expect(requests).toHaveLength(0); + // Nothing was generated, so the last message of the run is still the prompt. + expect(response.choices[0].message).toEqual({ role: "user", content: "hello" }); }); it("calls one middleware sub flow for both the before and the after phase", async () => { @@ -203,43 +418,102 @@ describe("the agent loop", () => { return null; }); - const agent = create.run(context(), "support", "", run, [], [observe]); - const result = await agent({ messages: [user("hello")] }); + const response = await create.run( + context(), + "support", + "", + run, + "hello", + [], + undefined, + undefined, + [observe], + ); expect(hooks).toEqual(["before_model", "after_model"]); - expect(textOf(result.messages.at(-1))).toEqual("ok"); + expect(replyOf(response)).toEqual("ok"); }); it("takes sub flow tools and MCP servers in the same list", async () => { const { run, requests } = scriptedModel([answer("ok")]); const lookup = subFlow(() => ({ status: "shipped" }), { type: "object", description: "Looks an order up." }); - expect(() => - create.run(context(), "support", "", run, [lookup, { name: "docs", transport: "stdio" }] as never), - ).toThrow(/needs a command/); + await expect( + create.run(context(), "support", "", run, "hello", [ + lookup, + { name: "docs", transport: "stdio" }, + ] as never), + ).rejects.toThrow(/needs a command/); - const agent = create.run(context(), "support", "", run, [lookup]); - await agent({ messages: [user("hello")] }); + await create.run(context(), "support", "", run, "hello", [lookup]); expect(requests[0].tools.map((t) => t.name)).toEqual(["tool_1"]); }); + it("names a tool after the sub flow and passes its schema on", async () => { + const { run, requests } = scriptedModel([answer("ok")]); + const now = subFlow(() => 1793919755965663, { + $schema: "https://json-schema.org/draft/2020-12/schema", + title: "Current time", + description: "Answers with the current time in microseconds.", + type: "object", + properties: { timezone: { type: "string" } }, + }); + const nameless = subFlow(() => "nothing"); + + await create.run(context(), "support", "", run, "hello", [now as never, nameless as never]); + + expect(requests[0].tools).toEqual([ + { + name: "Current_time", + description: "Answers with the current time in microseconds.", + input_schema: { + $schema: "https://json-schema.org/draft/2020-12/schema", + title: "Current time", + description: "Answers with the current time in microseconds.", + type: "object", + properties: { timezone: { type: "string" } }, + }, + }, + { name: "tool_2", description: "", input_schema: { type: "object", properties: {} } }, + ]); + }); + + it("reads a name and description out of the raw struct aquila sends", async () => { + const { run, requests } = scriptedModel([answer("ok")]); + const lookup = subFlow( + () => ({ status: "shipped" }), + asStruct({ title: "Look up order", description: "Looks an order up.", type: "object" }) as never, + ); + const sameName = subFlow(() => null, asStruct({ title: "Look up order" }) as never); + + await create.run(context(), "support", "", run, "hello", [lookup as never, sameName as never]); + + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Look_up_order", "Look_up_order_2"]); + expect(requests[0].tools[0].description).toEqual("Looks an order up."); + expect(requests[0].tools[0].input_schema).toEqual({ + title: "Look up order", + description: "Looks an order up.", + type: "object", + }); + }); + it("rejects a tool entry that is neither a sub flow nor an MCP server", async () => { const { run } = scriptedModel([answer("ok")]); - expect(() => create.run(context(), "support", "", run, [{ nonsense: true }] as never)).toThrow( - /Entry 1 of "tools"/, - ); + await expect( + create.run(context(), "support", "", run, "hello", [{ nonsense: true }] as never), + ).rejects.toThrow(/Entry 1 of "tools"/); }); it("fails with a clear error when the model sub flow answers with the wrong shape", async () => { const run = subFlow(() => ({ message: { role: "ai", content: "not a list" } })); - const agent = create.run(context(), "greeter", "", run); - - await expect(agent({ messages: [user("hello")] })).rejects.toThrow(/did not return a valid model response/); + await expect(create.run(context(), "greeter", "", run, "hello")).rejects.toThrow( + /did not return a valid model response/, + ); }); }); describe("what a middleware flow is handed", () => { - it("forwards the run's thread, not just the messages", async () => { + it("is handed the conversation, the agent's name and the phase, and nothing more", async () => { const seen: AiAgentState[] = []; const { run } = scriptedModel([answer("ok")]); const observe = subFlow((input: never) => { @@ -247,12 +521,10 @@ describe("what a middleware flow is handed", () => { return {}; }); - const agent = create.run(context(), "support", "You are helpful.", run, [], [observe]); - await agent({ messages: [user("hello")], thread_id: "thread-1" }); + await create.run(context(), "support", "You are helpful.", run, "hello", [], undefined, undefined, [observe]); - expect(seen[0].thread_id).toEqual("thread-1"); expect(seen[0].context).toBeUndefined(); - expect(Object.keys(seen[0])).toEqual(["messages", "agent_name", "hook", "thread_id"]); + expect(Object.keys(seen[0])).toEqual(["messages", "agent_name", "hook"]); }); }); @@ -264,16 +536,25 @@ describe("composing the shipped functions into an agent", () => { const { run, requests } = scriptedModel([answer("ok")]); const long = Array.from({ length: 12 }, (_, turn) => turn % 2 === 0 - ? user(`question ${turn} ${"padding ".repeat(40)}`) - : assistant(`answer ${turn} ${"padding ".repeat(40)}`), + ? { role: "user" as const, content: `question ${turn} ${"padding ".repeat(40)}` } + : { role: "assistant" as const, content: `answer ${turn} ${"padding ".repeat(40)}` }, ); - const agent = create.run(context(), "support", "You are helpful.", run, [], [middlewareFlow]); - const result = await agent({ messages: long }); + const response = await create.run( + context(), + "support", + "You are helpful.", + run, + "", + [], + undefined, + { messages: long }, + [asFlowValue(middlewareFlow)], + ); expect(requests).toHaveLength(1); expect(requests[0].messages.length).toBeLessThan(long.length + 1); expect(requests[0].messages[0].role).toEqual("system"); - expect(textOf(result.messages.at(-1))).toEqual("ok"); + expect(replyOf(response)).toEqual("ok"); }); }); diff --git a/actions/ai-action/test/approval.test.ts b/actions/ai-action/test/approval.test.ts new file mode 100644 index 0000000..160580a --- /dev/null +++ b/actions/ai-action/test/approval.test.ts @@ -0,0 +1,305 @@ +import "reflect-metadata"; +import type { FunctionContext, SubFlow } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; +import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { HumanInTheLoopMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; +import { askFor } from "../src/utils/middleware/Approval.askFor.util.js"; +import { describeCall } from "../src/utils/middleware/Approval.describeCall.util.js"; +import { newCode } from "../src/utils/middleware/Approval.newCode.util.js"; + +const create = new CreateAgentFunction(); +const humanInTheLoop = new HumanInTheLoopMiddlewareFunction(); + +/** + * The middleware as a flow receives it: the function returns a sub flow function, and + * hercules hands the consuming node a callable. + */ +function asMiddleware(tools: string[]): SubFlow { + const definition = humanInTheLoop.run(context(), tools); + return ((state: unknown) => Promise.resolve(definition.run(state as never))) as unknown as SubFlow; +} + +/** The question for one call, as the middleware wrote it, with a known code. */ +const question = (call: { name: string; args?: Record }, code: string): string => + askFor([call], code); + +function context(): FunctionContext { + return { + projectId: 1, + executionId: "approval-execution", + matchedConfig: { projectId: 1, configValues: [], findConfig: () => undefined }, + executeFlow: async () => null, + }; +} + +function answer(text: string, toolCalls: { id: string; name: string; args: object }[] = []): AiModelResponse { + return { + message: { + role: "ai", + content: [ + ...(text.length > 0 ? [{ type: "text", text }] : []), + ...toolCalls.map((call) => ({ type: "tool_call", ...call })), + ], + }, + }; +} + +function scriptedModel(responses: AiModelResponse[]) { + let call = 0; + const requests: unknown[] = []; + const run = (async (input: unknown) => { + requests.push(input); + return responses[Math.min(call++, responses.length - 1)]; + }) as unknown as SubFlow; + return { run, requests }; +} + +function tool(name: string, calls: unknown[], answers: unknown = { ok: true }): SubFlow { + const run = (async (args: unknown) => { + calls.push({ [name]: args }); + return answers; + }) as unknown as { inputSchema?: unknown }; + run.inputSchema = { type: "object", title: name, description: `Runs ${name}.`, properties: {} }; + return run as unknown as SubFlow; +} + +type Turn = { role: "user" | "assistant"; content: string }; + +/** One request on /chat/completions: the whole conversation, as a client resends it. */ +function chat( + model: SubFlow, + tools: SubFlow[], + conversation: Turn[], + askBefore: string[] = ["refund"], +): Promise { + return create.run( + context(), + "support", + "You help.", + model, + "", + tools, + undefined, + { messages: conversation } as never, + [asMiddleware(askBefore)], + ); +} + +describe("what the answer carries about the agent's work", () => { + it("lists every tool the agent used, with arguments and result", async () => { + const calls: unknown[] = []; + const { run } = scriptedModel([ + answer("", [{ id: "c1", name: "lookup", args: { order: "A-1" } }]), + answer("Order A-1 has shipped."), + ]); + + const response = await chat(run, [tool("lookup", calls, { status: "shipped" })], [ + { role: "user", content: "where is A-1?" }, + ]); + + expect(response.steps).toEqual([ + { name: "lookup", args: { order: "A-1" }, result: '{"status":"shipped"}' }, + ]); + expect(response.choices[0].message.content).toEqual("Order A-1 has shipped."); + }); + + it("reports what a failed tool answered as that step's result", async () => { + const broken = (async () => { + throw new Error("the warehouse is offline"); + }) as unknown as { inputSchema?: unknown }; + broken.inputSchema = { type: "object", title: "lookup", description: "Looks an order up.", properties: {} }; + const { run } = scriptedModel([ + answer("", [{ id: "c1", name: "lookup", args: {} }]), + answer("That did not work."), + ]); + + const response = await chat(run, [broken as unknown as SubFlow], [{ role: "user", content: "status?" }]); + + // The step is named after the call the model made, and the tool's failure is + // what came back from it. + expect(response.steps?.[0].name).toEqual("lookup"); + expect(response.steps?.[0].result).toContain("the warehouse is offline"); + }); + + it("carries no steps when the agent answered on its own", async () => { + const { run } = scriptedModel([answer("Hello.")]); + + const response = await chat(run, [], [{ role: "user", content: "hi" }]); + + expect(response.steps).toBeUndefined(); + }); + + it("needs a tool to guard", () => { + expect(() => humanInTheLoop.run(context(), [])).toThrow(/at least one tool/); + expect(() => humanInTheLoop.run(context(), [7] as never)).toThrow(/Entry 1 of "tools"/); + }); + + it("is a middleware like any other, which is how an agent gets it", () => { + const definition = humanInTheLoop.run(context(), ["refund"]); + + expect(definition.name).toEqual("human_in_the_loop:refund"); + expect(definition.inputSchema).toBeDefined(); + expect(definition.outputSchema).toBeDefined(); + }); +}); + +describe("a tool the agent has to ask about", () => { + it("is held back, and the turn ends with the question", async () => { + const calls: unknown[] = []; + const { run } = scriptedModel([answer("", [{ id: "c1", name: "refund", args: { order: "A-1" } }])]); + + const response = await chat(run, [tool("refund", calls)], [{ role: "user", content: "refund A-1" }]); + + expect(calls).toEqual([]); + // The question carries the calls and the two answers, and no sentence: it has + // to work in any language the flow is used in. + const asked = String(response.choices[0].message.content); + expect(asked).toMatch(/^refund\(\{"order":"A-1"\}\)\n\nAPPROVE [0-9a-f]{6}\nDECLINE [0-9a-f]{6}$/); + expect(asked).not.toMatch(/[a-z]{4,} [a-z]{3,}/); + expect(response.awaiting_approval?.[0]).toMatchObject({ name: "refund", args: { order: "A-1" } }); + expect(response.awaiting_approval?.[0].code).toMatch(/^[0-9a-f]{6}$/); + // The answer is a finished turn, not a half-open one. + expect(response.choices[0].finish_reason).toEqual("stop"); + }); + + it("runs the call when the reply carries the question's approval code", async () => { + const calls: unknown[] = []; + const refund = tool("refund", calls, { refunded: true }); + // A model that wants the same call both times, as one would after an approval. + const wants = () => + scriptedModel([ + answer("", [{ id: "c1", name: "refund", args: { order: "A-1" } }]), + answer("Refunded A-1."), + ]).run; + + // Turn one: the question, whose code the answer has to carry. + const asked = await chat(wants(), [refund], [{ role: "user", content: "refund A-1" }]); + const code: string = asked.awaiting_approval![0].code!; + + // Turn two: a request of its own, with the conversation the client resends. + const done = await chat(wants(), [refund], [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: String(asked.choices[0].message.content) }, + { role: "user", content: `APPROVE ${code}` }, + ]); + + expect(calls).toEqual([{ refund: { order: "A-1" } }]); + expect(done.awaiting_approval).toBeUndefined(); + expect(done.choices[0].message.content).toEqual("Refunded A-1."); + expect(done.steps).toEqual([{ name: "refund", args: { order: "A-1" }, result: '{"refunded":true}' }]); + }); + + it("does not run a call the reply refused, however the model insists", async () => { + const calls: unknown[] = []; + const refund = tool("refund", calls); + const { run } = scriptedModel([answer("", [{ id: "c1", name: "refund", args: { order: "A-1" } }])]); + + const response = await chat( + run, + [refund], + [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: question({ name: "refund", args: { order: "A-1" } }, "abc123") }, + { role: "user", content: "DECLINE abc123" }, + ], + ); + + expect(calls).toEqual([]); + // The refusal is reported the same way the question was asked: markers, no prose. + expect(response.choices[0].message.content).toEqual('DECLINE abc123\nrefund({"order":"A-1"})'); + expect(response.awaiting_approval).toBeUndefined(); + }); + + it("runs nothing on a reply that does not carry the code, however it is worded", async () => { + const calls: unknown[] = []; + const refund = tool("refund", calls); + + for (const reply of ["yes", "ja, mach das", "approve", "APPROVE deadbeef", "sure, go ahead"]) { + const { run } = scriptedModel([answer("", [{ id: "c1", name: "refund", args: { order: "A-1" } }])]); + const response = await chat(run, [refund], [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: question({ name: "refund", args: { order: "A-1" } }, "abc123") }, + { role: "user", content: reply }, + ]); + + // The question stands, with its own code - nothing was released. + expect(calls).toEqual([]); + expect(response.awaiting_approval?.[0].code).toEqual("abc123"); + } + }); + + it("spends an approval on one call, so the next one is asked about again", async () => { + const calls: unknown[] = []; + const refund = tool("refund", calls); + const wants = () => + scriptedModel([ + answer("", [{ id: "c1", name: "refund", args: { order: "A-1" } }]), + answer("Refunded A-1."), + ]).run; + + const asked = question({ name: "refund", args: { order: "A-1" } }, "abc123"); + + // The approval of the first call, which the agent carries out. + const first = await chat(wants(), [refund], [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: asked }, + { role: "user", content: "APPROVE abc123" }, + ]); + expect(calls).toHaveLength(1); + + // The same call again, with the spent approval still in the conversation. + const again = await chat(wants(), [refund], [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: asked }, + { role: "user", content: "APPROVE abc123" }, + { role: "assistant", content: String(first.choices[0].message.content) }, + { role: "user", content: "do it again" }, + ]); + + expect(calls).toHaveLength(1); + expect(again.awaiting_approval?.[0]).toMatchObject({ name: "refund", args: { order: "A-1" } }); + // A new question, so the old approval cannot release it. + expect(again.awaiting_approval?.[0].code).not.toEqual("abc123"); + }); + + it("asks again for a different call", async () => { + const calls: unknown[] = []; + const { run } = scriptedModel([answer("", [{ id: "c2", name: "refund", args: { order: "B-2" } }])]); + + const response = await chat(run, [tool("refund", calls)], [ + { role: "user", content: "refund A-1" }, + { role: "assistant", content: question({ name: "refund", args: { order: "A-1" } }, "abc123") }, + { role: "user", content: "APPROVE abc123" }, + { role: "user", content: "and refund B-2" }, + ]); + + expect(calls).toEqual([]); + expect(response.awaiting_approval?.[0]).toMatchObject({ name: "refund", args: { order: "B-2" } }); + expect(response.awaiting_approval?.[0].code).not.toEqual("abc123"); + }); + + it("leaves tools nobody asked about alone", async () => { + const calls: unknown[] = []; + const { run } = scriptedModel([ + answer("", [{ id: "c1", name: "lookup", args: { order: "A-1" } }]), + answer("It shipped."), + ]); + + const response = await chat(run, [tool("lookup", calls)], [{ role: "user", content: "where is A-1?" }]); + + expect(calls).toEqual([{ lookup: { order: "A-1" } }]); + expect(response.awaiting_approval).toBeUndefined(); + }); + + it("writes a call the same way in the question and when matching it back", () => { + expect(describeCall({ name: "refund", args: { order: "A-1" } })).toEqual('refund({"order":"A-1"})'); + expect(askFor([{ name: "refund", args: { order: "A-1" } }], "abc123")).toContain('refund({"order":"A-1"})'); + }); + + it("gives every question a code of its own", () => { + expect(newCode()).not.toEqual(newCode()); + expect(newCode()).toMatch(/^[0-9a-f]{6}$/); + }); +}); diff --git a/actions/ai-action/test/dataTypes.test.ts b/actions/ai-action/test/dataTypes.test.ts index 4b064d7..245b051 100644 --- a/actions/ai-action/test/dataTypes.test.ts +++ b/actions/ai-action/test/dataTypes.test.ts @@ -1,17 +1,17 @@ import "reflect-metadata"; import { AIMessage, HumanMessage, SystemMessage, ToolMessage } from "@langchain/core/messages"; import { describe, expect, it } from "vitest"; -import { fromChatMessage } from "../src/chat/utils/Chat.fromChatMessage.util.js"; -import { toChatMessage } from "../src/chat/utils/Chat.toChatMessage.util.js"; -import { toChatResponse } from "../src/chat/utils/Chat.toChatResponse.util.js"; -import { toFlowMessage } from "../src/message/utils/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../src/message/utils/Message.toLangChainMessage.util.js"; -import type { AiChatMessage } from "../src/chat/datatypes/Chat.message.datatype.js"; -import { AiMcpServerSchema } from "../src/mcp/datatypes/Mcp.server.datatype.js"; -import { AiMessageSchema } from "../src/message/datatypes/Message.datatype.js"; -import { AiStateUpdateSchema } from "../src/middleware/datatypes/Middleware.stateUpdate.datatype.js"; -import { AiModelRequestSchema } from "../src/model/datatypes/Model.request.datatype.js"; -import { AiModelResponseSchema } from "../src/model/datatypes/Model.response.datatype.js"; +import { fromChatMessage } from "../src/utils/chat/Chat.fromChatMessage.util.js"; +import { toChatMessage } from "../src/utils/chat/Chat.toChatMessage.util.js"; +import { toChatResponse } from "../src/utils/chat/Chat.toChatResponse.util.js"; +import { toFlowMessage } from "../src/utils/message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../src/utils/message/Message.toLangChainMessage.util.js"; +import type { AiChatMessage } from "../src/datatypes/chat/Chat.message.datatype.js"; +import { AiMcpServerSchema } from "../src/datatypes/mcp/Mcp.server.datatype.js"; +import { AiMessageSchema } from "../src/datatypes/message/Message.datatype.js"; +import { AiStateUpdateSchema } from "../src/datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import { AiModelRequestSchema } from "../src/datatypes/model/Model.request.datatype.js"; +import { AiModelResponseSchema } from "../src/datatypes/model/Model.response.datatype.js"; describe("AiModelResponseSchema", () => { it("accepts a tool-only turn, which carries no text block at all", () => { diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts index 831c81d..4ddcd80 100644 --- a/actions/ai-action/test/functions.test.ts +++ b/actions/ai-action/test/functions.test.ts @@ -1,24 +1,33 @@ import "reflect-metadata"; import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; -import { describe, expect, it } from "vitest"; -import type { AiContentBlock } from "../src/message/datatypes/Message.contentBlock.datatype.js"; -import type { AiMessage } from "../src/message/datatypes/Message.datatype.js"; -import { AiChatResponseSchema } from "../src/chat/datatypes/Chat.response.datatype.js"; -import type { AiModelRequest } from "../src/model/datatypes/Model.request.datatype.js"; -import { AiModelResponseSchema, type AiModelResponse } from "../src/model/datatypes/Model.response.datatype.js"; -import { AiStateUpdateSchema } from "../src/middleware/datatypes/Middleware.stateUpdate.datatype.js"; -import { AiWebSearchResultSchema } from "../src/websearch/datatypes/WebSearch.result.datatype.js"; -import { TrimMessagesMiddlewareFunction } from "../src/middleware/runtimefunctions/Middleware.trimMessages.runtimefunction.js"; -import { OpenRouterModelFunction } from "../src/model/runtimefunctions/Model.openRouter.runtimefunction.js"; -import { WebSearchToolFunction } from "../src/websearch/runtimefunctions/WebSearch.search.runtimefunction.js"; -import { CreateAgentFunction } from "../src/agent/runtimefunctions/Agent.create.runtimefunction.js"; -import { InvokeAgentFunction } from "../src/agent/runtimefunctions/Agent.invoke.runtimefunction.js"; +import { describe, expect, it, vi } from "vitest"; +import { AIMessage } from "@langchain/core/messages"; +import { ChatOpenAI } from "@langchain/openai"; +import { toJsonSchema } from "@langchain/core/utils/json_schema"; +import type { AiContentBlock } from "../src/datatypes/message/Message.contentBlock.datatype.js"; +import type { AiMessage } from "../src/datatypes/message/Message.datatype.js"; +import { AiChatResponseSchema } from "../src/datatypes/chat/Chat.response.datatype.js"; +import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; +import { AiModelResponseSchema, type AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; +import { AiStateUpdateSchema } from "../src/datatypes/middleware/Middleware.stateUpdate.datatype.js"; +import { TrimMessagesMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; +import { OpenRouterModelFunction } from "../src/runtimefunctions/model/Model.openRouter.runtimefunction.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; const model = new OpenRouterModelFunction(); const middleware = new TrimMessagesMiddlewareFunction(); -const search = new WebSearchToolFunction(); const create = new CreateAgentFunction(); +/** + * Mirrors how hercules hands a sub flow function from one node to the next: the + * producing node returns a sub flow function definition, the consuming node receives + * a callable sub flow. + */ +function asFlowValue(definition: { run: (...args: never[]) => R | Promise }): (...args: unknown[]) => Promise { + const call = definition.run.bind(definition) as unknown as (...args: unknown[]) => R | Promise; + return (...args: unknown[]) => Promise.resolve(call(...args)); +} + function context(): FunctionContext { return { projectId: 1, @@ -39,9 +48,13 @@ function state(count: number, hook: "before_model" | "after_model" = "before_mod } describe("ai::model::openrouter", () => { - it("returns a callable, which is what TRANSFORM<_, _> is", () => { + it("returns a sub flow function definition, which is what hercules can serialize", () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); - expect(typeof transform).toEqual("function"); + + expect(typeof transform.run).toEqual("function"); + expect(transform.name).toEqual("openrouter:anthropic/claude-opus-5"); + expect(transform.inputSchema).toBeDefined(); + expect(transform.outputSchema).toBeDefined(); }); it("needs a model identifier and an API key", () => { @@ -51,27 +64,121 @@ describe("ai::model::openrouter", () => { it("rejects a call whose argument is not a model request", async () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); - await expect(transform({ messages: [] } as never)).rejects.toThrow(/model request is not valid/); + await expect(transform.run({ messages: [] } as never)).rejects.toThrow(/model request is not valid/); }); it("reports a failed call as a runtime error rather than leaking the provider's", async () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-invalid-key-for-test"); await expect( - transform({ messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] } as never), + transform.run({ messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] } as never), ).rejects.toThrow(RuntimeError); }, 30_000); - it("is accepted by ai::agent::create as the agent's model", () => { - const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); - const agent = create.run(context(), "support", "You are helpful.", transform); - expect(typeof agent).toEqual("function"); + it("hands the provider's own web search to the model only when it is switched on", async () => { + const answer = new AIMessage("ok"); + const bindTools = vi + .spyOn(ChatOpenAI.prototype, "bindTools") + .mockReturnValue({ invoke: async () => answer } as never); + vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(answer as never); + const request = { messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] }; + + await model.run(context(), "anthropic/claude-opus-5", "sk-or-test").run(request as never); + expect(bindTools).not.toHaveBeenCalled(); + + await model + .run(context(), "anthropic/claude-opus-5", "sk-or-test", undefined, undefined, true) + .run(request as never); + expect(bindTools).toHaveBeenCalledWith([{ type: "openrouter:web_search" }]); + + vi.restoreAllMocks(); + }); + + it("stops declaring that it can constrain its own output once that is switched off", () => { + const off = model.run(context(), "openai/gpt-oss-120b", "sk-or-test", undefined, undefined, undefined, false); + const on = model.run(context(), "openai/gpt-oss-120b", "sk-or-test"); + + // The declared request schema is what the agent reads to choose between + // asking the provider for the type and binding it as a tool call. + const properties = (schema: unknown): string[] => + Object.keys((toJsonSchema(schema as never) as { properties?: object }).properties ?? {}); + + expect(properties(off.inputSchema)).not.toContain("response_format"); + expect(properties(on.inputSchema)).toContain("response_format"); + }); + + it("ignores an output type once switched off, so a model that cannot do it is not asked to", async () => { + const answer = new AIMessage("ok"); + const invoke = vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(answer as never); + const request = { + messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], + tools: [], + response_format: { name: "extract", schema: { type: "object", properties: {} } }, + }; + + await model + .run(context(), "openai/gpt-oss-120b", "sk-or-test", undefined, undefined, undefined, false) + .run(request as never); + expect(invoke.mock.calls[0]?.[1]).not.toHaveProperty("response_format"); + + await model.run(context(), "openai/gpt-oss-120b", "sk-or-test").run(request as never); + expect(invoke.mock.calls[1]?.[1]).toMatchObject({ response_format: { type: "json_schema" } }); + + vi.restoreAllMocks(); + }); + + it("fails a call the provider gave up on, rather than passing its half answer off as an answer", async () => { + const cutShort = new AIMessage({ + content: "Here's a user object: { }", + response_metadata: { finish_reason: "error" }, + }); + vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(cutShort as never); + + const transform = model.run(context(), "openai/gpt-oss-120b", "sk-or-test"); + await expect( + transform.run({ + messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], + tools: [], + } as never), + ).rejects.toThrow(/gave up mid-generation/); + + vi.restoreAllMocks(); + }); + + it("routes only to a provider that supports what the request carries", async () => { + const answer = new AIMessage("ok"); + const invoke = vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(answer as never); + + await model + .run(context(), "openai/gpt-oss-120b", "sk-or-test") + .run({ messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] } as never); + + // OpenRouter serves one model from many endpoints with different parameter + // support, so without this a tool call or an output type reaches one that + // cannot serve it. + const model_ = invoke.mock.instances[0] as ChatOpenAI; + expect(model_.modelKwargs).toMatchObject({ provider: { require_parameters: true } }); + + vi.restoreAllMocks(); }); + + it("is accepted by ai::agent::create as the agent's model", async () => { + const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); + + // Reaches the model, which rejects the test key - proof the agent accepted it. + await expect( + create.run(context(), "support", "You are helpful.", asFlowValue(transform), "hi"), + ).rejects.toThrow(RuntimeError); + }, 30_000); }); describe("ai::middleware::trim_messages", () => { - it("returns a callable, which is what TRANSFORM<_, _> is", () => { + it("returns a sub flow function definition, which is what hercules can serialize", () => { const transform = middleware.run(context(), 200); - expect(typeof transform).toEqual("function"); + + expect(typeof transform.run).toEqual("function"); + expect(transform.name).toEqual("trim_messages:last:200"); + expect(transform.inputSchema).toBeDefined(); + expect(transform.outputSchema).toBeDefined(); }); it("rejects a budget that is not a positive number", () => { @@ -84,13 +191,13 @@ describe("ai::middleware::trim_messages", () => { }); it("returns no change when the conversation already fits", async () => { - const update = await middleware.run(context(), 100_000)(state(1)); + const update = await middleware.run(context(), 100_000).run(state(1)); expect(update).toEqual({}); }); it("drops whole messages until the conversation fits the budget", async () => { const before = state(12); - const update = await middleware.run(context(), 200)(before); + const update = await middleware.run(context(), 200).run(before); const parsed = AiStateUpdateSchema.parse(update); expect(parsed.messages).toBeDefined(); @@ -99,36 +206,22 @@ describe("ai::middleware::trim_messages", () => { }); it("keeps the system prompt when it trims", async () => { - const update = await middleware.run(context(), 200, "last", true)(state(12)); + const update = await middleware.run(context(), 200, "last", true).run(state(12)); const parsed = AiStateUpdateSchema.parse(update); expect(parsed.messages![0].role).toEqual("system"); }); it("rejects a state that is not an agent state", async () => { const transform = middleware.run(context(), 500); - await expect(transform({ messages: [] } as never)).rejects.toThrow(/agent state is not valid/); + await expect(transform.run({ messages: [] } as never)).rejects.toThrow(/agent state is not valid/); }); it("produces an update the agent will accept", async () => { - const update = await middleware.run(context(), 200)(state(12)); + const update = await middleware.run(context(), 200).run(state(12)); expect(() => AiStateUpdateSchema.parse(update)).not.toThrow(); }); }); -describe("ai::tool::web_search", () => { - it("needs a query and an API key", async () => { - await expect(search.run(context(), "", "key")).rejects.toThrow(RuntimeError); - await expect(search.run(context(), " ", "key")).rejects.toThrow(RuntimeError); - await expect(search.run(context(), "what is langchain", "")).rejects.toThrow(RuntimeError); - }); - - it("reports a failed search as a runtime error", async () => { - await expect(search.run(context(), "what is langchain", "tvly-invalid-key-for-test")).rejects.toThrow( - RuntimeError, - ); - }, 30_000); -}); - describe("the contracts the functions implement", () => { it("the model function's output is a valid AI_MODEL_RESPONSE", () => { expect(() => @@ -145,21 +238,9 @@ describe("the contracts the functions implement", () => { }), ).not.toThrow(); }); - - it("the search function's output is a valid AI_WEB_SEARCH_RESULT", () => { - expect(() => - AiWebSearchResultSchema.parse({ - query: "what is langchain", - results: [{ title: "LangChain", url: "https://x", content: "a framework", score: 0.9 }], - answer: "A framework for LLM applications.", - }), - ).not.toThrow(); - }); }); -describe("ai::agent::invoke", () => { - const invoke = new InvokeAgentFunction(); - +describe("the chat format of ai::agent::create", () => { function scriptedModel(responses: AiModelResponse[]) { const requests: AiModelRequest[] = []; let call = 0; @@ -189,12 +270,16 @@ describe("ai::agent::invoke", () => { total_tokens: 14, }), ]); - const agent = create.run(context(), "greeter", "You greet people.", run); - - const response = await invoke.run(context(), agent, "hello", { - model: "my-agent", - messages: [{ role: "system", content: "Be brief." }], - }); + const response = await create.run( + context(), + "greeter", + "You greet people.", + run, + "hello", + undefined, + undefined, + { model: "my-agent", messages: [{ role: "system", content: "Be brief." }] }, + ); const parsed = AiChatResponseSchema.parse(response); expect(parsed.object).toEqual("chat.completion"); @@ -202,6 +287,7 @@ describe("ai::agent::invoke", () => { expect(parsed.choices).toHaveLength(1); expect(parsed.choices[0].finish_reason).toEqual("stop"); expect(parsed.choices[0].message).toEqual({ role: "assistant", content: "Hi there.", name: "greeter" }); + expect(parsed.response).toEqual("Hi there."); expect(parsed.usage).toEqual({ prompt_tokens: 11, completion_tokens: 3, total_tokens: 14 }); expect(requests[0].messages.map((message) => message.role)).toEqual(["system", "system", "human"]); @@ -209,9 +295,7 @@ describe("ai::agent::invoke", () => { it("translates a multimodal prompt into content blocks", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "A cat." }])]); - const agent = create.run(context(), "describer", "", run); - - await invoke.run(context(), agent, "", { + await create.run(context(), "describer", "", run, "", undefined, undefined, { messages: [ { role: "user", @@ -235,10 +319,16 @@ describe("ai::agent::invoke", () => { generation([{ type: "text", text: "Order A-1 has shipped." }]), ]); const lookup = (async () => ({ status: "shipped" })) as unknown as SubFlow; - const agent = create.run(context(), "support", "", run, [lookup]); - - const response = await invoke.run(context(), agent, "and A-1?", { - messages: [ + const response = await create.run( + context(), + "support", + "", + run, + "and A-1?", + [lookup], + undefined, + { + messages: [ { role: "user", content: "where is A-0?" }, { role: "assistant", @@ -247,9 +337,10 @@ describe("ai::agent::invoke", () => { { id: "call-0", type: "function", function: { name: "tool_1", arguments: '{"order":"A-0"}' } }, ], }, - { role: "tool", tool_call_id: "call-0", content: '{"status":"delivered"}' }, - ], - }); + { role: "tool", tool_call_id: "call-0", content: '{"status":"delivered"}' }, + ], + }, + ); const asked = requests[0].messages.find((message) => message.role === "ai"); expect(asked?.content).toEqual([{ type: "tool_call", id: "call-0", name: "tool_1", args: { order: "A-0" } }]); @@ -263,9 +354,7 @@ describe("ai::agent::invoke", () => { it("keeps a malformed tool call instead of failing the request", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - const agent = create.run(context(), "support", "", run); - - await invoke.run(context(), agent, "again?", { + await create.run(context(), "support", "", run, "again?", undefined, undefined, { messages: [ { role: "assistant", @@ -288,18 +377,14 @@ describe("ai::agent::invoke", () => { { type: "text", text: "Hi." }, ]), ]); - const agent = create.run(context(), "greeter", "", run); - - const response = await invoke.run(context(), agent, "hello"); + const response = await create.run(context(), "greeter", "", run, "hello"); expect(response.choices[0].message.content).toEqual("Hi."); }); it("takes just a prompt, with no request at all", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Hi." }])]); - const agent = create.run(context(), "greeter", "", run); - - const response = await invoke.run(context(), agent, "hello"); + const response = await create.run(context(), "greeter", "", run, "hello"); expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "hello" }]); expect(response.choices[0].message.content).toEqual("Hi."); @@ -307,9 +392,7 @@ describe("ai::agent::invoke", () => { it("appends the prompt to the conversation the request carries", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Still fine." }])]); - const agent = create.run(context(), "greeter", "", run); - - await invoke.run(context(), agent, "and now?", { + await create.run(context(), "greeter", "", run, "and now?", undefined, undefined, { messages: [ { role: "user", content: "how are you?" }, { role: "assistant", content: "fine" }, @@ -320,16 +403,40 @@ describe("ai::agent::invoke", () => { expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "and now?" }]); }); - it("rejects anything that is not an agent", async () => { - await expect(invoke.run(context(), { id: "agent-1" } as never, "hello")).rejects.toThrow(/has to be an agent/); + it("carries the answer as plain text next to the OpenAI shape", async () => { + const { run } = scriptedModel([generation([{ type: "text", text: "Two parts. " }, { type: "text", text: "One answer." }])]); + + const response = await create.run(context(), "greeter", "", run, "hello"); + + expect(response.response).toEqual("Two parts. One answer."); + expect(response.object).toEqual("chat.completion"); + }); + + it("leaves the plain text empty when the model only asked for a tool", async () => { + const { run } = scriptedModel([ + generation([{ type: "tool_call", id: "call-1", name: "tool_1", args: {} }]), + generation([{ type: "text", text: "done" }]), + ]); + const lookup = (async () => ({ ok: true })) as unknown as SubFlow; + + const response = await create.run(context(), "support", "", run, "hi", [lookup]); + + // The run ends on a text answer, so this one is filled; the tool-call-only + // turn in between is what an empty `response` would come from. + expect(response.response).toEqual("done"); }); it("rejects having nothing to ask", async () => { const { run } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - const agent = create.run(context(), "greeter", "", run); - await expect(invoke.run(context(), agent, "")).rejects.toThrow(/nothing to ask/); - await expect(invoke.run(context(), agent, "", { messages: [] })).rejects.toThrow(/nothing to ask/); - await expect(invoke.run(context(), agent, "hi", { messages: "nope" } as never)).rejects.toThrow(/not valid/); + await expect(create.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + await expect( + create.run(context(), "greeter", "", run, "", undefined, undefined, { messages: [] }), + ).rejects.toThrow(/nothing to ask/); + await expect( + create.run(context(), "greeter", "", run, "hi", undefined, undefined, { + messages: "nope", + } as never), + ).rejects.toThrow(/not valid/); }); }); diff --git a/actions/ai-action/test/log.test.ts b/actions/ai-action/test/log.test.ts new file mode 100644 index 0000000..237fefe --- /dev/null +++ b/actions/ai-action/test/log.test.ts @@ -0,0 +1,86 @@ +import "reflect-metadata"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { describeValue } from "../src/utils/shared/Log.describeValue.util.js"; +import { logger } from "../src/utils/shared/Log.logger.util.js"; + +const original: string | undefined = process.env.AI_LOG_LEVEL; + +afterEach(() => { + if (original === undefined) delete process.env.AI_LOG_LEVEL; + else process.env.AI_LOG_LEVEL = original; + vi.restoreAllMocks(); +}); + +/** The lines a block of code writes, with the level turned up for the test. */ +function captured(level: string | undefined, run: () => void): string[] { + if (level === undefined) delete process.env.AI_LOG_LEVEL; + else process.env.AI_LOG_LEVEL = level; + const lines: string[] = []; + for (const channel of ["log", "warn", "error"] as const) { + vi.spyOn(console, channel).mockImplementation((...args: unknown[]) => { + lines.push(args.map(String).join(" ")); + }); + } + run(); + return lines; +} + +describe("the action's logging", () => { + it("is off while the tests run, so a suite stays readable", () => { + const lines = captured(undefined, () => { + logger("openai").debug("a line nobody asked for"); + logger("openai").error("and one that would otherwise show"); + }); + + expect(lines).toEqual([]); + }); + + it("writes the scope, the level and the run it belongs to", () => { + const lines = captured("debug", () => logger("openai", "abc123").info("a request arrived", { status: 200 })); + + expect(lines).toHaveLength(1); + expect(lines[0]).toContain("INFO [ai:openai] (abc123) a request arrived"); + expect(lines[0]).toContain('{"status":200}'); + expect(lines[0]).toMatch(/^\d{4}-\d{2}-\d{2}T/); + }); + + it("writes only what the level asks for", () => { + expect(captured("warn", () => logger("x").debug("quiet"))).toEqual([]); + expect(captured("warn", () => logger("x").error("loud"))).toHaveLength(1); + expect(captured("off", () => logger("x").error("silenced"))).toEqual([]); + }); + + it("never writes a key, however deep it sits", () => { + const line = captured("debug", () => + logger("model").debug("the request", { + api_key: "sk-secret", + headers: { authorization: "Bearer sk-secret", "api-key": "sk-secret" }, + nested: [{ openRouterApiKey: "sk-secret", prompt: "keep me" }], + }), + )[0]; + + expect(line).not.toContain("sk-secret"); + expect(line).toContain("keep me"); + expect(line.match(/\[redacted\]/g)).toHaveLength(4); + }); + + it("cuts a value that would bury the line and survives a cycle", () => { + const long = describeValue({ text: "x".repeat(5000) }); + const cyclic: Record = { name: "a" }; + cyclic.self = cyclic; + + expect(long.length).toBeLessThan(2100); + expect(long).toContain("chars)"); + expect(describeValue(cyclic)).toEqual('{"name":"a","self":"[circular]"}'); + expect(describeValue({ id: 7n, run: () => undefined })).toEqual('{"id":"7","run":"[function]"}'); + }); + + it("keeps a child's scope and swaps what ties the lines together", () => { + const lines = captured("debug", () => { + const parent = logger("openai", "one"); + parent.child("two").warn("second"); + }); + + expect(lines[0]).toContain("[ai:openai] (two) second"); + }); +}); diff --git a/actions/ai-action/test/openai.test.ts b/actions/ai-action/test/openai.test.ts new file mode 100644 index 0000000..367f843 --- /dev/null +++ b/actions/ai-action/test/openai.test.ts @@ -0,0 +1,548 @@ +import "reflect-metadata"; +import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import type { FunctionContext, PlainValue } from "@code0-tech/hercules"; +import { afterEach, describe, expect, it } from "vitest"; +import type { AiChatRequest } from "../src/datatypes/chat/Chat.request.datatype.js"; +import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; +import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AiOpenAiServerRuntimeEvent } from "../src/runtimeevents/openai/OpenAi.server.runtimeevent.js"; +import { OpenAiOpenWebUiFormattingFunction } from "../src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.js"; +import { OpenAiRespondFunction } from "../src/runtimefunctions/openai/OpenAi.respond.runtimefunction.js"; +import { normalizeRoute } from "../src/utils/openai/OpenAi.normalizeRoute.util.js"; +import { toEndpoints } from "../src/utils/openai/OpenAi.toEndpoints.util.js"; +import { OpenAiServer } from "../src/server/openai/OpenAi.server.js"; +import { parseRequestPath } from "../src/utils/openai/OpenAi.parsePath.util.js"; +import { toChatResponse } from "../src/utils/chat/Chat.toChatResponse.util.js"; +import { toModelList } from "../src/utils/openai/OpenAi.toModelList.util.js"; +import { toStreamChunks } from "../src/utils/openai/OpenAi.toStream.util.js"; + +interface FlowSpec { + id: number; + slug: string; + route?: string; + model?: string; + apiKey?: string; + type?: string; +} + +/** A flow as aquila reports it: settings carry protobuf values, not plain text. */ +function flow({ + id, + slug, + route = "/v1", + model = "support", + apiKey, + type = "ai::openai::server", +}: FlowSpec): ActionFlow { + const setting = (identifier: string, value: string) => ({ + flowSettingId: identifier, + value: { kind: { oneofKind: "stringValue" as const, stringValue: value } }, + }); + + return { + flowId: BigInt(id), + projectId: 1n, + type, + projectSlug: slug, + name: `flow ${id}`, + settings: [ + ...(route ? [setting("route", route)] : []), + ...(model ? [setting("model", model)] : []), + ...(apiKey ? [setting("api_key", apiKey)] : []), + ], + } as unknown as ActionFlow; +} + +function answer(text: string): AiChatResponse { + return toChatResponse({ role: "ai", content: [{ type: "text", text }] }, ""); +} + +const servers: OpenAiServer[] = []; +const respond = new OpenAiRespondFunction(); +const formatting = new OpenAiOpenWebUiFormattingFunction(); + +/** + * The context a runtime function of a flow is handed. `executionId` is the flow's own + * execution, which is what ties a respond call to the waiting request - aquila hands + * a node the id the flow was started with. + */ +function context(executionId = "openai-execution"): FunctionContext { + return { + projectId: 1, + executionId, + matchedConfig: { projectId: 1, configValues: [], findConfig: () => undefined }, + executeFlow: async () => null, + }; +} + +/** A flow run, as the server starts it: the execution it got and what it was handed. */ +interface Run { + executionId: string; + flowId: bigint; + payload: PlainValue; +} + +/** A server on a free port, with the flows and the answers a test needs. */ +async function serve( + flows: ActionFlow[], + run: (flow: Run) => Promise = async () => answer("hello") as never, +): Promise<{ url: (path: string) => string; calls: Run[] }> { + const calls: Run[] = []; + let reserved = 0; + const server = new OpenAiServer( + { + flows: () => flows, + reserveExecutionId: () => `execution-${(reserved += 1)}`, + executeFlowWithId: (executionId, flowId, payload) => { + calls.push({ executionId, flowId, payload }); + return run({ executionId, flowId, payload }); + }, + }, + { port: 0, host: "127.0.0.1" }, + ); + await server.listen(); + servers.push(server); + + return { url: (path: string) => `http://127.0.0.1:${server.address}${path}`, calls }; +} + +afterEach(async () => { + await Promise.all(servers.splice(0).map((server) => server.close())); +}); + +describe("the route a flow is reached under", () => { + it("reads the project out of the path, because a route is only unique inside one", () => { + expect(parseRequestPath("/acme/v1/chat/completions")).toEqual({ + slug: "acme", + route: "/v1", + kind: "chat_completions", + }); + expect(parseRequestPath("/acme/v1/models?limit=5")).toEqual({ slug: "acme", route: "/v1", kind: "models" }); + expect(parseRequestPath("/acme/openai/v1/chat/completions")?.route).toEqual("/openai/v1"); + expect(parseRequestPath("/acme/models")?.route).toEqual(""); + }); + + it("is unknown without a project or a known endpoint", () => { + // The first segment is always the project, so this is the project "v1" + // serving its root - a request only reaches a flow that says so. + expect(parseRequestPath("/v1/chat/completions")).toEqual({ slug: "v1", route: "", kind: "chat_completions" }); + expect(parseRequestPath("/chat/completions")).toBeUndefined(); + expect(parseRequestPath("/acme/v1/embeddings")).toBeUndefined(); + expect(parseRequestPath("/")).toBeUndefined(); + }); + + it("compares a route the way a flow may have typed it", () => { + expect(["/v1", "v1", "/v1/", "v1/"].map(normalizeRoute)).toEqual(["/v1", "/v1", "/v1", "/v1"]); + }); + + it("leaves out a flow that has no route or no model to be asked for", () => { + const flows = [ + flow({ id: 1, slug: "acme" }), + flow({ id: 2, slug: "acme", model: "" }), + flow({ id: 3, slug: "acme", route: "" }), + flow({ id: 4, slug: "acme", type: "REST" }), + ]; + + expect(toEndpoints(flows).map((endpoint) => endpoint.flow.flowId)).toEqual([1n]); + }); +}); + +describe("the OpenAI endpoint", () => { + it("lists the flows of the route as models, which is what a client asks for first", async () => { + const { url } = await serve([ + flow({ id: 1, slug: "acme", model: "support" }), + flow({ id: 2, slug: "acme", model: "triage" }), + flow({ id: 3, slug: "other", model: "elsewhere" }), + flow({ id: 4, slug: "acme", route: "/v2", model: "other-route" }), + ]); + + const response = await fetch(url("/acme/v1/models")); + const body = (await response.json()) as { object: string; data: { id: string; owned_by: string }[] }; + + expect(response.status).toEqual(200); + expect(body.object).toEqual("list"); + expect(body.data.map((model) => model.id)).toEqual(["support", "triage"]); + expect(body.data[0].owned_by).toEqual("acme"); + }); + + it("runs the flow of the model a client picked and answers with what it returned", async () => { + const { url, calls } = await serve( + [flow({ id: 1, slug: "acme", model: "support" }), flow({ id: 2, slug: "acme", model: "triage" })], + async ({ flowId }) => answer(flowId === 2n ? "triage here" : "support here") as never, + ); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "triage", messages: [{ role: "user", content: "hi" }] }), + }); + const body = (await response.json()) as AiChatResponse; + + expect(response.status).toEqual(200); + expect(calls.map((call) => call.flowId)).toEqual([2n]); + // The flow is handed the request itself, which is what ai::agent::create takes. + expect(calls[0].payload).toMatchObject({ messages: [{ role: "user", content: "hi" }] }); + expect(body.response).toEqual("triage here"); + // A client matches the answer against the model it asked for. + expect(body.model).toEqual("triage"); + }); + + it("serves a route with a single flow without being told the model", async () => { + const { url, calls } = await serve([flow({ id: 7, slug: "acme", model: "support" })]); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }), + }); + + expect(response.status).toEqual(200); + expect(calls.map((call) => call.flowId)).toEqual([7n]); + }); + + it("answers a client that asked for a stream as a stream", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme" })]); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "support", stream: true, messages: [{ role: "user", content: "hi" }] }), + }); + const text = await response.text(); + + expect(response.headers.get("content-type")).toEqual("text/event-stream"); + expect(text).toContain('"object":"chat.completion.chunk"'); + expect(text).toContain('"content":"hello"'); + expect(text.trimEnd().endsWith("data: [DONE]")).toEqual(true); + }); + + it("tells a client which model does not exist rather than running the wrong flow", async () => { + const { url, calls } = await serve([ + flow({ id: 1, slug: "acme", model: "support" }), + flow({ id: 2, slug: "acme", model: "triage" }), + ]); + + const missing = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "nope", messages: [{ role: "user", content: "hi" }] }), + }); + // Two models on the route, so a request naming none is ambiguous. + const ambiguous = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ messages: [{ role: "user", content: "hi" }] }), + }); + + expect(missing.status).toEqual(404); + expect(((await missing.json()) as { error: { code: string } }).error.code).toEqual("model_not_found"); + expect(ambiguous.status).toEqual(404); + expect(calls).toEqual([]); + }); + + it("answers nothing on a route no flow serves", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme" })]); + + expect((await fetch(url("/other/v1/models"))).status).toEqual(404); + expect((await fetch(url("/acme/v2/models"))).status).toEqual(404); + expect((await fetch(url("/acme/v1/embeddings"))).status).toEqual(404); + }); + + it("runs the route's only flow even when a client asks for another name", async () => { + // A route holds one flow, so there is nothing else the request could mean - + // and a client that kept an old model name still gets an answer. + const { url, calls } = await serve([flow({ id: 1, slug: "acme", model: "support" })]); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "gpt-4o", messages: [{ role: "user", content: "hi" }] }), + }); + + expect(response.status).toEqual(200); + expect(calls.map((call) => call.flowId)).toEqual([1n]); + }); + + it("asks for the key the flow declared", async () => { + const { url, calls } = await serve([flow({ id: 1, slug: "acme", apiKey: "sk-secret" })]); + const body = JSON.stringify({ model: "support", messages: [{ role: "user", content: "hi" }] }); + + const without = await fetch(url("/acme/v1/chat/completions"), { method: "POST", body }); + const wrong = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + headers: { authorization: "Bearer nope" }, + body, + }); + const right = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + headers: { authorization: "Bearer sk-secret" }, + body, + }); + + expect([without.status, wrong.status, right.status]).toEqual([401, 401, 200]); + expect(calls.map((call) => call.flowId)).toEqual([1n]); + // A client listing models without the key is not shown the guarded one either. + expect((await fetch(url("/acme/v1/models"))).status).toEqual(401); + expect((await fetch(url("/acme/v1/models"), { headers: { authorization: "Bearer sk-secret" } })).status).toEqual( + 200, + ); + }); + + it("answers without a key when the flow set none", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme" })]); + + expect((await fetch(url("/acme/v1/models"))).status).toEqual(200); + }); + + it("answers a preflight before it asks for anything", async () => { + const { url, calls } = await serve([flow({ id: 1, slug: "acme", apiKey: "sk-secret" })]); + + const preflight = await fetch(url("/acme/v1/chat/completions"), { method: "OPTIONS" }); + + expect(preflight.status).toEqual(204); + expect(preflight.headers.get("access-control-allow-methods")).toContain("POST"); + expect(preflight.headers.get("access-control-allow-headers")).toContain("authorization"); + expect(calls).toEqual([]); + }); + + it("says which method completions take when another one is used", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme" })]); + + const response = await fetch(url("/acme/v1/chat/completions")); + + expect(response.status).toEqual(405); + expect(response.headers.get("allow")).toEqual("POST, OPTIONS"); + expect(((await response.json()) as { error: { message: string } }).error.message).toContain("not GET"); + }); + + it("rejects a body it cannot answer instead of running the flow", async () => { + const { url, calls } = await serve([flow({ id: 1, slug: "acme" })]); + + const broken = await fetch(url("/acme/v1/chat/completions"), { method: "POST", body: "{nope" }); + const empty = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "support", messages: [] }), + }); + const wrongMethod = await fetch(url("/acme/v1/chat/completions")); + + expect([broken.status, empty.status, wrongMethod.status]).toEqual([400, 400, 405]); + expect(calls).toEqual([]); + }); + + it("reports a flow that answered with something else as a failure of the endpoint", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme" })], async () => ({ nonsense: true }) as never); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "support", messages: [{ role: "user", content: "hi" }] }), + }); + + expect(response.status).toEqual(502); + expect(((await response.json()) as { error: { message: string } }).error.message).toMatch( + /did not answer with a chat response/, + ); + }); +}); + +describe("the flow a client ends up talking to", () => { + it("is the agent: the trigger's request goes in, its answer comes back", async () => { + const seen: AiModelRequest[] = []; + const model = (async (request: AiModelRequest) => { + seen.push(request); + return { message: { role: "ai", content: [{ type: "text", text: "Order A-1 has shipped." }] } }; + }) as never; + + // What a flow of the ideal shape does: take the request the trigger handed it, + // ask the agent, answer through the respond node - and carry on afterwards, + // which is exactly what the flow's return value could not express. + const after: string[] = []; + const { url } = await serve([flow({ id: 1, slug: "acme", model: "support" })], async ({ executionId, payload }) => { + const answer = await new CreateAgentFunction().run( + context(executionId) as never, + "support", + "You track orders.", + model, + "", + undefined, + undefined, + payload as unknown as AiChatRequest, + ); + + // The respond node of this flow, which knows the request only through the + // execution it runs as. + respond.run(context(executionId), answer as never); + + // A node after the answer, whose value is what the flow returns. + after.push("stored the conversation"); + return "nothing the client should see" as never; + }); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + model: "support", + messages: [ + { role: "user", content: "where is A-1?" }, + { role: "assistant", content: "Let me look." }, + { role: "user", content: "thanks" }, + ], + }), + }); + const body = (await response.json()) as AiChatResponse; + + // The client's whole conversation reached the model, after the system prompt. + expect(seen[0].messages.map((message) => message.role)).toEqual(["system", "human", "ai", "human"]); + expect(body.choices[0].message).toMatchObject({ role: "assistant", content: "Order A-1 has shipped." }); + expect(body.object).toEqual("chat.completion"); + expect(body.model).toEqual("support"); + // The node after the answer ran, and did not become the answer. + expect(after).toEqual(["stored the conversation"]); + }); + + it("answers through respond even while the flow is still running", async () => { + let release: () => void = () => undefined; + const blocked = new Promise((resolve) => { + release = resolve; + }); + + const { url } = await serve([flow({ id: 1, slug: "acme", model: "support" })], async ({ executionId }) => { + respond.run(context(executionId), answer("early") as never); + // The flow goes on - the client is not kept waiting for it. + await blocked; + return null; + }); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "support", messages: [{ role: "user", content: "hi" }] }), + }); + + expect(((await response.json()) as AiChatResponse).response).toEqual("early"); + release(); + }); + + it("does not fail a flow nobody is waiting on, e.g. a manual run", () => { + expect(() => respond.run(context("never-started-by-the-server"), answer("hi") as never)).not.toThrow(); + }); + + it("rejects an answer that is not a chat response", async () => { + const { url } = await serve([flow({ id: 1, slug: "acme", model: "support" })], async ({ executionId }) => { + expect(() => respond.run(context(executionId), { nonsense: true } as never)).toThrow( + /has to be a chat response/, + ); + return answer("fell back to the return value") as never; + }); + + const response = await fetch(url("/acme/v1/chat/completions"), { + method: "POST", + body: JSON.stringify({ model: "support", messages: [{ role: "user", content: "hi" }] }), + }); + + // The respond call failed, so the flow's return value answered instead. + expect(((await response.json()) as AiChatResponse).response).toEqual("fell back to the return value"); + }); +}); + +describe("what the event offers a flow", () => { + it("asks for a route and a model, and leaves the key to the flow", () => { + const settings: { identifier: string; unique?: string; optional?: boolean; defaultValue?: unknown }[] = + Reflect.getOwnMetadata("hercules:flow_settings", AiOpenAiServerRuntimeEvent) ?? []; + const byIdentifier = Object.fromEntries(settings.map((setting) => [setting.identifier, setting])); + + expect(settings.map((setting) => setting.identifier)).toEqual(["route", "model", "api_key"]); + expect(byIdentifier.route).toMatchObject({ unique: "PROJECT", defaultValue: "/v1" }); + expect(byIdentifier.model).toMatchObject({ unique: "PROJECT" }); + expect(byIdentifier.model.optional).toBeUndefined(); + expect(byIdentifier.api_key.optional).toEqual(true); + }); + + it("hands the flow the client's request as a chat request", () => { + expect(Reflect.getMetadata("hercules:signature", AiOpenAiServerRuntimeEvent)).toEqual( + "(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST", + ); + }); +}); + +describe("a finished answer as a stream", () => { + it("sends the content and then the end, because the flow answered in one piece", () => { + const chunks = toStreamChunks(answer("done")); + + expect(chunks).toHaveLength(3); + expect(JSON.parse(chunks[0]).choices[0].delta).toEqual({ role: "assistant", content: "done" }); + expect(JSON.parse(chunks[1]).choices[0]).toEqual({ index: 0, delta: {}, finish_reason: "stop" }); + expect(chunks[2]).toEqual("[DONE]"); + }); + + it("lists a model once, however many flows carry the name", () => { + const endpoints = toEndpoints([flow({ id: 1, slug: "acme" }), flow({ id: 2, slug: "acme" })]); + + expect(toModelList(endpoints).data.map((model) => model.id)).toEqual(["support"]); + }); +}); + +describe("an answer formatted for Open WebUI", () => { + it("leaves an answer with nothing to show as it is, because there is nothing to fold away", () => { + const plain = answer("hello"); + + expect(formatting.run(context(), plain)).toEqual(plain); + }); + + it("writes the reasoning into the text as a block the client folds, since it reads no field of ours", () => { + const thinking = toChatResponse( + { + role: "ai", + content: [ + { type: "reasoning", reasoning: "first\nsecond" }, + { type: "text", text: "the answer" }, + ], + }, + "", + ); + + const formatted = formatting.run(context(), thinking); + + expect(formatted.response).toEqual( + '
\nThought\n> first\n> second\n
\nthe answer', + ); + expect(formatted.choices[0].message.content).toEqual(formatted.response); + // The fields stay data, so a flow reading them after this node still gets the + // reasoning rather than the markup around it. + expect(formatted.reasoning).toEqual("first\nsecond"); + }); + + it("writes one block per tool the agent used, with its arguments and what came back", () => { + const used: AiChatResponse = { + ...answer("berlin is cold"), + steps: [ + { name: "weather", args: { city: "Berlin" }, result: "5°C" }, + { name: "broken", error: 'it said "no"' }, + ], + }; + + const formatted = formatting.run(context(), used); + + expect(formatted.response).toContain( + '
', + ); + expect(formatted.response).toContain("Tool Executed"); + // A failure is shown where the result would be, and the quotes in it cannot end + // the attribute early. + expect(formatted.response).toContain('result=""it said \\"no\\"""'); + expect(formatted.response).toContain("Tool Failed"); + expect(formatted.response.endsWith("berlin is cold")).toBe(true); + expect(formatted.steps).toEqual(used.steps); + }); + + it("formats an answer once, so a flow with the node twice does not stack the blocks", () => { + const used: AiChatResponse = { ...answer("hi"), steps: [{ name: "weather", result: "5°C" }] }; + + const once = formatting.run(context(), used); + + expect(formatting.run(context(), once)).toEqual(once); + }); + + it("sends the formatted text to a streaming client, which is the only text it reads", () => { + const used: AiChatResponse = { ...answer("hi"), steps: [{ name: "weather", result: "5°C" }] }; + + const chunks = toStreamChunks(formatting.run(context(), used)); + + expect(JSON.parse(chunks[0]).choices[0].delta.content).toContain('
+ fs.readFile(new URL("../src/index.ts", import.meta.url), "utf8"), +); + +/** The entries of one of index.ts's registration lists. */ +function listed(name: string): string[] { + const match = new RegExp(`const ${name}[^=]*=\\s*\\[([^\\]]*)\\]`, "s").exec(source); + if (!match) throw new Error(`index.ts has no ${name} list`); + return match[1] + .split(",") + .map((entry) => entry.trim()) + .filter((entry) => entry.length > 0 && !entry.startsWith("//")); +} + +/** Every class the action declares, by the file it lives in. */ +async function classesIn(folder: string, suffix: string): Promise { + const fs = await import("node:fs/promises"); + const root = new URL("../src/", import.meta.url); + const found: string[] = []; + + for (const entry of await fs.readdir(root, { recursive: true, withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith(suffix)) continue; + if (!entry.parentPath.includes(folder)) continue; + + const file: string = await fs.readFile(new URL(`${entry.parentPath}/${entry.name}`, "file://"), "utf8"); + for (const match of file.matchAll(/export class (\w+)/g)) found.push(match[1]); + } + + return found; +} + +describe("what the action registers", () => { + it("registers every runtime function it declares", async () => { + const declared: string[] = await classesIn("runtimefunctions", ".runtimefunction.ts"); + const registered: string[] = listed("RUNTIME_FUNCTIONS"); + + expect(declared.length).toBeGreaterThan(0); + expect([...registered].sort()).toEqual([...declared].sort()); + }); + + it("registers every runtime event it declares", async () => { + const declared: string[] = await classesIn("runtimeevents", ".runtimeevent.ts"); + const registered: string[] = listed("RUNTIME_EVENTS"); + + expect([...registered].sort()).toEqual([...declared].sort()); + }); + + it("registers every data type it declares", async () => { + const declared: string[] = await classesIn("datatypes", ".datatype.ts"); + const registered: string[] = listed("DATA_TYPES"); + + expect([...registered].sort()).toEqual([...declared].sort()); + }); + + it("hands each list to the right registration call", () => { + expect(source).toContain("DATA_TYPES.forEach((dataType) => action.registerDataTypeClass(dataType))"); + expect(source).toContain( + "RUNTIME_FUNCTIONS.forEach((runtimeFunction) => action.registerRuntimeFunction(runtimeFunction))", + ); + expect(source).toContain("RUNTIME_EVENTS.forEach((event) => action.registerRuntimeEventClass(event))"); + }); + + it("is read from the file that actually registers them", () => { + // A guard for this test itself: a renamed Action constructor call would mean + // the lists above are no longer what runs. + expect(source).toContain("new Action("); + expect(([] as (DataTypeClass | RuntimeFunctionClass)[]).length).toEqual(0); + }); +}); diff --git a/actions/ai-action/test/stripUndefined.test.ts b/actions/ai-action/test/stripUndefined.test.ts new file mode 100644 index 0000000..e80128f --- /dev/null +++ b/actions/ai-action/test/stripUndefined.test.ts @@ -0,0 +1,72 @@ +import "reflect-metadata"; +import { AIMessage } from "@langchain/core/messages"; +import { describe, expect, it } from "vitest"; +import { stripUndefined } from "../src/utils/shared/Shared.stripUndefined.util.js"; +import { toFlowMessage } from "../src/utils/message/Message.toFlowMessage.util.js"; + +/** Walks a value and collects the paths that hold undefined - what hercules rejects. */ +function undefinedPaths(value: unknown, path = "$"): string[] { + if (value === undefined) return [path]; + if (Array.isArray(value)) return value.flatMap((entry, index) => undefinedPaths(entry, `${path}[${index}]`)); + if (typeof value === "object" && value !== null) { + return Object.entries(value as Record).flatMap(([key, entry]) => + undefinedPaths(entry, `${path}.${key}`), + ); + } + return []; +} + +describe("stripping undefined before it reaches the serializer", () => { + it("leaves out keys that hold undefined, however deep", () => { + const cleaned = stripUndefined({ + model: "x", + system_fingerprint: undefined, + usage: { input: 3, details: { audio: undefined, text: 3 } }, + }); + + expect(cleaned).toEqual({ model: "x", usage: { input: 3, details: { text: 3 } } }); + expect("system_fingerprint" in cleaned).toBe(false); + }); + + it("turns an undefined list entry into null rather than shifting the list", () => { + expect(stripUndefined([1, undefined, 3])).toEqual([1, null, 3]); + }); + + it("keeps null, empty objects and empty lists, which are all representable", () => { + expect(stripUndefined({ a: null, b: {}, c: [] })).toEqual({ a: null, b: {}, c: [] }); + }); + + it("leaves plain values alone", () => { + expect(stripUndefined("text")).toEqual("text"); + expect(stripUndefined(0)).toEqual(0); + expect(stripUndefined(false)).toEqual(false); + expect(stripUndefined(null)).toEqual(null); + }); +}); + +describe("a message carrying provider metadata", () => { + it("reaches the flow without a single undefined in it", () => { + const answer = new AIMessage({ + content: "Hi.", + response_metadata: { model_name: "openai/gpt-oss-120b", system_fingerprint: undefined }, + usage_metadata: { + input_tokens: 11, + output_tokens: 3, + total_tokens: 14, + input_token_details: { audio: undefined, cache_read: 0 }, + }, + invalid_tool_calls: [{ name: "tool_1", args: "{broken", id: "call-0", error: undefined }], + }); + + const flat = toFlowMessage(answer); + + expect(undefinedPaths(flat)).toEqual([]); + expect(flat.response_metadata).toEqual({ model_name: "openai/gpt-oss-120b" }); + expect(flat.usage_metadata).toEqual({ + input_tokens: 11, + output_tokens: 3, + total_tokens: 14, + input_token_details: { cache_read: 0 }, + }); + }); +}); From e0f8439a078cf00cd4ca15803513cb40a0359adf Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:07 +0100 Subject: [PATCH 05/19] feat: add runtime function definitions for various AI models including Anthropic, Groq, LiteLLM, Mistral, Ollama, OpenAI, and OpenRouter --- .../model/Model.anthropic.runtimefunction.ts | 132 +++++++++++ .../model/Model.groq.runtimefunction.ts | 106 +++++++++ .../model/Model.liteLlm.runtimefunction.ts | 155 +++++++++++++ .../model/Model.mistral.runtimefunction.ts | 110 ++++++++++ .../model/Model.ollama.runtimefunction.ts | 110 ++++++++++ .../model/Model.openAi.runtimefunction.ts | 120 ++++++++++ .../model/Model.openRouter.runtimefunction.ts | 205 ++++-------------- 7 files changed, 771 insertions(+), 167 deletions(-) create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts create mode 100644 actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts diff --git a/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts new file mode 100644 index 0000000..4ab14ef --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts @@ -0,0 +1,132 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatAnthropic } from "@langchain/anthropic"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +/** + * Anthropic's own web search, as a server tool: Anthropic runs the search and hands + * the model the results, so the flow needs no search tool and no key of its own. The + * model still decides for itself whether to search at all. + */ +const WEB_SEARCH_TOOL = { type: "web_search_20250305", name: "web_search" } as const; + +@Identifier("ai::model::anthropic") +@DisplayIcon("simple:anthropic") +@Signature( + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER, web_search?: BOOLEAN): TRANSFORM", +) +@Name({ code: "en-US", content: "Anthropic model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, called at Anthropic - the Claude models. Give the result to an agent as its model. It can also let the model search the web through Anthropic.", +}) +@DisplayMessage({ code: "en-US", content: "Anthropic ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The Claude model identifier, for example \"claude-sonnet-5\" or \"claude-haiku-4-5\". A bare family name without a date always means the current model of that family.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The Anthropic API key the requests are sent with. It is what the usage is billed against, so it belongs in a secret rather than in the node.", + }, + ], +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How freely the model may vary its answers, called temperature. Low values keep answers focused and repeatable, higher ones more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_answer_length", + name: [{ code: "en-US", content: "Maximum answer length" }], + description: [ + { + code: "en-US", + content: + "The longest a single answer may get, in tokens - about three quarters of a word each. Anthropic always needs a limit, so one is used when this is empty; raise it for long answers.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "web_search", + name: [{ code: "en-US", content: "Web search" }], + description: [ + { + code: "en-US", + content: + "Lets the model search the web through Anthropic, which runs the search for it - no search tool and no key of your own needed. Off unless switched on; the model decides whether to search.", + }, + ], + optional: true, +}) +export class AnthropicModelFunction { + run( + _context: FunctionContext, + model: string, + api_key: string, + temperature?: number, + max_answer_length?: number, + web_search?: boolean, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "An Anthropic model needs a model identifier.", + ); + const chat: ChatAnthropic = new ChatAnthropic({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "An Anthropic model needs an API key."), + temperature, + ...(max_answer_length !== undefined ? { maxTokens: max_answer_length } : {}), + }); + + return toModelTransform({ + provider: "Anthropic", + prefix: "anthropic", + identifier, + model: chat as never, + // Anthropic's own dialect for the same thing OpenAI calls + // "response_format": the schema travels under the output config, and + // what it does not carry - a name, a description, "strict" - Anthropic + // has no field for, so it is dropped rather than smuggled in. + responseFormat: (format: AiResponseFormat) => ({ + outputConfig: { format: { type: "json_schema", schema: format.schema } }, + }), + serverTools: web_search === true ? [WEB_SEARCH_TOOL] : [], + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts new file mode 100644 index 0000000..ae91e01 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts @@ -0,0 +1,106 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatGroq } from "@langchain/groq"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toJsonSchemaFormat } from "../../utils/model/Model.toJsonSchemaFormat.util.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +@Identifier("ai::model::groq") +@DisplayIcon("thesvg:groq/wordmark") +@Signature( + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER): TRANSFORM", +) +@Name({ code: "en-US", content: "Groq model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, served by Groq - open models on fast hardware. Give the result to an agent as its model. Not every model there accepts tools, so pick a larger one.", +}) +@DisplayMessage({ code: "en-US", content: "Groq ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The Groq model identifier, for example \"llama-3.3-70b-versatile\" or \"openai/gpt-oss-120b\". Groq serves open models, so this is the model's own name rather than Groq's.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The Groq API key the requests are sent with. It is what the usage is billed against, so it belongs in a secret rather than in the node.", + }, + ], +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How freely the model may vary its answers, called temperature. Low values keep answers focused and repeatable, higher ones more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_answer_length", + name: [{ code: "en-US", content: "Maximum answer length" }], + description: [ + { + code: "en-US", + content: + "The longest a single answer may get, in tokens - one token is about three quarters of a word. An answer that hits the limit is cut off mid-sentence, so cap it only if you must.", + }, + ], + optional: true, +}) +export class GroqModelFunction { + run( + _context: FunctionContext, + model: string, + api_key: string, + temperature?: number, + max_answer_length?: number, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "A Groq model needs a model identifier.", + ); + const chat: ChatGroq = new ChatGroq({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "A Groq model needs an API key."), + temperature, + maxTokens: max_answer_length, + }); + + return toModelTransform({ + provider: "Groq", + prefix: "groq", + identifier, + model: chat as never, + responseFormat: (format: AiResponseFormat) => ({ response_format: toJsonSchemaFormat(format) }), + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts new file mode 100644 index 0000000..b13445e --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts @@ -0,0 +1,155 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatOpenAI } from "@langchain/openai"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toJsonSchemaFormat } from "../../utils/model/Model.toJsonSchemaFormat.util.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +/** + * A key the server never reads. + * + * The OpenAI client refuses to be built without one and falls back to the process + * environment, where a key meant for OpenAI itself would then be sent to a server of + * your own. A proxy that authenticates nobody gets this instead. + */ +const NO_API_KEY = "none"; + +@Identifier("ai::model::litellm") +@DisplayIcon("thesvg:vllm/mono") +@Signature( + "(model: TEXT, server_url: TEXT, api_key?: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER, enforce_answer_type?: BOOLEAN): TRANSFORM", +) +@Name({ code: "en-US", content: "LiteLLM model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, served by a LiteLLM proxy or anything else that speaks the OpenAI protocol - vLLM, llama.cpp, LM Studio. Give the result to an agent as its model.", +}) +@DisplayMessage({ code: "en-US", content: "LiteLLM ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model as that server names it - a LiteLLM deployment alias, a vLLM model path, \"qwen3:8b\". Whatever the server lists under /v1/models is what it accepts here.", + }, + ], +}) +@Parameter({ + runtimeName: "server_url", + name: [{ code: "en-US", content: "Server address" }], + description: [ + { + code: "en-US", + content: + "Where the requests go, up to and including the version segment - \"http://litellm:4000/v1\", \"http://vllm.ai.svc:8000/v1\". The paths below it are the protocol's own, so leave them off.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The key the requests are sent with, if the server asks for one - a LiteLLM virtual key, say. Keep it in a secret. Left empty no key is sent, which suits a server in your own network.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How freely the model may vary its answers, called temperature. Low values keep answers focused and repeatable, higher ones more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_answer_length", + name: [{ code: "en-US", content: "Maximum answer length" }], + description: [ + { + code: "en-US", + content: + "The longest a single answer may get, in tokens - one token is about three quarters of a word. An answer that hits the limit is cut off mid-sentence, so cap it only if you must.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "enforce_answer_type", + name: [{ code: "en-US", content: "Enforce the answer type" }], + description: [ + { + code: "en-US", + content: + "Lets the server itself hold the answer to the type the agent asked for, the way OpenAI does. Off unless switched on - while off the type is asked for as a tool, which more servers support.", + }, + ], + optional: true, +}) +export class LiteLlmModelFunction { + run( + _context: FunctionContext, + model: string, + server_url: string, + api_key?: string, + temperature?: number, + max_answer_length?: number, + enforce_answer_type?: boolean, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "A LiteLLM model needs a model identifier.", + ); + const baseURL: string = requireText( + server_url, + "ERROR_INVALID_AI_MODEL", + "A LiteLLM model needs the address of the server serving it.", + ); + const chat: ChatOpenAI = new ChatOpenAI({ + model: identifier, + apiKey: api_key && api_key.trim().length > 0 ? api_key : NO_API_KEY, + configuration: { baseURL }, + temperature, + maxTokens: max_answer_length, + }); + + return toModelTransform({ + provider: "LiteLLM", + prefix: "litellm", + identifier, + model: chat as never, + // Left out unless the node says the server can do it: a server that + // cannot gets the agent's forced tool call instead of a rejection. + ...(enforce_answer_type === true + ? { + responseFormat: (format: AiResponseFormat) => ({ + response_format: toJsonSchemaFormat(format), + }), + } + : {}), + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts new file mode 100644 index 0000000..a359f6f --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts @@ -0,0 +1,110 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatMistralAI } from "@langchain/mistralai"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +@Identifier("ai::model::mistral") +@DisplayIcon("simple:mistralai") +@Signature( + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER): TRANSFORM", +) +@Name({ code: "en-US", content: "Mistral model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, called at Mistral. Give the result to an agent as its model. An answer type is asked for as a tool call, so it is checked rather than guaranteed.", +}) +@DisplayMessage({ code: "en-US", content: "Mistral ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The Mistral model identifier, for example \"mistral-large-latest\" or \"mistral-small-latest\". A \"-latest\" name always means the current version of that model.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The Mistral API key the requests are sent with. It is what the usage is billed against, so it belongs in a secret rather than in the node.", + }, + ], +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How freely the model may vary its answers, called temperature. Low values keep answers focused and repeatable, higher ones more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_answer_length", + name: [{ code: "en-US", content: "Maximum answer length" }], + description: [ + { + code: "en-US", + content: + "The longest a single answer may get, in tokens - one token is about three quarters of a word. An answer that hits the limit is cut off mid-sentence, so cap it only if you must.", + }, + ], + optional: true, +}) +export class MistralModelFunction { + /** + * This node hands no output type to the provider, and that is deliberate: + * Mistral's `response_format` takes a JSON mode but no schema through this + * client, so it cannot promise a constrained answer. Leaving the field out of the + * request schema is what tells the agent to ask for an output type as a forced + * tool call instead - which Mistral does support. + */ + run( + _context: FunctionContext, + model: string, + api_key: string, + temperature?: number, + max_answer_length?: number, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "A Mistral model needs a model identifier.", + ); + const chat: ChatMistralAI = new ChatMistralAI({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "A Mistral model needs an API key."), + temperature, + maxTokens: max_answer_length, + }); + + return toModelTransform({ + provider: "Mistral", + prefix: "mistral", + identifier, + model: chat as never, + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts new file mode 100644 index 0000000..d2e0def --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts @@ -0,0 +1,110 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatOllama } from "@langchain/ollama"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +const OLLAMA_BASE_URL = "http://127.0.0.1:11434"; + +@Identifier("ai::model::ollama") +@DisplayIcon("simple:ollama") +@Signature( + "(model: TEXT, server_url?: TEXT, temperature?: NUMBER, max_conversation_length?: NUMBER): TRANSFORM", +) +@Name({ code: "en-US", content: "Ollama model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, run by your own Ollama server - no key and no provider. Give the result to an agent as its model. Only a model trained for tools can be an agent's.", +}) +@DisplayMessage({ code: "en-US", content: "Ollama ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model as the Ollama server names it, tag and all - \"qwen3:8b\", \"llama3.1:70b\". It has to be pulled on that server already; this node does not fetch it.", + }, + ], +}) +@Parameter({ + runtimeName: "server_url", + name: [{ code: "en-US", content: "Server address" }], + description: [ + { + code: "en-US", + content: + "Where the Ollama server listens, for example \"http://ollama:11434\". Left empty, the one on this machine is used - which is the local port, not a server somewhere in the cluster.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How freely the model may vary its answers, called temperature. Low values keep answers focused and repeatable, higher ones more varied. Left empty, the model's own default applies.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_conversation_length", + name: [{ code: "en-US", content: "Maximum conversation length" }], + description: [ + { + code: "en-US", + content: + "How much of the conversation the model may read, in tokens - one token is about three quarters of a word. Ollama's default is small and the rest is dropped silently, so raise it.", + }, + ], + optional: true, +}) +export class OllamaModelFunction { + run( + _context: FunctionContext, + model: string, + server_url?: string, + temperature?: number, + max_conversation_length?: number, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "An Ollama model needs a model identifier.", + ); + const chat: ChatOllama = new ChatOllama({ + model: identifier, + baseUrl: server_url && server_url.trim().length > 0 ? server_url : OLLAMA_BASE_URL, + temperature, + ...(max_conversation_length !== undefined ? { numCtx: max_conversation_length } : {}), + }); + + return toModelTransform({ + provider: "Ollama", + prefix: "ollama", + identifier, + model: chat as never, + // Ollama's dialect for the same thing: the bare JSON schema under + // "format", with no room for the name or description the agent sent. + responseFormat: (format: AiResponseFormat) => ({ format: format.schema }), + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts new file mode 100644 index 0000000..0370773 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts @@ -0,0 +1,120 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { ChatOpenAI } from "@langchain/openai"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toJsonSchemaFormat } from "../../utils/model/Model.toJsonSchemaFormat.util.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +@Identifier("ai::model::openai") +@DisplayIcon("thesvg:openai-chatgpt/mono") +@Signature( + "(model: TEXT, api_key: TEXT, server_url?: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER): TRANSFORM", +) +@Name({ code: "en-US", content: "OpenAI model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, called at OpenAI. Give the result to an agent as its model. With another server address it serves anything else that speaks the OpenAI protocol.", +}) +@DisplayMessage({ code: "en-US", content: "OpenAI ${model}" }) +@ThrowsError() +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model identifier, for example \"gpt-5\" or \"gpt-4.1-mini\". Pointed at another OpenAI-compatible service, it is whatever that service calls the model.", + }, + ], +}) +@Parameter({ + runtimeName: "api_key", + name: [{ code: "en-US", content: "API key" }], + description: [ + { + code: "en-US", + content: + "The API key the requests are sent with. It is what the usage is billed against, so it belongs in a secret rather than in the node.", + }, + ], +}) +@Parameter({ + runtimeName: "server_url", + name: [{ code: "en-US", content: "Server address" }], + description: [ + { + code: "en-US", + content: + "Where the requests go, for a service that speaks OpenAI's protocol but is not OpenAI - \"http://localhost:11434/v1\" for a server of your own, for instance. Left empty, OpenAI itself is called.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "temperature", + name: [{ code: "en-US", content: "Creativity" }], + description: [ + { + code: "en-US", + content: + "How much the model may vary its answers: low values keep them focused and repeatable, higher ones more varied. Left empty the model's default applies - a reasoning model takes only that.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "max_answer_length", + name: [{ code: "en-US", content: "Maximum answer length" }], + description: [ + { + code: "en-US", + content: + "The longest a single answer may get, in tokens - one token is about three quarters of a word. An answer that hits the limit is cut off mid-sentence, so cap it only if you must.", + }, + ], + optional: true, +}) +export class OpenAiModelFunction { + run( + _context: FunctionContext, + model: string, + api_key: string, + server_url?: string, + temperature?: number, + max_answer_length?: number, + ): AiModelTransform { + const identifier: string = requireText( + model, + "ERROR_INVALID_AI_MODEL", + "An OpenAI model needs a model identifier.", + ); + const chat: ChatOpenAI = new ChatOpenAI({ + model: identifier, + apiKey: requireText(api_key, "ERROR_INVALID_AI_MODEL", "An OpenAI model needs an API key."), + ...(server_url && server_url.trim().length > 0 ? { configuration: { baseURL: server_url } } : {}), + temperature, + maxTokens: max_answer_length, + }); + + return toModelTransform({ + provider: "OpenAI", + prefix: "openai", + identifier, + model: chat as never, + responseFormat: (format: AiResponseFormat) => ({ response_format: toJsonSchemaFormat(format) }), + }); + } +} diff --git a/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts index aa23b74..3b3bea4 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts @@ -1,32 +1,24 @@ import { + Description, DisplayIcon, DisplayMessage, FunctionContext, Identifier, Name, Parameter, - RuntimeError, Signature, ThrowsError, } from "@code0-tech/hercules"; -import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; -import type { AIMessage, AIMessageChunk, BaseMessage } from "@langchain/core/messages"; -import type { Runnable } from "@langchain/core/runnables"; -import { ChatOpenAI, type ChatOpenAICallOptions } from "@langchain/openai"; -import { toFlowMessage } from "../../utils/message/Message.toFlowMessage.util.js"; -import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; -import { AiModelResponseSchema, type AiModelResponse } from "../../datatypes/model/Model.response.datatype.js"; +import { ChatOpenAI } from "@langchain/openai"; import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; -import { AiModelRequestSchema, type AiModelRequest } from "../../datatypes/model/Model.request.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import { toModelTransform } from "../../utils/model/Model.toTransform.util.js"; +import { toJsonSchemaFormat } from "../../utils/model/Model.toJsonSchemaFormat.util.js"; import { describeError } from "../../utils/shared/Shared.describeError.util.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; -import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; import { requireText } from "../../utils/shared/Shared.requireText.util.js"; const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; -const log = logger("model:openrouter"); - /** * OpenRouter's own web search, as a server tool: the provider runs the search and * hands the model the excerpts, so the flow needs no search tool and no key of its @@ -50,6 +42,12 @@ const WEB_SEARCH_TOOL = { type: "openrouter:web_search" } as const; */ const REQUIRE_SUPPORTED_PARAMETERS = { provider: { require_parameters: true } } as const; +/** + * Why a 200 answer is not always an answer here, and what that usually means. + */ +const CUT_SHORT = + 'the provider gave up mid-generation and reported "error" as the finish reason. This is what a model that cannot serve a parameter it was given does, so the usual cause is a request it does not support - a tool the model has to call above all, which is how an answer type is asked for from a model that cannot hold its own answer to one.'; + /** * What OpenRouter actually objected to. * @@ -71,23 +69,17 @@ function describeProviderError(error: unknown): string { return details.length > 0 ? `${described} (${details.join(": ")})` : described; } -interface ToolDefinition { - type: "function"; - function: { - name: string; - description: string; - parameters: Record; - }; -} - -type BoundModel = Runnable; - @Identifier("ai::model::openrouter") @DisplayIcon("simple:openrouter") @Signature( - "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_tokens?: NUMBER, web_search?: BOOLEAN, structured_output?: BOOLEAN): TRANSFORM", + "(model: TEXT, api_key: TEXT, temperature?: NUMBER, max_answer_length?: NUMBER, web_search?: BOOLEAN): TRANSFORM", ) @Name({ code: "en-US", content: "OpenRouter model" }) +@Description({ + code: "en-US", + content: + "The model an agent thinks with, served through OpenRouter - one key for every provider it routes to. Give the result to an agent as its model; the model is the only choice here.", +}) @DisplayMessage({ code: "en-US", content: "OpenRouter ${model}" }) @ThrowsError() @Parameter({ @@ -114,36 +106,24 @@ type BoundModel = Runnable => { - const parsed: AiModelRequest = parseOrThrow( - AiModelRequestSchema, - request, - "ERROR_INVALID_AI_MODEL_REQUEST", - "The model request is not valid", - ); - - const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ - type: "function", - function: { - name: tool.name, - description: tool.description, - parameters: tool.input_schema, - }, - })); - const bindable: (ToolDefinition | typeof WEB_SEARCH_TOOL)[] = [ - ...tools, - ...(web_search === true ? [WEB_SEARCH_TOOL] : []), - ]; - const bound: BoundModel = bindable.length > 0 ? chat.bindTools(bindable as never) : chat; - const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); - - // The type the answer has to come back in, in the OpenAI dialect. - // OpenRouter constrains the generation itself, so the model cannot - // answer anything but matching JSON and the agent needs no tool call - // to get a structured answer out of it - but only the model and the - // provider it is routed to decide whether that is possible at all, - // and one that cannot do it rejects the whole call. Hence the switch: - // the field is only read when the node was told this model can serve - // it. "strict" is forwarded as asked for, which means OpenAI requires - // every nested object to close itself with "additionalProperties": - // false rather than answering loosely. - const responseFormat = structured_output === false ? undefined : parsed.response_format; - - // What a model answered is only half of a failed run: whether it was - // asked to call a tool at all, and whether it then did, is the other - // half, and only this node sees both. - log.debug(`calling "${identifier}" with`, { - messages: parsed.messages.length, - tools: bindable.length, - tool_choice: parsed.tool_choice, - response_format: responseFormat?.name, - }); - - const answer: AIMessage = await bound - .invoke(messages, { - ...(parsed.stop ? { stop: parsed.stop } : {}), - ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), - ...(responseFormat - ? { - response_format: { - type: "json_schema", - json_schema: { - name: responseFormat.name, - schema: responseFormat.schema, - ...(responseFormat.description - ? { description: responseFormat.description } - : {}), - ...(responseFormat.strict !== undefined - ? { strict: responseFormat.strict } - : {}), - }, - }, - } - : {}), - }) - .catch((error: unknown) => { - // Which parameter a provider refused is only answerable - // against what was actually sent, and a rejected call is - // exactly when nobody can reconstruct that from the flow. - log.error(`the call to "${identifier}" was rejected, having sent`, { - tools: bindable, - tool_choice: parsed.tool_choice, - response_format: responseFormat, - }); - throw new RuntimeError( - "ERROR_AI_MODEL_CALL_FAILED", - `The OpenRouter call to "${identifier}" failed: ${describeProviderError(error)}`, - ); - }); - - const reply = toFlowMessage(answer); - const metadata = answer.response_metadata as { finish_reason?: unknown } | undefined; - log.debug(`"${identifier}" answered with`, { - blocks: (reply.content ?? []).map((block) => block.type), - tool_calls: (reply.content ?? []) - .filter((block) => block.type === "tool_call") - .map((block) => block.name), - finish_reason: (answer.response_metadata as { finish_reason?: unknown })?.finish_reason, - }); - - // A provider that gave up mid-generation still answers 200 through - // OpenRouter, with whatever text it had produced and "error" as the - // finish reason. Taken at face value that is a valid answer, and the - // run fails later and elsewhere - the agent gets blamed for not - // answering in the type it was asked for, when in truth it was never - // asked. The finish reason is the only place this is visible, so it - // is read here, where the provider's own vocabulary still applies. - if (metadata?.finish_reason === "error") { - throw new RuntimeError( - "ERROR_AI_MODEL_CALL_FAILED", - `The OpenRouter call to "${identifier}" was cut short: the provider gave up mid-generation and reported "error" as the finish reason. This is what a model that cannot serve a parameter it was given does, so the usual cause is a request it does not support - a forced tool call above all, which is how an output type is asked for from a model that cannot constrain its own output.`, - ); - } - - return { message: reply }; - }, - }; + return toModelTransform({ + provider: "OpenRouter", + prefix: "openrouter", + identifier, + model: chat as never, + // "strict" is forwarded as asked for, which means OpenAI requires every + // nested object to close itself with "additionalProperties": false + // rather than answering loosely. + responseFormat: (format: AiResponseFormat) => ({ response_format: toJsonSchemaFormat(format) }), + serverTools: web_search === true ? [WEB_SEARCH_TOOL] : [], + describeFailure: describeProviderError, + cutShort: CUT_SHORT, + }); } } From 49ba3cb91bf34af47e7c609643de28f627b8b473 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:13 +0100 Subject: [PATCH 06/19] feat: update human-in-the-loop and trim messages middleware with improved naming, descriptions, and parameters for clarity --- ...ddleware.humanInTheLoop.runtimefunction.ts | 14 +++- ...Middleware.trimMessages.runtimefunction.ts | 72 ++++++++++++------- 2 files changed, 57 insertions(+), 29 deletions(-) diff --git a/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts index 5c79e6b..59dab90 100644 --- a/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts @@ -1,4 +1,6 @@ import { + Alias, + Description, DisplayIcon, DisplayMessage, FunctionContext, @@ -32,7 +34,13 @@ const log = logger("middleware"); @Identifier("ai::middleware::human_in_the_loop") @DisplayIcon("tabler:message-ai") @Signature("(tools: LIST): TRANSFORM") -@Name({ code: "en-US", content: "Human in the loop" }) +@Name({ code: "en-US", content: "Ask a person first" }) +@Alias({ code: "en-US", content: "human in the loop;approval;approve;confirm;permission;middleware" }) +@Description({ + code: "en-US", + content: + "Makes the agent ask a person before it uses one of the tools you name. Give it to an agent as a rule: nothing happens until someone answers. Use it for tools that write, pay or delete.", +}) @DisplayMessage({ code: "en-US", content: "Ask before running ${tools}" }) @ThrowsError() @Parameter({ @@ -42,7 +50,7 @@ const log = logger("middleware"); { code: "en-US", content: - "The tools the agent has to ask about before running them. Instead of running one, it answers with what it wants to do and ends the turn; the reply to that question - the next message of the conversation - decides.", + "The tools the agent has to ask about, named as the agent sees them. It says what it wants to do and stops; the next message of the conversation is the answer.", }, ], }) @@ -51,7 +59,7 @@ export class HumanInTheLoopMiddlewareFunction { * A middleware that makes an agent ask before it runs certain tools, and holds it * to the answer. * - * It is a middleware like any other, so an agent gets it the same way it gets a + * It is a rule like any other, so an agent gets it the same way it gets a * trimmer or a flow of the project - the agent node itself knows nothing about * approvals. * diff --git a/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts index f28b744..9180fc6 100644 --- a/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts @@ -1,4 +1,6 @@ import { + Alias, + Description, DisplayIcon, DisplayMessage, FunctionContext, @@ -18,48 +20,56 @@ import { AiStateUpdateSchema, type AiStateUpdate } from "../../datatypes/middlew import { AiAgentStateSchema, type AiAgentState } from "../../datatypes/middleware/Middleware.agentState.datatype.js"; import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; -type TrimStrategy = "first" | "last"; +type TrimEnd = "first" | "last"; @Identifier("ai::middleware::trim_messages") @DisplayIcon("tabler:scissors") -@Signature("(max_tokens: NUMBER, strategy?: TEXT, keep_system?: BOOLEAN): TRANSFORM") -@Name({ code: "en-US", content: "Trim messages" }) +@Signature( + "(max_conversation_length: NUMBER, keep?: TEXT, keep_instructions?: BOOLEAN): TRANSFORM", +) +@Name({ code: "en-US", content: "Shorten long conversations" }) +@Alias({ code: "en-US", content: "trim;messages;history;context;window;tokens;middleware" }) +@Description({ + code: "en-US", + content: + "Keeps a conversation short enough for the model by dropping whole messages before the agent is asked again. Give it to an agent as a rule. Nothing is summarized - dropped messages are gone.", +}) @DisplayMessage({ code: "en-US", - content: "Trim the conversation to ${max_tokens} tokens", + content: "Shorten the conversation to ${max_conversation_length} tokens", }) @ThrowsError() @Parameter({ - runtimeName: "max_tokens", - name: [{ code: "en-US", content: "Maximum tokens" }], + runtimeName: "max_conversation_length", + name: [{ code: "en-US", content: "Maximum conversation length" }], description: [ { code: "en-US", content: - "The size the conversation is cut down to before it is sent to the model, counted in tokens and approximated rather than counted by the model's own tokenizer. It has to be a positive number.", + "The length the conversation is cut down to, in tokens - one token is about three quarters of a word. The count is an estimate, so stay below what the model can really read.", }, ], }) @Parameter({ - runtimeName: "strategy", - name: [{ code: "en-US", content: "Strategy" }], + runtimeName: "keep", + name: [{ code: "en-US", content: "Which messages to keep" }], description: [ { code: "en-US", content: - "Which end of the conversation survives the cut: \"last\" keeps the most recent messages, \"first\" keeps the oldest ones. Defaults to \"last\", which is what keeps an ongoing conversation usable.", + "Which end of the conversation survives: \"newest\" keeps what was said last, \"oldest\" keeps how it began. Left empty, the newest are kept.", }, ], optional: true, }) @Parameter({ - runtimeName: "keep_system", - name: [{ code: "en-US", content: "Keep system prompt" }], + runtimeName: "keep_instructions", + name: [{ code: "en-US", content: "Keep the instructions" }], description: [ { code: "en-US", content: - "Whether the system prompt is kept even when the rest is cut away. On by default, because an agent that loses its instructions mid-conversation stops behaving as it was set up to.", + "Whether the agent's instructions are kept even when the rest is cut away. On unless switched off, because an agent that loses its instructions mid-conversation stops behaving as it was set up to.", }, ], optional: true, @@ -67,26 +77,36 @@ type TrimStrategy = "first" | "last"; export class TrimMessagesMiddlewareFunction { run( _context: FunctionContext, - max_tokens: number, - strategy?: string, - keep_system?: boolean, + max_conversation_length: number, + keep?: string, + keep_instructions?: boolean, ): AiMiddlewareTransform { - if (typeof max_tokens !== "number" || !Number.isFinite(max_tokens) || max_tokens <= 0) { - throw new RuntimeError("ERROR_INVALID_AI_STATE_UPDATE", "Trimming needs a positive token budget."); + if ( + typeof max_conversation_length !== "number" || + !Number.isFinite(max_conversation_length) || + max_conversation_length <= 0 + ) { + throw new RuntimeError( + "ERROR_INVALID_AI_STATE_UPDATE", + "Shortening a conversation needs a positive length to shorten it to.", + ); } - if (strategy !== undefined && strategy !== "first" && strategy !== "last") { + // "first" and "last" are what the trimmer itself calls the two ends; the node + // asks for them as the ends of a conversation, which is what a person reading + // it sees. + if (keep !== undefined && !["newest", "oldest", "first", "last"].includes(keep)) { throw new RuntimeError( "ERROR_INVALID_AI_STATE_UPDATE", - `"${strategy}" is not a trim strategy; use "first" or "last".`, + `"${keep}" is not an end of the conversation; keep either the "newest" or the "oldest" messages.`, ); } - const trimStrategy: TrimStrategy = strategy === "first" ? "first" : "last"; - const includeSystem: boolean = keep_system ?? true; + const keptEnd: TrimEnd = keep === "oldest" || keep === "first" ? "first" : "last"; + const includeSystem: boolean = keep_instructions ?? true; return { - name: `trim_messages:${trimStrategy}:${max_tokens}`, - description: `Trims the conversation to ${max_tokens} tokens`, + name: `trim_messages:${keptEnd}:${max_conversation_length}`, + description: `Shortens the conversation to ${max_conversation_length} tokens`, inputSchema: AiAgentStateSchema, outputSchema: AiStateUpdateSchema, run: async (state: AiAgentState): Promise => { @@ -98,9 +118,9 @@ export class TrimMessagesMiddlewareFunction { ); const trimmed: BaseMessage[] = await trimMessages(parsed.messages.map(toLangChainMessage), { - maxTokens: max_tokens, + maxTokens: max_conversation_length, tokenCounter: countTokensApproximately, - strategy: trimStrategy, + strategy: keptEnd, includeSystem, allowPartial: false, startOn: "human", From 429451d51fc2dab96f6ad16a9ce5e6a8fac56670 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:17 +0100 Subject: [PATCH 07/19] feat: implement MCP server runtime function with detailed parameters and error handling --- .../mcp/Mcp.server.runtimefunction.ts | 177 ++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 actions/ai-action/src/runtimefunctions/mcp/Mcp.server.runtimefunction.ts diff --git a/actions/ai-action/src/runtimefunctions/mcp/Mcp.server.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/mcp/Mcp.server.runtimefunction.ts new file mode 100644 index 0000000..613d202 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/mcp/Mcp.server.runtimefunction.ts @@ -0,0 +1,177 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { AiMcpServerSchema, type AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; +import { asList } from "../../utils/shared/Shared.asList.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; +import { toPlainSchema } from "../../utils/shared/Shared.toPlainSchema.util.js"; + +/** + * The older of the two ways a server over the web is reached. Which one a server + * speaks is not announced anywhere, so it is taken from the address: a server on the + * older protocol is reached at its own event path, which is what that path is for, + * while everything else speaks the current one. + */ +const EVENT_STREAM_PATH = /\/sse\/?$/; + +@Identifier("ai::mcp::server") +@DisplayIcon("thesvg:model-context-protocol/mono") +@Signature( + "(name: TEXT, address: TEXT, access_token?: TEXT, headers?: OBJECT<{ [key: string]: string }>, allowed_tools?: LIST): AI_MCP_SERVER", +) +@Name({ code: "en-US", content: "MCP server" }) +@Alias({ code: "en-US", content: "mcp;model context protocol;tools;integration;server;connector" }) +@Description({ + code: "en-US", + content: + "A ready-made set of tools an agent can use, hosted elsewhere - a ticket system, a shop, a wiki. Give it to an agent as a tool: it asks the server what it offers and picks on its own.", +}) +@DisplayMessage({ code: "en-US", content: "The tools of ${name}" }) +@ThrowsError() +@Parameter({ + runtimeName: "name", + name: [{ code: "en-US", content: "Name" }], + description: [ + { + code: "en-US", + content: + "What this set of tools is called, chosen by you - \"tickets\", \"shop\". The agent sees it in front of every tool of the server, so two servers of one agent may not share a name.", + }, + ], +}) +@Parameter({ + runtimeName: "address", + name: [{ code: "en-US", content: "Address" }], + description: [ + { + code: "en-US", + content: + "The web address the provider gives you for its tools, pasted as it stands - for example \"https://example.com/mcp\". It has to start with http:// or https://.", + }, + ], +}) +@Parameter({ + runtimeName: "access_token", + name: [{ code: "en-US", content: "Access token" }], + description: [ + { + code: "en-US", + content: + "The token the provider gives you to prove the request is yours. Keep it in a secret, not in the node. Left empty nothing is sent, which only works for a server that asks for nothing.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "headers", + name: [{ code: "en-US", content: "Extra headers" }], + description: [ + { + code: "en-US", + content: + "Only for a server that wants something else sent along than an access token: the headers it asks for, spelled exactly as its documentation spells them. Leave this empty unless you were told otherwise.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "allowed_tools", + name: [{ code: "en-US", content: "Allowed tools" }], + description: [ + { + code: "en-US", + content: + "The tools of this server the agent may use, named as the server names them. Left empty it may use all of them, including the ones the server adds later.", + }, + ], + optional: true, +}) +export class McpServerFunction { + /** + * Describes a hosted set of tools, rather than connecting to it: the agent node + * opens the connections itself and closes them when it is done, so a server + * described here is only reached while an agent that was handed it works. + */ + run( + _context: FunctionContext, + name: string, + address: string, + access_token?: string, + headers?: unknown, + allowed_tools?: unknown[], + ): AiMcpServer { + const named: string = requireText(name, "ERROR_INVALID_AI_MCP_SERVER", "An MCP server needs a name."); + const url: string = requireText( + address, + "ERROR_INVALID_AI_MCP_SERVER", + `The MCP server "${named}" needs the address its tools are served at.`, + ); + + // A mistyped address is caught here rather than when the agent starts + // working, because here it is still clear which node is wrong. + let parsedUrl: URL; + try { + parsedUrl = new URL(url); + } catch { + throw new RuntimeError( + "ERROR_INVALID_AI_MCP_SERVER", + `"${url}" is not a web address, so the MCP server "${named}" cannot be reached at it.`, + ); + } + if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") { + throw new RuntimeError( + "ERROR_INVALID_AI_MCP_SERVER", + `The address of the MCP server "${named}" has to start with http:// or https://, but it starts with ${parsedUrl.protocol}`, + ); + } + + // What is sent with every request: the access token in the form every MCP + // server expects it, and whatever else the server asked for on top - listed + // last, so a server wanting its own kind of authorization can say so. + const sent: Record = {}; + if (typeof access_token === "string" && access_token.trim().length > 0) { + sent.Authorization = `Bearer ${access_token.trim()}`; + } + Object.entries(toPlainSchema(headers) ?? {}).forEach(([header, value]) => { + if (typeof value !== "string") { + throw new RuntimeError( + "ERROR_INVALID_AI_MCP_SERVER", + `The header "${header}" of the MCP server "${named}" has to be a text, but a ${typeof value} was passed.`, + ); + } + sent[header] = value; + }); + + const tools: string[] = asList(allowed_tools, "allowed_tools").map((tool, index) => + requireText( + tool, + "ERROR_INVALID_AI_MCP_SERVER", + `Entry ${index + 1} of "allowed_tools" has to be the name of a tool of "${named}".`, + ), + ); + + return parseOrThrow( + AiMcpServerSchema, + { + name: named, + transport: EVENT_STREAM_PATH.test(parsedUrl.pathname) ? "sse" : "http", + url, + ...(Object.keys(sent).length > 0 ? { headers: sent } : {}), + ...(tools.length > 0 ? { allowed_tools: tools } : {}), + }, + "ERROR_INVALID_AI_MCP_SERVER", + `The MCP server "${named}" is not valid`, + ); + } +} From 560b3e3eefb4c17723dfff5ed434b4b3e6a06160 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:28 +0100 Subject: [PATCH 08/19] feat: rename create agent function to ask agent, update parameters and descriptions for clarity, and add skills function for loading Markdown skills --- ...nction.ts => Agent.ask.runtimefunction.ts} | 210 ++++++++++++------ .../agent/Agent.skills.runtimefunction.ts | 146 ++++++++++++ 2 files changed, 285 insertions(+), 71 deletions(-) rename actions/ai-action/src/runtimefunctions/agent/{Agent.create.runtimefunction.ts => Agent.ask.runtimefunction.ts} (75%) create mode 100644 actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts similarity index 75% rename from actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts rename to actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts index 30718a7..20bf911 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts @@ -1,4 +1,6 @@ import { + Alias, + Description, DisplayIcon, DisplayMessage, FunctionContext, @@ -10,6 +12,7 @@ import { SubFlow, ThrowsError, } from "@code0-tech/hercules"; +import type { BaseMessage } from "@langchain/core/messages"; import type { ClientTool } from "@langchain/core/tools"; import { MultiServerMCPClient } from "@langchain/mcp-adapters"; import { createAgent, createMiddleware, tool, type AnyAgentMiddleware, type ReactAgent } from "langchain"; @@ -18,7 +21,11 @@ import { AiAgentRequestSchema, type AiAgentRequest } from "../../datatypes/agent import { AiAgentResponseSchema, type AiAgentResponse } from "../../datatypes/agent/Agent.response.datatype.js"; import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; -import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; +import { + AiChatRequestSchema, + type AiChatRequest, + type AiChatTool, +} from "../../datatypes/chat/Chat.request.datatype.js"; import { AiMcpServerSchema, type AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; import type { AgentDefinition, ToolEntry } from "../../types/agent/Agent.types.js"; @@ -62,13 +69,19 @@ const JUMP_TARGETS = ["model", "tools", "end"] as const; const EXTRACTION_PROMPT = "The conversation above is finished. Answer with what it produced, in the type you were given, and add nothing that was not said in it."; -@Identifier("ai::agent::create") +@Identifier("ai::agent::ask") @DisplayIcon("tabler:ai") @Signature( - "(name: TEXT, system_prompt: TEXT, model: TRANSFORM, prompt: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, output_schema?: T, request?: AI_CHAT_REQUEST, middleware?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", + "(name: TEXT, instructions: TEXT, model: TRANSFORM, question: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, answer_type?: T, conversation?: AI_CHAT_REQUEST, rules?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", ) -@Name({ code: "en-US", content: "Create agent" }) -@DisplayMessage({ code: "en-US", content: "Ask the agent ${name} ${prompt}" }) +@Name({ code: "en-US", content: "Ask agent" }) +@Alias({ code: "en-US", content: "agent;ai;llm;chat;prompt;assistant;tools" }) +@Description({ + code: "en-US", + content: + "Asks an AI agent a question and waits for its answer. Give it instructions, a model to think with and flows as tools - it decides on its own what to use until it can answer.", +}) +@DisplayMessage({ code: "en-US", content: "Ask the agent ${name} ${question}" }) @ThrowsError() @Parameter({ runtimeName: "name", @@ -82,13 +95,13 @@ const EXTRACTION_PROMPT = ], }) @Parameter({ - runtimeName: "system_prompt", - name: [{ code: "en-US", content: "System prompt" }], + runtimeName: "instructions", + name: [{ code: "en-US", content: "Instructions" }], description: [ { code: "en-US", content: - "The standing instructions the agent works under - its role, what it may and may not do, how the answer should read. They are sent ahead of every turn, so they hold for the whole conversation rather than for this prompt alone.", + "What the agent is and how it should work: its role, what it may do, how the answer should read. The agent is told this before every turn.", }, ], }) @@ -104,13 +117,13 @@ const EXTRACTION_PROMPT = ], }) @Parameter({ - runtimeName: "prompt", - name: [{ code: "en-US", content: "Prompt" }], + runtimeName: "question", + name: [{ code: "en-US", content: "Question" }], description: [ { code: "en-US", content: - "The question put to the agent in this run. It is appended to the messages the request already carries, so it is the last thing the agent reads before answering. It may be left empty when the request already carries the question.", + "What the agent is asked this time. It comes after everything the conversation already holds. Leave it empty when the conversation already ends in a question.", }, ], }) @@ -121,48 +134,48 @@ const EXTRACTION_PROMPT = { code: "en-US", content: - "What the agent may reach for while it works: flows of this project, each offered as a tool under its own name, and MCP servers, whose tools are discovered on connect. The agent decides on its own which of them to call, and how often.", + "What the agent may use while it works: flows of this project, each as its own tool, and whole sets of ready-made tools from an \"MCP server\" node. The agent picks what it needs.", }, ], optional: true, }) @Parameter({ - runtimeName: "output_schema", - name: [{ code: "en-US", content: "Output type" }], + runtimeName: "answer_type", + name: [{ code: "en-US", content: "Answer type" }], description: [ { code: "en-US", content: - "The data type the answer has to come back in, so the flow can read the fields instead of parsing prose. It has to be an object type; left empty, the agent answers in plain text.", + "The data type the answer has to come back in, so the flow can read its fields instead of searching a text. It needs fields; left empty the agent answers in plain text.", }, ], optional: true, }) @Parameter({ - runtimeName: "request", - name: [{ code: "en-US", content: "Request" }], + runtimeName: "conversation", + name: [{ code: "en-US", content: "Conversation" }], description: [ { code: "en-US", content: - "A conversation to continue, in the chat format an OpenAI-compatible client sends. Its messages go ahead of the prompt, which is how a chat endpoint hands the agent everything that was said before.", + "Everything that was said before, as a chat client sends it. Those messages go ahead of the question, which is how a chat endpoint hands the agent the conversation it is to carry on.", }, ], optional: true, }) @Parameter({ - runtimeName: "middleware", - name: [{ code: "en-US", content: "Middleware" }], + runtimeName: "rules", + name: [{ code: "en-US", content: "Rules" }], description: [ { code: "en-US", content: - "Steps that sit between the agent and its model and may change what happens on each turn - trimming the conversation, asking before a tool runs. They are applied in the order they are listed.", + "Rules the agent has to work by, checked on every turn: shortening a conversation that grew too long, asking a person before a tool runs. They apply in the order listed.", }, ], optional: true, }) -export class CreateAgentFunction { +export class AskAgentFunction { /** * Builds the agent and runs it in one node, rather than returning the agent for a * second node to invoke. A returned agent would be a sub flow function, and the @@ -174,30 +187,30 @@ export class CreateAgentFunction { * * The parameters are ordered by how often a flow reaches for them: what every * agent needs first, then the tools and the answer's type, and the conversation - * and middleware knobs last. + * and the rules last. */ async run( _context: FunctionContext, name: string, - system_prompt: string, + instructions: string, model: unknown, - prompt: string, + question: string, tools?: ToolEntry[], - output_schema?: unknown, - request?: AiChatRequest, - middleware?: unknown[], + answer_type?: unknown, + conversation?: AiChatRequest, + rules?: unknown[], ): Promise { const log: Logger = logger("agent", _context.executionId); const toolLog: Logger = logger("tool", _context.executionId); log.info(`the node asks the agent "${name}"`, { - prompt, + question, tools: Array.isArray(tools) ? tools.length : 0, - middleware: Array.isArray(middleware) ? middleware.length : 0, - request, - output_schema, + rules: Array.isArray(rules) ? rules.length : 0, + conversation, + answer_type, }); - // The "output_schema" parameter is a TYPE: the data type the flow wants the + // The "answer_type" parameter is a TYPE: the data type the flow wants the // agent to answer in. Its value reaches the action as that type's JSON schema // - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` // unwraps either way. langchain only accepts a plain JSON schema as a @@ -206,25 +219,25 @@ export class CreateAgentFunction { // type's value, so a schema for anything else is rejected here rather than // deep inside the agent. let outputSchema: Record | undefined; - if (output_schema !== undefined && output_schema !== null) { - outputSchema = toPlainSchema(output_schema); + if (answer_type !== undefined && answer_type !== null) { + outputSchema = toPlainSchema(answer_type); if (!outputSchema || typeof outputSchema !== "object") { throw new RuntimeError( "ERROR_INVALID_AI_OUTPUT_SCHEMA", - `The "output_schema" parameter has to be a type, but a ${typeof output_schema} was passed.`, + `The "answer_type" parameter has to be a type, but a ${typeof answer_type} was passed.`, ); } if (!("properties" in outputSchema)) { throw new RuntimeError( "ERROR_INVALID_AI_OUTPUT_SCHEMA", - 'The agent can only answer in an object type: the type passed as "output_schema" has no properties.', + 'The agent can only answer in a type with fields: the type passed as "answer_type" has none.', ); } } const definition: AgentDefinition = { name: requireText(name, "ERROR_INVALID_AI_AGENT", "An agent needs a name."), - systemPrompt: asText(system_prompt ?? "", "system_prompt", "ERROR_INVALID_AI_AGENT"), + systemPrompt: asText(instructions ?? "", "instructions", "ERROR_INVALID_AI_AGENT"), model: asSubFlow(model, "model"), // A tool is either a flow of the project or an MCP server; which entry was // neither is part of the error, because that is what makes it fixable. @@ -239,8 +252,8 @@ export class CreateAgentFunction { `Entry ${index + 1} of "tools" is neither a sub flow nor a valid MCP server: ${formatIssues(server.error.issues)}`, ); }), - middleware: asList(middleware, "middleware").map((entry, index): SubFlow => - asSubFlow(entry, `middleware[${index}]`), + middleware: asList(rules, "rules").map((entry, index): SubFlow => + asSubFlow(entry, `rules[${index}]`), ), ...(outputSchema ? { outputSchema } : {}), }; @@ -264,36 +277,36 @@ export class CreateAgentFunction { const parsed: AiChatRequest = parseOrThrow( AiChatRequestSchema, - request ?? { messages: [] }, + conversation ?? { messages: [] }, "ERROR_INVALID_AI_CHAT_REQUEST", "The chat request is not valid", ); - const question: string = asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"); - const conversation: AiMessage[] = [ + const asked: string = asText(question, "question", "ERROR_INVALID_AI_CHAT_REQUEST"); + const history: AiMessage[] = [ ...parsed.messages.map(fromChatMessage), - ...(question.length > 0 - ? [{ role: "human", content: [{ type: "text", text: question }] } as AiMessage] + ...(asked.length > 0 + ? [{ role: "human", content: [{ type: "text", text: asked }] } as AiMessage] : []), ]; - if (conversation.length === 0) { + if (history.length === 0) { throw new RuntimeError( "ERROR_INVALID_AI_CHAT_REQUEST", - "There is nothing to ask: the prompt is empty and the request carries no messages.", + "There is nothing to ask: the question is empty and the conversation carries no messages.", ); } const started: number = Date.now(); log.info(`running the agent "${definition.name}"`, { - messages: conversation.length, + messages: history.length, tools: definition.tools.length, - middleware: definition.middleware.length, - output_schema: definition.outputSchema, - system_prompt: definition.systemPrompt, + rules: definition.middleware.length, + answer_type: definition.outputSchema, + instructions: definition.systemPrompt, }); const agentRequest: AiAgentRequest = parseOrThrow( AiAgentRequestSchema, - { messages: conversation }, + { messages: history }, "ERROR_INVALID_AI_AGENT_REQUEST", "The agent request is not valid", ); @@ -325,19 +338,50 @@ export class CreateAgentFunction { ); } - const allowed = new Set(servers.flatMap((server) => server.allowed_tools ?? [])); + // Each server's list of allowed tools is its own, and a tool arrives + // under the name of the server it came from with its own after it - + // "tickets_search". So a tool is held to the list of that server alone, + // found by that prefix, longest name first for a server whose name + // begins like another's: tool names are not unique across servers, and a + // server that lists nothing may use everything it offers. + const listed = new Map>( + servers + .filter((server) => (server.allowed_tools ?? []).length > 0) + .sort((one, other) => other.name.length - one.name.length) + .map((server) => [server.name, new Set(server.allowed_tools)]), + ); mcpTools = - allowed.size === 0 + listed.size === 0 ? discovered - : discovered.filter((entry) => allowed.has(entry.name.split("__").pop() ?? entry.name)); + : discovered.filter((entry) => { + for (const [server, allowed] of listed) { + if (entry.name.startsWith(`${server}_`)) { + return allowed.has(entry.name.slice(server.length + 1)); + } + } + return true; + }); } let agent: ReactAgent; try { // Two sub flows may share a title, and the model needs to tell the tools // they become apart. - const taken = new Set(); + const externalTools: ClientTool[] = (parsed.tools ?? []).map((entry: AiChatTool): ClientTool => { + const name = entry.function.name; + return tool( + async () => `The external tool "${name}" must be run by the chat client.`, + { + name, + description: entry.function.description ?? "", + schema: (entry.function.parameters ?? emptyJsonSchema()) as never, + }, + ) as unknown as ClientTool; + }); + const externalNames = new Set(externalTools.map((entry) => (entry as { name: string }).name)); + const taken = new Set(externalNames); const agentTools: ClientTool[] = [ + ...externalTools, ...flows.map((flow, index): ClientTool => { const schema: Record | undefined = toPlainSchema(flow.inputSchema); @@ -414,20 +458,44 @@ export class CreateAgentFunction { agent = createAgent({ model: new FlowChatModel({ run: definition.model }), tools: agentTools, - middleware: definition.middleware.map( - (flow, index): AnyAgentMiddleware => - createMiddleware({ - name: `flow_middleware_${index + 1}`, - beforeModel: { - hook: createHookHandler(flow, definition.name, "before_model"), - canJumpTo: [...JUMP_TARGETS], - }, - afterModel: { - hook: createHookHandler(flow, definition.name, "after_model"), - canJumpTo: [...JUMP_TARGETS], - }, - } as never) as AnyAgentMiddleware, - ), + middleware: [ + ...definition.middleware.map( + (flow, index): AnyAgentMiddleware => + createMiddleware({ + name: `flow_middleware_${index + 1}`, + beforeModel: { + hook: createHookHandler(flow, definition.name, "before_model"), + canJumpTo: [...JUMP_TARGETS], + }, + afterModel: { + hook: createHookHandler(flow, definition.name, "after_model"), + canJumpTo: [...JUMP_TARGETS], + }, + } as never) as AnyAgentMiddleware, + ), + ...(externalNames.size > 0 + ? [ + createMiddleware({ + name: "return_external_tool_call", + afterModel: { + hook: async (state: { messages: BaseMessage[] }) => { + const last = state.messages.at(-1) as + | (BaseMessage & { tool_calls?: { name?: string }[] }) + | undefined; + const calls = last?.tool_calls ?? []; + return calls.some( + (call) => + typeof call.name === "string" && externalNames.has(call.name), + ) + ? { jumpTo: "end" } + : undefined; + }, + canJumpTo: ["end"], + }, + } as never) as AnyAgentMiddleware, + ] + : []), + ], name: definition.name, ...(definition.systemPrompt ? { systemPrompt: definition.systemPrompt } : {}), // An output type is only asked for here when the agent has no tools @@ -597,7 +665,7 @@ export class CreateAgentFunction { if (outputSchema && !answer.structured_response) { throw new RuntimeError( "ERROR_INVALID_AI_AGENT_RESPONSE", - `The agent "${definition.name}" did not answer in the type passed as "output_schema", not even when asked for it on its own.`, + `The agent "${definition.name}" did not answer in the type passed as "answer_type", not even when asked for it on its own.`, ); } diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts new file mode 100644 index 0000000..aa262d8 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts @@ -0,0 +1,146 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + type SubFlowFunctionDefinition, + ThrowsError, +} from "@code0-tech/hercules"; +import { asList } from "../../utils/shared/Shared.asList.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +interface Skill { + title: string; + markdown: string; +} + +const TITLE_KEY = (title: string): string => title.normalize("NFKC").trim().toLocaleLowerCase(); + +/** + * Finds the first Markdown heading, accepting ATX headings at any level and the + * older setext form. Fenced code blocks are skipped so an example heading cannot + * become the skill's title. + */ +function titleOf(markdown: string, index: number): string { + const lines: string[] = markdown.replace(/^\uFEFF/, "").split(/\r?\n/); + let fenced = false; + + for (let line = 0; line < lines.length; line += 1) { + const current: string = lines[line]; + if (/^\s{0,3}(```|~~~)/.test(current)) { + fenced = !fenced; + continue; + } + if (fenced) continue; + + const atx = current.match(/^\s{0,3}#{1,6}(?:\s+|$)(.*?)\s*#*\s*$/); + if (atx) { + const title: string = atx[1].trim(); + if (title.length > 0) return title; + } + + const next: string | undefined = lines[line + 1]; + if (current.trim().length > 0 && next && /^\s{0,3}(=+|-+)\s*$/.test(next)) { + return current.trim(); + } + } + + throw new RuntimeError( + "ERROR_INVALID_AI_SKILL", + `Skill ${index + 1} has no Markdown heading to use as its title.`, + ); +} + +function skillInput(input: unknown): string { + if (typeof input === "string") return input; + if (typeof input !== "object" || input === null) { + throw new RuntimeError( + "ERROR_INVALID_AI_SKILL", + 'The "use_skill" tool needs an object with a "title" text.', + ); + } + + const title: unknown = (input as { title?: unknown }).title; + return requireText(title, "ERROR_INVALID_AI_SKILL", 'The "title" argument of "use_skill" is required.'); +} + +@Identifier("ai::agent::skills") +@DisplayIcon("tabler:books") +@Signature("(skills: LIST): ((title: TEXT) => TEXT)") +@Name({ code: "en-US", content: "Skills" }) +@Alias({ code: "en-US", content: "skill;skills;instructions;knowledge;agent;markdown" }) +@Description({ + code: "en-US", + content: + "Creates a tool that lets an agent load one of the supplied Markdown skills by its title when it needs the skill.", +}) +@DisplayMessage({ code: "en-US", content: "Make ${skills} available as skills" }) +@ThrowsError() +@Parameter({ + runtimeName: "skills", + name: [{ code: "en-US", content: "Skills" }], + description: [ + { + code: "en-US", + content: + "Markdown documents the agent can load by their first heading. Every document needs a title, and titles must be unique.", + }, + ], +}) +export class SkillsFunction { + run(_context: FunctionContext, skills: unknown[]): SubFlowFunctionDefinition { + const entries: Skill[] = asList(skills, "skills").map((skill, index) => { + const markdown: string = requireText( + skill, + "ERROR_INVALID_AI_SKILL", + `Entry ${index + 1} of "skills" has to be a Markdown text.`, + ); + return { title: titleOf(markdown, index), markdown }; + }); + + const seen = new Set(); + entries.forEach((skill) => { + const key: string = TITLE_KEY(skill.title); + if (seen.has(key)) { + throw new RuntimeError( + "ERROR_INVALID_AI_SKILL", + `More than one skill is titled "${skill.title}". Skill titles must be unique.`, + ); + } + seen.add(key); + }); + + const byTitle = new Map(entries.map((skill) => [TITLE_KEY(skill.title), skill.markdown])); + const titles: string[] = entries.map((skill) => skill.title); + return { + name: "use_skill", + description: `Loads a Markdown skill by title. Available skills: ${titles.join(", ")}.`, + inputSchema: { + type: "object", + properties: { + title: { type: "string", enum: titles }, + }, + required: ["title"], + additionalProperties: false, + }, + outputSchema: { type: "string" }, + run: async (input: unknown): Promise => { + const requested: string = skillInput(input); + const markdown: string | undefined = byTitle.get(TITLE_KEY(requested)); + if (markdown === undefined) { + throw new RuntimeError( + "ERROR_INVALID_AI_SKILL", + `There is no skill titled "${requested}". Available skills: ${titles.join(", ")}.`, + ); + } + return markdown; + }, + }; + } +} From e31f32999692e7d5da8369239ef64552c193d51d Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:33 +0100 Subject: [PATCH 09/19] feat: rename create agent function to ask agent, update descriptions and parameters for clarity in OpenAI runtime event handling --- .../openai/OpenAi.server.runtimeevent.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts index 41b61ff..2394fb5 100644 --- a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts +++ b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts @@ -18,7 +18,7 @@ import { * matching flow for `POST /chat/completions`. * * The flow is handed the client's request as an `AI_CHAT_REQUEST` - the type - * `ai::agent::create` takes - and answers it with `ai::openai::respond`, from wherever + * `ai::agent::ask` takes - and answers it with `ai::openai::respond`, from wherever * in the flow that belongs, so a flow that logs or stores something after the agent * still answers with the agent's reply. A flow that never responds falls back to its * own return value. @@ -37,19 +37,19 @@ import { @Description({ code: "en-US", content: - "Serves this flow as one model of an OpenAI-compatible endpoint. Any OpenAI client - Open WebUI among them - can be pointed at the project's route and talk to the flow; the request arrives as a chat request, and the flow answers it with \"Respond to the OpenAI request\". The model name is what the client lists and picks.", + "Serves this flow as a model of an OpenAI-compatible endpoint. Any OpenAI client, Open WebUI among them, can be pointed at the project's path and talk to the flow.", }) @DisplayMessage({ code: "en-US", content: "OpenAI request for ${model} on ${route}" }) @Alias({ code: "en-US", content: "openai;chat;completions;endpoint;open web ui;llm;api" }) @EventSetting({ identifier: "route", unique: "PROJECT", - name: [{ code: "en-US", content: "Route" }], + name: [{ code: "en-US", content: "Path" }], description: [ { code: "en-US", content: - "The path this endpoint lives under, e.g. /v1. A client is pointed at the project's slug followed by this route as its base URL and appends /chat/completions and /models itself.", + "The path this endpoint is reached under, \"/v1\" by default. A chat client is given the project's own address followed by this path as its server address, and finds the rest on its own.", }, ], defaultValue: "/v1", @@ -62,7 +62,7 @@ import { { code: "en-US", content: - "The model name clients see and ask for, unique within the project. It can say what this flow does rather than name a provider's model - a client lists this name, so the endpoint serves nothing until it is set.", + "The name chat clients see in their model list and pick, unique in the project. It can say what this flow does rather than name a provider's model; without it the endpoint serves nothing.", }, ], }) @@ -74,7 +74,7 @@ import { { code: "en-US", content: - "The key a client has to send as its bearer token. Left empty, the endpoint answers without authentication - only do that where nothing else can reach it.", + "The key a client has to send along to be let in. Left empty, anyone who can reach this endpoint can run the flow - only do that where nothing else can reach it.", }, ], }) From d0663cba12d29cc2d909a67164ffb4c8e2a46c76 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:39 +0100 Subject: [PATCH 10/19] feat: add AiChatTool schema to support function tools in chat requests and remove unused structured_response field from responses --- .../src/datatypes/chat/Chat.request.datatype.ts | 11 +++++++++++ .../src/datatypes/chat/Chat.response.datatype.ts | 1 - 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts index c126f00..682e09a 100644 --- a/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts +++ b/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts @@ -2,9 +2,20 @@ import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; import { z } from "zod"; import { AiChatMessageSchema } from "./Chat.message.datatype.js"; +const AiChatToolSchema = z.object({ + type: z.literal("function"), + function: z.object({ + name: z.string(), + description: z.string().optional(), + parameters: z.looseObject({}).optional(), + }), +}); +export type AiChatTool = z.infer; + export const AiChatRequestSchema = z.object({ messages: z.array(AiChatMessageSchema), model: z.string().optional(), + tools: z.array(AiChatToolSchema).optional(), }); export type AiChatRequest = z.infer; diff --git a/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts index 7a02e72..aece679 100644 --- a/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts +++ b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts @@ -30,7 +30,6 @@ export const AiChatResponseSchema = z.object({ * was passed as `output_schema`. The signature carries that type as a generic, so * the flow reads this field as the very type it picked rather than as an object. */ - structured_response: z.looseObject({}).optional(), /** * Every tool the agent used for this answer, with its arguments and what came * back. Not part of the OpenAI schema - a chat completion has no field for the From 0f00a7c981e1b9ff294328d5cd52be74f9d65172 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:44 +0100 Subject: [PATCH 11/19] feat: enhance OpenAI runtime functions with detailed descriptions and update return types for clarity --- ...nAi.openWebUiFormatting.runtimefunction.ts | 8 ++++++- .../openai/OpenAi.respond.runtimefunction.ts | 22 +++++++++++++++---- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts index a1d49d7..b4e30e5 100644 --- a/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts @@ -1,4 +1,5 @@ import { + Description, DisplayIcon, DisplayMessage, FunctionContext, @@ -26,9 +27,14 @@ const asAttribute = (value: unknown): string => escaped(JSON.stringify(value ?? const FORMATTED = /
Date: Mon, 9 Nov 2026 14:51:48 +0100 Subject: [PATCH 12/19] feat: add utility functions for JSON schema formatting and model transformation in OpenAI dialect --- .../model/Model.toJsonSchemaFormat.util.ts | 21 +++ .../src/utils/model/Model.toTransform.util.ts | 178 ++++++++++++++++++ 2 files changed, 199 insertions(+) create mode 100644 actions/ai-action/src/utils/model/Model.toJsonSchemaFormat.util.ts create mode 100644 actions/ai-action/src/utils/model/Model.toTransform.util.ts diff --git a/actions/ai-action/src/utils/model/Model.toJsonSchemaFormat.util.ts b/actions/ai-action/src/utils/model/Model.toJsonSchemaFormat.util.ts new file mode 100644 index 0000000..c4c6cd5 --- /dev/null +++ b/actions/ai-action/src/utils/model/Model.toJsonSchemaFormat.util.ts @@ -0,0 +1,21 @@ +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; + +/** + * The output type an agent asked for, in the OpenAI dialect - what OpenAI itself, + * OpenRouter and Groq all expect under `response_format`. + * + * `strict` is forwarded as asked for, which means the provider requires every nested + * object to close itself with `"additionalProperties": false` rather than answering + * loosely. + */ +export function toJsonSchemaFormat(format: AiResponseFormat): Record { + return { + type: "json_schema", + json_schema: { + name: format.name, + schema: format.schema, + ...(format.description ? { description: format.description } : {}), + ...(format.strict !== undefined ? { strict: format.strict } : {}), + }, + }; +} diff --git a/actions/ai-action/src/utils/model/Model.toTransform.util.ts b/actions/ai-action/src/utils/model/Model.toTransform.util.ts new file mode 100644 index 0000000..5f06f9f --- /dev/null +++ b/actions/ai-action/src/utils/model/Model.toTransform.util.ts @@ -0,0 +1,178 @@ +import { RuntimeError } from "@code0-tech/hercules"; +import type { BaseLanguageModelInput } from "@langchain/core/language_models/base"; +import type { BaseChatModel, BaseChatModelCallOptions } from "@langchain/core/language_models/chat_models"; +import type { AIMessage, AIMessageChunk, BaseMessage } from "@langchain/core/messages"; +import type { Runnable } from "@langchain/core/runnables"; +import { AiModelRequestSchema, type AiModelRequest } from "../../datatypes/model/Model.request.datatype.js"; +import { AiModelResponseSchema, type AiModelResponse } from "../../datatypes/model/Model.response.datatype.js"; +import type { AiResponseFormat } from "../../datatypes/model/Model.responseFormat.datatype.js"; +import type { AiModelTransform } from "../../datatypes/model/Model.transform.datatype.js"; +import { toFlowMessage } from "../message/Message.toFlowMessage.util.js"; +import { toLangChainMessage } from "../message/Message.toLangChainMessage.util.js"; +import { describeError } from "../shared/Shared.describeError.util.js"; +import { logger } from "../shared/Log.logger.util.js"; +import { parseOrThrow } from "../shared/Shared.parseOrThrow.util.js"; + +/** A tool as every OpenAI-dialect provider wants to be handed it. */ +interface ToolDefinition { + type: "function"; + function: { + name: string; + description: string; + parameters: Record; + }; +} + +/** A provider client, narrowed to what a model call needs of it. */ +type AnyChatModel = BaseChatModel & { + bindTools: (tools: never) => BoundModel; +}; +type BoundModel = Runnable; + +/** + * What every model node has in common, and what only it can answer. + * + * The flow side of a model is the same everywhere: a request of messages, tools, a + * tool choice and possibly an output type goes in, one message comes back. What a + * provider differs in is narrow enough to name - the dialect its output type is + * written in, the tools it runs itself, what its rejections look like - so that is + * what a node passes in, and the rest lives here rather than once per provider. + */ +export interface ModelTransformOptions { + /** The provider as the flow reads it in a message, e.g. "OpenRouter". */ + provider: string; + /** What the sub flow's name is prefixed with, e.g. "openrouter". */ + prefix: string; + /** The model identifier the node was given. */ + identifier: string; + /** The provider client, already configured by the node. */ + model: AnyChatModel; + /** + * The output type in this provider's own dialect, as call options - OpenAI's + * `response_format`, Anthropic's `outputConfig`, Ollama's `format`. Left out, + * the node declares that it cannot constrain its own output at all, and the + * agent asks for an output type as a forced tool call instead. + */ + responseFormat?: (format: AiResponseFormat) => Record; + /** Tools the provider runs itself, bound alongside the flow's own. */ + serverTools?: unknown[]; + /** What the provider objected to, when its own message is not the whole of it. */ + describeFailure?: (error: unknown) => string; + /** + * Why a 200 answer that reports "error" as its finish reason is not an answer. + * Only a provider that answers that way at all sets this. + */ + cutShort?: string; +} + +/** + * A model node's return value: the sub flow an agent invokes to call the model. + * + * Hercules only turns a returned value into a sub flow when it is a sub flow function + * definition, so the provider call is wrapped in one rather than handed over as a + * closure. + */ +export function toModelTransform(options: ModelTransformOptions): AiModelTransform { + const { provider, prefix, identifier, model } = options; + const log = logger(`model:${prefix}`); + const native: boolean = options.responseFormat !== undefined; + + // What the agent reads to decide how to get a structured answer: carrying + // "response_format" is this node saying its provider can constrain its own + // output, and dropping it sends the agent down the tool call instead. It has to + // reach the agent as a schema, because a sub flow carries nothing else. + const requestSchema = native ? AiModelRequestSchema : AiModelRequestSchema.omit({ response_format: true }); + + return { + name: `${prefix}:${identifier}`, + description: `${provider} model ${identifier}`, + inputSchema: requestSchema, + outputSchema: AiModelResponseSchema, + run: async (request: AiModelRequest): Promise => { + const parsed: AiModelRequest = parseOrThrow( + AiModelRequestSchema, + request, + "ERROR_INVALID_AI_MODEL_REQUEST", + "The model request is not valid", + ); + + const tools: ToolDefinition[] = parsed.tools.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.input_schema, + }, + })); + const bindable: unknown[] = [...tools, ...(options.serverTools ?? [])]; + const bound: BoundModel = bindable.length > 0 ? model.bindTools(bindable as never) : model; + const messages: BaseMessage[] = parsed.messages.map(toLangChainMessage); + + // The type the answer has to come back in. A provider that constrains the + // generation itself cannot answer anything but matching JSON, so the agent + // needs no tool call to get a structured answer out of it - and a provider + // that cannot do it never sees the field, because its node declared no + // dialect to write it in and the agent was told as much. + const format: AiResponseFormat | undefined = native ? parsed.response_format : undefined; + const formatOptions: Record = + format && options.responseFormat ? options.responseFormat(format) : {}; + + // What a model answered is only half of a failed run: whether it was asked + // to call a tool at all, and whether it then did, is the other half, and + // only this node sees both. + log.debug(`calling "${identifier}" with`, { + messages: parsed.messages.length, + tools: bindable.length, + tool_choice: parsed.tool_choice, + response_format: format?.name, + }); + + const answer: AIMessage = await bound + .invoke(messages, { + ...(parsed.stop ? { stop: parsed.stop } : {}), + ...(parsed.tool_choice ? { tool_choice: parsed.tool_choice } : {}), + ...formatOptions, + } as never) + .catch((error: unknown) => { + // Which parameter a provider refused is only answerable against + // what was actually sent, and a rejected call is exactly when + // nobody can reconstruct that from the flow. + log.error(`the call to "${identifier}" was rejected, having sent`, { + tools: bindable, + tool_choice: parsed.tool_choice, + response_format: format, + }); + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The ${provider} call to "${identifier}" failed: ${(options.describeFailure ?? describeError)(error)}`, + ); + }); + + const reply = toFlowMessage(answer); + const metadata = answer.response_metadata as { finish_reason?: unknown } | undefined; + log.debug(`"${identifier}" answered with`, { + blocks: (reply.content ?? []).map((block) => block.type), + tool_calls: (reply.content ?? []) + .filter((block) => block.type === "tool_call") + .map((block) => block.name), + finish_reason: metadata?.finish_reason, + }); + + // A provider that gave up mid-generation can still answer 200, with + // whatever text it had produced and "error" as the finish reason. Taken at + // face value that is a valid answer, and the run fails later and elsewhere + // - the agent gets blamed for not answering in the type it was asked for, + // when in truth it was never asked. The finish reason is the only place + // this is visible, so it is read here, where the provider's own vocabulary + // still applies. + if (options.cutShort && metadata?.finish_reason === "error") { + throw new RuntimeError( + "ERROR_AI_MODEL_CALL_FAILED", + `The ${provider} call to "${identifier}" was cut short: ${options.cutShort}`, + ); + } + + return { message: reply }; + }, + }; +} From a6c91829c925da33e81bf0b2f6a1d8226f0b907d Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:53 +0100 Subject: [PATCH 13/19] feat: rename create agent function to ask agent, add skills function, and include additional model functions for enhanced runtime capabilities --- actions/ai-action/src/index.ts | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts index 0e7dca8..2eadaaf 100644 --- a/actions/ai-action/src/index.ts +++ b/actions/ai-action/src/index.ts @@ -33,9 +33,17 @@ import { AiModelResponseDataType } from "./datatypes/model/Model.response.dataty import { AiResponseFormatDataType } from "./datatypes/model/Model.responseFormat.datatype.js"; import { AiToolSpecDataType } from "./datatypes/model/Model.toolSpec.datatype.js"; -import { CreateAgentFunction } from "./runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AskAgentFunction } from "./runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { SkillsFunction } from "./runtimefunctions/agent/Agent.skills.runtimefunction.js"; +import { McpServerFunction } from "./runtimefunctions/mcp/Mcp.server.runtimefunction.js"; import { HumanInTheLoopMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; import { TrimMessagesMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; +import { AnthropicModelFunction } from "./runtimefunctions/model/Model.anthropic.runtimefunction.js"; +import { GroqModelFunction } from "./runtimefunctions/model/Model.groq.runtimefunction.js"; +import { LiteLlmModelFunction } from "./runtimefunctions/model/Model.liteLlm.runtimefunction.js"; +import { MistralModelFunction } from "./runtimefunctions/model/Model.mistral.runtimefunction.js"; +import { OllamaModelFunction } from "./runtimefunctions/model/Model.ollama.runtimefunction.js"; +import { OpenAiModelFunction } from "./runtimefunctions/model/Model.openAi.runtimefunction.js"; import { OpenRouterModelFunction } from "./runtimefunctions/model/Model.openRouter.runtimefunction.js"; import { OpenAiOpenWebUiFormattingFunction } from "./runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.js"; @@ -86,10 +94,18 @@ const DATA_TYPES: DataTypeClass[] = [ ]; const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ - CreateAgentFunction, + AskAgentFunction, + SkillsFunction, + McpServerFunction, HumanInTheLoopMiddlewareFunction, OpenAiOpenWebUiFormattingFunction, OpenAiRespondFunction, + AnthropicModelFunction, + GroqModelFunction, + LiteLlmModelFunction, + MistralModelFunction, + OllamaModelFunction, + OpenAiModelFunction, OpenRouterModelFunction, TrimMessagesMiddlewareFunction, ]; @@ -103,7 +119,7 @@ const action = new Action( process.env.AQUILA_URL ?? "127.0.0.1:8081", "code0-tech", "tabler:robot", - "AI agent integration: build LangChain agents whose model, tools and middleware are flows of the project itself.", + "AI agents built from what the project already has: the model they think with, the flows and MCP servers they use as tools, and the rules they follow.", [{ code: "en-US", content: "AI" }], ); From a19478fe6d5f767a7c5b58d9fbd3090da1f5a366 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:51:57 +0100 Subject: [PATCH 14/19] feat: rename create agent function to ask agent, update tests for new function name and enhance skill tool creation --- actions/ai-action/test/agent.test.ts | 128 +++++++--- actions/ai-action/test/approval.test.ts | 6 +- actions/ai-action/test/functions.test.ts | 252 +++++++++++++++++--- actions/ai-action/test/openai.test.ts | 6 +- actions/ai-action/test/registration.test.ts | 78 ++++++ actions/ai-action/test/skills.test.ts | 38 +++ 6 files changed, 432 insertions(+), 76 deletions(-) create mode 100644 actions/ai-action/test/skills.test.ts diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts index e0e38fd..e159a1e 100644 --- a/actions/ai-action/test/agent.test.ts +++ b/actions/ai-action/test/agent.test.ts @@ -5,7 +5,7 @@ import type { AiAgentState } from "../src/datatypes/middleware/Middleware.agentS import type { AiMessage } from "../src/datatypes/message/Message.datatype.js"; import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; -import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; import { TrimMessagesMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; function subFlow(implementation: (input: never) => unknown, inputSchema?: Record): SubFlow { @@ -72,7 +72,7 @@ const nativeModelSchema: Record = { properties: { messages: {}, tools: {}, response_format: {} }, }; -const create = new CreateAgentFunction(); +const ask = new AskAgentFunction(); /** A data type's JSON schema, which is what a `TYPE` parameter carries. */ const orderType: Record = { @@ -118,10 +118,10 @@ function asStruct(plain: Record): unknown { return { fields: Object.fromEntries(Object.entries(plain).map(([key, value]) => [key, asValue(value)])) }; } -describe("ai::agent::create", () => { +describe("ai::agent::ask", () => { it("answers with a chat response, because it runs the agent itself", async () => { const { run } = scriptedModel([answer("hello")]); - const response = await create.run(context(), "greeter", "You greet people.", run, "hi"); + const response = await ask.run(context(), "greeter", "You greet people.", run, "hi"); expect(response.object).toEqual("chat.completion"); expect(replyOf(response)).toEqual("hello"); @@ -132,7 +132,7 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), ]); - const response = await create.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + const response = await ask.run(context(), "support", "", run, "where is A-1?", undefined, orderType); // The type travels to the model as the tool it has to call to answer. expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Order"]); @@ -144,14 +144,14 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), ]); - await create.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + await ask.run(context(), "support", "", run, "where is A-1?", undefined, orderType); expect(requests[0].tool_choice).toBe("any"); }); it("leaves the tool choice alone when no type was asked for", async () => { const { run, requests } = scriptedModel([answer("hello")]); - await create.run(context(), "greeter", "", run, "hi"); + await ask.run(context(), "greeter", "", run, "hi"); expect(requests[0].tool_choice).toBeUndefined(); }); @@ -162,7 +162,7 @@ describe("ai::agent::create", () => { nativeModelSchema, ); - const response = await create.run(context(), "support", "", run, "where is A-3?", undefined, orderType); + const response = await ask.run(context(), "support", "", run, "where is A-3?", undefined, orderType); // No tool to call and nothing to force: the type travels as the format the // answer has to be written in, and is read back off the message. @@ -181,7 +181,7 @@ describe("ai::agent::create", () => { ); const flowTool = subFlow(() => "ok"); - const response = await create.run(context(), "support", "", run, "make one", [flowTool], orderType); + const response = await ask.run(context(), "support", "", run, "make one", [flowTool], orderType); // First the agent works, with its tools and no type in the request. expect(requests[0].tools.map((tool) => tool.name)).toEqual(["tool_1"]); @@ -200,7 +200,7 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-6", status: "open" } }]), ]); - const response = await create.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); + const response = await ask.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); // The flow tool is bound for the work, and the extract tool alone for the // type - never the two together, which is what a provider refuses. @@ -215,14 +215,14 @@ describe("ai::agent::create", () => { nativeModelSchema, ); - const response = await create.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); + const response = await ask.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); expect(replyOf(response)).toEqual("I made you a user object."); }); it("asks for no format when a model that could constrain its output was given no type", async () => { const { run, requests } = scriptedModel([answer("hello")], nativeModelSchema); - await create.run(context(), "greeter", "", run, "hi"); + await ask.run(context(), "greeter", "", run, "hi"); expect(requests[0].response_format).toBeUndefined(); }); @@ -232,7 +232,7 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-2", status: "delivered" } }]), ]); - const response = await create.run( + const response = await ask.run( context(), "support", "", @@ -248,7 +248,7 @@ describe("ai::agent::create", () => { it("leaves the structured answer out when no type was asked for", async () => { const { run } = scriptedModel([answer("hello")]); - const response = await create.run(context(), "greeter", "", run, "hi"); + const response = await ask.run(context(), "greeter", "", run, "hi"); expect(response.structured_response).toBeUndefined(); }); @@ -256,44 +256,44 @@ describe("ai::agent::create", () => { it("rejects a type the agent cannot answer in", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - create.run(context(), "support", "", run, "hi", undefined, { type: "string" }), - ).rejects.toThrow(/no properties/); + ask.run(context(), "support", "", run, "hi", undefined, { type: "string" }), + ).rejects.toThrow(/type with fields/); }); it("fails when the agent ignores the type it was asked to answer in", async () => { const { run } = scriptedModel([answer("just text")]); - await expect(create.run(context(), "support", "", run, "hi", undefined, orderType)).rejects.toThrow( + await expect(ask.run(context(), "support", "", run, "hi", undefined, orderType)).rejects.toThrow( /did not answer in the type/, ); }); it("needs a name", async () => { const { run } = scriptedModel([answer("hello")]); - await expect(create.run(context(), "", "", run, "hi")).rejects.toThrow(RuntimeError); + await expect(ask.run(context(), "", "", run, "hi")).rejects.toThrow(RuntimeError); }); it("needs something to ask", async () => { const { run } = scriptedModel([answer("hello")]); - await expect(create.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + await expect(ask.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); }); it("rejects a model that is not a sub flow", async () => { await expect( - create.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never, "hi"), + ask.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never, "hi"), ).rejects.toThrow(RuntimeError); }); it("rejects an MCP server missing what its transport needs, before the agent runs", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - create.run(context(), "greeter", "", run, "hi", [{ name: "docs", transport: "stdio" }] as never), + ask.run(context(), "greeter", "", run, "hi", [{ name: "docs", transport: "stdio" }] as never), ).rejects.toThrow(RuntimeError); }); it("rejects two MCP servers with the same name", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - create.run(context(), "greeter", "", run, "hi", [ + ask.run(context(), "greeter", "", run, "hi", [ { name: "docs", url: "https://a/mcp" }, { name: "docs", url: "https://b/mcp" }, ] as never), @@ -304,7 +304,7 @@ describe("ai::agent::create", () => { describe("the agent loop", () => { it("runs the model sub flow and returns its answer", async () => { const { run, requests } = scriptedModel([answer("Hi there.")]); - const response = await create.run(context(), "greeter", "You greet people.", run, "hello"); + const response = await ask.run(context(), "greeter", "You greet people.", run, "hello"); expect(requests).toHaveLength(1); expect(requests[0].messages.map((m) => m.role)).toEqual(["system", "human"]); @@ -326,7 +326,7 @@ describe("the agent loop", () => { { type: "object", description: "Looks an order up.", properties: { order: { type: "string" } } }, ); - const response = await create.run(context(), "support", "", run, "where is A-1?", [lookup]); + const response = await ask.run(context(), "support", "", run, "where is A-1?", [lookup]); expect(requests[0].tools).toEqual([ { @@ -341,6 +341,62 @@ describe("the agent loop", () => { expect(replyOf(response)).toEqual("Order A-1 has shipped."); }); + it("advertises client tools and returns their call without executing them", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "view_knowledge_file", args: { path: "guide.md" } }]), + ]); + + const response = await ask.run( + context(), + "support", + "", + run, + "read the guide", + undefined, + undefined, + { + messages: [{ role: "user", content: "read the guide" }], + tools: [ + { + type: "function", + function: { + name: "view_knowledge_file", + description: "Read a file from the knowledge base.", + parameters: { + type: "object", + properties: { path: { type: "string" } }, + required: ["path"], + }, + }, + }, + ], + }, + ); + + expect(requests).toHaveLength(1); + expect(requests[0].tools).toEqual([ + { + name: "view_knowledge_file", + description: "Read a file from the knowledge base.", + input_schema: { + type: "object", + properties: { path: { type: "string" } }, + required: ["path"], + }, + }, + ]); + expect(response.choices[0].message).toMatchObject({ + role: "assistant", + tool_calls: [ + { + id: "call-1", + type: "function", + function: { name: "view_knowledge_file", arguments: '{"path":"guide.md"}' }, + }, + ], + }); + }); + it("reports a failing tool to the model instead of aborting the run", async () => { const { run, requests } = scriptedModel([ answer("", [{ id: "call-1", name: "tool_1", args: {} }]), @@ -350,7 +406,7 @@ describe("the agent loop", () => { throw new Error("the warehouse is offline"); }); - const response = await create.run(context(), "support", "", run, "status?", [broken]); + const response = await ask.run(context(), "support", "", run, "status?", [broken]); expect(JSON.stringify(requests[1].messages.at(-1)?.content)).toContain("the warehouse is offline"); expect(replyOf(response)).toEqual("That did not work."); @@ -374,7 +430,7 @@ describe("the agent loop", () => { }; }); - await create.run( + await ask.run( context(), "support", "", @@ -393,7 +449,7 @@ describe("the agent loop", () => { const { run, requests } = scriptedModel([answer("should not be reached")]); const block = subFlow(() => ({ jump_to: "end" })); - const response = await create.run( + const response = await ask.run( context(), "support", "", @@ -418,7 +474,7 @@ describe("the agent loop", () => { return null; }); - const response = await create.run( + const response = await ask.run( context(), "support", "", @@ -439,13 +495,13 @@ describe("the agent loop", () => { const lookup = subFlow(() => ({ status: "shipped" }), { type: "object", description: "Looks an order up." }); await expect( - create.run(context(), "support", "", run, "hello", [ + ask.run(context(), "support", "", run, "hello", [ lookup, { name: "docs", transport: "stdio" }, ] as never), ).rejects.toThrow(/needs a command/); - await create.run(context(), "support", "", run, "hello", [lookup]); + await ask.run(context(), "support", "", run, "hello", [lookup]); expect(requests[0].tools.map((t) => t.name)).toEqual(["tool_1"]); }); @@ -460,7 +516,7 @@ describe("the agent loop", () => { }); const nameless = subFlow(() => "nothing"); - await create.run(context(), "support", "", run, "hello", [now as never, nameless as never]); + await ask.run(context(), "support", "", run, "hello", [now as never, nameless as never]); expect(requests[0].tools).toEqual([ { @@ -486,7 +542,7 @@ describe("the agent loop", () => { ); const sameName = subFlow(() => null, asStruct({ title: "Look up order" }) as never); - await create.run(context(), "support", "", run, "hello", [lookup as never, sameName as never]); + await ask.run(context(), "support", "", run, "hello", [lookup as never, sameName as never]); expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Look_up_order", "Look_up_order_2"]); expect(requests[0].tools[0].description).toEqual("Looks an order up."); @@ -500,13 +556,13 @@ describe("the agent loop", () => { it("rejects a tool entry that is neither a sub flow nor an MCP server", async () => { const { run } = scriptedModel([answer("ok")]); await expect( - create.run(context(), "support", "", run, "hello", [{ nonsense: true }] as never), + ask.run(context(), "support", "", run, "hello", [{ nonsense: true }] as never), ).rejects.toThrow(/Entry 1 of "tools"/); }); it("fails with a clear error when the model sub flow answers with the wrong shape", async () => { const run = subFlow(() => ({ message: { role: "ai", content: "not a list" } })); - await expect(create.run(context(), "greeter", "", run, "hello")).rejects.toThrow( + await expect(ask.run(context(), "greeter", "", run, "hello")).rejects.toThrow( /did not return a valid model response/, ); }); @@ -521,7 +577,7 @@ describe("what a middleware flow is handed", () => { return {}; }); - await create.run(context(), "support", "You are helpful.", run, "hello", [], undefined, undefined, [observe]); + await ask.run(context(), "support", "You are helpful.", run, "hello", [], undefined, undefined, [observe]); expect(seen[0].context).toBeUndefined(); expect(Object.keys(seen[0])).toEqual(["messages", "agent_name", "hook"]); @@ -540,7 +596,7 @@ describe("composing the shipped functions into an agent", () => { : { role: "assistant" as const, content: `answer ${turn} ${"padding ".repeat(40)}` }, ); - const response = await create.run( + const response = await ask.run( context(), "support", "You are helpful.", diff --git a/actions/ai-action/test/approval.test.ts b/actions/ai-action/test/approval.test.ts index 160580a..ceb667c 100644 --- a/actions/ai-action/test/approval.test.ts +++ b/actions/ai-action/test/approval.test.ts @@ -3,13 +3,13 @@ import type { FunctionContext, SubFlow } from "@code0-tech/hercules"; import { describe, expect, it } from "vitest"; import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; -import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; import { HumanInTheLoopMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; import { askFor } from "../src/utils/middleware/Approval.askFor.util.js"; import { describeCall } from "../src/utils/middleware/Approval.describeCall.util.js"; import { newCode } from "../src/utils/middleware/Approval.newCode.util.js"; -const create = new CreateAgentFunction(); +const ask = new AskAgentFunction(); const humanInTheLoop = new HumanInTheLoopMiddlewareFunction(); /** @@ -74,7 +74,7 @@ function chat( conversation: Turn[], askBefore: string[] = ["refund"], ): Promise { - return create.run( + return ask.run( context(), "support", "You help.", diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts index 4ddcd80..d8f14f6 100644 --- a/actions/ai-action/test/functions.test.ts +++ b/actions/ai-action/test/functions.test.ts @@ -2,6 +2,9 @@ import "reflect-metadata"; import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; import { describe, expect, it, vi } from "vitest"; import { AIMessage } from "@langchain/core/messages"; +import { ChatAnthropic } from "@langchain/anthropic"; +import { ChatGroq } from "@langchain/groq"; +import { ChatOllama } from "@langchain/ollama"; import { ChatOpenAI } from "@langchain/openai"; import { toJsonSchema } from "@langchain/core/utils/json_schema"; import type { AiContentBlock } from "../src/datatypes/message/Message.contentBlock.datatype.js"; @@ -11,12 +14,20 @@ import type { AiModelRequest } from "../src/datatypes/model/Model.request.dataty import { AiModelResponseSchema, type AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; import { AiStateUpdateSchema } from "../src/datatypes/middleware/Middleware.stateUpdate.datatype.js"; import { TrimMessagesMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; +import { AnthropicModelFunction } from "../src/runtimefunctions/model/Model.anthropic.runtimefunction.js"; +import { GroqModelFunction } from "../src/runtimefunctions/model/Model.groq.runtimefunction.js"; +import { MistralModelFunction } from "../src/runtimefunctions/model/Model.mistral.runtimefunction.js"; +import { OllamaModelFunction } from "../src/runtimefunctions/model/Model.ollama.runtimefunction.js"; +import { OpenAiModelFunction } from "../src/runtimefunctions/model/Model.openAi.runtimefunction.js"; import { OpenRouterModelFunction } from "../src/runtimefunctions/model/Model.openRouter.runtimefunction.js"; -import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { McpServerFunction } from "../src/runtimefunctions/mcp/Mcp.server.runtimefunction.js"; +import { AiMcpServerSchema } from "../src/datatypes/mcp/Mcp.server.datatype.js"; const model = new OpenRouterModelFunction(); const middleware = new TrimMessagesMiddlewareFunction(); -const create = new CreateAgentFunction(); +const ask = new AskAgentFunction(); +const mcp = new McpServerFunction(); /** * Mirrors how hercules hands a sub flow function from one node to the next: the @@ -93,20 +104,18 @@ describe("ai::model::openrouter", () => { vi.restoreAllMocks(); }); - it("stops declaring that it can constrain its own output once that is switched off", () => { - const off = model.run(context(), "openai/gpt-oss-120b", "sk-or-test", undefined, undefined, undefined, false); - const on = model.run(context(), "openai/gpt-oss-120b", "sk-or-test"); - + it("declares that it can constrain its own output, which is how OpenRouter serves an output type", () => { // The declared request schema is what the agent reads to choose between // asking the provider for the type and binding it as a tool call. const properties = (schema: unknown): string[] => Object.keys((toJsonSchema(schema as never) as { properties?: object }).properties ?? {}); - expect(properties(off.inputSchema)).not.toContain("response_format"); - expect(properties(on.inputSchema)).toContain("response_format"); + expect(properties(model.run(context(), "openai/gpt-oss-120b", "sk-or-test").inputSchema)).toContain( + "response_format", + ); }); - it("ignores an output type once switched off, so a model that cannot do it is not asked to", async () => { + it("asks the provider for the output type the agent wants", async () => { const answer = new AIMessage("ok"); const invoke = vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(answer as never); const request = { @@ -115,13 +124,8 @@ describe("ai::model::openrouter", () => { response_format: { name: "extract", schema: { type: "object", properties: {} } }, }; - await model - .run(context(), "openai/gpt-oss-120b", "sk-or-test", undefined, undefined, undefined, false) - .run(request as never); - expect(invoke.mock.calls[0]?.[1]).not.toHaveProperty("response_format"); - await model.run(context(), "openai/gpt-oss-120b", "sk-or-test").run(request as never); - expect(invoke.mock.calls[1]?.[1]).toMatchObject({ response_format: { type: "json_schema" } }); + expect(invoke.mock.calls[0]?.[1]).toMatchObject({ response_format: { type: "json_schema" } }); vi.restoreAllMocks(); }); @@ -161,12 +165,12 @@ describe("ai::model::openrouter", () => { vi.restoreAllMocks(); }); - it("is accepted by ai::agent::create as the agent's model", async () => { + it("is accepted by ai::agent::ask as the agent's model", async () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); // Reaches the model, which rejects the test key - proof the agent accepted it. await expect( - create.run(context(), "support", "You are helpful.", asFlowValue(transform), "hi"), + ask.run(context(), "support", "You are helpful.", asFlowValue(transform), "hi"), ).rejects.toThrow(RuntimeError); }, 30_000); }); @@ -186,8 +190,13 @@ describe("ai::middleware::trim_messages", () => { expect(() => middleware.run(context(), Number.NaN)).toThrow(RuntimeError); }); - it("rejects a strategy it has no meaning for", () => { - expect(() => middleware.run(context(), 500, "middle")).toThrow(/not a trim strategy/); + it("rejects an end of the conversation it has no meaning for", () => { + expect(() => middleware.run(context(), 500, "middle")).toThrow(/not an end of the conversation/); + }); + + it("keeps the oldest messages when asked to, under either name for that end", () => { + expect(middleware.run(context(), 500, "oldest").name).toEqual("trim_messages:first:500"); + expect(middleware.run(context(), 500, "first").name).toEqual("trim_messages:first:500"); }); it("returns no change when the conversation already fits", async () => { @@ -205,8 +214,8 @@ describe("ai::middleware::trim_messages", () => { expect(parsed.messages!.at(-1)?.content).toEqual(before.messages.at(-1)?.content); }); - it("keeps the system prompt when it trims", async () => { - const update = await middleware.run(context(), 200, "last", true).run(state(12)); + it("keeps the instructions when it trims", async () => { + const update = await middleware.run(context(), 200, "newest", true).run(state(12)); const parsed = AiStateUpdateSchema.parse(update); expect(parsed.messages![0].role).toEqual("system"); }); @@ -222,6 +231,54 @@ describe("ai::middleware::trim_messages", () => { }); }); +describe("ai::mcp::server", () => { + it("describes a server the agent node can use as a tool", () => { + const server = mcp.run(context(), "tickets", "https://example.com/mcp", "token-1"); + + expect(() => AiMcpServerSchema.parse(server)).not.toThrow(); + expect(server.transport).toEqual("http"); + expect(server.url).toEqual("https://example.com/mcp"); + expect(server.headers).toEqual({ Authorization: "Bearer token-1" }); + }); + + it("reads the older protocol off the address, since nothing else announces it", () => { + expect(mcp.run(context(), "tickets", "https://example.com/sse").transport).toEqual("sse"); + expect(mcp.run(context(), "tickets", "https://example.com/mcp").transport).toEqual("http"); + }); + + it("sends what a server asked for on top of the access token", () => { + const server = mcp.run(context(), "tickets", "https://example.com/mcp", "token-1", { + "X-Api-Key": "key-1", + }); + + expect(server.headers).toEqual({ Authorization: "Bearer token-1", "X-Api-Key": "key-1" }); + }); + + it("reads headers that arrive as a protobuf struct, which is how a flow may hand them over", () => { + const server = mcp.run(context(), "tickets", "https://example.com/mcp", undefined, { + fields: { "X-Api-Key": { kind: { oneofKind: "stringValue", stringValue: "key-1" } } }, + }); + + expect(server.headers).toEqual({ "X-Api-Key": "key-1" }); + }); + + it("limits the agent to the tools that were named, and leaves it everything otherwise", () => { + const limited = mcp.run(context(), "tickets", "https://example.com/mcp", undefined, undefined, ["search"]); + + expect(limited.allowed_tools).toEqual(["search"]); + expect(mcp.run(context(), "tickets", "https://example.com/mcp").allowed_tools).toBeUndefined(); + }); + + it("fails on the node rather than when the agent starts working", () => { + expect(() => mcp.run(context(), "", "https://example.com/mcp")).toThrow(/needs a name/); + expect(() => mcp.run(context(), "tickets", "example.com/mcp")).toThrow(/not a web address/); + expect(() => mcp.run(context(), "tickets", "ftp://example.com/mcp")).toThrow(/http:\/\/ or https:\/\//); + expect(() => + mcp.run(context(), "tickets", "https://example.com/mcp", undefined, { "X-Api-Key": 1 }), + ).toThrow(/has to be a text/); + }); +}); + describe("the contracts the functions implement", () => { it("the model function's output is a valid AI_MODEL_RESPONSE", () => { expect(() => @@ -240,7 +297,7 @@ describe("the contracts the functions implement", () => { }); }); -describe("the chat format of ai::agent::create", () => { +describe("the chat format of ai::agent::ask", () => { function scriptedModel(responses: AiModelResponse[]) { const requests: AiModelRequest[] = []; let call = 0; @@ -270,7 +327,7 @@ describe("the chat format of ai::agent::create", () => { total_tokens: 14, }), ]); - const response = await create.run( + const response = await ask.run( context(), "greeter", "You greet people.", @@ -295,7 +352,7 @@ describe("the chat format of ai::agent::create", () => { it("translates a multimodal prompt into content blocks", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "A cat." }])]); - await create.run(context(), "describer", "", run, "", undefined, undefined, { + await ask.run(context(), "describer", "", run, "", undefined, undefined, { messages: [ { role: "user", @@ -319,7 +376,7 @@ describe("the chat format of ai::agent::create", () => { generation([{ type: "text", text: "Order A-1 has shipped." }]), ]); const lookup = (async () => ({ status: "shipped" })) as unknown as SubFlow; - const response = await create.run( + const response = await ask.run( context(), "support", "", @@ -354,7 +411,7 @@ describe("the chat format of ai::agent::create", () => { it("keeps a malformed tool call instead of failing the request", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - await create.run(context(), "support", "", run, "again?", undefined, undefined, { + await ask.run(context(), "support", "", run, "again?", undefined, undefined, { messages: [ { role: "assistant", @@ -377,14 +434,14 @@ describe("the chat format of ai::agent::create", () => { { type: "text", text: "Hi." }, ]), ]); - const response = await create.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", "", run, "hello"); expect(response.choices[0].message.content).toEqual("Hi."); }); it("takes just a prompt, with no request at all", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Hi." }])]); - const response = await create.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", "", run, "hello"); expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "hello" }]); expect(response.choices[0].message.content).toEqual("Hi."); @@ -392,7 +449,7 @@ describe("the chat format of ai::agent::create", () => { it("appends the prompt to the conversation the request carries", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Still fine." }])]); - await create.run(context(), "greeter", "", run, "and now?", undefined, undefined, { + await ask.run(context(), "greeter", "", run, "and now?", undefined, undefined, { messages: [ { role: "user", content: "how are you?" }, { role: "assistant", content: "fine" }, @@ -406,7 +463,7 @@ describe("the chat format of ai::agent::create", () => { it("carries the answer as plain text next to the OpenAI shape", async () => { const { run } = scriptedModel([generation([{ type: "text", text: "Two parts. " }, { type: "text", text: "One answer." }])]); - const response = await create.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", "", run, "hello"); expect(response.response).toEqual("Two parts. One answer."); expect(response.object).toEqual("chat.completion"); @@ -419,7 +476,7 @@ describe("the chat format of ai::agent::create", () => { ]); const lookup = (async () => ({ ok: true })) as unknown as SubFlow; - const response = await create.run(context(), "support", "", run, "hi", [lookup]); + const response = await ask.run(context(), "support", "", run, "hi", [lookup]); // The run ends on a text answer, so this one is filled; the tool-call-only // turn in between is what an empty `response` would come from. @@ -429,14 +486,141 @@ describe("the chat format of ai::agent::create", () => { it("rejects having nothing to ask", async () => { const { run } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - await expect(create.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + await expect(ask.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); await expect( - create.run(context(), "greeter", "", run, "", undefined, undefined, { messages: [] }), + ask.run(context(), "greeter", "", run, "", undefined, undefined, { messages: [] }), ).rejects.toThrow(/nothing to ask/); await expect( - create.run(context(), "greeter", "", run, "hi", undefined, undefined, { + ask.run(context(), "greeter", "", run, "hi", undefined, undefined, { messages: "nope", } as never), ).rejects.toThrow(/not valid/); }); }); + +/** + * What every model node has to get right, whichever provider it calls. + * + * The flow side of a model is the same everywhere - a request in, one message back - + * so what is worth testing per provider is the narrow part each one differs in: the + * dialect its output type is written in, and whether it claims to serve one at all. + */ +describe("the model nodes", () => { + const anthropic = new AnthropicModelFunction(); + const groq = new GroqModelFunction(); + const mistral = new MistralModelFunction(); + const ollama = new OllamaModelFunction(); + const openai = new OpenAiModelFunction(); + + const request = { + messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], + tools: [], + response_format: { name: "extract", schema: { type: "object", properties: {} } }, + }; + + /** The names of the fields the node declares it takes a request with. */ + const fields = (schema: unknown): string[] => + Object.keys((toJsonSchema(schema as never) as { properties?: object }).properties ?? {}); + + it("names its sub flow after the provider and the model", () => { + expect(openai.run(context(), "gpt-5", "sk-test").name).toEqual("openai:gpt-5"); + expect(anthropic.run(context(), "claude-opus-5", "sk-ant-test").name).toEqual("anthropic:claude-opus-5"); + expect(groq.run(context(), "llama-3.3-70b-versatile", "gsk-test").name).toEqual( + "groq:llama-3.3-70b-versatile", + ); + expect(mistral.run(context(), "mistral-large-latest", "test").name).toEqual("mistral:mistral-large-latest"); + expect(ollama.run(context(), "qwen3:8b").name).toEqual("ollama:qwen3:8b"); + }); + + it("needs a model identifier, and a key wherever the provider has one", () => { + expect(() => openai.run(context(), "", "sk-test")).toThrow(RuntimeError); + expect(() => openai.run(context(), "gpt-5", "")).toThrow(RuntimeError); + expect(() => anthropic.run(context(), "claude-opus-5", "")).toThrow(RuntimeError); + expect(() => groq.run(context(), "llama-3.3-70b-versatile", "")).toThrow(RuntimeError); + expect(() => mistral.run(context(), "mistral-large-latest", "")).toThrow(RuntimeError); + // Ollama is a server of your own, so there is no key to be missing. + expect(() => ollama.run(context(), "")).toThrow(RuntimeError); + expect(ollama.run(context(), "qwen3:8b").inputSchema).toBeDefined(); + }); + + it("declares an output type only where the provider can constrain the answer", () => { + expect(fields(openai.run(context(), "gpt-5", "sk-test").inputSchema)).toContain("response_format"); + expect(fields(anthropic.run(context(), "claude-opus-5", "sk-ant-test").inputSchema)).toContain( + "response_format", + ); + expect(fields(ollama.run(context(), "qwen3:8b").inputSchema)).toContain("response_format"); + + // Mistral's client takes a JSON mode but no schema, so this node cannot + // promise a constrained answer - and the agent reads that off the schema and + // asks for the type as a forced tool call instead. + expect(fields(mistral.run(context(), "mistral-large-latest", "test").inputSchema)).not.toContain( + "response_format", + ); + expect(fields(groq.run(context(), "openai/gpt-oss-120b", "gsk-test").inputSchema)).toContain( + "response_format", + ); + }); + + it("writes the asked-for output type in the provider's own dialect", async () => { + const answer = new AIMessage("ok"); + const openAiInvoke = vi.spyOn(ChatOpenAI.prototype, "invoke").mockResolvedValue(answer as never); + const anthropicInvoke = vi.spyOn(ChatAnthropic.prototype, "invoke").mockResolvedValue(answer as never); + const groqInvoke = vi.spyOn(ChatGroq.prototype, "invoke").mockResolvedValue(answer as never); + const ollamaInvoke = vi.spyOn(ChatOllama.prototype, "invoke").mockResolvedValue(answer as never); + + await openai.run(context(), "gpt-5", "sk-test").run(request as never); + await anthropic.run(context(), "claude-opus-5", "sk-ant-test").run(request as never); + await groq.run(context(), "openai/gpt-oss-120b", "gsk-test").run(request as never); + await ollama.run(context(), "qwen3:8b").run(request as never); + + expect(openAiInvoke.mock.calls[0]?.[1]).toMatchObject({ response_format: { type: "json_schema" } }); + expect(groqInvoke.mock.calls[0]?.[1]).toMatchObject({ response_format: { type: "json_schema" } }); + expect(anthropicInvoke.mock.calls[0]?.[1]).toMatchObject({ + outputConfig: { format: { type: "json_schema", schema: request.response_format.schema } }, + }); + expect(ollamaInvoke.mock.calls[0]?.[1]).toMatchObject({ format: request.response_format.schema }); + + vi.restoreAllMocks(); + }); + + it("hands the provider's own web search to the model only when it is switched on", async () => { + const answer = new AIMessage("ok"); + const bindTools = vi + .spyOn(ChatAnthropic.prototype, "bindTools") + .mockReturnValue({ invoke: async () => answer } as never); + vi.spyOn(ChatAnthropic.prototype, "invoke").mockResolvedValue(answer as never); + + await anthropic.run(context(), "claude-opus-5", "sk-ant-test").run(request as never); + expect(bindTools).not.toHaveBeenCalled(); + + await anthropic + .run(context(), "claude-opus-5", "sk-ant-test", undefined, undefined, true) + .run(request as never); + expect(bindTools).toHaveBeenCalledWith([{ type: "web_search_20250305", name: "web_search" }]); + + vi.restoreAllMocks(); + }); + + it("calls an OpenAI-compatible service where it was pointed instead of OpenAI", () => { + const transform = openai.run(context(), "qwen3-32b", "sk-test", "http://localhost:8000/v1"); + + expect(transform.name).toEqual("openai:qwen3-32b"); + expect(fields(transform.inputSchema)).toContain("response_format"); + }); + + it("is accepted by ai::agent::ask as the agent's model", async () => { + const answer = new AIMessage("ok"); + vi.spyOn(ChatAnthropic.prototype, "invoke").mockResolvedValue(answer as never); + + const response = await ask.run( + context(), + "support", + "You are helpful.", + asFlowValue(anthropic.run(context(), "claude-opus-5", "sk-ant-test")), + "hi", + ); + expect(response.choices[0]?.message.content).toContain("ok"); + + vi.restoreAllMocks(); + }); +}); diff --git a/actions/ai-action/test/openai.test.ts b/actions/ai-action/test/openai.test.ts index 367f843..a085ea1 100644 --- a/actions/ai-action/test/openai.test.ts +++ b/actions/ai-action/test/openai.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { AiChatRequest } from "../src/datatypes/chat/Chat.request.datatype.js"; import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; -import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; import { AiOpenAiServerRuntimeEvent } from "../src/runtimeevents/openai/OpenAi.server.runtimeevent.js"; import { OpenAiOpenWebUiFormattingFunction } from "../src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.js"; import { OpenAiRespondFunction } from "../src/runtimefunctions/openai/OpenAi.respond.runtimefunction.js"; @@ -181,7 +181,7 @@ describe("the OpenAI endpoint", () => { expect(response.status).toEqual(200); expect(calls.map((call) => call.flowId)).toEqual([2n]); - // The flow is handed the request itself, which is what ai::agent::create takes. + // The flow is handed the request itself, which is what ai::agent::ask takes. expect(calls[0].payload).toMatchObject({ messages: [{ role: "user", content: "hi" }] }); expect(body.response).toEqual("triage here"); // A client matches the answer against the model it asked for. @@ -353,7 +353,7 @@ describe("the flow a client ends up talking to", () => { // which is exactly what the flow's return value could not express. const after: string[] = []; const { url } = await serve([flow({ id: 1, slug: "acme", model: "support" })], async ({ executionId, payload }) => { - const answer = await new CreateAgentFunction().run( + const answer = await new AskAgentFunction().run( context(executionId) as never, "support", "You track orders.", diff --git a/actions/ai-action/test/registration.test.ts b/actions/ai-action/test/registration.test.ts index 3c64c4d..6986784 100644 --- a/actions/ai-action/test/registration.test.ts +++ b/actions/ai-action/test/registration.test.ts @@ -41,6 +41,25 @@ async function classesIn(folder: string, suffix: string): Promise { return found; } +/** The contents of every file in a folder that ends in the given suffix. */ +async function filesIn(folder: string, suffix: string): Promise<{ name: string; content: string }[]> { + const fs = await import("node:fs/promises"); + const root = new URL("../src/", import.meta.url); + const found: { name: string; content: string }[] = []; + + for (const entry of await fs.readdir(root, { recursive: true, withFileTypes: true })) { + if (!entry.isFile() || !entry.name.endsWith(suffix)) continue; + if (!entry.parentPath.includes(folder)) continue; + + found.push({ + name: entry.name, + content: await fs.readFile(new URL(`${entry.parentPath}/${entry.name}`, "file://"), "utf8"), + }); + } + + return found; +} + describe("what the action registers", () => { it("registers every runtime function it declares", async () => { const declared: string[] = await classesIn("runtimefunctions", ".runtimefunction.ts"); @@ -72,6 +91,65 @@ describe("what the action registers", () => { expect(source).toContain("RUNTIME_EVENTS.forEach((event) => action.registerRuntimeEventClass(event))"); }); + it("says what each runtime function is for", async () => { + // The description is the whole of what the editor can tell someone picking a + // node out of a list, so a node without one is a name and nothing else. + const files = await filesIn("runtimefunctions", ".runtimefunction.ts"); + + expect(files.length).toBeGreaterThan(0); + expect(files.filter((file) => !file.content.includes("@Description(")).map((file) => file.name)).toEqual([]); + }); + + it("keeps every signature inside what the platform stores", async () => { + // A signature is stored in a 500 character column, and one that overruns it is + // rejected when the action registers rather than when it is written. + const files = [ + ...(await filesIn("runtimefunctions", ".runtimefunction.ts")), + ...(await filesIn("runtimeevents", ".runtimeevent.ts")), + ]; + + for (const file of files) { + const signature: string = /@Signature\(\s*"((?:[^"\\]|\\.)*)"/s.exec(file.content)?.[1] ?? ""; + expect(signature.length, `${file.name} has no signature`).toBeGreaterThan(0); + expect(signature.length, `${file.name} has a signature of ${signature.length} characters`).toBeLessThan( + 500, + ); + } + }); + + it("keeps every description inside what the platform stores", async () => { + // Documentation is stored in a 200 character column - the node's own, every + // parameter's and every event setting's - and one that overruns it is rejected + // when the action registers rather than when it is written. + const files = [ + ...(await filesIn("runtimefunctions", ".runtimefunction.ts")), + ...(await filesIn("runtimeevents", ".runtimeevent.ts")), + ...(await filesIn("datatypes", ".datatype.ts")), + ]; + + for (const file of files) { + // Every translated text of a node is written as `content: "..."`, which is + // the node's own description as much as a parameter's. + for (const match of file.content.matchAll(/content:\s*"((?:[^"\\]|\\.)*)"/gs)) { + const text: string = match[1].replaceAll('\\"', '"'); + const label = `${file.name}: "${text.slice(0, 40)}..."`; + + expect(text.length, `${label} is ${text.length} characters`).toBeLessThanOrEqual(200); + } + } + }); + + it("keeps the action's own documentation inside what the platform stores", () => { + // The module's documentation shares that 200 character column, and it is the + // one text that lives in index.ts rather than next to a node. + const documentation: string = /new Action\((?:[^)]*?)"((?:[^"\\]|\\.){40,})"/s.exec(source)?.[1] ?? ""; + + expect(documentation.length, "index.ts has no documentation for the action").toBeGreaterThan(0); + expect(documentation.length, `the action's documentation is ${documentation.length} characters`).toBeLessThanOrEqual( + 200, + ); + }); + it("is read from the file that actually registers them", () => { // A guard for this test itself: a renamed Action constructor call would mean // the lists above are no longer what runs. diff --git a/actions/ai-action/test/skills.test.ts b/actions/ai-action/test/skills.test.ts new file mode 100644 index 0000000..1141f81 --- /dev/null +++ b/actions/ai-action/test/skills.test.ts @@ -0,0 +1,38 @@ +import "reflect-metadata"; +import { RuntimeError } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import { SkillsFunction } from "../src/runtimefunctions/agent/Agent.skills.runtimefunction.js"; + +const skills = new SkillsFunction(); +const context = {} as never; + +describe("ai::agent::skills", () => { + it("creates a named tool that returns the complete Markdown skill", async () => { + const tool = skills.run(context, [ + "Intro text\n\n## SQL Analysis ##\n\nUse the query plan.", + "Customer Support\n================\n\nBe concise.", + ]); + + expect(tool.name).toEqual("use_skill"); + expect(tool.description).toContain("SQL Analysis"); + expect(tool.inputSchema).toMatchObject({ + properties: { title: { enum: ["SQL Analysis", "Customer Support"] } }, + }); + await expect(tool.run({ title: "sql analysis" } as never)).resolves.toContain("Use the query plan."); + await expect(tool.run({ title: "sql analysis" } as never)).resolves.toContain("## SQL Analysis ##"); + }); + + it("accepts headings at any Markdown level and ignores fenced examples", async () => { + const tool = skills.run(context, ["```md\n# Not the title\n```\n\n### Actual title\n\nBody"]); + + await expect(tool.run({ title: "Actual title" } as never)).resolves.toContain("Body"); + }); + + it("rejects missing titles, duplicate titles, and unknown requests", async () => { + expect(() => skills.run(context, ["No heading here"])).toThrow(RuntimeError); + expect(() => skills.run(context, ["# Same\none", "## same\ntwo"])).toThrow(/titles must be unique/); + + const tool = skills.run(context, ["# Known\nbody"]); + await expect(tool.run({ title: "Missing" } as never)).rejects.toThrow(/There is no skill titled/); + }); +}); From 4b0b8f546db27fc1fe8e79ac8ed80daa05320035 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 9 Nov 2026 14:52:10 +0100 Subject: [PATCH 15/19] feat: update AI agent description for clarity and bump @code0-tech/hercules and @code0-tech/tucana dependencies to latest versions --- actions/ai-action/manifest.json | 2 +- actions/ai-action/package-lock.json | 16 ++++++++-------- actions/ai-action/package.json | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/actions/ai-action/manifest.json b/actions/ai-action/manifest.json index 7701645..fb32089 100644 --- a/actions/ai-action/manifest.json +++ b/actions/ai-action/manifest.json @@ -1,7 +1,7 @@ { "name": "ai", "identifier": "ai-action", - "description": "AI agent integration: build LangChain agents from a model, tools (flows and MCP servers), middleware and a system prompt.", + "description": "AI agents built from what the project already has: the model they think with, the flows and MCP servers they use as tools, and the rules they follow.", "deployment": { "docker": { "image": "ghcr.io/code0-tech/centaurus/ci-builds/ai-action" diff --git a/actions/ai-action/package-lock.json b/actions/ai-action/package-lock.json index f1de115..d9aae34 100644 --- a/actions/ai-action/package-lock.json +++ b/actions/ai-action/package-lock.json @@ -8,7 +8,7 @@ "name": "@code0-tech/ai-action", "version": "1.0.0", "dependencies": { - "@code0-tech/hercules": "^1.8.0", + "@code0-tech/hercules": "^1.9.0", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", @@ -84,15 +84,15 @@ } }, "node_modules/@code0-tech/hercules": { - "version": "1.8.0", - "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.8.0.tgz", - "integrity": "sha512-0zIDkZoPneZP5a0wPjJEnOLMTTvJ6JeAco9JFVXzkui+S69g2WDFX92V8rm+29sIPorzgxy4Nvnn8M9TFhcF7A==", + "version": "1.9.0", + "resolved": "https://registry.npmjs.org/@code0-tech/hercules/-/hercules-1.9.0.tgz", + "integrity": "sha512-Hd5MzOz+qT+3HF0nUHNIHMPVlXwogOmtZp4guiTlo5cW/x/i5sBWs9PB6VX6aKjsNbDmPehNR+PzpB45Ncl4NA==", "license": "ISC", "bin": { "hercules": "bin/hercules.js" }, "peerDependencies": { - "@code0-tech/tucana": "0.0.84", + "@code0-tech/tucana": "0.0.86", "@grpc/grpc-js": "^1.14.3", "@protobuf-ts/grpc-backend": "^2.11.1", "@protobuf-ts/grpc-transport": "^2.11.1", @@ -106,9 +106,9 @@ } }, "node_modules/@code0-tech/tucana": { - "version": "0.0.84", - "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.84.tgz", - "integrity": "sha512-Rom4uDDrfRaC6YyLlxdqAmMDe4n6OuEdtzBukidYJXwIrMkz626/9sKZ9gSmqdCq0FfHEb3R+PpFbpg7KClEEw==", + "version": "0.0.86", + "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.86.tgz", + "integrity": "sha512-CUIjP837mXM8T6ILwRCZNKTTARt/i12JxjQw3YPB03Hn2L96aineDVOE4XxjxCRzMJRE9+aZZtwh0jZuzbKWVg==", "license": "MIT", "peer": true }, diff --git a/actions/ai-action/package.json b/actions/ai-action/package.json index 2dd8cf7..cc155c2 100644 --- a/actions/ai-action/package.json +++ b/actions/ai-action/package.json @@ -12,7 +12,7 @@ "start": "node dist/index.js" }, "dependencies": { - "@code0-tech/hercules": "^1.8.0", + "@code0-tech/hercules": "^1.9.0", "@langchain/anthropic": "^1.0.0", "@langchain/core": "^1.0.0", "@langchain/groq": "^1.0.0", From 9b99c73b5e6f3f8be930a83ae359bf8ab5553df9 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Fri, 13 Nov 2026 07:31:27 +0100 Subject: [PATCH 16/19] feat: enhance title handling in skills function with improved title extraction and uniqueness checks --- .../agent/Agent.ask.runtimefunction.ts | 7 +- .../agent/Agent.skills.runtimefunction.ts | 146 ++++++++++++++---- .../src/utils/model/Model.toTransform.util.ts | 10 +- actions/ai-action/test/agent.test.ts | 4 +- actions/ai-action/test/functions.test.ts | 18 ++- actions/ai-action/test/skills.test.ts | 48 +++++- 6 files changed, 189 insertions(+), 44 deletions(-) diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts index 20bf911..b731943 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts @@ -402,7 +402,12 @@ export class AskAgentFunction { (named?.enumerable ? named.value : undefined) ?? schema?.title ?? schema?.name; const cleaned: string = typeof declared === "string" - ? declared.trim().replace(TOOL_NAME_ALLOWED, "_").replace(/^_+|_+$/g, "").slice(0, 64) + ? declared + .trim() + .toLowerCase() + .replace(TOOL_NAME_ALLOWED, "_") + .replace(/^_+|_+$/g, "") + .slice(0, 64) : ""; let toolName: string = cleaned.length > 0 ? cleaned : `tool_${index + 1}`; if (taken.has(toolName)) { diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts index aa262d8..8395828 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts @@ -22,18 +22,69 @@ interface Skill { const TITLE_KEY = (title: string): string => title.normalize("NFKC").trim().toLocaleLowerCase(); +const TITLE_LIMIT = 80; + +const FENCE = /^\s{0,3}(?:```|~~~)/; +const BREAK = /^\s{0,3}(?:-{3,}|\*{3,}|_{3,})\s*$/; +const SETEXT = /^\s{0,3}(?:=+|-+)\s*$/; + +/** + * Turns one line into a plain title: list markers, quotes and inline Markdown + * are dropped so the title reads like text instead of markup. + */ +function plainTitle(line: string): string { + return line + .replace(/^\s{0,3}>+\s*/, "") + .replace(/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s+/, "") + .replace(/^\s{0,3}#{1,6}\s*/, "") + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[`*_~]+/g, "") + .replace(/\s*#+\s*$/, "") + .replace(/\s+/g, " ") + .trim(); +} + +function shorten(title: string): string { + if (title.length <= TITLE_LIMIT) return title; + const cut: string = title.slice(0, TITLE_LIMIT); + const space: number = cut.lastIndexOf(" "); + return `${(space > TITLE_LIMIT / 2 ? cut.slice(0, space) : cut).trimEnd()}…`; +} + +/** + * Reads a leading YAML front matter block and returns its title, plus the line + * the document itself starts on. + */ +function frontMatter(lines: string[]): { title?: string; body: number } { + if (!/^---\s*$/.test(lines[0] ?? "")) return { body: 0 }; + + for (let line = 1; line < lines.length; line += 1) { + if (!/^(?:---|\.\.\.)\s*$/.test(lines[line])) continue; + + const keys: string[] = lines.slice(1, line); + const entry: string | undefined = + keys.find((candidate) => /^\s*title\s*:/i.test(candidate)) ?? + keys.find((candidate) => /^\s*name\s*:/i.test(candidate)); + const value: string = plainTitle( + (entry ?? "").replace(/^[^:]*:\s*/, "").replace(/^["']|["']$/g, ""), + ); + return { title: value.length > 0 ? value : undefined, body: line + 1 }; + } + + return { body: 0 }; +} + /** * Finds the first Markdown heading, accepting ATX headings at any level and the * older setext form. Fenced code blocks are skipped so an example heading cannot * become the skill's title. */ -function titleOf(markdown: string, index: number): string { - const lines: string[] = markdown.replace(/^\uFEFF/, "").split(/\r?\n/); +function headingTitle(lines: string[]): string | undefined { let fenced = false; for (let line = 0; line < lines.length; line += 1) { const current: string = lines[line]; - if (/^\s{0,3}(```|~~~)/.test(current)) { + if (FENCE.test(current)) { fenced = !fenced; continue; } @@ -41,20 +92,69 @@ function titleOf(markdown: string, index: number): string { const atx = current.match(/^\s{0,3}#{1,6}(?:\s+|$)(.*?)\s*#*\s*$/); if (atx) { - const title: string = atx[1].trim(); + const title: string = plainTitle(atx[1]); if (title.length > 0) return title; } const next: string | undefined = lines[line + 1]; - if (current.trim().length > 0 && next && /^\s{0,3}(=+|-+)\s*$/.test(next)) { - return current.trim(); + if (current.trim().length > 0 && next !== undefined && SETEXT.test(next)) { + const title: string = plainTitle(current); + if (title.length > 0) return title; + } + } + + return undefined; +} + +/** Falls back to the first line that carries readable text. */ +function firstTextTitle(lines: string[], skipFenced: boolean): string | undefined { + let fenced = false; + + for (const current of lines) { + if (FENCE.test(current)) { + fenced = !fenced; + continue; } + if (skipFenced && fenced) continue; + if (current.trim().length === 0 || BREAK.test(current) || SETEXT.test(current)) continue; + + const title: string = plainTitle(current); + if (title.length > 0) return title; } - throw new RuntimeError( - "ERROR_INVALID_AI_SKILL", - `Skill ${index + 1} has no Markdown heading to use as its title.`, - ); + return undefined; +} + +/** + * Derives a title from any Markdown text: a front matter title, otherwise the + * first heading, otherwise the first readable line, and a numbered name as the + * last resort. Text always yields a title. + */ +function titleOf(markdown: string, index: number): string { + const lines: string[] = markdown.replace(/^/, "").split(/\r?\n/); + const front: { title?: string; body: number } = frontMatter(lines); + const body: string[] = lines.slice(front.body); + + const title: string | undefined = + front.title ?? + headingTitle(body) ?? + firstTextTitle(body, true) ?? + firstTextTitle(lines, false); + + return shorten(title ?? `Skill ${index + 1}`); +} + +/** + * Keeps titles distinct without failing: a repeated title is numbered, so the + * agent still sees one entry per skill. + */ +function unique(title: string, taken: Set): string { + if (!taken.has(TITLE_KEY(title))) return title; + + for (let copy = 2; ; copy += 1) { + const candidate = `${title} (${copy})`; + if (!taken.has(TITLE_KEY(candidate))) return candidate; + } } function skillInput(input: unknown): string { @@ -62,12 +162,12 @@ function skillInput(input: unknown): string { if (typeof input !== "object" || input === null) { throw new RuntimeError( "ERROR_INVALID_AI_SKILL", - 'The "use_skill" tool needs an object with a "title" text.', + 'The "Use a skill" tool needs an object with a "title" text.', ); } const title: unknown = (input as { title?: unknown }).title; - return requireText(title, "ERROR_INVALID_AI_SKILL", 'The "title" argument of "use_skill" is required.'); + return requireText(title, "ERROR_INVALID_AI_SKILL", 'The "title" argument of "Use a skill" is required.'); } @Identifier("ai::agent::skills") @@ -89,37 +189,29 @@ function skillInput(input: unknown): string { { code: "en-US", content: - "Markdown documents the agent can load by their first heading. Every document needs a title, and titles must be unique.", + "Markdown documents the agent can load. A title is taken from the front matter, the first heading or the first line of text. Repeated titles get numbered.", }, ], }) export class SkillsFunction { run(_context: FunctionContext, skills: unknown[]): SubFlowFunctionDefinition { + const taken = new Set(); const entries: Skill[] = asList(skills, "skills").map((skill, index) => { const markdown: string = requireText( skill, "ERROR_INVALID_AI_SKILL", `Entry ${index + 1} of "skills" has to be a Markdown text.`, ); - return { title: titleOf(markdown, index), markdown }; - }); - - const seen = new Set(); - entries.forEach((skill) => { - const key: string = TITLE_KEY(skill.title); - if (seen.has(key)) { - throw new RuntimeError( - "ERROR_INVALID_AI_SKILL", - `More than one skill is titled "${skill.title}". Skill titles must be unique.`, - ); - } - seen.add(key); + const title: string = unique(titleOf(markdown, index), taken); + taken.add(TITLE_KEY(title)); + return { title, markdown }; }); const byTitle = new Map(entries.map((skill) => [TITLE_KEY(skill.title), skill.markdown])); const titles: string[] = entries.map((skill) => skill.title); return { - name: "use_skill", + // A readable name; the agent turns it into a tool name a model accepts. + name: "Use a skill", description: `Loads a Markdown skill by title. Available skills: ${titles.join(", ")}.`, inputSchema: { type: "object", diff --git a/actions/ai-action/src/utils/model/Model.toTransform.util.ts b/actions/ai-action/src/utils/model/Model.toTransform.util.ts index 5f06f9f..f246614 100644 --- a/actions/ai-action/src/utils/model/Model.toTransform.util.ts +++ b/actions/ai-action/src/utils/model/Model.toTransform.util.ts @@ -41,7 +41,7 @@ type BoundModel = Runnable => { diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts index e159a1e..ffcbdee 100644 --- a/actions/ai-action/test/agent.test.ts +++ b/actions/ai-action/test/agent.test.ts @@ -520,7 +520,7 @@ describe("the agent loop", () => { expect(requests[0].tools).toEqual([ { - name: "Current_time", + name: "current_time", description: "Answers with the current time in microseconds.", input_schema: { $schema: "https://json-schema.org/draft/2020-12/schema", @@ -544,7 +544,7 @@ describe("the agent loop", () => { await ask.run(context(), "support", "", run, "hello", [lookup as never, sameName as never]); - expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Look_up_order", "Look_up_order_2"]); + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["look_up_order", "look_up_order_2"]); expect(requests[0].tools[0].description).toEqual("Looks an order up."); expect(requests[0].tools[0].input_schema).toEqual({ title: "Look up order", diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts index d8f14f6..f2067da 100644 --- a/actions/ai-action/test/functions.test.ts +++ b/actions/ai-action/test/functions.test.ts @@ -63,7 +63,7 @@ describe("ai::model::openrouter", () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); expect(typeof transform.run).toEqual("function"); - expect(transform.name).toEqual("openrouter:anthropic/claude-opus-5"); + expect(transform.name).toEqual("OpenRouter model anthropic/claude-opus-5"); expect(transform.inputSchema).toBeDefined(); expect(transform.outputSchema).toBeDefined(); }); @@ -523,13 +523,17 @@ describe("the model nodes", () => { Object.keys((toJsonSchema(schema as never) as { properties?: object }).properties ?? {}); it("names its sub flow after the provider and the model", () => { - expect(openai.run(context(), "gpt-5", "sk-test").name).toEqual("openai:gpt-5"); - expect(anthropic.run(context(), "claude-opus-5", "sk-ant-test").name).toEqual("anthropic:claude-opus-5"); + expect(openai.run(context(), "gpt-5", "sk-test").name).toEqual("OpenAI model gpt-5"); + expect(anthropic.run(context(), "claude-opus-5", "sk-ant-test").name).toEqual( + "Anthropic model claude-opus-5", + ); expect(groq.run(context(), "llama-3.3-70b-versatile", "gsk-test").name).toEqual( - "groq:llama-3.3-70b-versatile", + "Groq model llama-3.3-70b-versatile", + ); + expect(mistral.run(context(), "mistral-large-latest", "test").name).toEqual( + "Mistral model mistral-large-latest", ); - expect(mistral.run(context(), "mistral-large-latest", "test").name).toEqual("mistral:mistral-large-latest"); - expect(ollama.run(context(), "qwen3:8b").name).toEqual("ollama:qwen3:8b"); + expect(ollama.run(context(), "qwen3:8b").name).toEqual("Ollama model qwen3:8b"); }); it("needs a model identifier, and a key wherever the provider has one", () => { @@ -604,7 +608,7 @@ describe("the model nodes", () => { it("calls an OpenAI-compatible service where it was pointed instead of OpenAI", () => { const transform = openai.run(context(), "qwen3-32b", "sk-test", "http://localhost:8000/v1"); - expect(transform.name).toEqual("openai:qwen3-32b"); + expect(transform.name).toEqual("OpenAI model qwen3-32b"); expect(fields(transform.inputSchema)).toContain("response_format"); }); diff --git a/actions/ai-action/test/skills.test.ts b/actions/ai-action/test/skills.test.ts index 1141f81..681afec 100644 --- a/actions/ai-action/test/skills.test.ts +++ b/actions/ai-action/test/skills.test.ts @@ -13,7 +13,7 @@ describe("ai::agent::skills", () => { "Customer Support\n================\n\nBe concise.", ]); - expect(tool.name).toEqual("use_skill"); + expect(tool.name).toEqual("Use a skill"); expect(tool.description).toContain("SQL Analysis"); expect(tool.inputSchema).toMatchObject({ properties: { title: { enum: ["SQL Analysis", "Customer Support"] } }, @@ -28,9 +28,49 @@ describe("ai::agent::skills", () => { await expect(tool.run({ title: "Actual title" } as never)).resolves.toContain("Body"); }); - it("rejects missing titles, duplicate titles, and unknown requests", async () => { - expect(() => skills.run(context, ["No heading here"])).toThrow(RuntimeError); - expect(() => skills.run(context, ["# Same\none", "## same\ntwo"])).toThrow(/titles must be unique/); + it("prefers a front matter title over the body", async () => { + const tool = skills.run(context, ["---\nname: Billing\ntitle: Refund policy\n---\n\n# Body heading\n\nText"]); + + expect(tool.inputSchema).toMatchObject({ properties: { title: { enum: ["Refund policy"] } } }); + await expect(tool.run({ title: "refund policy" } as never)).resolves.toContain("Text"); + }); + + it("derives a title from plain text without any heading", async () => { + const tool = skills.run(context, [ + "- **Escalation** rules for [support](https://example.com)\nmore", + "```\nonly fenced content\n```", + "***", + ]); + + expect(tool.inputSchema).toMatchObject({ + properties: { + title: { enum: ["Escalation rules for support", "only fenced content", "Skill 3"] }, + }, + }); + }); + + it("shortens very long titles", () => { + const tool = skills.run(context, [`# ${"word ".repeat(40)}`]); + const [title] = (tool.inputSchema as { properties: { title: { enum: string[] } } }).properties + .title.enum; + + expect(title.length).toBeLessThanOrEqual(81); + expect(title.endsWith("\u2026")).toBe(true); + }); + + it("numbers repeated titles instead of failing", async () => { + const tool = skills.run(context, ["# Same\none", "## same\ntwo", "Same\n---\nthree"]); + + expect(tool.inputSchema).toMatchObject({ + properties: { title: { enum: ["Same", "same (2)", "Same (3)"] } }, + }); + await expect(tool.run({ title: "Same" } as never)).resolves.toContain("one"); + await expect(tool.run({ title: "same (2)" } as never)).resolves.toContain("two"); + await expect(tool.run({ title: "same (3)" } as never)).resolves.toContain("three"); + }); + + it("rejects empty entries and unknown requests", async () => { + expect(() => skills.run(context, [" "])).toThrow(RuntimeError); const tool = skills.run(context, ["# Known\nbody"]); await expect(tool.run({ title: "Missing" } as never)).rejects.toThrow(/There is no skill titled/); From a196335bc1cdaef471dfa584297db9bfefe9d1ff Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 23 Nov 2026 10:58:25 +0100 Subject: [PATCH 17/19] feat: remove prefix from model transformation functions and rename skills function to tool function --- actions/ai-action/src/index.ts | 52 +----- .../src/model/Model.flowChatModel.ts | 18 +- .../openai/OpenAi.server.runtimeevent.ts | 2 +- ...ion.ts => Agent.create.runtimefunction.ts} | 95 +--------- .../Extract.information.runtimefunction.ts | 169 +++++++++++++++++ ...ddleware.humanInTheLoop.runtimefunction.ts | 12 -- .../model/Model.anthropic.runtimefunction.ts | 1 - .../model/Model.groq.runtimefunction.ts | 1 - .../model/Model.liteLlm.runtimefunction.ts | 1 - .../model/Model.mistral.runtimefunction.ts | 1 - .../model/Model.ollama.runtimefunction.ts | 1 - .../model/Model.openAi.runtimefunction.ts | 1 - .../model/Model.openRouter.runtimefunction.ts | 1 - ...nAi.openWebUiFormatting.runtimefunction.ts | 10 +- .../openai/OpenAi.respond.runtimefunction.ts | 12 +- .../Tool.skills.runtimefunction.ts} | 2 +- .../src/server/openai/OpenAi.server.ts | 133 ++------------ .../src/server/openai/OpenAi.startServer.ts | 6 +- .../ai-action/src/types/shared/Log.types.ts | 15 -- .../src/utils/model/Model.toTransform.util.ts | 35 +--- .../src/utils/openai/OpenAi.pending.util.ts | 6 - .../src/utils/openai/OpenAi.sendJson.util.ts | 4 +- .../utils/openai/OpenAi.toEndpoints.util.ts | 16 +- .../utils/shared/Log.describeValue.util.ts | 28 --- .../src/utils/shared/Log.emit.util.ts | 38 ---- .../src/utils/shared/Log.logger.util.ts | 18 -- actions/ai-action/test/agent.test.ts | 6 +- actions/ai-action/test/approval.test.ts | 4 +- actions/ai-action/test/extract.test.ts | 171 ++++++++++++++++++ actions/ai-action/test/functions.test.ts | 10 +- actions/ai-action/test/log.test.ts | 86 --------- actions/ai-action/test/openai.test.ts | 6 +- actions/ai-action/test/skills.test.ts | 4 +- 33 files changed, 406 insertions(+), 559 deletions(-) rename actions/ai-action/src/runtimefunctions/agent/{Agent.ask.runtimefunction.ts => Agent.create.runtimefunction.ts} (87%) create mode 100644 actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts rename actions/ai-action/src/runtimefunctions/{agent/Agent.skills.runtimefunction.ts => tool/Tool.skills.runtimefunction.ts} (99%) delete mode 100644 actions/ai-action/src/types/shared/Log.types.ts delete mode 100644 actions/ai-action/src/utils/shared/Log.describeValue.util.ts delete mode 100644 actions/ai-action/src/utils/shared/Log.emit.util.ts delete mode 100644 actions/ai-action/src/utils/shared/Log.logger.util.ts create mode 100644 actions/ai-action/test/extract.test.ts delete mode 100644 actions/ai-action/test/log.test.ts diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts index 2eadaaf..70aad83 100644 --- a/actions/ai-action/src/index.ts +++ b/actions/ai-action/src/index.ts @@ -33,8 +33,9 @@ import { AiModelResponseDataType } from "./datatypes/model/Model.response.dataty import { AiResponseFormatDataType } from "./datatypes/model/Model.responseFormat.datatype.js"; import { AiToolSpecDataType } from "./datatypes/model/Model.toolSpec.datatype.js"; -import { AskAgentFunction } from "./runtimefunctions/agent/Agent.ask.runtimefunction.js"; -import { SkillsFunction } from "./runtimefunctions/agent/Agent.skills.runtimefunction.js"; +import { CreateAgentFunction } from "./runtimefunctions/agent/Agent.create.runtimefunction.js"; +import { SkillsFunction } from "./runtimefunctions/tool/Tool.skills.runtimefunction.js"; +import { ExtractInformationFunction } from "./runtimefunctions/extract/Extract.information.runtimefunction.js"; import { McpServerFunction } from "./runtimefunctions/mcp/Mcp.server.runtimefunction.js"; import { HumanInTheLoopMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; import { TrimMessagesMiddlewareFunction } from "./runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; @@ -52,13 +53,9 @@ import { OpenAiRespondFunction } from "./runtimefunctions/openai/OpenAi.respond. import { AiOpenAiServerRuntimeEvent } from "./runtimeevents/openai/OpenAi.server.runtimeevent.js"; import { startOpenAiServer } from "./server/openai/OpenAi.startServer.js"; -import type { ActionExecutionRequest, ActionFlow } from "@code0-tech/tucana/aquila"; - import { connectToAquila } from "./utils/shared/Shared.connectToAquila.util.js"; -import { logger } from "./utils/shared/Log.logger.util.js"; const RECONNECT_DELAY_MS = 5000; -const log = logger("action"); const DATA_TYPES: DataTypeClass[] = [ AiMessageRoleDataType, @@ -94,8 +91,9 @@ const DATA_TYPES: DataTypeClass[] = [ ]; const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ - AskAgentFunction, + CreateAgentFunction, SkillsFunction, + ExtractInformationFunction, McpServerFunction, HumanInTheLoopMiddlewareFunction, OpenAiOpenWebUiFormattingFunction, @@ -114,7 +112,7 @@ const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ const RUNTIME_EVENTS: RuntimeEventClass[] = [AiOpenAiServerRuntimeEvent]; const action = new Action( - process.env.ACTION_ID ?? "testing-action", + process.env.ACTION_ID ?? "ai-action", process.env.VERSION ?? "1.0.0", process.env.AQUILA_URL ?? "127.0.0.1:8081", "code0-tech", @@ -127,44 +125,10 @@ DATA_TYPES.forEach((dataType) => action.registerDataTypeClass(dataType)); RUNTIME_FUNCTIONS.forEach((runtimeFunction) => action.registerRuntimeFunction(runtimeFunction)); RUNTIME_EVENTS.forEach((event) => action.registerRuntimeEventClass(event)); -action.on(CodeZeroEvent.connected, () => { - log.info("connected to aquila", { - data_types: DATA_TYPES.length, - runtime_functions: RUNTIME_FUNCTIONS.length, - runtime_events: RUNTIME_EVENTS.length, - flows: action.flows.size, - }); -}); - -action.on(CodeZeroEvent.error, (error: Error) => { - log.error(`stream error, reconnecting in ${RECONNECT_DELAY_MS / 1000}s`, { error: error.message }); +action.on(CodeZeroEvent.error, () => { setTimeout(() => connectToAquila(action), RECONNECT_DELAY_MS); }); -// Which flows the action knows decides what the OpenAI endpoint serves, so every -// change to the registry is logged: a client finding no model is answered here. -action.on(CodeZeroEvent.flowUpdated, (flow: ActionFlow) => { - log.info(`flow ${flow.flowId} of project ${flow.projectSlug} is bound to ${flow.type}`, { - name: flow.name, - settings: flow.settings.map((setting: { flowSettingId: string }) => setting.flowSettingId), - }); -}); - -action.on(CodeZeroEvent.flowDeleted, (flowId: bigint) => { - log.info(`flow ${flowId} is gone`, { flows: action.flows.size }); -}); - -action.on(CodeZeroEvent.executionRequestReceived, (request: ActionExecutionRequest) => { - log.debug("aquila asks for an execution", { - execution_id: request.executionIdentifier, - function: request.functionIdentifier, - }); -}); - -action.on(CodeZeroEvent.moduleUpdated, () => { - log.debug("the module configuration was updated"); -}); - connectToAquila(action); // The action serves the OpenAI protocol itself: the server answers on its own port and @@ -175,8 +139,6 @@ startOpenAiServer({ reserveExecutionId: () => action.reserveExecutionId(), executeFlowWithId: (executionId: string, flowId: bigint, payload: PlainValue) => action.executeFlowWithId(executionId, flowId, payload), -}).catch((error: unknown) => { - console.error("Could not start the OpenAI endpoint:", error instanceof Error ? error.message : error); }); export { action }; diff --git a/actions/ai-action/src/model/Model.flowChatModel.ts b/actions/ai-action/src/model/Model.flowChatModel.ts index f172a78..29c487b 100644 --- a/actions/ai-action/src/model/Model.flowChatModel.ts +++ b/actions/ai-action/src/model/Model.flowChatModel.ts @@ -19,14 +19,11 @@ import { parseOrThrow } from "../utils/shared/Shared.parseOrThrow.util.js"; import { stripUndefined } from "../utils/shared/Shared.stripUndefined.util.js"; import { toFlowMessage } from "../utils/message/Message.toFlowMessage.util.js"; import { toLangChainMessage } from "../utils/message/Message.toLangChainMessage.util.js"; -import { logger } from "../utils/shared/Log.logger.util.js"; import { emptyJsonSchema } from "../utils/shared/Shared.emptyJsonSchema.util.js"; import { toPlainSchema } from "../utils/shared/Shared.toPlainSchema.util.js"; type BoundFlowChatModel = Runnable; -const log = logger("model"); - interface FlowChatModelFields { run: SubFlow; toolSpecs?: AiToolSpec[]; @@ -144,10 +141,6 @@ export class FlowChatModel extends BaseChatModel { input_schema: inputSchema, }); }); - log.debug( - `${specs.length} tools are bound to the model`, - specs.map((spec) => spec.name), - ); return new FlowChatModel({ run: this.run, toolSpecs: specs, @@ -169,16 +162,7 @@ export class FlowChatModel extends BaseChatModel { ...(responseFormat ? { response_format: responseFormat } : {}), }; - log.debug(`calling the model sub flow with ${request.messages.length} messages`, request); - - const started: number = Date.now(); - const raw: unknown = await this.run(request as never).catch((error: unknown) => { - log.error(`the model sub flow failed after ${Date.now() - started}ms`, { - error: error instanceof Error ? error.message : String(error), - }); - throw error; - }); - log.debug(`the model sub flow answered after ${Date.now() - started}ms with`, raw); + const raw: unknown = await this.run(request as never); const answer = parseOrThrow( AiModelResponseSchema, diff --git a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts index 2394fb5..6d363cd 100644 --- a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts +++ b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts @@ -18,7 +18,7 @@ import { * matching flow for `POST /chat/completions`. * * The flow is handed the client's request as an `AI_CHAT_REQUEST` - the type - * `ai::agent::ask` takes - and answers it with `ai::openai::respond`, from wherever + * `ai::agent::create` takes - and answers it with `ai::openai::respond`, from wherever * in the flow that belongs, so a flow that logs or stores something after the agent * still answers with the agent's reply. A flow that never responds falls back to its * own return value. diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts similarity index 87% rename from actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts rename to actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts index b731943..b333b2f 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.ask.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts @@ -29,7 +29,6 @@ import { import { AiMcpServerSchema, type AiMcpServer } from "../../datatypes/mcp/Mcp.server.datatype.js"; import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; import type { AgentDefinition, ToolEntry } from "../../types/agent/Agent.types.js"; -import type { Logger } from "../../types/shared/Log.types.js"; import { asList } from "../../utils/shared/Shared.asList.util.js"; import { asSubFlow } from "../../utils/shared/Shared.asSubFlow.util.js"; import { asText } from "../../utils/shared/Shared.asText.util.js"; @@ -42,7 +41,6 @@ import { FlowChatModel } from "../../model/Model.flowChatModel.js"; import { formatIssues } from "../../utils/shared/Shared.formatIssues.util.js"; import { fromChatMessage } from "../../utils/chat/Chat.fromChatMessage.util.js"; import { isSubFlow } from "../../utils/shared/Shared.isSubFlow.util.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; import { requireText } from "../../utils/shared/Shared.requireText.util.js"; import { textOf } from "../../utils/message/Message.textOf.util.js"; @@ -69,12 +67,12 @@ const JUMP_TARGETS = ["model", "tools", "end"] as const; const EXTRACTION_PROMPT = "The conversation above is finished. Answer with what it produced, in the type you were given, and add nothing that was not said in it."; -@Identifier("ai::agent::ask") +@Identifier("ai::agent::create") @DisplayIcon("tabler:ai") @Signature( "(name: TEXT, instructions: TEXT, model: TRANSFORM, question: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, answer_type?: T, conversation?: AI_CHAT_REQUEST, rules?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", ) -@Name({ code: "en-US", content: "Ask agent" }) +@Name({ code: "en-US", content: "Create agent" }) @Alias({ code: "en-US", content: "agent;ai;llm;chat;prompt;assistant;tools" }) @Description({ code: "en-US", @@ -90,7 +88,7 @@ const EXTRACTION_PROMPT = { code: "en-US", content: - "The agent's own name. It identifies the agent in the node's message and in the logs, and is what an error names when the agent fails.", + "The agent's own name. It identifies the agent in the node's message, and is what an error names when the agent fails.", }, ], }) @@ -175,7 +173,7 @@ const EXTRACTION_PROMPT = ], optional: true, }) -export class AskAgentFunction { +export class CreateAgentFunction { /** * Builds the agent and runs it in one node, rather than returning the agent for a * second node to invoke. A returned agent would be a sub flow function, and the @@ -200,16 +198,6 @@ export class AskAgentFunction { conversation?: AiChatRequest, rules?: unknown[], ): Promise { - const log: Logger = logger("agent", _context.executionId); - const toolLog: Logger = logger("tool", _context.executionId); - log.info(`the node asks the agent "${name}"`, { - question, - tools: Array.isArray(tools) ? tools.length : 0, - rules: Array.isArray(rules) ? rules.length : 0, - conversation, - answer_type, - }); - // The "answer_type" parameter is a TYPE: the data type the flow wants the // agent to answer in. Its value reaches the action as that type's JSON schema // - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` @@ -295,15 +283,6 @@ export class AskAgentFunction { ); } - const started: number = Date.now(); - log.info(`running the agent "${definition.name}"`, { - messages: history.length, - tools: definition.tools.length, - rules: definition.middleware.length, - answer_type: definition.outputSchema, - instructions: definition.systemPrompt, - }); - const agentRequest: AiAgentRequest = parseOrThrow( AiAgentRequestSchema, { messages: history }, @@ -312,10 +291,6 @@ export class AskAgentFunction { ); const flows: SubFlow[] = definition.tools.filter(isSubFlow); - log.debug(`building the agent "${definition.name}"`, { - mcp_servers: servers.map((server) => server.name), - flow_tools: flows.length, - }); // The MCP connections stay open for as long as the agent may call a tool, so // closing them is the one thing that has to happen on every way out below. @@ -419,33 +394,13 @@ export class AskAgentFunction { const described: unknown = flow.description ?? schema?.description; const description: string = typeof described === "string" ? described : ""; - toolLog.debug(`the tool "${toolName}" is built from a flow`, { - declared, - description, - schema, - }); - return tool( - (args: unknown) => { - const calledAt: number = Date.now(); - toolLog.info(`the agent calls the tool "${toolName}" with`, args); - - return Promise.resolve(flow(args as never)).then( - (result) => { - toolLog.info( - `the tool "${toolName}" answered after ${Date.now() - calledAt}ms with`, - result, - ); - return typeof result === "string" ? result : JSON.stringify(result ?? null); - }, - (error: unknown) => { - toolLog.error(`the tool "${toolName}" failed after ${Date.now() - calledAt}ms`, { - error: describeError(error), - }); - return `The tool failed: ${describeError(error)}`; - }, - ); - }, + (args: unknown) => + Promise.resolve(flow(args as never)).then( + (result) => + typeof result === "string" ? result : JSON.stringify(result ?? null), + (error: unknown) => `The tool failed: ${describeError(error)}`, + ), { name: toolName, description, @@ -455,11 +410,6 @@ export class AskAgentFunction { }), ...mcpTools, ]; - log.debug( - `the agent "${definition.name}" has ${agentTools.length} tools`, - agentTools.map((entry) => (entry as { name?: string }).name), - ); - agent = createAgent({ model: new FlowChatModel({ run: definition.model }), tools: agentTools, @@ -514,7 +464,6 @@ export class AskAgentFunction { : {}), } as never) as unknown as ReactAgent; } catch (error: unknown) { - log.error(`the agent "${definition.name}" could not be built`, { error: describeError(error) }); await close().catch(() => undefined); if (error instanceof RuntimeError) throw error; throw new RuntimeError( @@ -525,7 +474,6 @@ export class AskAgentFunction { let answer: AiAgentResponse; try { - log.debug("the conversation the agent starts from", agentRequest.messages); const result = await agent.invoke({ messages: agentRequest.messages.map(toLangChainMessage) }); // The run only ever produced what is in the conversation, so both what it @@ -587,10 +535,6 @@ export class AskAgentFunction { } } - if (pending.length > 0) { - log.info(`the agent "${definition.name}" is waiting for approval`, pending); - } - answer = parseOrThrow( AiAgentResponseSchema, { @@ -602,11 +546,6 @@ export class AskAgentFunction { "ERROR_INVALID_AI_AGENT_RESPONSE", "The agent did not answer with a valid agent response", ); - log.info( - `the agent "${definition.name}" finished after ${Date.now() - started}ms with ${answer.messages.length} messages`, - { structured_response: answer.structured_response }, - ); - log.debug("the conversation the agent ends with", answer.messages); // The second phase: the agent has finished working, so the type can now // be asked for on its own, with no tools in the request to collide with @@ -622,10 +561,6 @@ export class AskAgentFunction { .filter((line) => line.length > 0) .join("\n\n"); - log.debug(`asking the agent "${definition.name}" for the type on its own`, { - transcript: transcript.length, - }); - const extractor = createAgent({ model: new FlowChatModel({ run: definition.model }), tools: [], @@ -643,17 +578,8 @@ export class AskAgentFunction { if (extracted.structuredResponse) { answer = { ...answer, structured_response: extracted.structuredResponse }; - log.info(`the agent "${definition.name}" answered the type on the second turn`, { - structured_response: answer.structured_response, - }); } } - } catch (error: unknown) { - log.error(`the agent "${definition.name}" failed after ${Date.now() - started}ms`, { - error: error instanceof Error ? error.message : String(error), - stack: error instanceof Error ? error.stack : undefined, - }); - throw error; } finally { await close().catch(() => undefined); } @@ -678,7 +604,6 @@ export class AskAgentFunction { ...(answer.steps ? { steps: answer.steps } : {}), ...(answer.awaiting_approval ? { awaitingApproval: answer.awaiting_approval } : {}), }); - log.info(`the agent "${definition.name}" answers the node with`, response); return response; } } diff --git a/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts new file mode 100644 index 0000000..10dcad6 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts @@ -0,0 +1,169 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { createAgent, type ReactAgent } from "langchain"; +import { FlowChatModel } from "../../model/Model.flowChatModel.js"; +import { asSubFlow } from "../../utils/shared/Shared.asSubFlow.util.js"; +import { asText } from "../../utils/shared/Shared.asText.util.js"; +import { describeError } from "../../utils/shared/Shared.describeError.util.js"; +import { requireText } from "../../utils/shared/Shared.requireText.util.js"; +import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; +import { toPlainSchema } from "../../utils/shared/Shared.toPlainSchema.util.js"; + +/** + * What the model is told before the text, ahead of whatever the flow adds. + * + * The type itself already says which fields are wanted and which of them may be + * left out, so this only has to settle what the model is not to do: invent what + * the text does not say, and answer in anything but the type. + */ +const EXTRACTION_PROMPT = + "Read the text the user sends and answer with what it says, in the type you were given. Take nothing from outside the text, and leave a field out rather than guessing at it."; + +@Identifier("ai::extract::information") +@DisplayIcon("tabler:ai") +@Signature( + "(text: TEXT, information: T, model: TRANSFORM, instructions?: TEXT): T", +) +@Name({ code: "en-US", content: "Read information from text" }) +@Alias({ code: "en-US", content: "extract;extraction;information;read;parse;fields;structured;ai;llm" }) +@Description({ + code: "en-US", + content: + "Reads a text and fills the fields of a data type with what it says - names, dates, amounts - so the flow can work with them instead of searching the text itself.", +}) +@DisplayMessage({ code: "en-US", content: "Read ${information} out of ${text}" }) +@ThrowsError() +@Parameter({ + runtimeName: "text", + name: [{ code: "en-US", content: "Text" }], + description: [ + { + code: "en-US", + content: + "The text that is read: an email, a message, a document, anything the flow has as text. Only what stands in it ends up in the fields.", + }, + ], +}) +@Parameter({ + runtimeName: "information", + name: [{ code: "en-US", content: "Information" }], + description: [ + { + code: "en-US", + content: + "The data type whose fields are filled from the text. It needs fields; make a field optional when the text may not say it, because a missing one is then simply left empty.", + }, + ], +}) +@Parameter({ + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "The model that reads the text, built by one of the model nodes. The model decides which provider is called and on what key.", + }, + ], +}) +@Parameter({ + runtimeName: "instructions", + name: [{ code: "en-US", content: "Instructions" }], + description: [ + { + code: "en-US", + content: + "How the text is to be read, if it needs saying: which date format to use, which currency amounts are in, which language to answer in, what to do with several candidates.", + }, + ], + optional: true, +}) +export class ExtractInformationFunction { + /** + * One model call with the type forced on the answer, and no tools: there is + * nothing for a model to decide here beyond what the text says, so this is the + * agent node without its loop. Which way the type reaches the provider - as a + * response format or as a forced tool call - is {@link FlowChatModel}'s business, + * decided from what the model node declared it can do. + * + * The parameters read as the sentence the node is: this text, this information, + * read by this model. + */ + async run( + _context: FunctionContext, + text: string, + information: unknown, + model: unknown, + instructions?: string, + ): Promise> { + const read: string = requireText( + text, + "ERROR_INVALID_AI_EXTRACTION", + 'There is nothing to read: the "text" parameter is empty.', + ); + const added: string = asText(instructions ?? "", "instructions", "ERROR_INVALID_AI_EXTRACTION"); + + // The "information" parameter is a TYPE, so it arrives as that type's JSON + // schema - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` + // unwraps either way. A structured answer has to be an object to come back as + // a data type's value, so anything else is rejected here rather than deep + // inside the model call. + const schema: Record | undefined = toPlainSchema(information); + if (!schema || typeof schema !== "object") { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + `The "information" parameter has to be a type, but a ${typeof information} was passed.`, + ); + } + if (!("properties" in schema)) { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + 'The text can only be read into a type with fields: the type passed as "information" has none.', + ); + } + + let extractor: ReactAgent; + try { + extractor = createAgent({ + model: new FlowChatModel({ run: asSubFlow(model, "model") }), + tools: [], + responseFormat: schema, + systemPrompt: added.length > 0 ? `${EXTRACTION_PROMPT}\n\n${added}` : EXTRACTION_PROMPT, + } as never) as unknown as ReactAgent; + } catch (error: unknown) { + if (error instanceof RuntimeError) throw error; + throw new RuntimeError( + "ERROR_BUILDING_AI_EXTRACTION", + `Could not build the extraction: ${describeError(error)}`, + ); + } + + const result = await extractor.invoke({ + messages: [toLangChainMessage({ role: "human", content: [{ type: "text", text: read }] })], + }); + const answer: unknown = result.structuredResponse; + + // Without the structured answer the node's return value would be missing the + // very fields the flow reads, so a model that would not answer in the type + // fails the node instead of handing back an empty value. + if (!answer || typeof answer !== "object") { + throw new RuntimeError( + "ERROR_FAILED_AI_EXTRACTION", + 'The model did not answer in the type passed as "information".', + ); + } + + return answer as Record; + } +} diff --git a/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts index 59dab90..5047a5e 100644 --- a/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts @@ -22,15 +22,12 @@ import { asList } from "../../utils/shared/Shared.asList.util.js"; import { askFor } from "../../utils/middleware/Approval.askFor.util.js"; import { codeOf } from "../../utils/middleware/Approval.codeOf.util.js"; import { describeCall } from "../../utils/middleware/Approval.describeCall.util.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { newCode } from "../../utils/middleware/Approval.newCode.util.js"; import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; import { requireText } from "../../utils/shared/Shared.requireText.util.js"; import { settle } from "../../utils/middleware/Approval.settle.util.js"; import { textOf } from "../../utils/message/Message.textOf.util.js"; -const log = logger("middleware"); - @Identifier("ai::middleware::human_in_the_loop") @DisplayIcon("tabler:message-ai") @Signature("(tools: LIST): TRANSFORM") @@ -114,7 +111,6 @@ export class HumanInTheLoopMiddlewareFunction { // chose, narrowed to the ones this middleware guards. const held: ToolCall[] = []; const declined: ToolCall[] = []; - const approved: ToolCall[] = []; const calls: ToolCall[] = (last.content ?? []) .filter( (block): block is AiContentBlock & { name: string } => @@ -186,7 +182,6 @@ export class HumanInTheLoopMiddlewareFunction { switch (question.decision) { case "approved": settled.set(question.at, settle(earlier[question.at], question.code)); - approved.push(call); break; case "declined": settled.set(question.at, settle(earlier[question.at], question.code)); @@ -200,10 +195,6 @@ export class HumanInTheLoopMiddlewareFunction { open ??= question.code; break; case "spent": - log.debug("an earlier approval was already spent, so this call is asked about again", { - call: describeCall(call), - code: question.code, - }); held.push(call); break; } @@ -217,7 +208,6 @@ export class HumanInTheLoopMiddlewareFunction { // decision nobody made. if (held.length > 0) { const code: string = open ?? newCode(); - log.info(`the agent asks before it runs (${code})`, held.map(describeCall)); return { messages: [ ...history, @@ -232,7 +222,6 @@ export class HumanInTheLoopMiddlewareFunction { } if (declined.length > 0) { - log.info("the agent does not run what was declined", declined.map(describeCall)); return { messages: [ ...history, @@ -256,7 +245,6 @@ export class HumanInTheLoopMiddlewareFunction { // Everything was approved: the calls stay as the model made them, and // only the questions behind them are marked as spent. - log.info("the agent runs what was approved", approved.map(describeCall)); return { messages: [...history, last] }; }, }; diff --git a/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts index 4ab14ef..2ff192f 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts @@ -116,7 +116,6 @@ export class AnthropicModelFunction { return toModelTransform({ provider: "Anthropic", - prefix: "anthropic", identifier, model: chat as never, // Anthropic's own dialect for the same thing OpenAI calls diff --git a/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts index ae91e01..f9f4c41 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts @@ -97,7 +97,6 @@ export class GroqModelFunction { return toModelTransform({ provider: "Groq", - prefix: "groq", identifier, model: chat as never, responseFormat: (format: AiResponseFormat) => ({ response_format: toJsonSchemaFormat(format) }), diff --git a/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts index b13445e..b587a23 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts @@ -138,7 +138,6 @@ export class LiteLlmModelFunction { return toModelTransform({ provider: "LiteLLM", - prefix: "litellm", identifier, model: chat as never, // Left out unless the node says the server can do it: a server that diff --git a/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts index a359f6f..e5e0a98 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts @@ -102,7 +102,6 @@ export class MistralModelFunction { return toModelTransform({ provider: "Mistral", - prefix: "mistral", identifier, model: chat as never, }); diff --git a/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts index d2e0def..096f6ba 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts @@ -99,7 +99,6 @@ export class OllamaModelFunction { return toModelTransform({ provider: "Ollama", - prefix: "ollama", identifier, model: chat as never, // Ollama's dialect for the same thing: the bare JSON schema under diff --git a/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts index 0370773..5d28adb 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts @@ -111,7 +111,6 @@ export class OpenAiModelFunction { return toModelTransform({ provider: "OpenAI", - prefix: "openai", identifier, model: chat as never, responseFormat: (format: AiResponseFormat) => ({ response_format: toJsonSchemaFormat(format) }), diff --git a/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts index 3b3bea4..455090a 100644 --- a/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts @@ -170,7 +170,6 @@ export class OpenRouterModelFunction { return toModelTransform({ provider: "OpenRouter", - prefix: "openrouter", identifier, model: chat as never, // "strict" is forwarded as asked for, which means OpenAI requires every diff --git a/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts index b4e30e5..e3d1d87 100644 --- a/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts @@ -11,7 +11,6 @@ import { } from "@code0-tech/hercules"; import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; /** Open WebUI reads these blocks out of the answer's text, so they have to survive as markup. */ @@ -64,8 +63,7 @@ export class OpenAiOpenWebUiFormattingFunction { * still gets the data rather than the markup. An answer with nothing to show, and * one that came through here already, are returned untouched. */ - run(context: FunctionContext, response: unknown): AiChatResponse { - const log = logger("openai", context.executionId); + run(_context: FunctionContext, response: unknown): AiChatResponse { const answer: AiChatResponse = parseOrThrow( AiChatResponseSchema, response, @@ -77,10 +75,7 @@ export class OpenAiOpenWebUiFormattingFunction { const thought: string = answer.reasoning?.trim() ?? ""; if (thought.length === 0 && steps.length === 0) return answer; - if (FORMATTED.test(answer.response)) { - log.debug("this answer was already formatted for Open WebUI, so it is left as it is"); - return answer; - } + if (FORMATTED.test(answer.response)) return answer; const blocks: string[] = []; @@ -109,7 +104,6 @@ export class OpenAiOpenWebUiFormattingFunction { }); const content: string = [...blocks, answer.response].filter((part) => part.length > 0).join("\n"); - log.info("formatted the answer for Open WebUI", { reasoning: thought.length > 0, steps: steps.length }); return { ...answer, diff --git a/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts index 13de43e..c7870b6 100644 --- a/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts @@ -10,7 +10,6 @@ import { ThrowsError, } from "@code0-tech/hercules"; import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; import { pendingResponses } from "../../utils/openai/OpenAi.pending.util.js"; @@ -46,7 +45,7 @@ export class OpenAiRespondFunction { * The request is answered the moment this runs; the flow carries on, and anything * after this node no longer changes what the client got. A second call, or a run * of a flow nobody is waiting on - a manual execution from the editor, say - is - * logged rather than failed: the flow did nothing wrong, there is simply no + * passed over rather than failed: the flow did nothing wrong, there is simply no * connection to write to. * * The answer is returned rather than dropped, so it is the node's result and, for @@ -56,7 +55,6 @@ export class OpenAiRespondFunction { * answer from the wait this settles and ignores the flow's result. */ run(context: FunctionContext, response: unknown): AiChatResponse { - const log = logger("openai", context.executionId); const answer: AiChatResponse = parseOrThrow( AiChatResponseSchema, response, @@ -64,13 +62,7 @@ export class OpenAiRespondFunction { "The answer for an OpenAI client has to be a chat response", ); - if (pendingResponses.settle(context.executionId, answer)) { - log.info("answered the waiting OpenAI request", { model: answer.model }); - } else { - log.info("nothing is waiting for this execution's answer, so it stays this node's result", { - model: answer.model, - }); - } + pendingResponses.settle(context.executionId, answer); return answer; } diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts similarity index 99% rename from actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts rename to actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts index 8395828..11bf672 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.skills.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts @@ -170,7 +170,7 @@ function skillInput(input: unknown): string { return requireText(title, "ERROR_INVALID_AI_SKILL", 'The "title" argument of "Use a skill" is required.'); } -@Identifier("ai::agent::skills") +@Identifier("ai::tool::skills") @DisplayIcon("tabler:books") @Signature("(skills: LIST): ((title: TEXT) => TEXT)") @Name({ code: "en-US", content: "Skills" }) diff --git a/actions/ai-action/src/server/openai/OpenAi.server.ts b/actions/ai-action/src/server/openai/OpenAi.server.ts index f0563e5..8e9654c 100644 --- a/actions/ai-action/src/server/openai/OpenAi.server.ts +++ b/actions/ai-action/src/server/openai/OpenAi.server.ts @@ -1,16 +1,13 @@ -import { randomUUID } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import type { PlainValue } from "@code0-tech/hercules"; import type { ActionFlow } from "@code0-tech/tucana/aquila"; import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; -import type { Logger } from "../../types/shared/Log.types.js"; import type { OpenAiEndpoint, OpenAiRequestPath } from "../../types/openai/OpenAi.types.js"; import type { OpenAiServerHost, OpenAiServerOptions } from "../../types/openai/OpenAiServer.types.js"; import { corsHeaders } from "../../utils/openai/OpenAi.corsHeaders.util.js"; import { describeError } from "../../utils/shared/Shared.describeError.util.js"; import { errorBody } from "../../utils/openai/OpenAi.errorBody.util.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { parseRequestPath } from "../../utils/openai/OpenAi.parsePath.util.js"; import { pendingResponses } from "../../utils/openai/OpenAi.pending.util.js"; import { sendJson } from "../../utils/openai/OpenAi.sendJson.util.js"; @@ -21,7 +18,6 @@ import { toStreamChunks } from "../../utils/openai/OpenAi.toStream.util.js"; const DEFAULT_PORT = 8080; /** The endpoint is reachable from outside, so a body is read only up to this. */ const MAX_BODY_BYTES = 10 * 1024 * 1024; -const log: Logger = logger("openai"); export class OpenAiServer { private readonly server: Server; @@ -34,31 +30,13 @@ export class OpenAiServer { ) { this.port = options.port ?? Number(process.env.AI_OPENAI_PORT ?? process.env.PORT ?? DEFAULT_PORT); this.host = options.host ?? "0.0.0.0"; - log.info("the OpenAI endpoint is configured", { port: this.port, host: this.host }); this.server = createServer((request, response) => { - // One identifier per request, so every line of one call can be read as a - // sequence even while several clients are talking to the action. - const trace: Logger = log.child(randomUUID().slice(0, 8)); - const started: number = Date.now(); - - trace.info(`${request.method ?? "GET"} ${request.url ?? "/"}`, { - headers: request.headers, - remote: request.socket.remoteAddress, - }); - response.on("finish", () => { - trace.info(`answered ${response.statusCode} in ${Date.now() - started}ms`); - }); - - this.handle(request, response, trace).catch((error: unknown) => { - trace.error("the request failed before an answer was sent", { - error: describeError(error), - stack: error instanceof Error ? error.stack : undefined, - }); + this.handle(request, response).catch((error: unknown) => { if (response.headersSent) { response.end(); return; } - sendJson(response, 500, errorBody(describeError(error), "internal_error"), trace); + sendJson(response, 500, errorBody(describeError(error), "internal_error")); }); }); } @@ -68,14 +46,12 @@ export class OpenAiServer { this.server.once("error", reject); this.server.listen(this.port, this.host, () => { this.server.removeListener("error", reject); - log.info("listening", { port: this.address, host: this.host }); resolve({ port: this.port, host: this.host }); }); }); } close(): Promise { - log.info("closing the OpenAI endpoint"); return new Promise((resolve) => this.server.close(() => resolve())); } @@ -85,13 +61,12 @@ export class OpenAiServer { return address && typeof address === "object" ? address.port : this.port; } - private async handle(request: IncomingMessage, response: ServerResponse, trace: Logger): Promise { + private async handle(request: IncomingMessage, response: ServerResponse): Promise { const method: string = (request.method ?? "GET").toUpperCase(); // A preflight asks what is allowed and carries neither key nor body, so it is // answered before anything is looked up. if (method === "OPTIONS") { - trace.debug("answering a preflight"); response.writeHead(204, corsHeaders()); response.end(); return; @@ -99,11 +74,9 @@ export class OpenAiServer { const path: OpenAiRequestPath | undefined = parseRequestPath(request.url ?? "/"); if (!path) { - trace.warn("no endpoint of the protocol matches this path", { url: request.url }); - sendJson(response, 404, errorBody("Unknown endpoint.", "invalid_request_error"), trace); + sendJson(response, 404, errorBody("Unknown endpoint.", "invalid_request_error")); return; } - trace.debug("the path resolves to", path); const flows: ActionFlow[] = this.action.flows(); const known: OpenAiEndpoint[] = toEndpoints(flows); @@ -112,23 +85,12 @@ export class OpenAiServer { const endpoints: OpenAiEndpoint[] = known.filter( (endpoint) => endpoint.slug === path.slug && endpoint.route === path.route, ); - trace.debug(`${flows.length} flows known, ${known.length} of them endpoints, ${endpoints.length} on this route`, { - all: known.map((endpoint) => ({ - flow: `${endpoint.flow.flowId}`, - slug: endpoint.slug, - route: endpoint.route, - model: endpoint.model, - guarded: Boolean(endpoint.apiKey), - })), - }); if (endpoints.length === 0) { - trace.warn("no flow serves this route", { slug: path.slug, route: path.route }); sendJson( response, 404, errorBody(`No flow serves ${path.kind === "models" ? "models" : "completions"} here.`, "invalid_request_error"), - trace, ); return; } @@ -142,33 +104,25 @@ export class OpenAiServer { authorization?.replace(/^Bearer\s+/i, "").trim() || (Array.isArray(apiKeyHeader) ? apiKeyHeader[0] : apiKeyHeader)?.trim() || undefined; - trace.debug("the request carries a bearer token", { present: Boolean(token) }); if (path.kind === "models") { const listed: OpenAiEndpoint[] = endpoints.filter( (endpoint) => !endpoint.apiKey || endpoint.apiKey === token, ); if (listed.length === 0) { - trace.warn("the token matches no endpoint of this route, so nothing is listed"); - sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key"), trace); + sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key")); return; } - trace.info( - `listing ${listed.length} of ${endpoints.length} models`, - listed.map((endpoint) => endpoint.model), - ); - sendJson(response, 200, toModelList(listed), trace); + sendJson(response, 200, toModelList(listed)); return; } if (method !== "POST") { - trace.warn("completions were asked for with the wrong method", { method }); response.setHeader("allow", "POST, OPTIONS"); sendJson( response, 405, errorBody(`Completions are asked for with POST, not ${method}.`, "invalid_request_error"), - trace, ); return; } @@ -182,14 +136,12 @@ export class OpenAiServer { parts.push(part); } const body: string = Buffer.concat(parts).toString("utf8"); - trace.debug(`the body is ${Buffer.byteLength(body)} bytes`, body); let parsed: unknown; try { parsed = JSON.parse(body || "{}"); - } catch (error: unknown) { - trace.warn("the body is not valid JSON", { error: describeError(error) }); - sendJson(response, 400, errorBody("The request body is not valid JSON.", "invalid_request_error"), trace); + } catch { + sendJson(response, 400, errorBody("The request body is not valid JSON.", "invalid_request_error")); return; } @@ -203,49 +155,31 @@ export class OpenAiServer { endpoints.find((candidate) => candidate.model === asked) ?? (endpoints.length === 1 ? endpoints[0] : undefined); if (!endpoint) { - trace.warn("no flow of this route carries the model asked for", { - asked: payload.model ?? null, - available: endpoints.map((candidate) => candidate.model), - }); sendJson( response, 404, errorBody(`The model "${payload.model ?? ""}" does not exist.`, "invalid_request_error", "model_not_found"), - trace, ); return; } - trace.info("the request is for", { - model: endpoint.model, - asked_for: payload.model ?? null, - flow: `${endpoint.flow.flowId}`, - project: endpoint.slug, - stream: payload.stream === true, - }); if (endpoint.apiKey && endpoint.apiKey !== token) { - trace.warn("the token does not match the key the flow declared", { model: endpoint.model }); - sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key"), trace); + sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key")); return; } const validation = AiChatRequestSchema.safeParse(parsed); const request_: AiChatRequest | undefined = validation.data; if (!request_ || request_.messages.length === 0) { - trace.warn("the request carries nothing to answer", { - issues: validation.error?.issues, - messages: request_?.messages.length ?? 0, - }); sendJson( response, 400, errorBody("The request carries no messages to answer.", "invalid_request_error"), - trace, ); return; } - const answer: AiChatResponse | undefined = await this.run(endpoint, request_, trace); + const answer: AiChatResponse | undefined = await this.run(endpoint, request_); if (!answer) { sendJson( response, @@ -254,14 +188,12 @@ export class OpenAiServer { `The flow serving "${endpoint.model}" did not answer with a chat response.`, "internal_error", ), - trace, ); return; } if (payload.stream === true) { const chunks: string[] = toStreamChunks(answer); - trace.debug(`answering 200 as a stream of ${chunks.length} chunks`, chunks); response.writeHead(200, { ...corsHeaders(), @@ -273,30 +205,23 @@ export class OpenAiServer { response.end(); return; } - sendJson(response, 200, answer, trace); + sendJson(response, 200, answer); } /** * Runs the flow and takes its answer, from whichever of the two comes first. * * `ai::openai::respond` is the way a flow answers: it settles the request from - * wherever in the flow it sits, so nodes after it - logging, storing, a second - * branch - no longer change what the client got. The flow's return value is only - * used when the flow ended without ever responding, which keeps a flow of two - * nodes working without a respond node. + * wherever in the flow it sits, so nodes after it - storing, a second branch - + * no longer change what the client got. The flow's return value is only used + * when the flow ended without ever responding, which keeps a flow of two nodes + * working without a respond node. */ - private async run( - endpoint: OpenAiEndpoint, - request: AiChatRequest, - trace: Logger, - ): Promise { - const started: number = Date.now(); + private async run(endpoint: OpenAiEndpoint, request: AiChatRequest): Promise { // Reserved before the flow starts, because the wait has to exist by the time // its respond node runs - which can be before executeFlow even resolves. const executionId: string = this.action.reserveExecutionId(); - trace.debug(`running flow ${endpoint.flow.flowId} as execution ${executionId} with`, request); - const responded: Promise<{ answer: AiChatResponse }> = pendingResponses .open(executionId, endpoint.model) .then((answer) => ({ answer })); @@ -307,28 +232,11 @@ export class OpenAiServer { try { const outcome = await Promise.race([responded, finished]); - if ("answer" in outcome) { - trace.info(`the flow answered through respond after ${Date.now() - started}ms`); - return this.named(outcome.answer, endpoint, trace); - } + if ("answer" in outcome) return this.named(outcome.answer, endpoint); - trace.debug( - `flow ${endpoint.flow.flowId} ended after ${Date.now() - started}ms without responding, taking its result`, - outcome.result, - ); const validation = AiChatResponseSchema.safeParse(outcome.result); - if (!validation.data) { - trace.error("the flow neither responded nor returned a chat response", { - issues: validation.error?.issues, - }); - return undefined; - } - return this.named(validation.data, endpoint, trace); - } catch (error: unknown) { - trace.error(`flow ${endpoint.flow.flowId} failed after ${Date.now() - started}ms`, { - error: describeError(error), - }); - throw error; + if (!validation.data) return undefined; + return this.named(validation.data, endpoint); } finally { // Whatever happened, nothing is waiting any more: a later respond call // finds no connection rather than settling a request that is gone. @@ -341,9 +249,8 @@ export class OpenAiServer { * the model it asked for, so the flow's own name stands in where a flow - or an * agent that reported no model - left the field empty. */ - private named(answer: AiChatResponse, endpoint: OpenAiEndpoint, trace: Logger): AiChatResponse { + private named(answer: AiChatResponse, endpoint: OpenAiEndpoint): AiChatResponse { if (answer.model.trim().length > 0) return answer; - trace.debug("the answer carries no model, so the flow's own name stands in", { model: endpoint.model }); return { ...answer, model: endpoint.model }; } } diff --git a/actions/ai-action/src/server/openai/OpenAi.startServer.ts b/actions/ai-action/src/server/openai/OpenAi.startServer.ts index a382e60..caa86e8 100644 --- a/actions/ai-action/src/server/openai/OpenAi.startServer.ts +++ b/actions/ai-action/src/server/openai/OpenAi.startServer.ts @@ -1,9 +1,6 @@ import type { OpenAiServerHost, OpenAiServerOptions } from "../../types/openai/OpenAiServer.types.js"; -import { logger } from "../../utils/shared/Log.logger.util.js"; import { OpenAiServer } from "./OpenAi.server.js"; -const log = logger("openai"); - /** * Starts the OpenAI endpoint of every project this action serves. It is the action's * own HTTP server: a flow bound to `ai::openai::server` is reachable the moment @@ -14,7 +11,6 @@ export async function startOpenAiServer( options: OpenAiServerOptions = {}, ): Promise { const server = new OpenAiServer(action, options); - const { host, port } = await server.listen(); - log.info(`OpenAI endpoint listening on http://${host}:${port}//`); + await server.listen(); return server; } diff --git a/actions/ai-action/src/types/shared/Log.types.ts b/actions/ai-action/src/types/shared/Log.types.ts deleted file mode 100644 index dfcd2aa..0000000 --- a/actions/ai-action/src/types/shared/Log.types.ts +++ /dev/null @@ -1,15 +0,0 @@ -/** How much is written, from the quietest to everything. */ -export const LOG_LEVELS = ["debug", "info", "warn", "error", "off"] as const; -export type LogLevel = (typeof LOG_LEVELS)[number]; - -/** A level that actually writes, which is every one but `off`. */ -export type WritingLevel = Exclude; - -export interface Logger { - debug: (message: string, details?: unknown) => void; - info: (message: string, details?: unknown) => void; - warn: (message: string, details?: unknown) => void; - error: (message: string, details?: unknown) => void; - /** A logger of the same scope, with something to tie lines of one run together. */ - child: (correlation: string) => Logger; -} diff --git a/actions/ai-action/src/utils/model/Model.toTransform.util.ts b/actions/ai-action/src/utils/model/Model.toTransform.util.ts index f246614..a1fd341 100644 --- a/actions/ai-action/src/utils/model/Model.toTransform.util.ts +++ b/actions/ai-action/src/utils/model/Model.toTransform.util.ts @@ -10,7 +10,6 @@ import type { AiModelTransform } from "../../datatypes/model/Model.transform.dat import { toFlowMessage } from "../message/Message.toFlowMessage.util.js"; import { toLangChainMessage } from "../message/Message.toLangChainMessage.util.js"; import { describeError } from "../shared/Shared.describeError.util.js"; -import { logger } from "../shared/Log.logger.util.js"; import { parseOrThrow } from "../shared/Shared.parseOrThrow.util.js"; /** A tool as every OpenAI-dialect provider wants to be handed it. */ @@ -41,8 +40,6 @@ type BoundModel = Runnable = format && options.responseFormat ? options.responseFormat(format) : {}; - // What a model answered is only half of a failed run: whether it was asked - // to call a tool at all, and whether it then did, is the other half, and - // only this node sees both. - log.debug(`calling "${identifier}" with`, { - messages: parsed.messages.length, - tools: bindable.length, - tool_choice: parsed.tool_choice, - response_format: format?.name, - }); - const answer: AIMessage = await bound .invoke(messages, { ...(parsed.stop ? { stop: parsed.stop } : {}), @@ -138,14 +124,6 @@ export function toModelTransform(options: ModelTransformOptions): AiModelTransfo ...formatOptions, } as never) .catch((error: unknown) => { - // Which parameter a provider refused is only answerable against - // what was actually sent, and a rejected call is exactly when - // nobody can reconstruct that from the flow. - log.error(`the call to "${identifier}" was rejected, having sent`, { - tools: bindable, - tool_choice: parsed.tool_choice, - response_format: format, - }); throw new RuntimeError( "ERROR_AI_MODEL_CALL_FAILED", `The ${provider} call to "${identifier}" failed: ${(options.describeFailure ?? describeError)(error)}`, @@ -154,13 +132,6 @@ export function toModelTransform(options: ModelTransformOptions): AiModelTransfo const reply = toFlowMessage(answer); const metadata = answer.response_metadata as { finish_reason?: unknown } | undefined; - log.debug(`"${identifier}" answered with`, { - blocks: (reply.content ?? []).map((block) => block.type), - tool_calls: (reply.content ?? []) - .filter((block) => block.type === "tool_call") - .map((block) => block.name), - finish_reason: metadata?.finish_reason, - }); // A provider that gave up mid-generation can still answer 200, with // whatever text it had produced and "error" as the finish reason. Taken at diff --git a/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts b/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts index 6749b29..e912666 100644 --- a/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts +++ b/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts @@ -1,8 +1,4 @@ import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; -import { logger } from "../shared/Log.logger.util.js"; - -const log = logger("openai"); - interface Waiting { resolve: (response: AiChatResponse) => void; model: string; @@ -26,7 +22,6 @@ class PendingResponses { open(executionId: string, model: string): Promise { return new Promise((resolve) => { this.waiting.set(executionId, { resolve, model }); - log.debug(`waiting for execution ${executionId} to answer`, { model, waiting: this.waiting.size }); }); } @@ -37,7 +32,6 @@ class PendingResponses { this.waiting.delete(executionId); waiting.resolve(response); - log.debug(`execution ${executionId} answered its request`, { waiting: this.waiting.size }); return true; } diff --git a/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts b/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts index 0c2dd09..391c765 100644 --- a/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts +++ b/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts @@ -1,11 +1,9 @@ import type { ServerResponse } from "node:http"; -import type { Logger } from "../../types/shared/Log.types.js"; import { corsHeaders } from "./OpenAi.corsHeaders.util.js"; /** Answers with JSON, which is every answer of this endpoint but a stream. */ -export function sendJson(response: ServerResponse, status: number, body: unknown, trace: Logger): void { +export function sendJson(response: ServerResponse, status: number, body: unknown): void { const payload: string = JSON.stringify(body); - trace.debug(`answering ${status} as json`, body); response.writeHead(status, { ...corsHeaders(), diff --git a/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts b/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts index 8abe25c..1bb60f7 100644 --- a/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts +++ b/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts @@ -1,18 +1,14 @@ import type { ActionFlow } from "@code0-tech/tucana/aquila"; import { OPENAI_EVENT, type OpenAiEndpoint } from "../../types/openai/OpenAi.types.js"; -import { logger } from "../shared/Log.logger.util.js"; import { normalizeRoute } from "./OpenAi.normalizeRoute.util.js"; import { textSetting } from "./OpenAi.textSetting.util.js"; -const log = logger("openai"); - /** * The endpoints the action currently serves. * * A flow missing its route or its model name is left out rather than guessed at: the * route is what makes it reachable and the model is what a client asks for, so - * standing in for either would answer under a name nobody picked. It is logged, - * because a model missing from a client's list is otherwise a silent gap. + * standing in for either would answer under a name nobody picked. */ export function toEndpoints(flows: ActionFlow[]): OpenAiEndpoint[] { return flows @@ -22,15 +18,7 @@ export function toEndpoints(flows: ActionFlow[]): OpenAiEndpoint[] { const model: string | undefined = textSetting(flow, "model"); const slug: string = flow.projectSlug.trim(); - if (!route || !model || slug.length === 0) { - log.warn(`flow ${flow.flowId} is bound to the OpenAI endpoint but serves nothing`, { - name: flow.name, - route: route ?? null, - model: model ?? null, - project: slug || null, - }); - return undefined; - } + if (!route || !model || slug.length === 0) return undefined; const apiKey: string | undefined = textSetting(flow, "api_key"); return { flow, slug, route: normalizeRoute(route), model, ...(apiKey ? { apiKey } : {}) }; diff --git a/actions/ai-action/src/utils/shared/Log.describeValue.util.ts b/actions/ai-action/src/utils/shared/Log.describeValue.util.ts deleted file mode 100644 index 0ae2160..0000000 --- a/actions/ai-action/src/utils/shared/Log.describeValue.util.ts +++ /dev/null @@ -1,28 +0,0 @@ -/** Keys whose value never reaches a log line, wherever they sit in a payload. */ -const SECRETS = /^(api[-_]?key|authorization|auth|token|password|secret|[a-z]+[-_]?api[-_]?key)$/i; -const REDACTED = "[redacted]"; -const MAX_VALUE_CHARS = 2000; - -/** - * A value as a log line: secrets dropped, long values cut, cycles survived. - * - * Everything logged goes through here, so no line can carry an API key, a payload - * cannot bury the rest of a run, and a value that refers to itself does not throw - * where it is only meant to be described. - */ -export function describeValue(value: unknown): string { - const seen = new WeakSet(); - const text: string = - JSON.stringify(value, (key: string, entry: unknown): unknown => { - if (SECRETS.test(key)) return REDACTED; - if (typeof entry === "bigint") return `${entry}`; - if (typeof entry === "function") return "[function]"; - if (typeof entry === "object" && entry !== null) { - if (seen.has(entry)) return "[circular]"; - seen.add(entry); - } - return entry; - }) ?? String(value); - - return text.length > MAX_VALUE_CHARS ? `${text.slice(0, MAX_VALUE_CHARS)}…(${text.length} chars)` : text; -} diff --git a/actions/ai-action/src/utils/shared/Log.emit.util.ts b/actions/ai-action/src/utils/shared/Log.emit.util.ts deleted file mode 100644 index d03ff58..0000000 --- a/actions/ai-action/src/utils/shared/Log.emit.util.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { LOG_LEVELS, type LogLevel, type WritingLevel } from "../../types/shared/Log.types.js"; -import { describeValue } from "./Log.describeValue.util.js"; - -/** - * Writes one line, if a line of this level is written at all. - * - * How much is logged comes from `AI_LOG_LEVEL`: `debug` by default so a run can be - * followed end to end while the action is being tried out, and off under vitest, - * where the lines would bury the test output. Set `AI_LOG_LEVEL=off` to silence it, - * or `AI_LOG_LEVEL=debug` in a test run to see everything. - */ -export function emit( - level: WritingLevel, - scope: string, - correlation: string | undefined, - message: string, - details?: unknown, -): void { - const configured: string | undefined = process.env.AI_LOG_LEVEL?.trim().toLowerCase(); - const wanted: LogLevel = - configured && (LOG_LEVELS as readonly string[]).includes(configured) - ? (configured as LogLevel) - : process.env.VITEST || process.env.NODE_ENV === "test" - ? "off" - : "debug"; - if (LOG_LEVELS.indexOf(level) < LOG_LEVELS.indexOf(wanted)) return; - - const line: string = [ - new Date().toISOString(), - level.toUpperCase().padEnd(5), - `[ai${scope ? `:${scope}` : ""}]${correlation ? ` (${correlation})` : ""}`, - message, - ].join(" "); - - const write = level === "error" ? console.error : level === "warn" ? console.warn : console.log; - if (details === undefined) write(line); - else write(`${line} ${describeValue(details)}`); -} diff --git a/actions/ai-action/src/utils/shared/Log.logger.util.ts b/actions/ai-action/src/utils/shared/Log.logger.util.ts deleted file mode 100644 index 7d378e8..0000000 --- a/actions/ai-action/src/utils/shared/Log.logger.util.ts +++ /dev/null @@ -1,18 +0,0 @@ -import type { Logger } from "../../types/shared/Log.types.js"; -import { emit } from "./Log.emit.util.js"; - -/** - * The action's logging, scoped by what it is about (`openai`, `agent`, `model`). - * - * Every line goes through here rather than to `console` directly, so one environment - * variable turns the whole run quiet or loud, and so nothing logs an API key. - */ -export function logger(scope: string, correlation?: string): Logger { - return { - debug: (message, details) => emit("debug", scope, correlation, message, details), - info: (message, details) => emit("info", scope, correlation, message, details), - warn: (message, details) => emit("warn", scope, correlation, message, details), - error: (message, details) => emit("error", scope, correlation, message, details), - child: (next: string) => logger(scope, next), - }; -} diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts index ffcbdee..355cd4c 100644 --- a/actions/ai-action/test/agent.test.ts +++ b/actions/ai-action/test/agent.test.ts @@ -5,7 +5,7 @@ import type { AiAgentState } from "../src/datatypes/middleware/Middleware.agentS import type { AiMessage } from "../src/datatypes/message/Message.datatype.js"; import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; -import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; import { TrimMessagesMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.js"; function subFlow(implementation: (input: never) => unknown, inputSchema?: Record): SubFlow { @@ -72,7 +72,7 @@ const nativeModelSchema: Record = { properties: { messages: {}, tools: {}, response_format: {} }, }; -const ask = new AskAgentFunction(); +const ask = new CreateAgentFunction(); /** A data type's JSON schema, which is what a `TYPE` parameter carries. */ const orderType: Record = { @@ -118,7 +118,7 @@ function asStruct(plain: Record): unknown { return { fields: Object.fromEntries(Object.entries(plain).map(([key, value]) => [key, asValue(value)])) }; } -describe("ai::agent::ask", () => { +describe("ai::agent::create", () => { it("answers with a chat response, because it runs the agent itself", async () => { const { run } = scriptedModel([answer("hello")]); const response = await ask.run(context(), "greeter", "You greet people.", run, "hi"); diff --git a/actions/ai-action/test/approval.test.ts b/actions/ai-action/test/approval.test.ts index ceb667c..0a12704 100644 --- a/actions/ai-action/test/approval.test.ts +++ b/actions/ai-action/test/approval.test.ts @@ -3,13 +3,13 @@ import type { FunctionContext, SubFlow } from "@code0-tech/hercules"; import { describe, expect, it } from "vitest"; import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; -import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; import { HumanInTheLoopMiddlewareFunction } from "../src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.js"; import { askFor } from "../src/utils/middleware/Approval.askFor.util.js"; import { describeCall } from "../src/utils/middleware/Approval.describeCall.util.js"; import { newCode } from "../src/utils/middleware/Approval.newCode.util.js"; -const ask = new AskAgentFunction(); +const ask = new CreateAgentFunction(); const humanInTheLoop = new HumanInTheLoopMiddlewareFunction(); /** diff --git a/actions/ai-action/test/extract.test.ts b/actions/ai-action/test/extract.test.ts new file mode 100644 index 0000000..bffeede --- /dev/null +++ b/actions/ai-action/test/extract.test.ts @@ -0,0 +1,171 @@ +import "reflect-metadata"; +import { type FunctionContext, type SubFlow } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; +import type { AiModelResponse } from "../src/datatypes/model/Model.response.datatype.js"; +import { ExtractInformationFunction } from "../src/runtimefunctions/extract/Extract.information.runtimefunction.js"; + +function subFlow(implementation: (input: never) => unknown, inputSchema?: Record): SubFlow { + const flow = (async (input: never) => implementation(input)) as unknown as { inputSchema?: unknown }; + if (inputSchema) flow.inputSchema = inputSchema; + return flow as unknown as SubFlow; +} + +function context(): FunctionContext { + return { + projectId: 1, + executionId: "extract-execution", + matchedConfig: { projectId: 1, configValues: [], findConfig: () => undefined }, + executeFlow: async () => null, + }; +} + +function answer(text: string, toolCalls: { id: string; name: string; args: object }[] = []): AiModelResponse { + return { + message: { + role: "ai", + content: [ + ...(text.length > 0 ? [{ type: "text", text }] : []), + ...toolCalls.map((call) => ({ type: "tool_call", ...call })), + ], + }, + }; +} + +function scriptedModel(responses: AiModelResponse[], inputSchema?: Record) { + const requests: AiModelRequest[] = []; + let call = 0; + const run = subFlow((input: never) => { + requests.push(input as unknown as AiModelRequest); + return responses[Math.min(call++, responses.length - 1)]; + }, inputSchema); + return { run, requests }; +} + +/** + * The input schema of a model node that can constrain its own output, which is how + * such a node tells the extraction to ask the provider for the type directly instead + * of binding it as a tool the model has to call. + */ +const nativeModelSchema: Record = { + type: "object", + properties: { messages: {}, tools: {}, response_format: {} }, +}; + +/** A data type's JSON schema, which is what a `TYPE` parameter carries. */ +const invoiceType: Record = { + title: "Invoice", + type: "object", + properties: { number: { type: "string" }, total: { type: "number" } }, + required: ["number"], +}; + +/** Wraps a plain schema the way aquila sends it: a shared.Struct. */ +function asStruct(plain: Record): unknown { + const asValue = (value: unknown): unknown => { + if (typeof value === "string") return { kind: { oneofKind: "stringValue", stringValue: value } }; + if (typeof value === "boolean") return { kind: { oneofKind: "boolValue", boolValue: value } }; + if (typeof value === "number") + return { + kind: { + oneofKind: "numberValue", + numberValue: { number: { oneofKind: "integer", integer: BigInt(value) } }, + }, + }; + if (Array.isArray(value)) return { kind: { oneofKind: "listValue", listValue: { values: value.map(asValue) } } }; + if (value && typeof value === "object") + return { kind: { oneofKind: "structValue", structValue: asStruct(value as Record) } }; + return { kind: { oneofKind: "nullValue", nullValue: 0 } }; + }; + + return { fields: Object.fromEntries(Object.entries(plain).map(([key, value]) => [key, asValue(value)])) }; +} + +const extract = new ExtractInformationFunction(); +const text = "Invoice R-77 came to 42.50 euros."; + +describe("ai::extract::information", () => { + it("answers with the type's fields, read out of the text", async () => { + const { run } = scriptedModel([answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77", total: 42.5 } }])]); + + await expect(extract.run(context(), text, invoiceType, run)).resolves.toEqual({ + number: "R-77", + total: 42.5, + }); + }); + + it("sends the text as the only message and binds no tool but the type", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77" } }]), + ]); + + await extract.run(context(), text, invoiceType, run); + + // One model call, with the system prompt ahead of the text, and the type as + // the one tool there is - forced, because an offered tool may be skipped. + expect(requests).toHaveLength(1); + expect(requests[0].messages.map((message) => message.role)).toEqual(["system", "human"]); + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Invoice"]); + expect(requests[0].tool_choice).toBe("any"); + }); + + it("asks a model that can constrain its own output for the type directly", async () => { + const { run, requests } = scriptedModel( + [answer(JSON.stringify({ number: "R-77", total: 42.5 }))], + nativeModelSchema, + ); + + const read = await extract.run(context(), text, invoiceType, run); + + expect(requests[0].tools).toEqual([]); + expect(requests[0].response_format?.schema).toMatchObject({ + properties: { number: { type: "string" }, total: { type: "number" } }, + }); + expect(read).toEqual({ number: "R-77", total: 42.5 }); + }); + + it("puts the instructions behind its own, so they add to them instead of replacing them", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77" } }]), + ]); + + await extract.run(context(), text, invoiceType, run, "Amounts are in euros."); + + const system: string = (requests[0].messages[0].content ?? []) + .map((block) => String(block.text ?? "")) + .join(""); + expect(system).toContain("Take nothing from outside the text"); + expect(system.endsWith("Amounts are in euros.")).toBe(true); + }); + + it("takes the type as the struct aquila wraps it in", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77" } }]), + ]); + + await expect(extract.run(context(), text, asStruct(invoiceType), run)).resolves.toEqual({ number: "R-77" }); + expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Invoice"]); + }); + + it("needs a text to read", async () => { + const { run } = scriptedModel([answer("")]); + + await expect(extract.run(context(), " ", invoiceType, run)).rejects.toThrow(/nothing to read/); + }); + + it("rejects a type that has no fields to fill", async () => { + const { run } = scriptedModel([answer("")]); + + await expect(extract.run(context(), text, { type: "string" }, run)).rejects.toThrow(/type with fields/); + }); + + it("fails when the model answers in anything but the type", async () => { + const { run } = scriptedModel([answer("The invoice is R-77.")]); + + await expect(extract.run(context(), text, invoiceType, run)).rejects.toThrow(/did not answer in the type/); + }); + + it("needs a model to read with", async () => { + await expect(extract.run(context(), text, invoiceType, "gpt-4o")).rejects.toThrow(/has to be a sub flow/); + }); +}); diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts index f2067da..30ab53f 100644 --- a/actions/ai-action/test/functions.test.ts +++ b/actions/ai-action/test/functions.test.ts @@ -20,13 +20,13 @@ import { MistralModelFunction } from "../src/runtimefunctions/model/Model.mistra import { OllamaModelFunction } from "../src/runtimefunctions/model/Model.ollama.runtimefunction.js"; import { OpenAiModelFunction } from "../src/runtimefunctions/model/Model.openAi.runtimefunction.js"; import { OpenRouterModelFunction } from "../src/runtimefunctions/model/Model.openRouter.runtimefunction.js"; -import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; import { McpServerFunction } from "../src/runtimefunctions/mcp/Mcp.server.runtimefunction.js"; import { AiMcpServerSchema } from "../src/datatypes/mcp/Mcp.server.datatype.js"; const model = new OpenRouterModelFunction(); const middleware = new TrimMessagesMiddlewareFunction(); -const ask = new AskAgentFunction(); +const ask = new CreateAgentFunction(); const mcp = new McpServerFunction(); /** @@ -165,7 +165,7 @@ describe("ai::model::openrouter", () => { vi.restoreAllMocks(); }); - it("is accepted by ai::agent::ask as the agent's model", async () => { + it("is accepted by ai::agent::create as the agent's model", async () => { const transform = model.run(context(), "anthropic/claude-opus-5", "sk-or-test"); // Reaches the model, which rejects the test key - proof the agent accepted it. @@ -297,7 +297,7 @@ describe("the contracts the functions implement", () => { }); }); -describe("the chat format of ai::agent::ask", () => { +describe("the chat format of ai::agent::create", () => { function scriptedModel(responses: AiModelResponse[]) { const requests: AiModelRequest[] = []; let call = 0; @@ -612,7 +612,7 @@ describe("the model nodes", () => { expect(fields(transform.inputSchema)).toContain("response_format"); }); - it("is accepted by ai::agent::ask as the agent's model", async () => { + it("is accepted by ai::agent::create as the agent's model", async () => { const answer = new AIMessage("ok"); vi.spyOn(ChatAnthropic.prototype, "invoke").mockResolvedValue(answer as never); diff --git a/actions/ai-action/test/log.test.ts b/actions/ai-action/test/log.test.ts deleted file mode 100644 index 237fefe..0000000 --- a/actions/ai-action/test/log.test.ts +++ /dev/null @@ -1,86 +0,0 @@ -import "reflect-metadata"; -import { afterEach, describe, expect, it, vi } from "vitest"; -import { describeValue } from "../src/utils/shared/Log.describeValue.util.js"; -import { logger } from "../src/utils/shared/Log.logger.util.js"; - -const original: string | undefined = process.env.AI_LOG_LEVEL; - -afterEach(() => { - if (original === undefined) delete process.env.AI_LOG_LEVEL; - else process.env.AI_LOG_LEVEL = original; - vi.restoreAllMocks(); -}); - -/** The lines a block of code writes, with the level turned up for the test. */ -function captured(level: string | undefined, run: () => void): string[] { - if (level === undefined) delete process.env.AI_LOG_LEVEL; - else process.env.AI_LOG_LEVEL = level; - const lines: string[] = []; - for (const channel of ["log", "warn", "error"] as const) { - vi.spyOn(console, channel).mockImplementation((...args: unknown[]) => { - lines.push(args.map(String).join(" ")); - }); - } - run(); - return lines; -} - -describe("the action's logging", () => { - it("is off while the tests run, so a suite stays readable", () => { - const lines = captured(undefined, () => { - logger("openai").debug("a line nobody asked for"); - logger("openai").error("and one that would otherwise show"); - }); - - expect(lines).toEqual([]); - }); - - it("writes the scope, the level and the run it belongs to", () => { - const lines = captured("debug", () => logger("openai", "abc123").info("a request arrived", { status: 200 })); - - expect(lines).toHaveLength(1); - expect(lines[0]).toContain("INFO [ai:openai] (abc123) a request arrived"); - expect(lines[0]).toContain('{"status":200}'); - expect(lines[0]).toMatch(/^\d{4}-\d{2}-\d{2}T/); - }); - - it("writes only what the level asks for", () => { - expect(captured("warn", () => logger("x").debug("quiet"))).toEqual([]); - expect(captured("warn", () => logger("x").error("loud"))).toHaveLength(1); - expect(captured("off", () => logger("x").error("silenced"))).toEqual([]); - }); - - it("never writes a key, however deep it sits", () => { - const line = captured("debug", () => - logger("model").debug("the request", { - api_key: "sk-secret", - headers: { authorization: "Bearer sk-secret", "api-key": "sk-secret" }, - nested: [{ openRouterApiKey: "sk-secret", prompt: "keep me" }], - }), - )[0]; - - expect(line).not.toContain("sk-secret"); - expect(line).toContain("keep me"); - expect(line.match(/\[redacted\]/g)).toHaveLength(4); - }); - - it("cuts a value that would bury the line and survives a cycle", () => { - const long = describeValue({ text: "x".repeat(5000) }); - const cyclic: Record = { name: "a" }; - cyclic.self = cyclic; - - expect(long.length).toBeLessThan(2100); - expect(long).toContain("chars)"); - expect(describeValue(cyclic)).toEqual('{"name":"a","self":"[circular]"}'); - expect(describeValue({ id: 7n, run: () => undefined })).toEqual('{"id":"7","run":"[function]"}'); - }); - - it("keeps a child's scope and swaps what ties the lines together", () => { - const lines = captured("debug", () => { - const parent = logger("openai", "one"); - parent.child("two").warn("second"); - }); - - expect(lines[0]).toContain("[ai:openai] (two) second"); - }); -}); diff --git a/actions/ai-action/test/openai.test.ts b/actions/ai-action/test/openai.test.ts index a085ea1..367f843 100644 --- a/actions/ai-action/test/openai.test.ts +++ b/actions/ai-action/test/openai.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it } from "vitest"; import type { AiChatRequest } from "../src/datatypes/chat/Chat.request.datatype.js"; import type { AiChatResponse } from "../src/datatypes/chat/Chat.response.datatype.js"; import type { AiModelRequest } from "../src/datatypes/model/Model.request.datatype.js"; -import { AskAgentFunction } from "../src/runtimefunctions/agent/Agent.ask.runtimefunction.js"; +import { CreateAgentFunction } from "../src/runtimefunctions/agent/Agent.create.runtimefunction.js"; import { AiOpenAiServerRuntimeEvent } from "../src/runtimeevents/openai/OpenAi.server.runtimeevent.js"; import { OpenAiOpenWebUiFormattingFunction } from "../src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.js"; import { OpenAiRespondFunction } from "../src/runtimefunctions/openai/OpenAi.respond.runtimefunction.js"; @@ -181,7 +181,7 @@ describe("the OpenAI endpoint", () => { expect(response.status).toEqual(200); expect(calls.map((call) => call.flowId)).toEqual([2n]); - // The flow is handed the request itself, which is what ai::agent::ask takes. + // The flow is handed the request itself, which is what ai::agent::create takes. expect(calls[0].payload).toMatchObject({ messages: [{ role: "user", content: "hi" }] }); expect(body.response).toEqual("triage here"); // A client matches the answer against the model it asked for. @@ -353,7 +353,7 @@ describe("the flow a client ends up talking to", () => { // which is exactly what the flow's return value could not express. const after: string[] = []; const { url } = await serve([flow({ id: 1, slug: "acme", model: "support" })], async ({ executionId, payload }) => { - const answer = await new AskAgentFunction().run( + const answer = await new CreateAgentFunction().run( context(executionId) as never, "support", "You track orders.", diff --git a/actions/ai-action/test/skills.test.ts b/actions/ai-action/test/skills.test.ts index 681afec..c2b26cf 100644 --- a/actions/ai-action/test/skills.test.ts +++ b/actions/ai-action/test/skills.test.ts @@ -1,12 +1,12 @@ import "reflect-metadata"; import { RuntimeError } from "@code0-tech/hercules"; import { describe, expect, it } from "vitest"; -import { SkillsFunction } from "../src/runtimefunctions/agent/Agent.skills.runtimefunction.js"; +import { SkillsFunction } from "../src/runtimefunctions/tool/Tool.skills.runtimefunction.js"; const skills = new SkillsFunction(); const context = {} as never; -describe("ai::agent::skills", () => { +describe("ai::tool::skills", () => { it("creates a named tool that returns the complete Markdown skill", async () => { const tool = skills.run(context, [ "Intro text\n\n## SQL Analysis ##\n\nUse the query plan.", From 7b1ba6d05a535b6e8da18c58bc16e16f0371f1f3 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 23 Nov 2026 14:57:32 +0100 Subject: [PATCH 18/19] feat: update AiChatResponse to AiStructuredChatResponse for enhanced type handling and update related function signatures --- .gitlab-ci.yml | 1 + .../datatypes/chat/Chat.response.datatype.ts | 13 ++++++++----- .../agent/Agent.create.runtimefunction.ts | 17 +++++++++++------ .../src/utils/chat/Chat.toChatResponse.util.ts | 4 ++-- actions/ai-action/test/registration.test.ts | 2 +- 5 files changed, 23 insertions(+), 14 deletions(-) diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index e9953a6..091a359 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -29,6 +29,7 @@ include: - stripe-action - smtp-action - github-action + - ai-action .rust-actions: - cron-action diff --git a/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts index aece679..3403d8c 100644 --- a/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts +++ b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts @@ -25,11 +25,6 @@ export const AiChatResponseSchema = z.object({ model: z.string(), choices: z.array(AiChatChoiceSchema), usage: AiChatUsageSchema.optional(), - /** - * The answer in the type the node was asked to produce, present only when a type - * was passed as `output_schema`. The signature carries that type as a generic, so - * the flow reads this field as the very type it picked rather than as an object. - */ /** * Every tool the agent used for this answer, with its arguments and what came * back. Not part of the OpenAI schema - a chat completion has no field for the @@ -46,6 +41,14 @@ export const AiChatResponseSchema = z.object({ }); export type AiChatResponse = z.infer; +/** + * A chat response that also carries the answer in the type the node was asked to + * produce, present only when a type was passed as `answer_type`. The field is not + * part of the registered data type: the node's signature adds it as a generic, so + * the flow reads it as the very type it picked rather than as an object. + */ +export type AiStructuredChatResponse = AiChatResponse & { structured_response?: Record }; + @Identifier("AI_CHAT_RESPONSE") @Name({ code: "en-US", content: "Chat response" }) @DisplayMessage({ code: "en-US", content: "Chat response" }) diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts index b333b2f..31f5751 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts @@ -20,7 +20,7 @@ import type { AiAgentApproval } from "../../datatypes/agent/Agent.approval.datat import { AiAgentRequestSchema, type AiAgentRequest } from "../../datatypes/agent/Agent.request.datatype.js"; import { AiAgentResponseSchema, type AiAgentResponse } from "../../datatypes/agent/Agent.response.datatype.js"; import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; -import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import type { AiStructuredChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; import { AiChatRequestSchema, type AiChatRequest, @@ -197,7 +197,7 @@ export class CreateAgentFunction { answer_type?: unknown, conversation?: AiChatRequest, rules?: unknown[], - ): Promise { + ): Promise { // The "answer_type" parameter is a TYPE: the data type the flow wants the // agent to answer in. Its value reaches the action as that type's JSON schema // - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` @@ -600,10 +600,15 @@ export class CreateAgentFunction { ); } - const response: AiChatResponse = toChatResponse(last, parsed.model ?? "", answer.structured_response, { - ...(answer.steps ? { steps: answer.steps } : {}), - ...(answer.awaiting_approval ? { awaitingApproval: answer.awaiting_approval } : {}), - }); + const response: AiStructuredChatResponse = toChatResponse( + last, + parsed.model ?? "", + answer.structured_response, + { + ...(answer.steps ? { steps: answer.steps } : {}), + ...(answer.awaiting_approval ? { awaitingApproval: answer.awaiting_approval } : {}), + }, + ); return response; } } diff --git a/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts b/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts index 20c0d83..f08c200 100644 --- a/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts +++ b/actions/ai-action/src/utils/chat/Chat.toChatResponse.util.ts @@ -3,7 +3,7 @@ import type { AiAgentApproval } from "../../datatypes/agent/Agent.approval.datat import type { AiAgentStep } from "../../datatypes/agent/Agent.step.datatype.js"; import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; import type { AiChatMessage } from "../../datatypes/chat/Chat.message.datatype.js"; -import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +import type { AiStructuredChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; import type { AiChatUsage } from "../../datatypes/chat/Chat.usage.datatype.js"; import { toChatContent } from "./Chat.toChatContent.util.js"; import { toChatMessage } from "./Chat.toChatMessage.util.js"; @@ -13,7 +13,7 @@ export function toChatResponse( fallbackModel: string, structuredResponse?: Record, extras: { steps?: AiAgentStep[]; awaitingApproval?: AiAgentApproval[] } = {}, -): AiChatResponse { +): AiStructuredChatResponse { const message: AiChatMessage = toChatMessage(answer); // What the provider counted, if it counted anything: a total it did not report is diff --git a/actions/ai-action/test/registration.test.ts b/actions/ai-action/test/registration.test.ts index 6986784..2bb9102 100644 --- a/actions/ai-action/test/registration.test.ts +++ b/actions/ai-action/test/registration.test.ts @@ -131,7 +131,7 @@ describe("what the action registers", () => { // Every translated text of a node is written as `content: "..."`, which is // the node's own description as much as a parameter's. for (const match of file.content.matchAll(/content:\s*"((?:[^"\\]|\\.)*)"/gs)) { - const text: string = match[1].replaceAll('\\"', '"'); + const text: string = match[1].replace(/\\"/g, '"'); const label = `${file.name}: "${text.slice(0, 40)}..."`; expect(text.length, `${label} is ${text.length} characters`).toBeLessThanOrEqual(200); From b431a104e2d410a97487c71d3cc6f16c7da59663 Mon Sep 17 00:00:00 2001 From: nicosammito Date: Mon, 23 Nov 2026 19:26:02 +0100 Subject: [PATCH 19/19] feat: update agent creation and extraction functions to include prompt handling and improve parameter naming for clarity --- actions/ai-action/src/index.ts | 13 +++- .../openai/OpenAi.server.runtimeevent.ts | 16 ++-- .../agent/Agent.create.runtimefunction.ts | 37 ++++----- .../Extract.information.runtimefunction.ts | 78 +++++++++++++------ .../src/server/openai/OpenAi.server.ts | 18 ++++- actions/ai-action/test/agent.test.ts | 66 ++++++++-------- actions/ai-action/test/approval.test.ts | 2 +- actions/ai-action/test/extract.test.ts | 25 ++++++ actions/ai-action/test/functions.test.ts | 28 +++---- actions/ai-action/test/openai.test.ts | 9 ++- 10 files changed, 188 insertions(+), 104 deletions(-) diff --git a/actions/ai-action/src/index.ts b/actions/ai-action/src/index.ts index 70aad83..f58013d 100644 --- a/actions/ai-action/src/index.ts +++ b/actions/ai-action/src/index.ts @@ -125,10 +125,21 @@ DATA_TYPES.forEach((dataType) => action.registerDataTypeClass(dataType)); RUNTIME_FUNCTIONS.forEach((runtimeFunction) => action.registerRuntimeFunction(runtimeFunction)); RUNTIME_EVENTS.forEach((event) => action.registerRuntimeEventClass(event)); -action.on(CodeZeroEvent.error, () => { +action.on(CodeZeroEvent.connected, () => { + console.log("Connected to aquila"); +}); + +action.on(CodeZeroEvent.error, (error: Error) => { + console.error("Stream error:", error.message); + console.log(`Attempting to reconnect in ${RECONNECT_DELAY_MS / 1000}s...`); setTimeout(() => connectToAquila(action), RECONNECT_DELAY_MS); }); +action.on(CodeZeroEvent.moduleUpdated, (message: unknown) => { + console.dir(message, { depth: null }); + console.dir(action.configs.values(), { depth: null }); +}); + connectToAquila(action); // The action serves the OpenAI protocol itself: the server answers on its own port and diff --git a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts index 6d363cd..b07bbd7 100644 --- a/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts +++ b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts @@ -18,10 +18,12 @@ import { * matching flow for `POST /chat/completions`. * * The flow is handed the client's request as an `AI_CHAT_REQUEST` - the type - * `ai::agent::create` takes - and answers it with `ai::openai::respond`, from wherever - * in the flow that belongs, so a flow that logs or stores something after the agent - * still answers with the agent's reply. A flow that never responds falls back to its - * own return value. + * `ai::agent::create` takes - with `prompt` added to it: what the user last said, as + * text, so a flow that only wants that one message reads a field instead of walking + * the messages itself. It answers with `ai::openai::respond`, from wherever in the + * flow that belongs, so a flow that logs or stores something after the agent still + * answers with the agent's reply. A flow that never responds falls back to its own + * return value. * * `route` is the path the endpoint lives under, with the project's slug in front of * it, and unique per project. `model` is the name a client sees and picks, which every @@ -32,7 +34,7 @@ import { @Identifier("ai::openai::server") @DisplayIcon("tabler:ai") @Editable() -@Signature("(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST") +@Signature("(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST & { prompt: TEXT }") @Name({ code: "en-US", content: "OpenAI endpoint" }) @Description({ code: "en-US", @@ -51,12 +53,10 @@ import { content: "The path this endpoint is reached under, \"/v1\" by default. A chat client is given the project's own address followed by this path as its server address, and finds the rest on its own.", }, - ], - defaultValue: "/v1", + ] }) @EventSetting({ identifier: "model", - unique: "PROJECT", name: [{ code: "en-US", content: "Model" }], description: [ { diff --git a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts index 31f5751..6e47d9c 100644 --- a/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts @@ -70,7 +70,7 @@ const EXTRACTION_PROMPT = @Identifier("ai::agent::create") @DisplayIcon("tabler:ai") @Signature( - "(name: TEXT, instructions: TEXT, model: TRANSFORM, question: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, answer_type?: T, conversation?: AI_CHAT_REQUEST, rules?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", + "(name: TEXT, model: TRANSFORM, prompt: TEXT, instructions?: TEXT, tools?: LIST<((...args: any[]) => any) | AI_MCP_SERVER>, answer_type?: T, conversation?: AI_CHAT_REQUEST, rules?: LIST>): AI_CHAT_RESPONSE & { structured_response: T }", ) @Name({ code: "en-US", content: "Create agent" }) @Alias({ code: "en-US", content: "agent;ai;llm;chat;prompt;assistant;tools" }) @@ -79,7 +79,7 @@ const EXTRACTION_PROMPT = content: "Asks an AI agent a question and waits for its answer. Give it instructions, a model to think with and flows as tools - it decides on its own what to use until it can answer.", }) -@DisplayMessage({ code: "en-US", content: "Ask the agent ${name} ${question}" }) +@DisplayMessage({ code: "en-US", content: "Ask the agent ${name} ${prompt}" }) @ThrowsError() @Parameter({ runtimeName: "name", @@ -93,37 +93,38 @@ const EXTRACTION_PROMPT = ], }) @Parameter({ - runtimeName: "instructions", - name: [{ code: "en-US", content: "Instructions" }], + runtimeName: "model", + name: [{ code: "en-US", content: "Model" }], description: [ { code: "en-US", content: - "What the agent is and how it should work: its role, what it may do, how the answer should read. The agent is told this before every turn.", + "The model the agent thinks with, built by one of the model nodes. The model decides which provider is called and on what key; the agent only hands it the conversation and the tools.", }, ], }) @Parameter({ - runtimeName: "model", - name: [{ code: "en-US", content: "Model" }], + runtimeName: "prompt", + name: [{ code: "en-US", content: "Prompt" }], description: [ { code: "en-US", content: - "The model the agent thinks with, built by one of the model nodes. The model decides which provider is called and on what key; the agent only hands it the conversation and the tools.", + "What the agent is asked this time. It comes after everything the conversation already holds. Leave it empty when the conversation already ends in a question.", }, ], }) @Parameter({ - runtimeName: "question", - name: [{ code: "en-US", content: "Question" }], + runtimeName: "instructions", + name: [{ code: "en-US", content: "Instructions" }], description: [ { code: "en-US", content: - "What the agent is asked this time. It comes after everything the conversation already holds. Leave it empty when the conversation already ends in a question.", + "What the agent is and how it should work: its role, what it may do, how the answer should read. The agent is told this before every turn.", }, ], + optional: true, }) @Parameter({ runtimeName: "tools", @@ -156,7 +157,7 @@ const EXTRACTION_PROMPT = { code: "en-US", content: - "Everything that was said before, as a chat client sends it. Those messages go ahead of the question, which is how a chat endpoint hands the agent the conversation it is to carry on.", + "Everything that was said before, as a chat client sends it. Those messages go ahead of the prompt, which is how a chat endpoint hands the agent the conversation it is to carry on.", }, ], optional: true, @@ -184,15 +185,15 @@ export class CreateAgentFunction { * references are scoped to. * * The parameters are ordered by how often a flow reaches for them: what every - * agent needs first, then the tools and the answer's type, and the conversation - * and the rules last. + * agent needs first - a name, a model, a prompt - then the instructions, the + * tools and the answer's type, and the conversation and the rules last. */ async run( _context: FunctionContext, name: string, - instructions: string, model: unknown, - question: string, + prompt: string, + instructions?: string, tools?: ToolEntry[], answer_type?: unknown, conversation?: AiChatRequest, @@ -269,7 +270,7 @@ export class CreateAgentFunction { "ERROR_INVALID_AI_CHAT_REQUEST", "The chat request is not valid", ); - const asked: string = asText(question, "question", "ERROR_INVALID_AI_CHAT_REQUEST"); + const asked: string = asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"); const history: AiMessage[] = [ ...parsed.messages.map(fromChatMessage), ...(asked.length > 0 @@ -279,7 +280,7 @@ export class CreateAgentFunction { if (history.length === 0) { throw new RuntimeError( "ERROR_INVALID_AI_CHAT_REQUEST", - "There is nothing to ask: the question is empty and the conversation carries no messages.", + "There is nothing to ask: the prompt is empty and the conversation carries no messages.", ); } diff --git a/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts index 10dcad6..f87a4e4 100644 --- a/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts +++ b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts @@ -12,11 +12,14 @@ import { ThrowsError, } from "@code0-tech/hercules"; import { createAgent, type ReactAgent } from "langchain"; +import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; +import type { AiMessage } from "../../datatypes/message/Message.datatype.js"; import { FlowChatModel } from "../../model/Model.flowChatModel.js"; import { asSubFlow } from "../../utils/shared/Shared.asSubFlow.util.js"; import { asText } from "../../utils/shared/Shared.asText.util.js"; import { describeError } from "../../utils/shared/Shared.describeError.util.js"; -import { requireText } from "../../utils/shared/Shared.requireText.util.js"; +import { fromChatMessage } from "../../utils/chat/Chat.fromChatMessage.util.js"; +import { parseOrThrow } from "../../utils/shared/Shared.parseOrThrow.util.js"; import { toLangChainMessage } from "../../utils/message/Message.toLangChainMessage.util.js"; import { toPlainSchema } from "../../utils/shared/Shared.toPlainSchema.util.js"; @@ -33,7 +36,7 @@ const EXTRACTION_PROMPT = @Identifier("ai::extract::information") @DisplayIcon("tabler:ai") @Signature( - "(text: TEXT, information: T, model: TRANSFORM, instructions?: TEXT): T", + "(prompt: TEXT, answer_type: T, model: TRANSFORM, instructions?: TEXT, conversation?: AI_CHAT_REQUEST): T", ) @Name({ code: "en-US", content: "Read information from text" }) @Alias({ code: "en-US", content: "extract;extraction;information;read;parse;fields;structured;ai;llm" }) @@ -42,11 +45,11 @@ const EXTRACTION_PROMPT = content: "Reads a text and fills the fields of a data type with what it says - names, dates, amounts - so the flow can work with them instead of searching the text itself.", }) -@DisplayMessage({ code: "en-US", content: "Read ${information} out of ${text}" }) +@DisplayMessage({ code: "en-US", content: "Read ${answer_type} out of ${prompt}" }) @ThrowsError() @Parameter({ - runtimeName: "text", - name: [{ code: "en-US", content: "Text" }], + runtimeName: "prompt", + name: [{ code: "en-US", content: "Prompt" }], description: [ { code: "en-US", @@ -56,8 +59,8 @@ const EXTRACTION_PROMPT = ], }) @Parameter({ - runtimeName: "information", - name: [{ code: "en-US", content: "Information" }], + runtimeName: "answer_type", + name: [{ code: "en-US", content: "Answer type" }], description: [ { code: "en-US", @@ -89,6 +92,18 @@ const EXTRACTION_PROMPT = ], optional: true, }) +@Parameter({ + runtimeName: "conversation", + name: [{ code: "en-US", content: "Conversation" }], + description: [ + { + code: "en-US", + content: + "Everything that was said before, as a chat client sends it. Those messages go ahead of the prompt, so the fields are read out of the whole conversation and not just one text.", + }, + ], + optional: true, +}) export class ExtractInformationFunction { /** * One model call with the type forced on the answer, and no tools: there is @@ -97,39 +112,56 @@ export class ExtractInformationFunction { * response format or as a forced tool call - is {@link FlowChatModel}'s business, * decided from what the model node declared it can do. * - * The parameters read as the sentence the node is: this text, this information, - * read by this model. + * The parameters read as the sentence the node is: this prompt, read into this + * answer type by this model. */ async run( _context: FunctionContext, - text: string, - information: unknown, + prompt: string, + answer_type: unknown, model: unknown, instructions?: string, + conversation?: AiChatRequest, ): Promise> { - const read: string = requireText( - text, - "ERROR_INVALID_AI_EXTRACTION", - 'There is nothing to read: the "text" parameter is empty.', - ); + const read: string = asText(prompt, "prompt", "ERROR_INVALID_AI_EXTRACTION").trim(); const added: string = asText(instructions ?? "", "instructions", "ERROR_INVALID_AI_EXTRACTION"); - // The "information" parameter is a TYPE, so it arrives as that type's JSON + // What was said before comes ahead of the prompt, which is how a chat endpoint + // hands this node the conversation the fields are read out of. The prompt may + // then be empty, as long as the conversation carries something to read. + const parsed: AiChatRequest = parseOrThrow( + AiChatRequestSchema, + conversation ?? { messages: [] }, + "ERROR_INVALID_AI_CHAT_REQUEST", + "The chat request is not valid", + ); + const history: AiMessage[] = [ + ...parsed.messages.map(fromChatMessage), + ...(read.length > 0 ? [{ role: "human", content: [{ type: "text", text: read }] } as AiMessage] : []), + ]; + if (history.length === 0) { + throw new RuntimeError( + "ERROR_INVALID_AI_EXTRACTION", + "There is nothing to read: the prompt is empty and the conversation carries no messages.", + ); + } + + // The "answer_type" parameter is a TYPE, so it arrives as that type's JSON // schema - as a protobuf Struct when aquila wrapped it, which `toPlainSchema` // unwraps either way. A structured answer has to be an object to come back as // a data type's value, so anything else is rejected here rather than deep // inside the model call. - const schema: Record | undefined = toPlainSchema(information); + const schema: Record | undefined = toPlainSchema(answer_type); if (!schema || typeof schema !== "object") { throw new RuntimeError( "ERROR_INVALID_AI_OUTPUT_SCHEMA", - `The "information" parameter has to be a type, but a ${typeof information} was passed.`, + `The "answer_type" parameter has to be a type, but a ${typeof answer_type} was passed.`, ); } if (!("properties" in schema)) { throw new RuntimeError( "ERROR_INVALID_AI_OUTPUT_SCHEMA", - 'The text can only be read into a type with fields: the type passed as "information" has none.', + 'The text can only be read into a type with fields: the type passed as "answer_type" has none.', ); } @@ -149,9 +181,7 @@ export class ExtractInformationFunction { ); } - const result = await extractor.invoke({ - messages: [toLangChainMessage({ role: "human", content: [{ type: "text", text: read }] })], - }); + const result = await extractor.invoke({ messages: history.map(toLangChainMessage) }); const answer: unknown = result.structuredResponse; // Without the structured answer the node's return value would be missing the @@ -160,7 +190,7 @@ export class ExtractInformationFunction { if (!answer || typeof answer !== "object") { throw new RuntimeError( "ERROR_FAILED_AI_EXTRACTION", - 'The model did not answer in the type passed as "information".', + 'The model did not answer in the type passed as "answer_type".', ); } diff --git a/actions/ai-action/src/server/openai/OpenAi.server.ts b/actions/ai-action/src/server/openai/OpenAi.server.ts index 8e9654c..09513a9 100644 --- a/actions/ai-action/src/server/openai/OpenAi.server.ts +++ b/actions/ai-action/src/server/openai/OpenAi.server.ts @@ -1,6 +1,7 @@ import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; import type { PlainValue } from "@code0-tech/hercules"; import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import type { AiChatMessage } from "../../datatypes/chat/Chat.message.datatype.js"; import { AiChatRequestSchema, type AiChatRequest } from "../../datatypes/chat/Chat.request.datatype.js"; import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; import type { OpenAiEndpoint, OpenAiRequestPath } from "../../types/openai/OpenAi.types.js"; @@ -222,11 +223,26 @@ export class OpenAiServer { // its respond node runs - which can be before executeFlow even resolves. const executionId: string = this.action.reserveExecutionId(); + // What the user last said, flattened to text and handed over next to the + // request itself: a flow that only wants that one message then reads a field + // instead of walking the messages. Empty when the last turn was not the + // user's, which the flow can treat the way the agent treats an empty prompt. + const last: AiChatMessage | undefined = [...request.messages] + .reverse() + .find((message) => message.role === "user"); + const prompt: string = + typeof last?.content === "string" + ? last.content + : (Array.isArray(last?.content) ? last.content : []) + .filter((part) => part.type === "text") + .map((part) => String((part as { text?: unknown }).text ?? "")) + .join(""); + const responded: Promise<{ answer: AiChatResponse }> = pendingResponses .open(executionId, endpoint.model) .then((answer) => ({ answer })); const finished: Promise<{ result: PlainValue }> = this.action - .executeFlowWithId(executionId, endpoint.flow.flowId, request as unknown as PlainValue) + .executeFlowWithId(executionId, endpoint.flow.flowId, { ...request, prompt } as unknown as PlainValue) .then((result) => ({ result })); try { diff --git a/actions/ai-action/test/agent.test.ts b/actions/ai-action/test/agent.test.ts index 355cd4c..3d13cb8 100644 --- a/actions/ai-action/test/agent.test.ts +++ b/actions/ai-action/test/agent.test.ts @@ -121,7 +121,7 @@ function asStruct(plain: Record): unknown { describe("ai::agent::create", () => { it("answers with a chat response, because it runs the agent itself", async () => { const { run } = scriptedModel([answer("hello")]); - const response = await ask.run(context(), "greeter", "You greet people.", run, "hi"); + const response = await ask.run(context(), "greeter", run, "hi", "You greet people."); expect(response.object).toEqual("chat.completion"); expect(replyOf(response)).toEqual("hello"); @@ -132,7 +132,7 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), ]); - const response = await ask.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + const response = await ask.run(context(), "support", run, "where is A-1?", "", undefined, orderType); // The type travels to the model as the tool it has to call to answer. expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Order"]); @@ -144,14 +144,14 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-1", status: "shipped" } }]), ]); - await ask.run(context(), "support", "", run, "where is A-1?", undefined, orderType); + await ask.run(context(), "support", run, "where is A-1?", "", undefined, orderType); expect(requests[0].tool_choice).toBe("any"); }); it("leaves the tool choice alone when no type was asked for", async () => { const { run, requests } = scriptedModel([answer("hello")]); - await ask.run(context(), "greeter", "", run, "hi"); + await ask.run(context(), "greeter", run, "hi", ""); expect(requests[0].tool_choice).toBeUndefined(); }); @@ -162,7 +162,7 @@ describe("ai::agent::create", () => { nativeModelSchema, ); - const response = await ask.run(context(), "support", "", run, "where is A-3?", undefined, orderType); + const response = await ask.run(context(), "support", run, "where is A-3?", "", undefined, orderType); // No tool to call and nothing to force: the type travels as the format the // answer has to be written in, and is read back off the message. @@ -181,7 +181,7 @@ describe("ai::agent::create", () => { ); const flowTool = subFlow(() => "ok"); - const response = await ask.run(context(), "support", "", run, "make one", [flowTool], orderType); + const response = await ask.run(context(), "support", run, "make one", "", [flowTool], orderType); // First the agent works, with its tools and no type in the request. expect(requests[0].tools.map((tool) => tool.name)).toEqual(["tool_1"]); @@ -200,7 +200,7 @@ describe("ai::agent::create", () => { answer("", [{ id: "call-1", name: "Order", args: { order: "A-6", status: "open" } }]), ]); - const response = await ask.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); + const response = await ask.run(context(), "support", run, "make one", "", [subFlow(() => "ok")], orderType); // The flow tool is bound for the work, and the extract tool alone for the // type - never the two together, which is what a provider refuses. @@ -215,14 +215,14 @@ describe("ai::agent::create", () => { nativeModelSchema, ); - const response = await ask.run(context(), "support", "", run, "make one", [subFlow(() => "ok")], orderType); + const response = await ask.run(context(), "support", run, "make one", "", [subFlow(() => "ok")], orderType); expect(replyOf(response)).toEqual("I made you a user object."); }); it("asks for no format when a model that could constrain its output was given no type", async () => { const { run, requests } = scriptedModel([answer("hello")], nativeModelSchema); - await ask.run(context(), "greeter", "", run, "hi"); + await ask.run(context(), "greeter", run, "hi", ""); expect(requests[0].response_format).toBeUndefined(); }); @@ -235,9 +235,9 @@ describe("ai::agent::create", () => { const response = await ask.run( context(), "support", - "", run, "where is A-2?", + "", undefined, asStruct(orderType), ); @@ -248,7 +248,7 @@ describe("ai::agent::create", () => { it("leaves the structured answer out when no type was asked for", async () => { const { run } = scriptedModel([answer("hello")]); - const response = await ask.run(context(), "greeter", "", run, "hi"); + const response = await ask.run(context(), "greeter", run, "hi", ""); expect(response.structured_response).toBeUndefined(); }); @@ -256,44 +256,44 @@ describe("ai::agent::create", () => { it("rejects a type the agent cannot answer in", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - ask.run(context(), "support", "", run, "hi", undefined, { type: "string" }), + ask.run(context(), "support", run, "hi", "", undefined, { type: "string" }), ).rejects.toThrow(/type with fields/); }); it("fails when the agent ignores the type it was asked to answer in", async () => { const { run } = scriptedModel([answer("just text")]); - await expect(ask.run(context(), "support", "", run, "hi", undefined, orderType)).rejects.toThrow( + await expect(ask.run(context(), "support", run, "hi", "", undefined, orderType)).rejects.toThrow( /did not answer in the type/, ); }); it("needs a name", async () => { const { run } = scriptedModel([answer("hello")]); - await expect(ask.run(context(), "", "", run, "hi")).rejects.toThrow(RuntimeError); + await expect(ask.run(context(), "", run, "hi", "")).rejects.toThrow(RuntimeError); }); it("needs something to ask", async () => { const { run } = scriptedModel([answer("hello")]); - await expect(ask.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + await expect(ask.run(context(), "greeter", run, "", "")).rejects.toThrow(/nothing to ask/); }); it("rejects a model that is not a sub flow", async () => { await expect( - ask.run(context(), "greeter", "", { provider: "anthropic", model: "claude-opus-5" } as never, "hi"), + ask.run(context(), "greeter", { provider: "anthropic", model: "claude-opus-5" } as never, "hi", ""), ).rejects.toThrow(RuntimeError); }); it("rejects an MCP server missing what its transport needs, before the agent runs", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - ask.run(context(), "greeter", "", run, "hi", [{ name: "docs", transport: "stdio" }] as never), + ask.run(context(), "greeter", run, "hi", "", [{ name: "docs", transport: "stdio" }] as never), ).rejects.toThrow(RuntimeError); }); it("rejects two MCP servers with the same name", async () => { const { run } = scriptedModel([answer("hello")]); await expect( - ask.run(context(), "greeter", "", run, "hi", [ + ask.run(context(), "greeter", run, "hi", "", [ { name: "docs", url: "https://a/mcp" }, { name: "docs", url: "https://b/mcp" }, ] as never), @@ -304,7 +304,7 @@ describe("ai::agent::create", () => { describe("the agent loop", () => { it("runs the model sub flow and returns its answer", async () => { const { run, requests } = scriptedModel([answer("Hi there.")]); - const response = await ask.run(context(), "greeter", "You greet people.", run, "hello"); + const response = await ask.run(context(), "greeter", run, "hello", "You greet people."); expect(requests).toHaveLength(1); expect(requests[0].messages.map((m) => m.role)).toEqual(["system", "human"]); @@ -326,7 +326,7 @@ describe("the agent loop", () => { { type: "object", description: "Looks an order up.", properties: { order: { type: "string" } } }, ); - const response = await ask.run(context(), "support", "", run, "where is A-1?", [lookup]); + const response = await ask.run(context(), "support", run, "where is A-1?", "", [lookup]); expect(requests[0].tools).toEqual([ { @@ -349,9 +349,9 @@ describe("the agent loop", () => { const response = await ask.run( context(), "support", - "", run, "read the guide", + "", undefined, undefined, { @@ -406,7 +406,7 @@ describe("the agent loop", () => { throw new Error("the warehouse is offline"); }); - const response = await ask.run(context(), "support", "", run, "status?", [broken]); + const response = await ask.run(context(), "support", run, "status?", "", [broken]); expect(JSON.stringify(requests[1].messages.at(-1)?.content)).toContain("the warehouse is offline"); expect(replyOf(response)).toEqual("That did not work."); @@ -433,9 +433,9 @@ describe("the agent loop", () => { await ask.run( context(), "support", - "", run, "my card is 4111111111111111", + "", [], undefined, undefined, @@ -452,9 +452,9 @@ describe("the agent loop", () => { const response = await ask.run( context(), "support", - "", run, "hello", + "", [], undefined, undefined, @@ -477,9 +477,9 @@ describe("the agent loop", () => { const response = await ask.run( context(), "support", - "", run, "hello", + "", [], undefined, undefined, @@ -495,13 +495,13 @@ describe("the agent loop", () => { const lookup = subFlow(() => ({ status: "shipped" }), { type: "object", description: "Looks an order up." }); await expect( - ask.run(context(), "support", "", run, "hello", [ + ask.run(context(), "support", run, "hello", "", [ lookup, { name: "docs", transport: "stdio" }, ] as never), ).rejects.toThrow(/needs a command/); - await ask.run(context(), "support", "", run, "hello", [lookup]); + await ask.run(context(), "support", run, "hello", "", [lookup]); expect(requests[0].tools.map((t) => t.name)).toEqual(["tool_1"]); }); @@ -516,7 +516,7 @@ describe("the agent loop", () => { }); const nameless = subFlow(() => "nothing"); - await ask.run(context(), "support", "", run, "hello", [now as never, nameless as never]); + await ask.run(context(), "support", run, "hello", "", [now as never, nameless as never]); expect(requests[0].tools).toEqual([ { @@ -542,7 +542,7 @@ describe("the agent loop", () => { ); const sameName = subFlow(() => null, asStruct({ title: "Look up order" }) as never); - await ask.run(context(), "support", "", run, "hello", [lookup as never, sameName as never]); + await ask.run(context(), "support", run, "hello", "", [lookup as never, sameName as never]); expect(requests[0].tools.map((tool) => tool.name)).toEqual(["look_up_order", "look_up_order_2"]); expect(requests[0].tools[0].description).toEqual("Looks an order up."); @@ -556,13 +556,13 @@ describe("the agent loop", () => { it("rejects a tool entry that is neither a sub flow nor an MCP server", async () => { const { run } = scriptedModel([answer("ok")]); await expect( - ask.run(context(), "support", "", run, "hello", [{ nonsense: true }] as never), + ask.run(context(), "support", run, "hello", "", [{ nonsense: true }] as never), ).rejects.toThrow(/Entry 1 of "tools"/); }); it("fails with a clear error when the model sub flow answers with the wrong shape", async () => { const run = subFlow(() => ({ message: { role: "ai", content: "not a list" } })); - await expect(ask.run(context(), "greeter", "", run, "hello")).rejects.toThrow( + await expect(ask.run(context(), "greeter", run, "hello", "")).rejects.toThrow( /did not return a valid model response/, ); }); @@ -577,7 +577,7 @@ describe("what a middleware flow is handed", () => { return {}; }); - await ask.run(context(), "support", "You are helpful.", run, "hello", [], undefined, undefined, [observe]); + await ask.run(context(), "support", run, "hello", "You are helpful.", [], undefined, undefined, [observe]); expect(seen[0].context).toBeUndefined(); expect(Object.keys(seen[0])).toEqual(["messages", "agent_name", "hook"]); @@ -599,9 +599,9 @@ describe("composing the shipped functions into an agent", () => { const response = await ask.run( context(), "support", - "You are helpful.", run, "", + "You are helpful.", [], undefined, { messages: long }, diff --git a/actions/ai-action/test/approval.test.ts b/actions/ai-action/test/approval.test.ts index 0a12704..d3c3c43 100644 --- a/actions/ai-action/test/approval.test.ts +++ b/actions/ai-action/test/approval.test.ts @@ -77,9 +77,9 @@ function chat( return ask.run( context(), "support", - "You help.", model, "", + "You help.", tools, undefined, { messages: conversation } as never, diff --git a/actions/ai-action/test/extract.test.ts b/actions/ai-action/test/extract.test.ts index bffeede..917a0ac 100644 --- a/actions/ai-action/test/extract.test.ts +++ b/actions/ai-action/test/extract.test.ts @@ -147,6 +147,31 @@ describe("ai::extract::information", () => { expect(requests[0].tools.map((tool) => tool.name)).toEqual(["Invoice"]); }); + it("puts what was said before ahead of the prompt", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77" } }]), + ]); + + await extract.run(context(), "what is the number?", invoiceType, run, undefined, { + messages: [{ role: "user", content: text }], + }); + + // The system prompt, then the conversation, then what this call asks for. + expect(requests[0].messages.map((message) => message.role)).toEqual(["system", "human", "human"]); + expect(requests[0].messages[1].content).toEqual([{ type: "text", text }]); + }); + + it("reads a conversation without a prompt of its own", async () => { + const { run, requests } = scriptedModel([ + answer("", [{ id: "call-1", name: "Invoice", args: { number: "R-77" } }]), + ]); + + await expect( + extract.run(context(), "", invoiceType, run, undefined, { messages: [{ role: "user", content: text }] }), + ).resolves.toEqual({ number: "R-77" }); + expect(requests[0].messages.map((message) => message.role)).toEqual(["system", "human"]); + }); + it("needs a text to read", async () => { const { run } = scriptedModel([answer("")]); diff --git a/actions/ai-action/test/functions.test.ts b/actions/ai-action/test/functions.test.ts index 30ab53f..94909e4 100644 --- a/actions/ai-action/test/functions.test.ts +++ b/actions/ai-action/test/functions.test.ts @@ -170,7 +170,7 @@ describe("ai::model::openrouter", () => { // Reaches the model, which rejects the test key - proof the agent accepted it. await expect( - ask.run(context(), "support", "You are helpful.", asFlowValue(transform), "hi"), + ask.run(context(), "support", asFlowValue(transform), "hi", "You are helpful."), ).rejects.toThrow(RuntimeError); }, 30_000); }); @@ -330,9 +330,9 @@ describe("the chat format of ai::agent::create", () => { const response = await ask.run( context(), "greeter", - "You greet people.", run, "hello", + "You greet people.", undefined, undefined, { model: "my-agent", messages: [{ role: "system", content: "Be brief." }] }, @@ -352,7 +352,7 @@ describe("the chat format of ai::agent::create", () => { it("translates a multimodal prompt into content blocks", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "A cat." }])]); - await ask.run(context(), "describer", "", run, "", undefined, undefined, { + await ask.run(context(), "describer", run, "", "", undefined, undefined, { messages: [ { role: "user", @@ -379,9 +379,9 @@ describe("the chat format of ai::agent::create", () => { const response = await ask.run( context(), "support", - "", run, "and A-1?", + "", [lookup], undefined, { @@ -411,7 +411,7 @@ describe("the chat format of ai::agent::create", () => { it("keeps a malformed tool call instead of failing the request", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - await ask.run(context(), "support", "", run, "again?", undefined, undefined, { + await ask.run(context(), "support", run, "again?", "", undefined, undefined, { messages: [ { role: "assistant", @@ -434,14 +434,14 @@ describe("the chat format of ai::agent::create", () => { { type: "text", text: "Hi." }, ]), ]); - const response = await ask.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", run, "hello", ""); expect(response.choices[0].message.content).toEqual("Hi."); }); it("takes just a prompt, with no request at all", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Hi." }])]); - const response = await ask.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", run, "hello", ""); expect(requests[0].messages.at(-1)?.content).toEqual([{ type: "text", text: "hello" }]); expect(response.choices[0].message.content).toEqual("Hi."); @@ -449,7 +449,7 @@ describe("the chat format of ai::agent::create", () => { it("appends the prompt to the conversation the request carries", async () => { const { run, requests } = scriptedModel([generation([{ type: "text", text: "Still fine." }])]); - await ask.run(context(), "greeter", "", run, "and now?", undefined, undefined, { + await ask.run(context(), "greeter", run, "and now?", "", undefined, undefined, { messages: [ { role: "user", content: "how are you?" }, { role: "assistant", content: "fine" }, @@ -463,7 +463,7 @@ describe("the chat format of ai::agent::create", () => { it("carries the answer as plain text next to the OpenAI shape", async () => { const { run } = scriptedModel([generation([{ type: "text", text: "Two parts. " }, { type: "text", text: "One answer." }])]); - const response = await ask.run(context(), "greeter", "", run, "hello"); + const response = await ask.run(context(), "greeter", run, "hello", ""); expect(response.response).toEqual("Two parts. One answer."); expect(response.object).toEqual("chat.completion"); @@ -476,7 +476,7 @@ describe("the chat format of ai::agent::create", () => { ]); const lookup = (async () => ({ ok: true })) as unknown as SubFlow; - const response = await ask.run(context(), "support", "", run, "hi", [lookup]); + const response = await ask.run(context(), "support", run, "hi", "", [lookup]); // The run ends on a text answer, so this one is filled; the tool-call-only // turn in between is what an empty `response` would come from. @@ -486,12 +486,12 @@ describe("the chat format of ai::agent::create", () => { it("rejects having nothing to ask", async () => { const { run } = scriptedModel([generation([{ type: "text", text: "ok" }])]); - await expect(ask.run(context(), "greeter", "", run, "")).rejects.toThrow(/nothing to ask/); + await expect(ask.run(context(), "greeter", run, "", "")).rejects.toThrow(/nothing to ask/); await expect( - ask.run(context(), "greeter", "", run, "", undefined, undefined, { messages: [] }), + ask.run(context(), "greeter", run, "", "", undefined, undefined, { messages: [] }), ).rejects.toThrow(/nothing to ask/); await expect( - ask.run(context(), "greeter", "", run, "hi", undefined, undefined, { + ask.run(context(), "greeter", run, "hi", "", undefined, undefined, { messages: "nope", } as never), ).rejects.toThrow(/not valid/); @@ -619,9 +619,9 @@ describe("the model nodes", () => { const response = await ask.run( context(), "support", - "You are helpful.", asFlowValue(anthropic.run(context(), "claude-opus-5", "sk-ant-test")), "hi", + "You are helpful.", ); expect(response.choices[0]?.message.content).toContain("ok"); diff --git a/actions/ai-action/test/openai.test.ts b/actions/ai-action/test/openai.test.ts index 367f843..86a14ec 100644 --- a/actions/ai-action/test/openai.test.ts +++ b/actions/ai-action/test/openai.test.ts @@ -181,8 +181,9 @@ describe("the OpenAI endpoint", () => { expect(response.status).toEqual(200); expect(calls.map((call) => call.flowId)).toEqual([2n]); - // The flow is handed the request itself, which is what ai::agent::create takes. - expect(calls[0].payload).toMatchObject({ messages: [{ role: "user", content: "hi" }] }); + // The flow is handed the request itself, which is what ai::agent::create takes, + // with what the user last said next to it as plain text. + expect(calls[0].payload).toMatchObject({ messages: [{ role: "user", content: "hi" }], prompt: "hi" }); expect(body.response).toEqual("triage here"); // A client matches the answer against the model it asked for. expect(body.model).toEqual("triage"); @@ -356,9 +357,9 @@ describe("the flow a client ends up talking to", () => { const answer = await new CreateAgentFunction().run( context(executionId) as never, "support", - "You track orders.", model, "", + "You track orders.", undefined, undefined, payload as unknown as AiChatRequest, @@ -455,7 +456,7 @@ describe("what the event offers a flow", () => { it("hands the flow the client's request as a chat request", () => { expect(Reflect.getMetadata("hercules:signature", AiOpenAiServerRuntimeEvent)).toEqual( - "(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST", + "(route: TEXT, model: TEXT, api_key?: TEXT): AI_CHAT_REQUEST & { prompt: TEXT }", ); }); });