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/.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..5e636be --- /dev/null +++ b/actions/ai-action/Dockerfile @@ -0,0 +1,16 @@ +FROM node:24.10.0-alpine + +WORKDIR /app + +COPY package.json package-lock.json* ./ + +RUN npm ci + +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/manifest.json b/actions/ai-action/manifest.json new file mode 100644 index 0000000..fb32089 --- /dev/null +++ b/actions/ai-action/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "ai", + "identifier": "ai-action", + "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 new file mode 100644 index 0000000..d9aae34 --- /dev/null +++ b/actions/ai-action/package-lock.json @@ -0,0 +1,3944 @@ +{ + "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.9.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": "^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.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": { + "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.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.86", + "@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.86", + "resolved": "https://registry.npmjs.org/@code0-tech/tucana/-/tucana-0.0.86.tgz", + "integrity": "sha512-CUIjP837mXM8T6ILwRCZNKTTARt/i12JxjQw3YPB03Hn2L96aineDVOE4XxjxCRzMJRE9+aZZtwh0jZuzbKWVg==", + "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.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.1.4", + "@standard-schema/spec": "^1.1.0", + "js-tiktoken": "^1.0.12", + "langsmith": ">=0.11.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.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.20", + "@types/json-schema": "^7.0.15", + "p-queue": "^9.0.1", + "p-retry": "^7.1.1" + }, + "peerDependencies": { + "@langchain/core": "^1.3.2", + "react": "^18 || ^19", + "react-dom": "^18 || ^19" + }, + "peerDependenciesMeta": { + "react": { + "optional": true + }, + "react-dom": { + "optional": true + } + } + }, + "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", + "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==", + "license": "MIT" + }, + "node_modules/@langchain/langgraph-sdk/node_modules/p-queue": { + "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", + "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/@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.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" + }, + "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..cc155c2 --- /dev/null +++ b/actions/ai-action/package.json @@ -0,0 +1,32 @@ +{ + "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.9.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": "^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/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/datatypes/agent/Agent.request.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.request.datatype.ts new file mode 100644 index 0000000..61a1da9 --- /dev/null +++ b/actions/ai-action/src/datatypes/agent/Agent.request.datatype.ts @@ -0,0 +1,14 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../message/Message.datatype.js"; + +export const AiAgentRequestSchema = z.object({ + messages: z.array(AiMessageSchema), +}); +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/datatypes/agent/Agent.response.datatype.ts b/actions/ai-action/src/datatypes/agent/Agent.response.datatype.ts new file mode 100644 index 0000000..be02294 --- /dev/null +++ b/actions/ai-action/src/datatypes/agent/Agent.response.datatype.ts @@ -0,0 +1,21 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +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; + +@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/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/datatypes/chat/Chat.choice.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.choice.datatype.ts new file mode 100644 index 0000000..cb344df --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/chat/Chat.contentPart.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.contentPart.datatype.ts new file mode 100644 index 0000000..3a99862 --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/chat/Chat.message.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.message.datatype.ts new file mode 100644 index 0000000..e2f79b3 --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/chat/Chat.request.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts new file mode 100644 index 0000000..682e09a --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/Chat.request.datatype.ts @@ -0,0 +1,26 @@ +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; + +@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/datatypes/chat/Chat.response.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts new file mode 100644 index 0000000..3403d8c --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/Chat.response.datatype.ts @@ -0,0 +1,56 @@ +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(), + /** + * 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; + +/** + * 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" }) +@Schema(AiChatResponseSchema) +export class AiChatResponseDataType {} diff --git a/actions/ai-action/src/datatypes/chat/Chat.role.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.role.datatype.ts new file mode 100644 index 0000000..24a8164 --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/chat/Chat.toolCall.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.toolCall.datatype.ts new file mode 100644 index 0000000..79c4271 --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/chat/Chat.usage.datatype.ts b/actions/ai-action/src/datatypes/chat/Chat.usage.datatype.ts new file mode 100644 index 0000000..475499b --- /dev/null +++ b/actions/ai-action/src/datatypes/chat/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/datatypes/mcp/Mcp.server.datatype.ts b/actions/ai-action/src/datatypes/mcp/Mcp.server.datatype.ts new file mode 100644 index 0000000..33019f8 --- /dev/null +++ b/actions/ai-action/src/datatypes/mcp/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/datatypes/mcp/Mcp.transport.datatype.ts b/actions/ai-action/src/datatypes/mcp/Mcp.transport.datatype.ts new file mode 100644 index 0000000..2e067c6 --- /dev/null +++ b/actions/ai-action/src/datatypes/mcp/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/datatypes/message/Message.contentBlock.datatype.ts b/actions/ai-action/src/datatypes/message/Message.contentBlock.datatype.ts new file mode 100644 index 0000000..6164849 --- /dev/null +++ b/actions/ai-action/src/datatypes/message/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/datatypes/message/Message.datatype.ts b/actions/ai-action/src/datatypes/message/Message.datatype.ts new file mode 100644 index 0000000..14a76f3 --- /dev/null +++ b/actions/ai-action/src/datatypes/message/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/datatypes/message/Message.role.datatype.ts b/actions/ai-action/src/datatypes/message/Message.role.datatype.ts new file mode 100644 index 0000000..fa0990d --- /dev/null +++ b/actions/ai-action/src/datatypes/message/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/datatypes/message/Message.toolStatus.datatype.ts b/actions/ai-action/src/datatypes/message/Message.toolStatus.datatype.ts new file mode 100644 index 0000000..bef0a11 --- /dev/null +++ b/actions/ai-action/src/datatypes/message/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/datatypes/middleware/Middleware.agentState.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.agentState.datatype.ts new file mode 100644 index 0000000..55fa1e9 --- /dev/null +++ b/actions/ai-action/src/datatypes/middleware/Middleware.agentState.datatype.ts @@ -0,0 +1,19 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +import { AiMessageSchema } from "../message/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(), +}); +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/datatypes/middleware/Middleware.hook.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.hook.datatype.ts new file mode 100644 index 0000000..e636d62 --- /dev/null +++ b/actions/ai-action/src/datatypes/middleware/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/datatypes/middleware/Middleware.stateUpdate.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.stateUpdate.datatype.ts new file mode 100644 index 0000000..6a9f6ec --- /dev/null +++ b/actions/ai-action/src/datatypes/middleware/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/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/datatypes/middleware/Middleware.transform.datatype.ts b/actions/ai-action/src/datatypes/middleware/Middleware.transform.datatype.ts new file mode 100644 index 0000000..6f2d68e --- /dev/null +++ b/actions/ai-action/src/datatypes/middleware/Middleware.transform.datatype.ts @@ -0,0 +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"; + +/** + * 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/datatypes/model/Model.request.datatype.ts b/actions/ai-action/src/datatypes/model/Model.request.datatype.ts new file mode 100644 index 0000000..9190dea --- /dev/null +++ b/actions/ai-action/src/datatypes/model/Model.request.datatype.ts @@ -0,0 +1,24 @@ +import { DisplayMessage, Identifier, Name, Schema } from "@code0-tech/hercules"; +import { z } from "zod"; +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"; + +export const AiModelRequestSchema = z.object({ + messages: z.array(AiMessageSchema), + 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; + +@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/datatypes/model/Model.response.datatype.ts b/actions/ai-action/src/datatypes/model/Model.response.datatype.ts new file mode 100644 index 0000000..cd74c6e --- /dev/null +++ b/actions/ai-action/src/datatypes/model/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/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/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/datatypes/model/Model.toolChoice.datatype.ts b/actions/ai-action/src/datatypes/model/Model.toolChoice.datatype.ts new file mode 100644 index 0000000..3e8e854 --- /dev/null +++ b/actions/ai-action/src/datatypes/model/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/datatypes/model/Model.toolSpec.datatype.ts b/actions/ai-action/src/datatypes/model/Model.toolSpec.datatype.ts new file mode 100644 index 0000000..5b4cf93 --- /dev/null +++ b/actions/ai-action/src/datatypes/model/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/datatypes/model/Model.transform.datatype.ts b/actions/ai-action/src/datatypes/model/Model.transform.datatype.ts new file mode 100644 index 0000000..52d2348 --- /dev/null +++ b/actions/ai-action/src/datatypes/model/Model.transform.datatype.ts @@ -0,0 +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"; + +/** + * 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/index.ts b/actions/ai-action/src/index.ts new file mode 100644 index 0000000..f58013d --- /dev/null +++ b/actions/ai-action/src/index.ts @@ -0,0 +1,155 @@ +import "reflect-metadata"; +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 { 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"; +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"; +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 { connectToAquila } from "./utils/shared/Shared.connectToAquila.util.js"; + +const RECONNECT_DELAY_MS = 5000; + +const DATA_TYPES: DataTypeClass[] = [ + AiMessageRoleDataType, + AiToolStatusDataType, + AiContentBlockDataType, + AiMessageDataType, + AiToolSpecDataType, + AiResponseFormatDataType, + AiModelRequestDataType, + AiModelResponseDataType, + + AiMiddlewareHookDataType, + AiAgentStateDataType, + AiStateUpdateDataType, + + AiMcpTransportDataType, + AiMcpServerDataType, + + AiAgentApprovalDataType, + AiAgentStepDataType, + AiAgentRequestDataType, + AiAgentResponseDataType, + + AiChatRoleDataType, + AiChatContentPartDataType, + AiChatToolCallDataType, + AiChatMessageDataType, + AiChatRequestDataType, + AiChatUsageDataType, + AiChatChoiceDataType, + AiChatResponseDataType, + +]; + +const RUNTIME_FUNCTIONS: RuntimeFunctionClass[] = [ + CreateAgentFunction, + SkillsFunction, + ExtractInformationFunction, + McpServerFunction, + HumanInTheLoopMiddlewareFunction, + OpenAiOpenWebUiFormattingFunction, + OpenAiRespondFunction, + AnthropicModelFunction, + GroqModelFunction, + LiteLlmModelFunction, + MistralModelFunction, + OllamaModelFunction, + OpenAiModelFunction, + OpenRouterModelFunction, + TrimMessagesMiddlewareFunction, +]; + +/** 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 ?? "ai-action", + process.env.VERSION ?? "1.0.0", + process.env.AQUILA_URL ?? "127.0.0.1:8081", + "code0-tech", + "tabler:robot", + "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" }], +); + +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"); +}); + +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 +// 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), +}); + +export { action }; 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..29c487b --- /dev/null +++ b/actions/ai-action/src/model/Model.flowChatModel.ts @@ -0,0 +1,184 @@ +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 { emptyJsonSchema } from "../utils/shared/Shared.emptyJsonSchema.util.js"; +import { toPlainSchema } from "../utils/shared/Shared.toPlainSchema.util.js"; + +type BoundFlowChatModel = Runnable; + +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, + }); + }); + 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 } : {}), + }; + + const raw: unknown = await this.run(request as never); + + 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/runtimeevents/openai/OpenAi.server.runtimeevent.ts b/actions/ai-action/src/runtimeevents/openai/OpenAi.server.runtimeevent.ts new file mode 100644 index 0000000..b07bbd7 --- /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 - 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 + * 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 & { prompt: TEXT }") +@Name({ code: "en-US", content: "OpenAI endpoint" }) +@Description({ + code: "en-US", + content: + "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: "Path" }], + description: [ + { + code: "en-US", + 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.", + }, + ] +}) +@EventSetting({ + identifier: "model", + name: [{ code: "en-US", content: "Model" }], + description: [ + { + code: "en-US", + content: + "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.", + }, + ], +}) +@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 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.", + }, + ], +}) +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..6e47d9c --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/agent/Agent.create.runtimefunction.ts @@ -0,0 +1,615 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + 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"; +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 { AiStructuredChatResponse } from "../../datatypes/chat/Chat.response.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"; +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 { 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, 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" }) +@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} ${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 is what an error names when the agent fails.", + }, + ], +}) +@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: + "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: "instructions", + name: [{ code: "en-US", content: "Instructions" }], + 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.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "tools", + name: [{ code: "en-US", content: "Tools" }], + description: [ + { + code: "en-US", + content: + "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: "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 its fields instead of searching a text. It needs fields; left empty the agent answers in plain text.", + }, + ], + 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, which is how a chat endpoint hands the agent the conversation it is to carry on.", + }, + ], + optional: true, +}) +@Parameter({ + runtimeName: "rules", + name: [{ code: "en-US", content: "Rules" }], + description: [ + { + code: "en-US", + content: + "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 { + /** + * 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 - 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, + model: unknown, + prompt: string, + instructions?: string, + tools?: ToolEntry[], + answer_type?: unknown, + conversation?: AiChatRequest, + rules?: unknown[], + ): 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` + // 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 (answer_type !== undefined && answer_type !== null) { + outputSchema = toPlainSchema(answer_type); + if (!outputSchema || typeof outputSchema !== "object") { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + `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 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(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. + 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(rules, "rules").map((entry, index): SubFlow => + asSubFlow(entry, `rules[${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, + conversation ?? { messages: [] }, + "ERROR_INVALID_AI_CHAT_REQUEST", + "The chat request is not valid", + ); + const asked: string = asText(prompt, "prompt", "ERROR_INVALID_AI_CHAT_REQUEST"); + const history: AiMessage[] = [ + ...parsed.messages.map(fromChatMessage), + ...(asked.length > 0 + ? [{ role: "human", content: [{ type: "text", text: asked }] } as AiMessage] + : []), + ]; + if (history.length === 0) { + throw new RuntimeError( + "ERROR_INVALID_AI_CHAT_REQUEST", + "There is nothing to ask: the prompt is empty and the conversation carries no messages.", + ); + } + + const agentRequest: AiAgentRequest = parseOrThrow( + AiAgentRequestSchema, + { messages: history }, + "ERROR_INVALID_AI_AGENT_REQUEST", + "The agent request is not valid", + ); + + const flows: SubFlow[] = definition.tools.filter(isSubFlow); + + // 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)}`, + ); + } + + // 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 = + listed.size === 0 + ? discovered + : 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 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); + + // 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() + .toLowerCase() + .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 : ""; + return tool( + (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, + schema: (schema ?? emptyJsonSchema()) as never, + }, + ) as unknown as ClientTool; + }), + ...mcpTools, + ]; + 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, + ), + ...(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 + // 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) { + 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 { + 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 }); + } + } + + 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", + ); + + // 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"); + + 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 }; + } + } + } 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 "answer_type", not even when asked for it on its own.`, + ); + } + + 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/runtimefunctions/extract/Extract.information.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts new file mode 100644 index 0000000..f87a4e4 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/extract/Extract.information.runtimefunction.ts @@ -0,0 +1,199 @@ +import { + Alias, + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + RuntimeError, + Signature, + 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 { 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"; + +/** + * 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( + "(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" }) +@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 ${answer_type} out of ${prompt}" }) +@ThrowsError() +@Parameter({ + runtimeName: "prompt", + name: [{ code: "en-US", content: "Prompt" }], + 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: "answer_type", + name: [{ code: "en-US", content: "Answer type" }], + 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, +}) +@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 + * 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 prompt, read into this + * answer type by this model. + */ + async run( + _context: FunctionContext, + prompt: string, + answer_type: unknown, + model: unknown, + instructions?: string, + conversation?: AiChatRequest, + ): Promise> { + const read: string = asText(prompt, "prompt", "ERROR_INVALID_AI_EXTRACTION").trim(); + const added: string = asText(instructions ?? "", "instructions", "ERROR_INVALID_AI_EXTRACTION"); + + // 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(answer_type); + if (!schema || typeof schema !== "object") { + throw new RuntimeError( + "ERROR_INVALID_AI_OUTPUT_SCHEMA", + `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 "answer_type" 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: history.map(toLangChainMessage) }); + 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 "answer_type".', + ); + } + + return answer as Record; + } +} 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`, + ); + } +} 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..5047a5e --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.humanInTheLoop.runtimefunction.ts @@ -0,0 +1,252 @@ +import { + Alias, + Description, + 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 { 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"; + +@Identifier("ai::middleware::human_in_the_loop") +@DisplayIcon("tabler:message-ai") +@Signature("(tools: LIST): TRANSFORM") +@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({ + runtimeName: "tools", + name: [{ code: "en-US", content: "Tools" }], + description: [ + { + code: "en-US", + content: + "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.", + }, + ], +}) +export class HumanInTheLoopMiddlewareFunction { + /** + * A middleware that makes an agent ask before it runs certain tools, and holds it + * to the answer. + * + * 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. + * + * 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 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)); + 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": + 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(); + return { + messages: [ + ...history, + { + role: "ai", + content: [{ type: "text", text: askFor(held, code) }], + ...(last.id ? { id: last.id } : {}), + }, + ], + jump_to: "end", + }; + } + + if (declined.length > 0) { + 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. + return { messages: [...history, last] }; + }, + }; + } +} diff --git a/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts new file mode 100644 index 0000000..9180fc6 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/middleware/Middleware.trimMessages.runtimefunction.ts @@ -0,0 +1,135 @@ +import { + Alias, + Description, + 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 "../../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 TrimEnd = "first" | "last"; + +@Identifier("ai::middleware::trim_messages") +@DisplayIcon("tabler:scissors") +@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: "Shorten the conversation to ${max_conversation_length} tokens", +}) +@ThrowsError() +@Parameter({ + runtimeName: "max_conversation_length", + name: [{ code: "en-US", content: "Maximum conversation length" }], + description: [ + { + code: "en-US", + content: + "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: "keep", + name: [{ code: "en-US", content: "Which messages to keep" }], + description: [ + { + code: "en-US", + content: + "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_instructions", + name: [{ code: "en-US", content: "Keep the instructions" }], + description: [ + { + code: "en-US", + content: + "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, +}) +export class TrimMessagesMiddlewareFunction { + run( + _context: FunctionContext, + max_conversation_length: number, + keep?: string, + keep_instructions?: boolean, + ): AiMiddlewareTransform { + 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.", + ); + } + // "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", + `"${keep}" is not an end of the conversation; keep either the "newest" or the "oldest" messages.`, + ); + } + + const keptEnd: TrimEnd = keep === "oldest" || keep === "first" ? "first" : "last"; + const includeSystem: boolean = keep_instructions ?? true; + + return { + 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 => { + 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_conversation_length, + tokenCounter: countTokensApproximately, + strategy: keptEnd, + includeSystem, + allowPartial: false, + startOn: "human", + }); + + if (trimmed.length === parsed.messages.length) return {}; + + return { messages: trimmed.map(toFlowMessage) }; + }, + }; + } +} 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..2ff192f --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.anthropic.runtimefunction.ts @@ -0,0 +1,131 @@ +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", + 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..f9f4c41 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.groq.runtimefunction.ts @@ -0,0 +1,105 @@ +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", + 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..b587a23 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.liteLlm.runtimefunction.ts @@ -0,0 +1,154 @@ +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", + 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..e5e0a98 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.mistral.runtimefunction.ts @@ -0,0 +1,109 @@ +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", + 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..096f6ba --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.ollama.runtimefunction.ts @@ -0,0 +1,109 @@ +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", + 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..5d28adb --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.openAi.runtimefunction.ts @@ -0,0 +1,119 @@ +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", + 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 new file mode 100644 index 0000000..455090a --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/model/Model.openRouter.runtimefunction.ts @@ -0,0 +1,184 @@ +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 { 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 { requireText } from "../../utils/shared/Shared.requireText.util.js"; + +const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"; + +/** + * 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; + +/** + * 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. + * + * 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; +} + +@Identifier("ai::model::openrouter") +@DisplayIcon("simple:openrouter") +@Signature( + "(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({ + 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: "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: "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 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 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_answer_length?: number, + web_search?: 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_answer_length, + modelKwargs: { ...REQUIRE_SUPPORTED_PARAMETERS }, + }); + + return toModelTransform({ + provider: "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, + }); + } +} 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..e3d1d87 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.openWebUiFormatting.runtimefunction.ts @@ -0,0 +1,118 @@ +import { + Description, + 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 { 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 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)) 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"); + + 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..c7870b6 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/openai/OpenAi.respond.runtimefunction.ts @@ -0,0 +1,69 @@ +import { + Description, + DisplayIcon, + DisplayMessage, + FunctionContext, + Identifier, + Name, + Parameter, + Signature, + ThrowsError, +} from "@code0-tech/hercules"; +import { AiChatResponseSchema, type AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.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): AI_CHAT_RESPONSE") +@Name({ code: "en-US", content: "Respond to the OpenAI request" }) +@Description({ + code: "en-US", + content: + "Answers the waiting OpenAI client with this response, from wherever in the flow it belongs, so the flow can go on afterwards without the client waiting. It is also this node's result.", +}) +@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 + * 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 + * the last node of a flow, the flow's. That is what a manual execution has to go + * on: there is no connection to deliver to, and a void node would leave such a run + * ending in nothing. For an HTTP request it changes nothing - the server takes the + * answer from the wait this settles and ignores the flow's result. + */ + run(context: FunctionContext, response: unknown): AiChatResponse { + const answer: AiChatResponse = parseOrThrow( + AiChatResponseSchema, + response, + "ERROR_INVALID_AI_OPENAI_RESPONSE", + "The answer for an OpenAI client has to be a chat response", + ); + + pendingResponses.settle(context.executionId, answer); + + return answer; + } +} diff --git a/actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts b/actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts new file mode 100644 index 0000000..11bf672 --- /dev/null +++ b/actions/ai-action/src/runtimefunctions/tool/Tool.skills.runtimefunction.ts @@ -0,0 +1,238 @@ +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(); + +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 headingTitle(lines: string[]): string | undefined { + let fenced = false; + + for (let line = 0; line < lines.length; line += 1) { + const current: string = lines[line]; + if (FENCE.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 = plainTitle(atx[1]); + if (title.length > 0) return title; + } + + const next: string | undefined = lines[line + 1]; + 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; + } + + 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 { + if (typeof input === "string") return input; + if (typeof input !== "object" || input === null) { + throw new RuntimeError( + "ERROR_INVALID_AI_SKILL", + '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 a skill" is required.'); +} + +@Identifier("ai::tool::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. 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.`, + ); + 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 { + // 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", + 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; + }, + }; + } +} 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..09513a9 --- /dev/null +++ b/actions/ai-action/src/server/openai/OpenAi.server.ts @@ -0,0 +1,272 @@ +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"; +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 { 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; + +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"; + this.server = createServer((request, response) => { + this.handle(request, response).catch((error: unknown) => { + if (response.headersSent) { + response.end(); + return; + } + sendJson(response, 500, errorBody(describeError(error), "internal_error")); + }); + }); + } + + 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); + resolve({ port: this.port, host: this.host }); + }); + }); + } + + close(): Promise { + 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): 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") { + response.writeHead(204, corsHeaders()); + response.end(); + return; + } + + const path: OpenAiRequestPath | undefined = parseRequestPath(request.url ?? "/"); + if (!path) { + sendJson(response, 404, errorBody("Unknown endpoint.", "invalid_request_error")); + return; + } + + 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, + ); + + if (endpoints.length === 0) { + sendJson( + response, + 404, + errorBody(`No flow serves ${path.kind === "models" ? "models" : "completions"} here.`, "invalid_request_error"), + ); + 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; + + if (path.kind === "models") { + const listed: OpenAiEndpoint[] = endpoints.filter( + (endpoint) => !endpoint.apiKey || endpoint.apiKey === token, + ); + if (listed.length === 0) { + sendJson(response, 401, errorBody("Invalid API key.", "invalid_request_error", "invalid_api_key")); + return; + } + sendJson(response, 200, toModelList(listed)); + return; + } + + if (method !== "POST") { + response.setHeader("allow", "POST, OPTIONS"); + sendJson( + response, + 405, + errorBody(`Completions are asked for with POST, not ${method}.`, "invalid_request_error"), + ); + 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"); + + let parsed: unknown; + try { + parsed = JSON.parse(body || "{}"); + } catch { + sendJson(response, 400, errorBody("The request body is not valid JSON.", "invalid_request_error")); + 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) { + sendJson( + response, + 404, + errorBody(`The model "${payload.model ?? ""}" does not exist.`, "invalid_request_error", "model_not_found"), + ); + return; + } + + if (endpoint.apiKey && endpoint.apiKey !== token) { + 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) { + sendJson( + response, + 400, + errorBody("The request carries no messages to answer.", "invalid_request_error"), + ); + return; + } + + const answer: AiChatResponse | undefined = await this.run(endpoint, request_); + if (!answer) { + sendJson( + response, + 502, + errorBody( + `The flow serving "${endpoint.model}" did not answer with a chat response.`, + "internal_error", + ), + ); + return; + } + + if (payload.stream === true) { + const chunks: string[] = toStreamChunks(answer); + + 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); + } + + /** + * 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 - 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): 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(); + + // 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, prompt } as unknown as PlainValue) + .then((result) => ({ result })); + + try { + const outcome = await Promise.race([responded, finished]); + + if ("answer" in outcome) return this.named(outcome.answer, endpoint); + + const validation = AiChatResponseSchema.safeParse(outcome.result); + 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. + 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): AiChatResponse { + if (answer.model.trim().length > 0) return answer; + 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..caa86e8 --- /dev/null +++ b/actions/ai-action/src/server/openai/OpenAi.startServer.ts @@ -0,0 +1,16 @@ +import type { OpenAiServerHost, OpenAiServerOptions } from "../../types/openai/OpenAiServer.types.js"; +import { OpenAiServer } from "./OpenAi.server.js"; + +/** + * 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); + await server.listen(); + return server; +} 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/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/utils/chat/Chat.toChatContent.util.ts b/actions/ai-action/src/utils/chat/Chat.toChatContent.util.ts new file mode 100644 index 0000000..506651a --- /dev/null +++ b/actions/ai-action/src/utils/chat/Chat.toChatContent.util.ts @@ -0,0 +1,8 @@ +import type { AiMessage } from "../../datatypes/message/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/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..f08c200 --- /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 { 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"; + +export function toChatResponse( + answer: AiMessage, + fallbackModel: string, + structuredResponse?: Record, + extras: { steps?: AiAgentStep[]; awaitingApproval?: AiAgentApproval[] } = {}, +): AiStructuredChatResponse { + 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/utils/mcp/Mcp.toConnection.util.ts b/actions/ai-action/src/utils/mcp/Mcp.toConnection.util.ts new file mode 100644 index 0000000..41c14fd --- /dev/null +++ b/actions/ai-action/src/utils/mcp/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/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/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/utils/message/Message.toFlowMessage.util.ts b/actions/ai-action/src/utils/message/Message.toFlowMessage.util.ts new file mode 100644 index 0000000..f7080d8 --- /dev/null +++ b/actions/ai-action/src/utils/message/Message.toFlowMessage.util.ts @@ -0,0 +1,47 @@ +import * as lc from "@langchain/core/messages"; +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", + human: "human", + ai: "ai", + 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", + 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 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/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..a1fd341 --- /dev/null +++ b/actions/ai-action/src/utils/model/Model.toTransform.util.ts @@ -0,0 +1,153 @@ +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 { 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; + /** 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, identifier, model } = options; + 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 { + // A readable name, since this is what a flow shows the model call under; the + // identifier alone would not say whose model it is. + name: `${provider} model ${identifier}`, + description: + `Sends a conversation and the tools that may be called to the ${provider} model ` + + `"${identifier}" and returns the one message it answers with.`, + 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) : {}; + + 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) => { + 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; + + // 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 }; + }, + }; +} 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..e912666 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.pending.util.ts @@ -0,0 +1,48 @@ +import type { AiChatResponse } from "../../datatypes/chat/Chat.response.datatype.js"; +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 }); + }); + } + + /** 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); + 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..391c765 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.sendJson.util.ts @@ -0,0 +1,14 @@ +import type { ServerResponse } from "node:http"; +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): void { + const payload: string = JSON.stringify(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..1bb60f7 --- /dev/null +++ b/actions/ai-action/src/utils/openai/OpenAi.toEndpoints.util.ts @@ -0,0 +1,27 @@ +import type { ActionFlow } from "@code0-tech/tucana/aquila"; +import { OPENAI_EVENT, type OpenAiEndpoint } from "../../types/openai/OpenAi.types.js"; +import { normalizeRoute } from "./OpenAi.normalizeRoute.util.js"; +import { textSetting } from "./OpenAi.textSetting.util.js"; + +/** + * 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. + */ +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) 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/Shared.asList.util.ts b/actions/ai-action/src/utils/shared/Shared.asList.util.ts new file mode 100644 index 0000000..45f1c0f --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.asSubFlow.util.ts b/actions/ai-action/src/utils/shared/Shared.asSubFlow.util.ts new file mode 100644 index 0000000..98e53f6 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.asText.util.ts b/actions/ai-action/src/utils/shared/Shared.asText.util.ts new file mode 100644 index 0000000..30807a3 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.connectToAquila.util.ts b/actions/ai-action/src/utils/shared/Shared.connectToAquila.util.ts new file mode 100644 index 0000000..e11c6bd --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.describeError.util.ts b/actions/ai-action/src/utils/shared/Shared.describeError.util.ts new file mode 100644 index 0000000..159df9c --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.emptyJsonSchema.util.ts b/actions/ai-action/src/utils/shared/Shared.emptyJsonSchema.util.ts new file mode 100644 index 0000000..1c37663 --- /dev/null +++ b/actions/ai-action/src/utils/shared/Shared.emptyJsonSchema.util.ts @@ -0,0 +1,3 @@ +export function emptyJsonSchema(): Record { + return { type: "object", properties: {} }; +} diff --git a/actions/ai-action/src/utils/shared/Shared.formatIssues.util.ts b/actions/ai-action/src/utils/shared/Shared.formatIssues.util.ts new file mode 100644 index 0000000..ad231a7 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/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/utils/shared/Shared.hasEntries.util.ts b/actions/ai-action/src/utils/shared/Shared.hasEntries.util.ts new file mode 100644 index 0000000..5a8d4a7 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.isSubFlow.util.ts b/actions/ai-action/src/utils/shared/Shared.isSubFlow.util.ts new file mode 100644 index 0000000..c8f080f --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.parseOrThrow.util.ts b/actions/ai-action/src/utils/shared/Shared.parseOrThrow.util.ts new file mode 100644 index 0000000..5b337f5 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/utils/shared/Shared.requireText.util.ts b/actions/ai-action/src/utils/shared/Shared.requireText.util.ts new file mode 100644 index 0000000..6a8bdf3 --- /dev/null +++ b/actions/ai-action/src/utils/shared/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/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/test/agent.test.ts b/actions/ai-action/test/agent.test.ts new file mode 100644 index 0000000..3d13cb8 --- /dev/null +++ b/actions/ai-action/test/agent.test.ts @@ -0,0 +1,616 @@ +import "reflect-metadata"; +import { RuntimeError, type FunctionContext, type SubFlow } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +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 { + inputSchema?: unknown; + outputSchema?: unknown; + }; + if (inputSchema) flow.inputSchema = inputSchema; + 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, + 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[], 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 ask = 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 }] }; +} + +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(""); +} + +/** 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("answers with a chat response, because it runs the agent itself", async () => { + const { run } = scriptedModel([answer("hello")]); + const response = await ask.run(context(), "greeter", run, "hi", "You greet people."); + + 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 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"]); + 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 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", ""); + + 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 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. + 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 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"]); + 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 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. + 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 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", ""); + + 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 ask.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")]); + const response = await ask.run(context(), "greeter", run, "hi", ""); + + expect(response.structured_response).toBeUndefined(); + }); + + 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" }), + ).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( + /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); + }); + + it("needs something to ask", async () => { + const { run } = scriptedModel([answer("hello")]); + 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", ""), + ).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), + ).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", "", [ + { name: "docs", url: "https://a/mcp" }, + { name: "docs", url: "https://b/mcp" }, + ] as never), + ).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 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"]); + expect(requests[0].messages[0].content).toEqual([{ type: "text", text: "You greet people." }]); + expect(replyOf(response)).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 response = await ask.run(context(), "support", run, "where is A-1?", "", [lookup]); + + 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(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: {} }]), + answer("That did not work."), + ]); + const broken = subFlow(() => { + throw new Error("the warehouse is offline"); + }); + + 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."); + }); + + 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, + ), + })), + }; + }); + + await ask.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 ****" }]); + }); + + 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 response = await ask.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 () => { + 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 response = await ask.run( + context(), + "support", + run, + "hello", + "", + [], + undefined, + undefined, + [observe], + ); + + expect(hooks).toEqual(["before_model", "after_model"]); + 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." }); + + await expect( + 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]); + 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 ask.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 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."); + 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")]); + await expect( + 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( + /did not return a valid model response/, + ); + }); +}); + +describe("what a middleware flow is handed", () => { + 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) => { + seen.push(input as unknown as AiAgentState); + return {}; + }); + + 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"]); + }); +}); + +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 + ? { role: "user" as const, content: `question ${turn} ${"padding ".repeat(40)}` } + : { role: "assistant" as const, content: `answer ${turn} ${"padding ".repeat(40)}` }, + ); + + const response = await ask.run( + context(), + "support", + run, + "", + "You are helpful.", + [], + 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(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..d3c3c43 --- /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 ask = 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 ask.run( + context(), + "support", + model, + "", + "You help.", + 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 new file mode 100644 index 0000000..245b051 --- /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/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", () => { + 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/extract.test.ts b/actions/ai-action/test/extract.test.ts new file mode 100644 index 0000000..917a0ac --- /dev/null +++ b/actions/ai-action/test/extract.test.ts @@ -0,0 +1,196 @@ +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("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("")]); + + 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 new file mode 100644 index 0000000..94909e4 --- /dev/null +++ b/actions/ai-action/test/functions.test.ts @@ -0,0 +1,630 @@ +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"; +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 { 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 { 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 CreateAgentFunction(); +const mcp = new McpServerFunction(); + +/** + * 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, + 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 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.run).toEqual("function"); + expect(transform.name).toEqual("OpenRouter model anthropic/claude-opus-5"); + expect(transform.inputSchema).toBeDefined(); + expect(transform.outputSchema).toBeDefined(); + }); + + 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.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.run({ messages: [{ role: "human", content: [{ type: "text", text: "hi" }] }], tools: [] } as never), + ).rejects.toThrow(RuntimeError); + }, 30_000); + + 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("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(model.run(context(), "openai/gpt-oss-120b", "sk-or-test").inputSchema)).toContain( + "response_format", + ); + }); + + 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 = { + 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").run(request as never); + expect(invoke.mock.calls[0]?.[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( + ask.run(context(), "support", asFlowValue(transform), "hi", "You are helpful."), + ).rejects.toThrow(RuntimeError); + }, 30_000); +}); + +describe("ai::middleware::trim_messages", () => { + it("returns a sub flow function definition, which is what hercules can serialize", () => { + const transform = middleware.run(context(), 200); + + 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", () => { + expect(() => middleware.run(context(), 0)).toThrow(RuntimeError); + expect(() => middleware.run(context(), Number.NaN)).toThrow(RuntimeError); + }); + + 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 () => { + 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).run(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 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"); + }); + + it("rejects a state that is not an agent state", async () => { + const transform = middleware.run(context(), 500); + 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).run(state(12)); + expect(() => AiStateUpdateSchema.parse(update)).not.toThrow(); + }); +}); + +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(() => + 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(); + }); +}); + +describe("the chat format of ai::agent::create", () => { + 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 response = await ask.run( + context(), + "greeter", + run, + "hello", + "You greet people.", + undefined, + undefined, + { 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.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"]); + }); + + 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, { + 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 response = await ask.run( + context(), + "support", + run, + "and A-1?", + "", + [lookup], + undefined, + { + 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" }])]); + await ask.run(context(), "support", run, "again?", "", undefined, undefined, { + 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 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", ""); + + 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." }])]); + await ask.run(context(), "greeter", run, "and now?", "", undefined, undefined, { + 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("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", ""); + + 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 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. + expect(response.response).toEqual("done"); + }); + + 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, "", "", undefined, undefined, { messages: [] }), + ).rejects.toThrow(/nothing to ask/); + await expect( + 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 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 model llama-3.3-70b-versatile", + ); + expect(mistral.run(context(), "mistral-large-latest", "test").name).toEqual( + "Mistral model mistral-large-latest", + ); + 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", () => { + 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 model qwen3-32b"); + expect(fields(transform.inputSchema)).toContain("response_format"); + }); + + 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); + + const response = await ask.run( + context(), + "support", + asFlowValue(anthropic.run(context(), "claude-opus-5", "sk-ant-test")), + "hi", + "You are helpful.", + ); + 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 new file mode 100644 index 0000000..86a14ec --- /dev/null +++ b/actions/ai-action/test/openai.test.ts @@ -0,0 +1,549 @@ +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, + // 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"); + }); + + 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", + model, + "", + "You track orders.", + 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 & { prompt: TEXT }", + ); + }); +}); + +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; +} + +/** 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"); + 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("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].replace(/\\"/g, '"'); + 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. + expect(source).toContain("new Action("); + expect(([] as (DataTypeClass | RuntimeFunctionClass)[]).length).toEqual(0); + }); +}); diff --git a/actions/ai-action/test/skills.test.ts b/actions/ai-action/test/skills.test.ts new file mode 100644 index 0000000..c2b26cf --- /dev/null +++ b/actions/ai-action/test/skills.test.ts @@ -0,0 +1,78 @@ +import "reflect-metadata"; +import { RuntimeError } from "@code0-tech/hercules"; +import { describe, expect, it } from "vitest"; +import { SkillsFunction } from "../src/runtimefunctions/tool/Tool.skills.runtimefunction.js"; + +const skills = new SkillsFunction(); +const context = {} as never; + +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.", + "Customer Support\n================\n\nBe concise.", + ]); + + expect(tool.name).toEqual("Use a 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("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/); + }); +}); 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 }, + }); + }); +}); 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:') + } + } +});